echarts.js 2.6 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188351893519035191351923519335194351953519635197351983519935200352013520235203352043520535206352073520835209352103521135212352133521435215352163521735218352193522035221352223522335224352253522635227352283522935230352313523235233352343523535236352373523835239352403524135242352433524435245352463524735248352493525035251352523525335254352553525635257352583525935260352613526235263352643526535266352673526835269352703527135272352733527435275352763527735278352793528035281352823528335284352853528635287352883528935290352913529235293352943529535296352973529835299353003530135302353033530435305353063530735308353093531035311353123531335314353153531635317353183531935320353213532235323353243532535326353273532835329353303533135332353333533435335353363533735338353393534035341353423534335344353453534635347353483534935350353513535235353353543535535356353573535835359353603536135362353633536435365353663536735368353693537035371353723537335374353753537635377353783537935380353813538235383353843538535386353873538835389353903539135392353933539435395353963539735398353993540035401354023540335404354053540635407354083540935410354113541235413354143541535416354173541835419354203542135422354233542435425354263542735428354293543035431354323543335434354353543635437354383543935440354413544235443354443544535446354473544835449354503545135452354533545435455354563545735458354593546035461354623546335464354653546635467354683546935470354713547235473354743547535476354773547835479354803548135482354833548435485354863548735488354893549035491354923549335494354953549635497354983549935500355013550235503355043550535506355073550835509355103551135512355133551435515355163551735518355193552035521355223552335524355253552635527355283552935530355313553235533355343553535536355373553835539355403554135542355433554435545355463554735548355493555035551355523555335554355553555635557355583555935560355613556235563355643556535566355673556835569355703557135572355733557435575355763557735578355793558035581355823558335584355853558635587355883558935590355913559235593355943559535596355973559835599356003560135602356033560435605356063560735608356093561035611356123561335614356153561635617356183561935620356213562235623356243562535626356273562835629356303563135632356333563435635356363563735638356393564035641356423564335644356453564635647356483564935650356513565235653356543565535656356573565835659356603566135662356633566435665356663566735668356693567035671356723567335674356753567635677356783567935680356813568235683356843568535686356873568835689356903569135692356933569435695356963569735698356993570035701357023570335704357053570635707357083570935710357113571235713357143571535716357173571835719357203572135722357233572435725357263572735728357293573035731357323573335734357353573635737357383573935740357413574235743357443574535746357473574835749357503575135752357533575435755357563575735758357593576035761357623576335764357653576635767357683576935770357713577235773357743577535776357773577835779357803578135782357833578435785357863578735788357893579035791357923579335794357953579635797357983579935800358013580235803358043580535806358073580835809358103581135812358133581435815358163581735818358193582035821358223582335824358253582635827358283582935830358313583235833358343583535836358373583835839358403584135842358433584435845358463584735848358493585035851358523585335854358553585635857358583585935860358613586235863358643586535866358673586835869358703587135872358733587435875358763587735878358793588035881358823588335884358853588635887358883588935890358913589235893358943589535896358973589835899359003590135902359033590435905359063590735908359093591035911359123591335914359153591635917359183591935920359213592235923359243592535926359273592835929359303593135932359333593435935359363593735938359393594035941359423594335944359453594635947359483594935950359513595235953359543595535956359573595835959359603596135962359633596435965359663596735968359693597035971359723597335974359753597635977359783597935980359813598235983359843598535986359873598835989359903599135992359933599435995359963599735998359993600036001360023600336004360053600636007360083600936010360113601236013360143601536016360173601836019360203602136022360233602436025360263602736028360293603036031360323603336034360353603636037360383603936040360413604236043360443604536046360473604836049360503605136052360533605436055360563605736058360593606036061360623606336064360653606636067360683606936070360713607236073360743607536076360773607836079360803608136082360833608436085360863608736088360893609036091360923609336094360953609636097360983609936100361013610236103361043610536106361073610836109361103611136112361133611436115361163611736118361193612036121361223612336124361253612636127361283612936130361313613236133361343613536136361373613836139361403614136142361433614436145361463614736148361493615036151361523615336154361553615636157361583615936160361613616236163361643616536166361673616836169361703617136172361733617436175361763617736178361793618036181361823618336184361853618636187361883618936190361913619236193361943619536196361973619836199362003620136202362033620436205362063620736208362093621036211362123621336214362153621636217362183621936220362213622236223362243622536226362273622836229362303623136232362333623436235362363623736238362393624036241362423624336244362453624636247362483624936250362513625236253362543625536256362573625836259362603626136262362633626436265362663626736268362693627036271362723627336274362753627636277362783627936280362813628236283362843628536286362873628836289362903629136292362933629436295362963629736298362993630036301363023630336304363053630636307363083630936310363113631236313363143631536316363173631836319363203632136322363233632436325363263632736328363293633036331363323633336334363353633636337363383633936340363413634236343363443634536346363473634836349363503635136352363533635436355363563635736358363593636036361363623636336364363653636636367363683636936370363713637236373363743637536376363773637836379363803638136382363833638436385363863638736388363893639036391363923639336394363953639636397363983639936400364013640236403364043640536406364073640836409364103641136412364133641436415364163641736418364193642036421364223642336424364253642636427364283642936430364313643236433364343643536436364373643836439364403644136442364433644436445364463644736448364493645036451364523645336454364553645636457364583645936460364613646236463364643646536466364673646836469364703647136472364733647436475364763647736478364793648036481364823648336484364853648636487364883648936490364913649236493364943649536496364973649836499365003650136502365033650436505365063650736508365093651036511365123651336514365153651636517365183651936520365213652236523365243652536526365273652836529365303653136532365333653436535365363653736538365393654036541365423654336544365453654636547365483654936550365513655236553365543655536556365573655836559365603656136562365633656436565365663656736568365693657036571365723657336574365753657636577365783657936580365813658236583365843658536586365873658836589365903659136592365933659436595365963659736598365993660036601366023660336604366053660636607366083660936610366113661236613366143661536616366173661836619366203662136622366233662436625366263662736628366293663036631366323663336634366353663636637366383663936640366413664236643366443664536646366473664836649366503665136652366533665436655366563665736658366593666036661366623666336664366653666636667366683666936670366713667236673366743667536676366773667836679366803668136682366833668436685366863668736688366893669036691366923669336694366953669636697366983669936700367013670236703367043670536706367073670836709367103671136712367133671436715367163671736718367193672036721367223672336724367253672636727367283672936730367313673236733367343673536736367373673836739367403674136742367433674436745367463674736748367493675036751367523675336754367553675636757367583675936760367613676236763367643676536766367673676836769367703677136772367733677436775367763677736778367793678036781367823678336784367853678636787367883678936790367913679236793367943679536796367973679836799368003680136802368033680436805368063680736808368093681036811368123681336814368153681636817368183681936820368213682236823368243682536826368273682836829368303683136832368333683436835368363683736838368393684036841368423684336844368453684636847368483684936850368513685236853368543685536856368573685836859368603686136862368633686436865368663686736868368693687036871368723687336874368753687636877368783687936880368813688236883368843688536886368873688836889368903689136892368933689436895368963689736898368993690036901369023690336904369053690636907369083690936910369113691236913369143691536916369173691836919369203692136922369233692436925369263692736928369293693036931369323693336934369353693636937369383693936940369413694236943369443694536946369473694836949369503695136952369533695436955369563695736958369593696036961369623696336964369653696636967369683696936970369713697236973369743697536976369773697836979369803698136982369833698436985369863698736988369893699036991369923699336994369953699636997369983699937000370013700237003370043700537006370073700837009370103701137012370133701437015370163701737018370193702037021370223702337024370253702637027370283702937030370313703237033370343703537036370373703837039370403704137042370433704437045370463704737048370493705037051370523705337054370553705637057370583705937060370613706237063370643706537066370673706837069370703707137072370733707437075370763707737078370793708037081370823708337084370853708637087370883708937090370913709237093370943709537096370973709837099371003710137102371033710437105371063710737108371093711037111371123711337114371153711637117371183711937120371213712237123371243712537126371273712837129371303713137132371333713437135371363713737138371393714037141371423714337144371453714637147371483714937150371513715237153371543715537156371573715837159371603716137162371633716437165371663716737168371693717037171371723717337174371753717637177371783717937180371813718237183371843718537186371873718837189371903719137192371933719437195371963719737198371993720037201372023720337204372053720637207372083720937210372113721237213372143721537216372173721837219372203722137222372233722437225372263722737228372293723037231372323723337234372353723637237372383723937240372413724237243372443724537246372473724837249372503725137252372533725437255372563725737258372593726037261372623726337264372653726637267372683726937270372713727237273372743727537276372773727837279372803728137282372833728437285372863728737288372893729037291372923729337294372953729637297372983729937300373013730237303373043730537306373073730837309373103731137312373133731437315373163731737318373193732037321373223732337324373253732637327373283732937330373313733237333373343733537336373373733837339373403734137342373433734437345373463734737348373493735037351373523735337354373553735637357373583735937360373613736237363373643736537366373673736837369373703737137372373733737437375373763737737378373793738037381373823738337384373853738637387373883738937390373913739237393373943739537396373973739837399374003740137402374033740437405374063740737408374093741037411374123741337414374153741637417374183741937420374213742237423374243742537426374273742837429374303743137432374333743437435374363743737438374393744037441374423744337444374453744637447374483744937450374513745237453374543745537456374573745837459374603746137462374633746437465374663746737468374693747037471374723747337474374753747637477374783747937480374813748237483374843748537486374873748837489374903749137492374933749437495374963749737498374993750037501375023750337504375053750637507375083750937510375113751237513375143751537516375173751837519375203752137522375233752437525375263752737528375293753037531375323753337534375353753637537375383753937540375413754237543375443754537546375473754837549375503755137552375533755437555375563755737558375593756037561375623756337564375653756637567375683756937570375713757237573375743757537576375773757837579375803758137582375833758437585375863758737588375893759037591375923759337594375953759637597375983759937600376013760237603376043760537606376073760837609376103761137612376133761437615376163761737618376193762037621376223762337624376253762637627376283762937630376313763237633376343763537636376373763837639376403764137642376433764437645376463764737648376493765037651376523765337654376553765637657376583765937660376613766237663376643766537666376673766837669376703767137672376733767437675376763767737678376793768037681376823768337684376853768637687376883768937690376913769237693376943769537696376973769837699377003770137702377033770437705377063770737708377093771037711377123771337714377153771637717377183771937720377213772237723377243772537726377273772837729377303773137732377333773437735377363773737738377393774037741377423774337744377453774637747377483774937750377513775237753377543775537756377573775837759377603776137762377633776437765377663776737768377693777037771377723777337774377753777637777377783777937780377813778237783377843778537786377873778837789377903779137792377933779437795377963779737798377993780037801378023780337804378053780637807378083780937810378113781237813378143781537816378173781837819378203782137822378233782437825378263782737828378293783037831378323783337834378353783637837378383783937840378413784237843378443784537846378473784837849378503785137852378533785437855378563785737858378593786037861378623786337864378653786637867378683786937870378713787237873378743787537876378773787837879378803788137882378833788437885378863788737888378893789037891378923789337894378953789637897378983789937900379013790237903379043790537906379073790837909379103791137912379133791437915379163791737918379193792037921379223792337924379253792637927379283792937930379313793237933379343793537936379373793837939379403794137942379433794437945379463794737948379493795037951379523795337954379553795637957379583795937960379613796237963379643796537966379673796837969379703797137972379733797437975379763797737978379793798037981379823798337984379853798637987379883798937990379913799237993379943799537996379973799837999380003800138002380033800438005380063800738008380093801038011380123801338014380153801638017380183801938020380213802238023380243802538026380273802838029380303803138032380333803438035380363803738038380393804038041380423804338044380453804638047380483804938050380513805238053380543805538056380573805838059380603806138062380633806438065380663806738068380693807038071380723807338074380753807638077380783807938080380813808238083380843808538086380873808838089380903809138092380933809438095380963809738098380993810038101381023810338104381053810638107381083810938110381113811238113381143811538116381173811838119381203812138122381233812438125381263812738128381293813038131381323813338134381353813638137381383813938140381413814238143381443814538146381473814838149381503815138152381533815438155381563815738158381593816038161381623816338164381653816638167381683816938170381713817238173381743817538176381773817838179381803818138182381833818438185381863818738188381893819038191381923819338194381953819638197381983819938200382013820238203382043820538206382073820838209382103821138212382133821438215382163821738218382193822038221382223822338224382253822638227382283822938230382313823238233382343823538236382373823838239382403824138242382433824438245382463824738248382493825038251382523825338254382553825638257382583825938260382613826238263382643826538266382673826838269382703827138272382733827438275382763827738278382793828038281382823828338284382853828638287382883828938290382913829238293382943829538296382973829838299383003830138302383033830438305383063830738308383093831038311383123831338314383153831638317383183831938320383213832238323383243832538326383273832838329383303833138332383333833438335383363833738338383393834038341383423834338344383453834638347383483834938350383513835238353383543835538356383573835838359383603836138362383633836438365383663836738368383693837038371383723837338374383753837638377383783837938380383813838238383383843838538386383873838838389383903839138392383933839438395383963839738398383993840038401384023840338404384053840638407384083840938410384113841238413384143841538416384173841838419384203842138422384233842438425384263842738428384293843038431384323843338434384353843638437384383843938440384413844238443384443844538446384473844838449384503845138452384533845438455384563845738458384593846038461384623846338464384653846638467384683846938470384713847238473384743847538476384773847838479384803848138482384833848438485384863848738488384893849038491384923849338494384953849638497384983849938500385013850238503385043850538506385073850838509385103851138512385133851438515385163851738518385193852038521385223852338524385253852638527385283852938530385313853238533385343853538536385373853838539385403854138542385433854438545385463854738548385493855038551385523855338554385553855638557385583855938560385613856238563385643856538566385673856838569385703857138572385733857438575385763857738578385793858038581385823858338584385853858638587385883858938590385913859238593385943859538596385973859838599386003860138602386033860438605386063860738608386093861038611386123861338614386153861638617386183861938620386213862238623386243862538626386273862838629386303863138632386333863438635386363863738638386393864038641386423864338644386453864638647386483864938650386513865238653386543865538656386573865838659386603866138662386633866438665386663866738668386693867038671386723867338674386753867638677386783867938680386813868238683386843868538686386873868838689386903869138692386933869438695386963869738698386993870038701387023870338704387053870638707387083870938710387113871238713387143871538716387173871838719387203872138722387233872438725387263872738728387293873038731387323873338734387353873638737387383873938740387413874238743387443874538746387473874838749387503875138752387533875438755387563875738758387593876038761387623876338764387653876638767387683876938770387713877238773387743877538776387773877838779387803878138782387833878438785387863878738788387893879038791387923879338794387953879638797387983879938800388013880238803388043880538806388073880838809388103881138812388133881438815388163881738818388193882038821388223882338824388253882638827388283882938830388313883238833388343883538836388373883838839388403884138842388433884438845388463884738848388493885038851388523885338854388553885638857388583885938860388613886238863388643886538866388673886838869388703887138872388733887438875388763887738878388793888038881388823888338884388853888638887388883888938890388913889238893388943889538896388973889838899389003890138902389033890438905389063890738908389093891038911389123891338914389153891638917389183891938920389213892238923389243892538926389273892838929389303893138932389333893438935389363893738938389393894038941389423894338944389453894638947389483894938950389513895238953389543895538956389573895838959389603896138962389633896438965389663896738968389693897038971389723897338974389753897638977389783897938980389813898238983389843898538986389873898838989389903899138992389933899438995389963899738998389993900039001390023900339004390053900639007390083900939010390113901239013390143901539016390173901839019390203902139022390233902439025390263902739028390293903039031390323903339034390353903639037390383903939040390413904239043390443904539046390473904839049390503905139052390533905439055390563905739058390593906039061390623906339064390653906639067390683906939070390713907239073390743907539076390773907839079390803908139082390833908439085390863908739088390893909039091390923909339094390953909639097390983909939100391013910239103391043910539106391073910839109391103911139112391133911439115391163911739118391193912039121391223912339124391253912639127391283912939130391313913239133391343913539136391373913839139391403914139142391433914439145391463914739148391493915039151391523915339154391553915639157391583915939160391613916239163391643916539166391673916839169391703917139172391733917439175391763917739178391793918039181391823918339184391853918639187391883918939190391913919239193391943919539196391973919839199392003920139202392033920439205392063920739208392093921039211392123921339214392153921639217392183921939220392213922239223392243922539226392273922839229392303923139232392333923439235392363923739238392393924039241392423924339244392453924639247392483924939250392513925239253392543925539256392573925839259392603926139262392633926439265392663926739268392693927039271392723927339274392753927639277392783927939280392813928239283392843928539286392873928839289392903929139292392933929439295392963929739298392993930039301393023930339304393053930639307393083930939310393113931239313393143931539316393173931839319393203932139322393233932439325393263932739328393293933039331393323933339334393353933639337393383933939340393413934239343393443934539346393473934839349393503935139352393533935439355393563935739358393593936039361393623936339364393653936639367393683936939370393713937239373393743937539376393773937839379393803938139382393833938439385393863938739388393893939039391393923939339394393953939639397393983939939400394013940239403394043940539406394073940839409394103941139412394133941439415394163941739418394193942039421394223942339424394253942639427394283942939430394313943239433394343943539436394373943839439394403944139442394433944439445394463944739448394493945039451394523945339454394553945639457394583945939460394613946239463394643946539466394673946839469394703947139472394733947439475394763947739478394793948039481394823948339484394853948639487394883948939490394913949239493394943949539496394973949839499395003950139502395033950439505395063950739508395093951039511395123951339514395153951639517395183951939520395213952239523395243952539526395273952839529395303953139532395333953439535395363953739538395393954039541395423954339544395453954639547395483954939550395513955239553395543955539556395573955839559395603956139562395633956439565395663956739568395693957039571395723957339574395753957639577395783957939580395813958239583395843958539586395873958839589395903959139592395933959439595395963959739598395993960039601396023960339604396053960639607396083960939610396113961239613396143961539616396173961839619396203962139622396233962439625396263962739628396293963039631396323963339634396353963639637396383963939640396413964239643396443964539646396473964839649396503965139652396533965439655396563965739658396593966039661396623966339664396653966639667396683966939670396713967239673396743967539676396773967839679396803968139682396833968439685396863968739688396893969039691396923969339694396953969639697396983969939700397013970239703397043970539706397073970839709397103971139712397133971439715397163971739718397193972039721397223972339724397253972639727397283972939730397313973239733397343973539736397373973839739397403974139742397433974439745397463974739748397493975039751397523975339754397553975639757397583975939760397613976239763397643976539766397673976839769397703977139772397733977439775397763977739778397793978039781397823978339784397853978639787397883978939790397913979239793397943979539796397973979839799398003980139802398033980439805398063980739808398093981039811398123981339814398153981639817398183981939820398213982239823398243982539826398273982839829398303983139832398333983439835398363983739838398393984039841398423984339844398453984639847398483984939850398513985239853398543985539856398573985839859398603986139862398633986439865398663986739868398693987039871398723987339874398753987639877398783987939880398813988239883398843988539886398873988839889398903989139892398933989439895398963989739898398993990039901399023990339904399053990639907399083990939910399113991239913399143991539916399173991839919399203992139922399233992439925399263992739928399293993039931399323993339934399353993639937399383993939940399413994239943399443994539946399473994839949399503995139952399533995439955399563995739958399593996039961399623996339964399653996639967399683996939970399713997239973399743997539976399773997839979399803998139982399833998439985399863998739988399893999039991399923999339994399953999639997399983999940000400014000240003400044000540006400074000840009400104001140012400134001440015400164001740018400194002040021400224002340024400254002640027400284002940030400314003240033400344003540036400374003840039400404004140042400434004440045400464004740048400494005040051400524005340054400554005640057400584005940060400614006240063400644006540066400674006840069400704007140072400734007440075400764007740078400794008040081400824008340084400854008640087400884008940090400914009240093400944009540096400974009840099401004010140102401034010440105401064010740108401094011040111401124011340114401154011640117401184011940120401214012240123401244012540126401274012840129401304013140132401334013440135401364013740138401394014040141401424014340144401454014640147401484014940150401514015240153401544015540156401574015840159401604016140162401634016440165401664016740168401694017040171401724017340174401754017640177401784017940180401814018240183401844018540186401874018840189401904019140192401934019440195401964019740198401994020040201402024020340204402054020640207402084020940210402114021240213402144021540216402174021840219402204022140222402234022440225402264022740228402294023040231402324023340234402354023640237402384023940240402414024240243402444024540246402474024840249402504025140252402534025440255402564025740258402594026040261402624026340264402654026640267402684026940270402714027240273402744027540276402774027840279402804028140282402834028440285402864028740288402894029040291402924029340294402954029640297402984029940300403014030240303403044030540306403074030840309403104031140312403134031440315403164031740318403194032040321403224032340324403254032640327403284032940330403314033240333403344033540336403374033840339403404034140342403434034440345403464034740348403494035040351403524035340354403554035640357403584035940360403614036240363403644036540366403674036840369403704037140372403734037440375403764037740378403794038040381403824038340384403854038640387403884038940390403914039240393403944039540396403974039840399404004040140402404034040440405404064040740408404094041040411404124041340414404154041640417404184041940420404214042240423404244042540426404274042840429404304043140432404334043440435404364043740438404394044040441404424044340444404454044640447404484044940450404514045240453404544045540456404574045840459404604046140462404634046440465404664046740468404694047040471404724047340474404754047640477404784047940480404814048240483404844048540486404874048840489404904049140492404934049440495404964049740498404994050040501405024050340504405054050640507405084050940510405114051240513405144051540516405174051840519405204052140522405234052440525405264052740528405294053040531405324053340534405354053640537405384053940540405414054240543405444054540546405474054840549405504055140552405534055440555405564055740558405594056040561405624056340564405654056640567405684056940570405714057240573405744057540576405774057840579405804058140582405834058440585405864058740588405894059040591405924059340594405954059640597405984059940600406014060240603406044060540606406074060840609406104061140612406134061440615406164061740618406194062040621406224062340624406254062640627406284062940630406314063240633406344063540636406374063840639406404064140642406434064440645406464064740648406494065040651406524065340654406554065640657406584065940660406614066240663406644066540666406674066840669406704067140672406734067440675406764067740678406794068040681406824068340684406854068640687406884068940690406914069240693406944069540696406974069840699407004070140702407034070440705407064070740708407094071040711407124071340714407154071640717407184071940720407214072240723407244072540726407274072840729407304073140732407334073440735407364073740738407394074040741407424074340744407454074640747407484074940750407514075240753407544075540756407574075840759407604076140762407634076440765407664076740768407694077040771407724077340774407754077640777407784077940780407814078240783407844078540786407874078840789407904079140792407934079440795407964079740798407994080040801408024080340804408054080640807408084080940810408114081240813408144081540816408174081840819408204082140822408234082440825408264082740828408294083040831408324083340834408354083640837408384083940840408414084240843408444084540846408474084840849408504085140852408534085440855408564085740858408594086040861408624086340864408654086640867408684086940870408714087240873408744087540876408774087840879408804088140882408834088440885408864088740888408894089040891408924089340894408954089640897408984089940900409014090240903409044090540906409074090840909409104091140912409134091440915409164091740918409194092040921409224092340924409254092640927409284092940930409314093240933409344093540936409374093840939409404094140942409434094440945409464094740948409494095040951409524095340954409554095640957409584095940960409614096240963409644096540966409674096840969409704097140972409734097440975409764097740978409794098040981409824098340984409854098640987409884098940990409914099240993409944099540996409974099840999410004100141002410034100441005410064100741008410094101041011410124101341014410154101641017410184101941020410214102241023410244102541026410274102841029410304103141032410334103441035410364103741038410394104041041410424104341044410454104641047410484104941050410514105241053410544105541056410574105841059410604106141062410634106441065410664106741068410694107041071410724107341074410754107641077410784107941080410814108241083410844108541086410874108841089410904109141092410934109441095410964109741098410994110041101411024110341104411054110641107411084110941110411114111241113411144111541116411174111841119411204112141122411234112441125411264112741128411294113041131411324113341134411354113641137411384113941140411414114241143411444114541146411474114841149411504115141152411534115441155411564115741158411594116041161411624116341164411654116641167411684116941170411714117241173411744117541176411774117841179411804118141182411834118441185411864118741188411894119041191411924119341194411954119641197411984119941200412014120241203412044120541206412074120841209412104121141212412134121441215412164121741218412194122041221412224122341224412254122641227412284122941230412314123241233412344123541236412374123841239412404124141242412434124441245412464124741248412494125041251412524125341254412554125641257412584125941260412614126241263412644126541266412674126841269412704127141272412734127441275412764127741278412794128041281412824128341284412854128641287412884128941290412914129241293412944129541296412974129841299413004130141302413034130441305413064130741308413094131041311413124131341314413154131641317413184131941320413214132241323413244132541326413274132841329413304133141332413334133441335413364133741338413394134041341413424134341344413454134641347413484134941350413514135241353413544135541356413574135841359413604136141362413634136441365413664136741368413694137041371413724137341374413754137641377413784137941380413814138241383413844138541386413874138841389413904139141392413934139441395413964139741398413994140041401414024140341404414054140641407414084140941410414114141241413414144141541416414174141841419414204142141422414234142441425414264142741428414294143041431414324143341434414354143641437414384143941440414414144241443414444144541446414474144841449414504145141452414534145441455414564145741458414594146041461414624146341464414654146641467414684146941470414714147241473414744147541476414774147841479414804148141482414834148441485414864148741488414894149041491414924149341494414954149641497414984149941500415014150241503415044150541506415074150841509415104151141512415134151441515415164151741518415194152041521415224152341524415254152641527415284152941530415314153241533415344153541536415374153841539415404154141542415434154441545415464154741548415494155041551415524155341554415554155641557415584155941560415614156241563415644156541566415674156841569415704157141572415734157441575415764157741578415794158041581415824158341584415854158641587415884158941590415914159241593415944159541596415974159841599416004160141602416034160441605416064160741608416094161041611416124161341614416154161641617416184161941620416214162241623416244162541626416274162841629416304163141632416334163441635416364163741638416394164041641416424164341644416454164641647416484164941650416514165241653416544165541656416574165841659416604166141662416634166441665416664166741668416694167041671416724167341674416754167641677416784167941680416814168241683416844168541686416874168841689416904169141692416934169441695416964169741698416994170041701417024170341704417054170641707417084170941710417114171241713417144171541716417174171841719417204172141722417234172441725417264172741728417294173041731417324173341734417354173641737417384173941740417414174241743417444174541746417474174841749417504175141752417534175441755417564175741758417594176041761417624176341764417654176641767417684176941770417714177241773417744177541776417774177841779417804178141782417834178441785417864178741788417894179041791417924179341794417954179641797417984179941800418014180241803418044180541806418074180841809418104181141812418134181441815418164181741818418194182041821418224182341824418254182641827418284182941830418314183241833418344183541836418374183841839418404184141842418434184441845418464184741848418494185041851418524185341854418554185641857418584185941860418614186241863418644186541866418674186841869418704187141872418734187441875418764187741878418794188041881418824188341884418854188641887418884188941890418914189241893418944189541896418974189841899419004190141902419034190441905419064190741908419094191041911419124191341914419154191641917419184191941920419214192241923419244192541926419274192841929419304193141932419334193441935419364193741938419394194041941419424194341944419454194641947419484194941950419514195241953419544195541956419574195841959419604196141962419634196441965419664196741968419694197041971419724197341974419754197641977419784197941980419814198241983419844198541986419874198841989419904199141992419934199441995419964199741998419994200042001420024200342004420054200642007420084200942010420114201242013420144201542016420174201842019420204202142022420234202442025420264202742028420294203042031420324203342034420354203642037420384203942040420414204242043420444204542046420474204842049420504205142052420534205442055420564205742058420594206042061420624206342064420654206642067420684206942070420714207242073420744207542076420774207842079420804208142082420834208442085420864208742088420894209042091420924209342094420954209642097420984209942100421014210242103421044210542106421074210842109421104211142112421134211442115421164211742118421194212042121421224212342124421254212642127421284212942130421314213242133421344213542136421374213842139421404214142142421434214442145421464214742148421494215042151421524215342154421554215642157421584215942160421614216242163421644216542166421674216842169421704217142172421734217442175421764217742178421794218042181421824218342184421854218642187421884218942190421914219242193421944219542196421974219842199422004220142202422034220442205422064220742208422094221042211422124221342214422154221642217422184221942220422214222242223422244222542226422274222842229422304223142232422334223442235422364223742238422394224042241422424224342244422454224642247422484224942250422514225242253422544225542256422574225842259422604226142262422634226442265422664226742268422694227042271422724227342274422754227642277422784227942280422814228242283422844228542286422874228842289422904229142292422934229442295422964229742298422994230042301423024230342304423054230642307423084230942310423114231242313423144231542316423174231842319423204232142322423234232442325423264232742328423294233042331423324233342334423354233642337423384233942340423414234242343423444234542346423474234842349423504235142352423534235442355423564235742358423594236042361423624236342364423654236642367423684236942370423714237242373423744237542376423774237842379423804238142382423834238442385423864238742388423894239042391423924239342394423954239642397423984239942400424014240242403424044240542406424074240842409424104241142412424134241442415424164241742418424194242042421424224242342424424254242642427424284242942430424314243242433424344243542436424374243842439424404244142442424434244442445424464244742448424494245042451424524245342454424554245642457424584245942460424614246242463424644246542466424674246842469424704247142472424734247442475424764247742478424794248042481424824248342484424854248642487424884248942490424914249242493424944249542496424974249842499425004250142502425034250442505425064250742508425094251042511425124251342514425154251642517425184251942520425214252242523425244252542526425274252842529425304253142532425334253442535425364253742538425394254042541425424254342544425454254642547425484254942550425514255242553425544255542556425574255842559425604256142562425634256442565425664256742568425694257042571425724257342574425754257642577425784257942580425814258242583425844258542586425874258842589425904259142592425934259442595425964259742598425994260042601426024260342604426054260642607426084260942610426114261242613426144261542616426174261842619426204262142622426234262442625426264262742628426294263042631426324263342634426354263642637426384263942640426414264242643426444264542646426474264842649426504265142652426534265442655426564265742658426594266042661426624266342664426654266642667426684266942670426714267242673426744267542676426774267842679426804268142682426834268442685426864268742688426894269042691426924269342694426954269642697426984269942700427014270242703427044270542706427074270842709427104271142712427134271442715427164271742718427194272042721427224272342724427254272642727427284272942730427314273242733427344273542736427374273842739427404274142742427434274442745427464274742748427494275042751427524275342754427554275642757427584275942760427614276242763427644276542766427674276842769427704277142772427734277442775427764277742778427794278042781427824278342784427854278642787427884278942790427914279242793427944279542796427974279842799428004280142802428034280442805428064280742808428094281042811428124281342814428154281642817428184281942820428214282242823428244282542826428274282842829428304283142832428334283442835428364283742838428394284042841428424284342844428454284642847428484284942850428514285242853428544285542856428574285842859428604286142862428634286442865428664286742868428694287042871428724287342874428754287642877428784287942880428814288242883428844288542886428874288842889428904289142892428934289442895428964289742898428994290042901429024290342904429054290642907429084290942910429114291242913429144291542916429174291842919429204292142922429234292442925429264292742928429294293042931429324293342934429354293642937429384293942940429414294242943429444294542946429474294842949429504295142952429534295442955429564295742958429594296042961429624296342964429654296642967429684296942970429714297242973429744297542976429774297842979429804298142982429834298442985429864298742988429894299042991429924299342994429954299642997429984299943000430014300243003430044300543006430074300843009430104301143012430134301443015430164301743018430194302043021430224302343024430254302643027430284302943030430314303243033430344303543036430374303843039430404304143042430434304443045430464304743048430494305043051430524305343054430554305643057430584305943060430614306243063430644306543066430674306843069430704307143072430734307443075430764307743078430794308043081430824308343084430854308643087430884308943090430914309243093430944309543096430974309843099431004310143102431034310443105431064310743108431094311043111431124311343114431154311643117431184311943120431214312243123431244312543126431274312843129431304313143132431334313443135431364313743138431394314043141431424314343144431454314643147431484314943150431514315243153431544315543156431574315843159431604316143162431634316443165431664316743168431694317043171431724317343174431754317643177431784317943180431814318243183431844318543186431874318843189431904319143192431934319443195431964319743198431994320043201432024320343204432054320643207432084320943210432114321243213432144321543216432174321843219432204322143222432234322443225432264322743228432294323043231432324323343234432354323643237432384323943240432414324243243432444324543246432474324843249432504325143252432534325443255432564325743258432594326043261432624326343264432654326643267432684326943270432714327243273432744327543276432774327843279432804328143282432834328443285432864328743288432894329043291432924329343294432954329643297432984329943300433014330243303433044330543306433074330843309433104331143312433134331443315433164331743318433194332043321433224332343324433254332643327433284332943330433314333243333433344333543336433374333843339433404334143342433434334443345433464334743348433494335043351433524335343354433554335643357433584335943360433614336243363433644336543366433674336843369433704337143372433734337443375433764337743378433794338043381433824338343384433854338643387433884338943390433914339243393433944339543396433974339843399434004340143402434034340443405434064340743408434094341043411434124341343414434154341643417434184341943420434214342243423434244342543426434274342843429434304343143432434334343443435434364343743438434394344043441434424344343444434454344643447434484344943450434514345243453434544345543456434574345843459434604346143462434634346443465434664346743468434694347043471434724347343474434754347643477434784347943480434814348243483434844348543486434874348843489434904349143492434934349443495434964349743498434994350043501435024350343504435054350643507435084350943510435114351243513435144351543516435174351843519435204352143522435234352443525435264352743528435294353043531435324353343534435354353643537435384353943540435414354243543435444354543546435474354843549435504355143552435534355443555435564355743558435594356043561435624356343564435654356643567435684356943570435714357243573435744357543576435774357843579435804358143582435834358443585435864358743588435894359043591435924359343594435954359643597435984359943600436014360243603436044360543606436074360843609436104361143612436134361443615436164361743618436194362043621436224362343624436254362643627436284362943630436314363243633436344363543636436374363843639436404364143642436434364443645436464364743648436494365043651436524365343654436554365643657436584365943660436614366243663436644366543666436674366843669436704367143672436734367443675436764367743678436794368043681436824368343684436854368643687436884368943690436914369243693436944369543696436974369843699437004370143702437034370443705437064370743708437094371043711437124371343714437154371643717437184371943720437214372243723437244372543726437274372843729437304373143732437334373443735437364373743738437394374043741437424374343744437454374643747437484374943750437514375243753437544375543756437574375843759437604376143762437634376443765437664376743768437694377043771437724377343774437754377643777437784377943780437814378243783437844378543786437874378843789437904379143792437934379443795437964379743798437994380043801438024380343804438054380643807438084380943810438114381243813438144381543816438174381843819438204382143822438234382443825438264382743828438294383043831438324383343834438354383643837438384383943840438414384243843438444384543846438474384843849438504385143852438534385443855438564385743858438594386043861438624386343864438654386643867438684386943870438714387243873438744387543876438774387843879438804388143882438834388443885438864388743888438894389043891438924389343894438954389643897438984389943900439014390243903439044390543906439074390843909439104391143912439134391443915439164391743918439194392043921439224392343924439254392643927439284392943930439314393243933439344393543936439374393843939439404394143942439434394443945439464394743948439494395043951439524395343954439554395643957439584395943960439614396243963439644396543966439674396843969439704397143972439734397443975439764397743978439794398043981439824398343984439854398643987439884398943990439914399243993439944399543996439974399843999440004400144002440034400444005440064400744008440094401044011440124401344014440154401644017440184401944020440214402244023440244402544026440274402844029440304403144032440334403444035440364403744038440394404044041440424404344044440454404644047440484404944050440514405244053440544405544056440574405844059440604406144062440634406444065440664406744068440694407044071440724407344074440754407644077440784407944080440814408244083440844408544086440874408844089440904409144092440934409444095440964409744098440994410044101441024410344104441054410644107441084410944110441114411244113441144411544116441174411844119441204412144122441234412444125441264412744128441294413044131441324413344134441354413644137441384413944140441414414244143441444414544146441474414844149441504415144152441534415444155441564415744158441594416044161441624416344164441654416644167441684416944170441714417244173441744417544176441774417844179441804418144182441834418444185441864418744188441894419044191441924419344194441954419644197441984419944200442014420244203442044420544206442074420844209442104421144212442134421444215442164421744218442194422044221442224422344224442254422644227442284422944230442314423244233442344423544236442374423844239442404424144242442434424444245442464424744248442494425044251442524425344254442554425644257442584425944260442614426244263442644426544266442674426844269442704427144272442734427444275442764427744278442794428044281442824428344284442854428644287442884428944290442914429244293442944429544296442974429844299443004430144302443034430444305443064430744308443094431044311443124431344314443154431644317443184431944320443214432244323443244432544326443274432844329443304433144332443334433444335443364433744338443394434044341443424434344344443454434644347443484434944350443514435244353443544435544356443574435844359443604436144362443634436444365443664436744368443694437044371443724437344374443754437644377443784437944380443814438244383443844438544386443874438844389443904439144392443934439444395443964439744398443994440044401444024440344404444054440644407444084440944410444114441244413444144441544416444174441844419444204442144422444234442444425444264442744428444294443044431444324443344434444354443644437444384443944440444414444244443444444444544446444474444844449444504445144452444534445444455444564445744458444594446044461444624446344464444654446644467444684446944470444714447244473444744447544476444774447844479444804448144482444834448444485444864448744488444894449044491444924449344494444954449644497444984449944500445014450244503445044450544506445074450844509445104451144512445134451444515445164451744518445194452044521445224452344524445254452644527445284452944530445314453244533445344453544536445374453844539445404454144542445434454444545445464454744548445494455044551445524455344554445554455644557445584455944560445614456244563445644456544566445674456844569445704457144572445734457444575445764457744578445794458044581445824458344584445854458644587445884458944590445914459244593445944459544596445974459844599446004460144602446034460444605446064460744608446094461044611446124461344614446154461644617446184461944620446214462244623446244462544626446274462844629446304463144632446334463444635446364463744638446394464044641446424464344644446454464644647446484464944650446514465244653446544465544656446574465844659446604466144662446634466444665446664466744668446694467044671446724467344674446754467644677446784467944680446814468244683446844468544686446874468844689446904469144692446934469444695446964469744698446994470044701447024470344704447054470644707447084470944710447114471244713447144471544716447174471844719447204472144722447234472444725447264472744728447294473044731447324473344734447354473644737447384473944740447414474244743447444474544746447474474844749447504475144752447534475444755447564475744758447594476044761447624476344764447654476644767447684476944770447714477244773447744477544776447774477844779447804478144782447834478444785447864478744788447894479044791447924479344794447954479644797447984479944800448014480244803448044480544806448074480844809448104481144812448134481444815448164481744818448194482044821448224482344824448254482644827448284482944830448314483244833448344483544836448374483844839448404484144842448434484444845448464484744848448494485044851448524485344854448554485644857448584485944860448614486244863448644486544866448674486844869448704487144872448734487444875448764487744878448794488044881448824488344884448854488644887448884488944890448914489244893448944489544896448974489844899449004490144902449034490444905449064490744908449094491044911449124491344914449154491644917449184491944920449214492244923449244492544926449274492844929449304493144932449334493444935449364493744938449394494044941449424494344944449454494644947449484494944950449514495244953449544495544956449574495844959449604496144962449634496444965449664496744968449694497044971449724497344974449754497644977449784497944980449814498244983449844498544986449874498844989449904499144992449934499444995449964499744998449994500045001450024500345004450054500645007450084500945010450114501245013450144501545016450174501845019450204502145022450234502445025450264502745028450294503045031450324503345034450354503645037450384503945040450414504245043450444504545046450474504845049450504505145052450534505445055450564505745058450594506045061450624506345064450654506645067450684506945070450714507245073450744507545076450774507845079450804508145082450834508445085450864508745088450894509045091450924509345094450954509645097450984509945100451014510245103451044510545106451074510845109451104511145112451134511445115451164511745118451194512045121451224512345124451254512645127451284512945130451314513245133451344513545136451374513845139451404514145142451434514445145451464514745148451494515045151451524515345154451554515645157451584515945160451614516245163451644516545166451674516845169451704517145172451734517445175451764517745178451794518045181451824518345184451854518645187451884518945190451914519245193451944519545196451974519845199452004520145202452034520445205452064520745208452094521045211452124521345214452154521645217452184521945220452214522245223452244522545226452274522845229452304523145232452334523445235452364523745238452394524045241452424524345244452454524645247452484524945250452514525245253452544525545256452574525845259452604526145262452634526445265452664526745268452694527045271452724527345274452754527645277452784527945280452814528245283452844528545286452874528845289452904529145292452934529445295452964529745298452994530045301453024530345304453054530645307453084530945310453114531245313453144531545316453174531845319453204532145322453234532445325453264532745328453294533045331453324533345334453354533645337453384533945340453414534245343453444534545346453474534845349453504535145352453534535445355453564535745358453594536045361453624536345364453654536645367453684536945370453714537245373453744537545376453774537845379453804538145382453834538445385453864538745388453894539045391453924539345394453954539645397453984539945400454014540245403454044540545406454074540845409454104541145412454134541445415454164541745418454194542045421454224542345424454254542645427454284542945430454314543245433454344543545436454374543845439454404544145442454434544445445454464544745448454494545045451454524545345454454554545645457454584545945460454614546245463454644546545466454674546845469454704547145472454734547445475454764547745478454794548045481454824548345484454854548645487454884548945490454914549245493454944549545496454974549845499455004550145502455034550445505455064550745508455094551045511455124551345514455154551645517455184551945520455214552245523455244552545526455274552845529455304553145532455334553445535455364553745538455394554045541455424554345544455454554645547455484554945550455514555245553455544555545556455574555845559455604556145562455634556445565455664556745568455694557045571455724557345574455754557645577455784557945580455814558245583455844558545586455874558845589455904559145592455934559445595455964559745598455994560045601456024560345604456054560645607456084560945610456114561245613456144561545616456174561845619456204562145622456234562445625456264562745628456294563045631456324563345634456354563645637456384563945640456414564245643456444564545646456474564845649456504565145652456534565445655456564565745658456594566045661456624566345664456654566645667456684566945670456714567245673456744567545676456774567845679456804568145682456834568445685456864568745688456894569045691456924569345694456954569645697456984569945700457014570245703457044570545706457074570845709457104571145712457134571445715457164571745718457194572045721457224572345724457254572645727457284572945730457314573245733457344573545736457374573845739457404574145742457434574445745457464574745748457494575045751457524575345754457554575645757457584575945760457614576245763457644576545766457674576845769457704577145772457734577445775457764577745778457794578045781457824578345784457854578645787457884578945790457914579245793457944579545796457974579845799458004580145802458034580445805458064580745808458094581045811458124581345814458154581645817458184581945820458214582245823458244582545826458274582845829458304583145832458334583445835458364583745838458394584045841458424584345844458454584645847458484584945850458514585245853458544585545856458574585845859458604586145862458634586445865458664586745868458694587045871458724587345874458754587645877458784587945880458814588245883458844588545886458874588845889458904589145892458934589445895458964589745898458994590045901459024590345904459054590645907459084590945910459114591245913459144591545916459174591845919459204592145922459234592445925459264592745928459294593045931459324593345934459354593645937459384593945940459414594245943459444594545946459474594845949459504595145952459534595445955459564595745958459594596045961459624596345964459654596645967459684596945970459714597245973459744597545976459774597845979459804598145982459834598445985459864598745988459894599045991459924599345994459954599645997459984599946000460014600246003460044600546006460074600846009460104601146012460134601446015460164601746018460194602046021460224602346024460254602646027460284602946030460314603246033460344603546036460374603846039460404604146042460434604446045460464604746048460494605046051460524605346054460554605646057460584605946060460614606246063460644606546066460674606846069460704607146072460734607446075460764607746078460794608046081460824608346084460854608646087460884608946090460914609246093460944609546096460974609846099461004610146102461034610446105461064610746108461094611046111461124611346114461154611646117461184611946120461214612246123461244612546126461274612846129461304613146132461334613446135461364613746138461394614046141461424614346144461454614646147461484614946150461514615246153461544615546156461574615846159461604616146162461634616446165461664616746168461694617046171461724617346174461754617646177461784617946180461814618246183461844618546186461874618846189461904619146192461934619446195461964619746198461994620046201462024620346204462054620646207462084620946210462114621246213462144621546216462174621846219462204622146222462234622446225462264622746228462294623046231462324623346234462354623646237462384623946240462414624246243462444624546246462474624846249462504625146252462534625446255462564625746258462594626046261462624626346264462654626646267462684626946270462714627246273462744627546276462774627846279462804628146282462834628446285462864628746288462894629046291462924629346294462954629646297462984629946300463014630246303463044630546306463074630846309463104631146312463134631446315463164631746318463194632046321463224632346324463254632646327463284632946330463314633246333463344633546336463374633846339463404634146342463434634446345463464634746348463494635046351463524635346354463554635646357463584635946360463614636246363463644636546366463674636846369463704637146372463734637446375463764637746378463794638046381463824638346384463854638646387463884638946390463914639246393463944639546396463974639846399464004640146402464034640446405464064640746408464094641046411464124641346414464154641646417464184641946420464214642246423464244642546426464274642846429464304643146432464334643446435464364643746438464394644046441464424644346444464454644646447464484644946450464514645246453464544645546456464574645846459464604646146462464634646446465464664646746468464694647046471464724647346474464754647646477464784647946480464814648246483464844648546486464874648846489464904649146492464934649446495464964649746498464994650046501465024650346504465054650646507465084650946510465114651246513465144651546516465174651846519465204652146522465234652446525465264652746528465294653046531465324653346534465354653646537465384653946540465414654246543465444654546546465474654846549465504655146552465534655446555465564655746558465594656046561465624656346564465654656646567465684656946570465714657246573465744657546576465774657846579465804658146582465834658446585465864658746588465894659046591465924659346594465954659646597465984659946600466014660246603466044660546606466074660846609466104661146612466134661446615466164661746618466194662046621466224662346624466254662646627466284662946630466314663246633466344663546636466374663846639466404664146642466434664446645466464664746648466494665046651466524665346654466554665646657466584665946660466614666246663466644666546666466674666846669466704667146672466734667446675466764667746678466794668046681466824668346684466854668646687466884668946690466914669246693466944669546696466974669846699467004670146702467034670446705467064670746708467094671046711467124671346714467154671646717467184671946720467214672246723467244672546726467274672846729467304673146732467334673446735467364673746738467394674046741467424674346744467454674646747467484674946750467514675246753467544675546756467574675846759467604676146762467634676446765467664676746768467694677046771467724677346774467754677646777467784677946780467814678246783467844678546786467874678846789467904679146792467934679446795467964679746798467994680046801468024680346804468054680646807468084680946810468114681246813468144681546816468174681846819468204682146822468234682446825468264682746828468294683046831468324683346834468354683646837468384683946840468414684246843468444684546846468474684846849468504685146852468534685446855468564685746858468594686046861468624686346864468654686646867468684686946870468714687246873468744687546876468774687846879468804688146882468834688446885468864688746888468894689046891468924689346894468954689646897468984689946900469014690246903469044690546906469074690846909469104691146912469134691446915469164691746918469194692046921469224692346924469254692646927469284692946930469314693246933469344693546936469374693846939469404694146942469434694446945469464694746948469494695046951469524695346954469554695646957469584695946960469614696246963469644696546966469674696846969469704697146972469734697446975469764697746978469794698046981469824698346984469854698646987469884698946990469914699246993469944699546996469974699846999470004700147002470034700447005470064700747008470094701047011470124701347014470154701647017470184701947020470214702247023470244702547026470274702847029470304703147032470334703447035470364703747038470394704047041470424704347044470454704647047470484704947050470514705247053470544705547056470574705847059470604706147062470634706447065470664706747068470694707047071470724707347074470754707647077470784707947080470814708247083470844708547086470874708847089470904709147092470934709447095470964709747098470994710047101471024710347104471054710647107471084710947110471114711247113471144711547116471174711847119471204712147122471234712447125471264712747128471294713047131471324713347134471354713647137471384713947140471414714247143471444714547146471474714847149471504715147152471534715447155471564715747158471594716047161471624716347164471654716647167471684716947170471714717247173471744717547176471774717847179471804718147182471834718447185471864718747188471894719047191471924719347194471954719647197471984719947200472014720247203472044720547206472074720847209472104721147212472134721447215472164721747218472194722047221472224722347224472254722647227472284722947230472314723247233472344723547236472374723847239472404724147242472434724447245472464724747248472494725047251472524725347254472554725647257472584725947260472614726247263472644726547266472674726847269472704727147272472734727447275472764727747278472794728047281472824728347284472854728647287472884728947290472914729247293472944729547296472974729847299473004730147302473034730447305473064730747308473094731047311473124731347314473154731647317473184731947320473214732247323473244732547326473274732847329473304733147332473334733447335473364733747338473394734047341473424734347344473454734647347473484734947350473514735247353473544735547356473574735847359473604736147362473634736447365473664736747368473694737047371473724737347374473754737647377473784737947380473814738247383473844738547386473874738847389473904739147392473934739447395473964739747398473994740047401474024740347404474054740647407474084740947410474114741247413474144741547416474174741847419474204742147422474234742447425474264742747428474294743047431474324743347434474354743647437474384743947440474414744247443474444744547446474474744847449474504745147452474534745447455474564745747458474594746047461474624746347464474654746647467474684746947470474714747247473474744747547476474774747847479474804748147482474834748447485474864748747488474894749047491474924749347494474954749647497474984749947500475014750247503475044750547506475074750847509475104751147512475134751447515475164751747518475194752047521475224752347524475254752647527475284752947530475314753247533475344753547536475374753847539475404754147542475434754447545475464754747548475494755047551475524755347554475554755647557475584755947560475614756247563475644756547566475674756847569475704757147572475734757447575475764757747578475794758047581475824758347584475854758647587475884758947590475914759247593475944759547596475974759847599476004760147602476034760447605476064760747608476094761047611476124761347614476154761647617476184761947620476214762247623476244762547626476274762847629476304763147632476334763447635476364763747638476394764047641476424764347644476454764647647476484764947650476514765247653476544765547656476574765847659476604766147662476634766447665476664766747668476694767047671476724767347674476754767647677476784767947680476814768247683476844768547686476874768847689476904769147692476934769447695476964769747698476994770047701477024770347704477054770647707477084770947710477114771247713477144771547716477174771847719477204772147722477234772447725477264772747728477294773047731477324773347734477354773647737477384773947740477414774247743477444774547746477474774847749477504775147752477534775447755477564775747758477594776047761477624776347764477654776647767477684776947770477714777247773477744777547776477774777847779477804778147782477834778447785477864778747788477894779047791477924779347794477954779647797477984779947800478014780247803478044780547806478074780847809478104781147812478134781447815478164781747818478194782047821478224782347824478254782647827478284782947830478314783247833478344783547836478374783847839478404784147842478434784447845478464784747848478494785047851478524785347854478554785647857478584785947860478614786247863478644786547866478674786847869478704787147872478734787447875478764787747878478794788047881478824788347884478854788647887478884788947890478914789247893478944789547896478974789847899479004790147902479034790447905479064790747908479094791047911479124791347914479154791647917479184791947920479214792247923479244792547926479274792847929479304793147932479334793447935479364793747938479394794047941479424794347944479454794647947479484794947950479514795247953479544795547956479574795847959479604796147962479634796447965479664796747968479694797047971479724797347974479754797647977479784797947980479814798247983479844798547986479874798847989479904799147992479934799447995479964799747998479994800048001480024800348004480054800648007480084800948010480114801248013480144801548016480174801848019480204802148022480234802448025480264802748028480294803048031480324803348034480354803648037480384803948040480414804248043480444804548046480474804848049480504805148052480534805448055480564805748058480594806048061480624806348064480654806648067480684806948070480714807248073480744807548076480774807848079480804808148082480834808448085480864808748088480894809048091480924809348094480954809648097480984809948100481014810248103481044810548106481074810848109481104811148112481134811448115481164811748118481194812048121481224812348124481254812648127481284812948130481314813248133481344813548136481374813848139481404814148142481434814448145481464814748148481494815048151481524815348154481554815648157481584815948160481614816248163481644816548166481674816848169481704817148172481734817448175481764817748178481794818048181481824818348184481854818648187481884818948190481914819248193481944819548196481974819848199482004820148202482034820448205482064820748208482094821048211482124821348214482154821648217482184821948220482214822248223482244822548226482274822848229482304823148232482334823448235482364823748238482394824048241482424824348244482454824648247482484824948250482514825248253482544825548256482574825848259482604826148262482634826448265482664826748268482694827048271482724827348274482754827648277482784827948280482814828248283482844828548286482874828848289482904829148292482934829448295482964829748298482994830048301483024830348304483054830648307483084830948310483114831248313483144831548316483174831848319483204832148322483234832448325483264832748328483294833048331483324833348334483354833648337483384833948340483414834248343483444834548346483474834848349483504835148352483534835448355483564835748358483594836048361483624836348364483654836648367483684836948370483714837248373483744837548376483774837848379483804838148382483834838448385483864838748388483894839048391483924839348394483954839648397483984839948400484014840248403484044840548406484074840848409484104841148412484134841448415484164841748418484194842048421484224842348424484254842648427484284842948430484314843248433484344843548436484374843848439484404844148442484434844448445484464844748448484494845048451484524845348454484554845648457484584845948460484614846248463484644846548466484674846848469484704847148472484734847448475484764847748478484794848048481484824848348484484854848648487484884848948490484914849248493484944849548496484974849848499485004850148502485034850448505485064850748508485094851048511485124851348514485154851648517485184851948520485214852248523485244852548526485274852848529485304853148532485334853448535485364853748538485394854048541485424854348544485454854648547485484854948550485514855248553485544855548556485574855848559485604856148562485634856448565485664856748568485694857048571485724857348574485754857648577485784857948580485814858248583485844858548586485874858848589485904859148592485934859448595485964859748598485994860048601486024860348604486054860648607486084860948610486114861248613486144861548616486174861848619486204862148622486234862448625486264862748628486294863048631486324863348634486354863648637486384863948640486414864248643486444864548646486474864848649486504865148652486534865448655486564865748658486594866048661486624866348664486654866648667486684866948670486714867248673486744867548676486774867848679486804868148682486834868448685486864868748688486894869048691486924869348694486954869648697486984869948700487014870248703487044870548706487074870848709487104871148712487134871448715487164871748718487194872048721487224872348724487254872648727487284872948730487314873248733487344873548736487374873848739487404874148742487434874448745487464874748748487494875048751487524875348754487554875648757487584875948760487614876248763487644876548766487674876848769487704877148772487734877448775487764877748778487794878048781487824878348784487854878648787487884878948790487914879248793487944879548796487974879848799488004880148802488034880448805488064880748808488094881048811488124881348814488154881648817488184881948820488214882248823488244882548826488274882848829488304883148832488334883448835488364883748838488394884048841488424884348844488454884648847488484884948850488514885248853488544885548856488574885848859488604886148862488634886448865488664886748868488694887048871488724887348874488754887648877488784887948880488814888248883488844888548886488874888848889488904889148892488934889448895488964889748898488994890048901489024890348904489054890648907489084890948910489114891248913489144891548916489174891848919489204892148922489234892448925489264892748928489294893048931489324893348934489354893648937489384893948940489414894248943489444894548946489474894848949489504895148952489534895448955489564895748958489594896048961489624896348964489654896648967489684896948970489714897248973489744897548976489774897848979489804898148982489834898448985489864898748988489894899048991489924899348994489954899648997489984899949000490014900249003490044900549006490074900849009490104901149012490134901449015490164901749018490194902049021490224902349024490254902649027490284902949030490314903249033490344903549036490374903849039490404904149042490434904449045490464904749048490494905049051490524905349054490554905649057490584905949060490614906249063490644906549066490674906849069490704907149072490734907449075490764907749078490794908049081490824908349084490854908649087490884908949090490914909249093490944909549096490974909849099491004910149102491034910449105491064910749108491094911049111491124911349114491154911649117491184911949120491214912249123491244912549126491274912849129491304913149132491334913449135491364913749138491394914049141491424914349144491454914649147491484914949150491514915249153491544915549156491574915849159491604916149162491634916449165491664916749168491694917049171491724917349174491754917649177491784917949180491814918249183491844918549186491874918849189491904919149192491934919449195491964919749198491994920049201492024920349204492054920649207492084920949210492114921249213492144921549216492174921849219492204922149222492234922449225492264922749228492294923049231492324923349234492354923649237492384923949240492414924249243492444924549246492474924849249492504925149252492534925449255492564925749258492594926049261492624926349264492654926649267492684926949270492714927249273492744927549276492774927849279492804928149282492834928449285492864928749288492894929049291492924929349294492954929649297492984929949300493014930249303493044930549306493074930849309493104931149312493134931449315493164931749318493194932049321493224932349324493254932649327493284932949330493314933249333493344933549336493374933849339493404934149342493434934449345493464934749348493494935049351493524935349354493554935649357493584935949360493614936249363493644936549366493674936849369493704937149372493734937449375493764937749378493794938049381493824938349384493854938649387493884938949390493914939249393493944939549396493974939849399494004940149402494034940449405494064940749408494094941049411494124941349414494154941649417494184941949420494214942249423494244942549426494274942849429494304943149432494334943449435494364943749438494394944049441494424944349444494454944649447494484944949450494514945249453494544945549456494574945849459494604946149462494634946449465494664946749468494694947049471494724947349474494754947649477494784947949480494814948249483494844948549486494874948849489494904949149492494934949449495494964949749498494994950049501495024950349504495054950649507495084950949510495114951249513495144951549516495174951849519495204952149522495234952449525495264952749528495294953049531495324953349534495354953649537495384953949540495414954249543495444954549546495474954849549495504955149552495534955449555495564955749558495594956049561495624956349564495654956649567495684956949570495714957249573495744957549576495774957849579495804958149582495834958449585495864958749588495894959049591495924959349594495954959649597495984959949600496014960249603496044960549606496074960849609496104961149612496134961449615496164961749618496194962049621496224962349624496254962649627496284962949630496314963249633496344963549636496374963849639496404964149642496434964449645496464964749648496494965049651496524965349654496554965649657496584965949660496614966249663496644966549666496674966849669496704967149672496734967449675496764967749678496794968049681496824968349684496854968649687496884968949690496914969249693496944969549696496974969849699497004970149702497034970449705497064970749708497094971049711497124971349714497154971649717497184971949720497214972249723497244972549726497274972849729497304973149732497334973449735497364973749738497394974049741497424974349744497454974649747497484974949750497514975249753497544975549756497574975849759497604976149762497634976449765497664976749768497694977049771497724977349774497754977649777497784977949780497814978249783497844978549786497874978849789497904979149792497934979449795497964979749798497994980049801498024980349804498054980649807498084980949810498114981249813498144981549816498174981849819498204982149822498234982449825498264982749828498294983049831498324983349834498354983649837498384983949840498414984249843498444984549846498474984849849498504985149852498534985449855498564985749858498594986049861498624986349864498654986649867498684986949870498714987249873498744987549876498774987849879498804988149882498834988449885498864988749888498894989049891498924989349894498954989649897498984989949900499014990249903499044990549906499074990849909499104991149912499134991449915499164991749918499194992049921499224992349924499254992649927499284992949930499314993249933499344993549936499374993849939499404994149942499434994449945499464994749948499494995049951499524995349954499554995649957499584995949960499614996249963499644996549966499674996849969499704997149972499734997449975499764997749978499794998049981499824998349984499854998649987499884998949990499914999249993499944999549996499974999849999500005000150002500035000450005500065000750008500095001050011500125001350014500155001650017500185001950020500215002250023500245002550026500275002850029500305003150032500335003450035500365003750038500395004050041500425004350044500455004650047500485004950050500515005250053500545005550056500575005850059500605006150062500635006450065500665006750068500695007050071500725007350074500755007650077500785007950080500815008250083500845008550086500875008850089500905009150092500935009450095500965009750098500995010050101501025010350104501055010650107501085010950110501115011250113501145011550116501175011850119501205012150122501235012450125501265012750128501295013050131501325013350134501355013650137501385013950140501415014250143501445014550146501475014850149501505015150152501535015450155501565015750158501595016050161501625016350164501655016650167501685016950170501715017250173501745017550176501775017850179501805018150182501835018450185501865018750188501895019050191501925019350194501955019650197501985019950200502015020250203502045020550206502075020850209502105021150212502135021450215502165021750218502195022050221502225022350224502255022650227502285022950230502315023250233502345023550236502375023850239502405024150242502435024450245502465024750248502495025050251502525025350254502555025650257502585025950260502615026250263502645026550266502675026850269502705027150272502735027450275502765027750278502795028050281502825028350284502855028650287502885028950290502915029250293502945029550296502975029850299503005030150302503035030450305503065030750308503095031050311503125031350314503155031650317503185031950320503215032250323503245032550326503275032850329503305033150332503335033450335503365033750338503395034050341503425034350344503455034650347503485034950350503515035250353503545035550356503575035850359503605036150362503635036450365503665036750368503695037050371503725037350374503755037650377503785037950380503815038250383503845038550386503875038850389503905039150392503935039450395503965039750398503995040050401504025040350404504055040650407504085040950410504115041250413504145041550416504175041850419504205042150422504235042450425504265042750428504295043050431504325043350434504355043650437504385043950440504415044250443504445044550446504475044850449504505045150452504535045450455504565045750458504595046050461504625046350464504655046650467504685046950470504715047250473504745047550476504775047850479504805048150482504835048450485504865048750488504895049050491504925049350494504955049650497504985049950500505015050250503505045050550506505075050850509505105051150512505135051450515505165051750518505195052050521505225052350524505255052650527505285052950530505315053250533505345053550536505375053850539505405054150542505435054450545505465054750548505495055050551505525055350554505555055650557505585055950560505615056250563505645056550566505675056850569505705057150572505735057450575505765057750578505795058050581505825058350584505855058650587505885058950590505915059250593505945059550596505975059850599506005060150602506035060450605506065060750608506095061050611506125061350614506155061650617506185061950620506215062250623506245062550626506275062850629506305063150632506335063450635506365063750638506395064050641506425064350644506455064650647506485064950650506515065250653506545065550656506575065850659506605066150662506635066450665506665066750668506695067050671506725067350674506755067650677506785067950680506815068250683506845068550686506875068850689506905069150692506935069450695506965069750698506995070050701507025070350704507055070650707507085070950710507115071250713507145071550716507175071850719507205072150722507235072450725507265072750728507295073050731507325073350734507355073650737507385073950740507415074250743507445074550746507475074850749507505075150752507535075450755507565075750758507595076050761507625076350764507655076650767507685076950770507715077250773507745077550776507775077850779507805078150782507835078450785507865078750788507895079050791507925079350794507955079650797507985079950800508015080250803508045080550806508075080850809508105081150812508135081450815508165081750818508195082050821508225082350824508255082650827508285082950830508315083250833508345083550836508375083850839508405084150842508435084450845508465084750848508495085050851508525085350854508555085650857508585085950860508615086250863508645086550866508675086850869508705087150872508735087450875508765087750878508795088050881508825088350884508855088650887508885088950890508915089250893508945089550896508975089850899509005090150902509035090450905509065090750908509095091050911509125091350914509155091650917509185091950920509215092250923509245092550926509275092850929509305093150932509335093450935509365093750938509395094050941509425094350944509455094650947509485094950950509515095250953509545095550956509575095850959509605096150962509635096450965509665096750968509695097050971509725097350974509755097650977509785097950980509815098250983509845098550986509875098850989509905099150992509935099450995509965099750998509995100051001510025100351004510055100651007510085100951010510115101251013510145101551016510175101851019510205102151022510235102451025510265102751028510295103051031510325103351034510355103651037510385103951040510415104251043510445104551046510475104851049510505105151052510535105451055510565105751058510595106051061510625106351064510655106651067510685106951070510715107251073510745107551076510775107851079510805108151082510835108451085510865108751088510895109051091510925109351094510955109651097510985109951100511015110251103511045110551106511075110851109511105111151112511135111451115511165111751118511195112051121511225112351124511255112651127511285112951130511315113251133511345113551136511375113851139511405114151142511435114451145511465114751148511495115051151511525115351154511555115651157511585115951160511615116251163511645116551166511675116851169511705117151172511735117451175511765117751178511795118051181511825118351184511855118651187511885118951190511915119251193511945119551196511975119851199512005120151202512035120451205512065120751208512095121051211512125121351214512155121651217512185121951220512215122251223512245122551226512275122851229512305123151232512335123451235512365123751238512395124051241512425124351244512455124651247512485124951250512515125251253512545125551256512575125851259512605126151262512635126451265512665126751268512695127051271512725127351274512755127651277512785127951280512815128251283512845128551286512875128851289512905129151292512935129451295512965129751298512995130051301513025130351304513055130651307513085130951310513115131251313513145131551316513175131851319513205132151322513235132451325513265132751328513295133051331513325133351334513355133651337513385133951340513415134251343513445134551346513475134851349513505135151352513535135451355513565135751358513595136051361513625136351364513655136651367513685136951370513715137251373513745137551376513775137851379513805138151382513835138451385513865138751388513895139051391513925139351394513955139651397513985139951400514015140251403514045140551406514075140851409514105141151412514135141451415514165141751418514195142051421514225142351424514255142651427514285142951430514315143251433514345143551436514375143851439514405144151442514435144451445514465144751448514495145051451514525145351454514555145651457514585145951460514615146251463514645146551466514675146851469514705147151472514735147451475514765147751478514795148051481514825148351484514855148651487514885148951490514915149251493514945149551496514975149851499515005150151502515035150451505515065150751508515095151051511515125151351514515155151651517515185151951520515215152251523515245152551526515275152851529515305153151532515335153451535515365153751538515395154051541515425154351544515455154651547515485154951550515515155251553515545155551556515575155851559515605156151562515635156451565515665156751568515695157051571515725157351574515755157651577515785157951580515815158251583515845158551586515875158851589515905159151592515935159451595515965159751598515995160051601516025160351604516055160651607516085160951610516115161251613516145161551616516175161851619516205162151622516235162451625516265162751628516295163051631516325163351634516355163651637516385163951640516415164251643516445164551646516475164851649516505165151652516535165451655516565165751658516595166051661516625166351664516655166651667516685166951670516715167251673516745167551676516775167851679516805168151682516835168451685516865168751688516895169051691516925169351694516955169651697516985169951700517015170251703517045170551706517075170851709517105171151712517135171451715517165171751718517195172051721517225172351724517255172651727517285172951730517315173251733517345173551736517375173851739517405174151742517435174451745517465174751748517495175051751517525175351754517555175651757517585175951760517615176251763517645176551766517675176851769517705177151772517735177451775517765177751778517795178051781517825178351784517855178651787517885178951790517915179251793517945179551796517975179851799518005180151802518035180451805518065180751808518095181051811518125181351814518155181651817518185181951820518215182251823518245182551826518275182851829518305183151832518335183451835518365183751838518395184051841518425184351844518455184651847518485184951850518515185251853518545185551856518575185851859518605186151862518635186451865518665186751868518695187051871518725187351874518755187651877518785187951880518815188251883518845188551886518875188851889518905189151892518935189451895518965189751898518995190051901519025190351904519055190651907519085190951910519115191251913519145191551916519175191851919519205192151922519235192451925519265192751928519295193051931519325193351934519355193651937519385193951940519415194251943519445194551946519475194851949519505195151952519535195451955519565195751958519595196051961519625196351964519655196651967519685196951970519715197251973519745197551976519775197851979519805198151982519835198451985519865198751988519895199051991519925199351994519955199651997519985199952000520015200252003520045200552006520075200852009520105201152012520135201452015520165201752018520195202052021520225202352024520255202652027520285202952030520315203252033520345203552036520375203852039520405204152042520435204452045520465204752048520495205052051520525205352054520555205652057520585205952060520615206252063520645206552066520675206852069520705207152072520735207452075520765207752078520795208052081520825208352084520855208652087520885208952090520915209252093520945209552096520975209852099521005210152102521035210452105521065210752108521095211052111521125211352114521155211652117521185211952120521215212252123521245212552126521275212852129521305213152132521335213452135521365213752138521395214052141521425214352144521455214652147521485214952150521515215252153521545215552156521575215852159521605216152162521635216452165521665216752168521695217052171521725217352174521755217652177521785217952180521815218252183521845218552186521875218852189521905219152192521935219452195521965219752198521995220052201522025220352204522055220652207522085220952210522115221252213522145221552216522175221852219522205222152222522235222452225522265222752228522295223052231522325223352234522355223652237522385223952240522415224252243522445224552246522475224852249522505225152252522535225452255522565225752258522595226052261522625226352264522655226652267522685226952270522715227252273522745227552276522775227852279522805228152282522835228452285522865228752288522895229052291522925229352294522955229652297522985229952300523015230252303523045230552306523075230852309523105231152312523135231452315523165231752318523195232052321523225232352324523255232652327523285232952330523315233252333523345233552336523375233852339523405234152342523435234452345523465234752348523495235052351523525235352354523555235652357523585235952360523615236252363523645236552366523675236852369523705237152372523735237452375523765237752378523795238052381523825238352384523855238652387523885238952390523915239252393523945239552396523975239852399524005240152402524035240452405524065240752408524095241052411524125241352414524155241652417524185241952420524215242252423524245242552426524275242852429524305243152432524335243452435524365243752438524395244052441524425244352444524455244652447524485244952450524515245252453524545245552456524575245852459524605246152462524635246452465524665246752468524695247052471524725247352474524755247652477524785247952480524815248252483524845248552486524875248852489524905249152492524935249452495524965249752498524995250052501525025250352504525055250652507525085250952510525115251252513525145251552516525175251852519525205252152522525235252452525525265252752528525295253052531525325253352534525355253652537525385253952540525415254252543525445254552546525475254852549525505255152552525535255452555525565255752558525595256052561525625256352564525655256652567525685256952570525715257252573525745257552576525775257852579525805258152582525835258452585525865258752588525895259052591525925259352594525955259652597525985259952600526015260252603526045260552606526075260852609526105261152612526135261452615526165261752618526195262052621526225262352624526255262652627526285262952630526315263252633526345263552636526375263852639526405264152642526435264452645526465264752648526495265052651526525265352654526555265652657526585265952660526615266252663526645266552666526675266852669526705267152672526735267452675526765267752678526795268052681526825268352684526855268652687526885268952690526915269252693526945269552696526975269852699527005270152702527035270452705527065270752708527095271052711527125271352714527155271652717527185271952720527215272252723527245272552726527275272852729527305273152732527335273452735527365273752738527395274052741527425274352744527455274652747527485274952750527515275252753527545275552756527575275852759527605276152762527635276452765527665276752768527695277052771527725277352774527755277652777527785277952780527815278252783527845278552786527875278852789527905279152792527935279452795527965279752798527995280052801528025280352804528055280652807528085280952810528115281252813528145281552816528175281852819528205282152822528235282452825528265282752828528295283052831528325283352834528355283652837528385283952840528415284252843528445284552846528475284852849528505285152852528535285452855528565285752858528595286052861528625286352864528655286652867528685286952870528715287252873528745287552876528775287852879528805288152882528835288452885528865288752888528895289052891528925289352894528955289652897528985289952900529015290252903529045290552906529075290852909529105291152912529135291452915529165291752918529195292052921529225292352924529255292652927529285292952930529315293252933529345293552936529375293852939529405294152942529435294452945529465294752948529495295052951529525295352954529555295652957529585295952960529615296252963529645296552966529675296852969529705297152972529735297452975529765297752978529795298052981529825298352984529855298652987529885298952990529915299252993529945299552996529975299852999530005300153002530035300453005530065300753008530095301053011530125301353014530155301653017530185301953020530215302253023530245302553026530275302853029530305303153032530335303453035530365303753038530395304053041530425304353044530455304653047530485304953050530515305253053530545305553056530575305853059530605306153062530635306453065530665306753068530695307053071530725307353074530755307653077530785307953080530815308253083530845308553086530875308853089530905309153092530935309453095530965309753098530995310053101531025310353104531055310653107531085310953110531115311253113531145311553116531175311853119531205312153122531235312453125531265312753128531295313053131531325313353134531355313653137531385313953140531415314253143531445314553146531475314853149531505315153152531535315453155531565315753158531595316053161531625316353164531655316653167531685316953170531715317253173531745317553176531775317853179531805318153182531835318453185531865318753188531895319053191531925319353194531955319653197531985319953200532015320253203532045320553206532075320853209532105321153212532135321453215532165321753218532195322053221532225322353224532255322653227532285322953230532315323253233532345323553236532375323853239532405324153242532435324453245532465324753248532495325053251532525325353254532555325653257532585325953260532615326253263532645326553266532675326853269532705327153272532735327453275532765327753278532795328053281532825328353284532855328653287532885328953290532915329253293532945329553296532975329853299533005330153302533035330453305533065330753308533095331053311533125331353314533155331653317533185331953320533215332253323533245332553326533275332853329533305333153332533335333453335533365333753338533395334053341533425334353344533455334653347533485334953350533515335253353533545335553356533575335853359533605336153362533635336453365533665336753368533695337053371533725337353374533755337653377533785337953380533815338253383533845338553386533875338853389533905339153392533935339453395533965339753398533995340053401534025340353404534055340653407534085340953410534115341253413534145341553416534175341853419534205342153422534235342453425534265342753428534295343053431534325343353434534355343653437534385343953440534415344253443534445344553446534475344853449534505345153452534535345453455534565345753458534595346053461534625346353464534655346653467534685346953470534715347253473534745347553476534775347853479534805348153482534835348453485534865348753488534895349053491534925349353494534955349653497534985349953500535015350253503535045350553506535075350853509535105351153512535135351453515535165351753518535195352053521535225352353524535255352653527535285352953530535315353253533535345353553536535375353853539535405354153542535435354453545535465354753548535495355053551535525355353554535555355653557535585355953560535615356253563535645356553566535675356853569535705357153572535735357453575535765357753578535795358053581535825358353584535855358653587535885358953590535915359253593535945359553596535975359853599536005360153602536035360453605536065360753608536095361053611536125361353614536155361653617536185361953620536215362253623536245362553626536275362853629536305363153632536335363453635536365363753638536395364053641536425364353644536455364653647536485364953650536515365253653536545365553656536575365853659536605366153662536635366453665536665366753668536695367053671536725367353674536755367653677536785367953680536815368253683536845368553686536875368853689536905369153692536935369453695536965369753698536995370053701537025370353704537055370653707537085370953710537115371253713537145371553716537175371853719537205372153722537235372453725537265372753728537295373053731537325373353734537355373653737537385373953740537415374253743537445374553746537475374853749537505375153752537535375453755537565375753758537595376053761537625376353764537655376653767537685376953770537715377253773537745377553776537775377853779537805378153782537835378453785537865378753788537895379053791537925379353794537955379653797537985379953800538015380253803538045380553806538075380853809538105381153812538135381453815538165381753818538195382053821538225382353824538255382653827538285382953830538315383253833538345383553836538375383853839538405384153842538435384453845538465384753848538495385053851538525385353854538555385653857538585385953860538615386253863538645386553866538675386853869538705387153872538735387453875538765387753878538795388053881538825388353884538855388653887538885388953890538915389253893538945389553896538975389853899539005390153902539035390453905539065390753908539095391053911539125391353914539155391653917539185391953920539215392253923539245392553926539275392853929539305393153932539335393453935539365393753938539395394053941539425394353944539455394653947539485394953950539515395253953539545395553956539575395853959539605396153962539635396453965539665396753968539695397053971539725397353974539755397653977539785397953980539815398253983539845398553986539875398853989539905399153992539935399453995539965399753998539995400054001540025400354004540055400654007540085400954010540115401254013540145401554016540175401854019540205402154022540235402454025540265402754028540295403054031540325403354034540355403654037540385403954040540415404254043540445404554046540475404854049540505405154052540535405454055540565405754058540595406054061540625406354064540655406654067540685406954070540715407254073540745407554076540775407854079540805408154082540835408454085540865408754088540895409054091540925409354094540955409654097540985409954100541015410254103541045410554106541075410854109541105411154112541135411454115541165411754118541195412054121541225412354124541255412654127541285412954130541315413254133541345413554136541375413854139541405414154142541435414454145541465414754148541495415054151541525415354154541555415654157541585415954160541615416254163541645416554166541675416854169541705417154172541735417454175541765417754178541795418054181541825418354184541855418654187541885418954190541915419254193541945419554196541975419854199542005420154202542035420454205542065420754208542095421054211542125421354214542155421654217542185421954220542215422254223542245422554226542275422854229542305423154232542335423454235542365423754238542395424054241542425424354244542455424654247542485424954250542515425254253542545425554256542575425854259542605426154262542635426454265542665426754268542695427054271542725427354274542755427654277542785427954280542815428254283542845428554286542875428854289542905429154292542935429454295542965429754298542995430054301543025430354304543055430654307543085430954310543115431254313543145431554316543175431854319543205432154322543235432454325543265432754328543295433054331543325433354334543355433654337543385433954340543415434254343543445434554346543475434854349543505435154352543535435454355543565435754358543595436054361543625436354364543655436654367543685436954370543715437254373543745437554376543775437854379543805438154382543835438454385543865438754388543895439054391543925439354394543955439654397543985439954400544015440254403544045440554406544075440854409544105441154412544135441454415544165441754418544195442054421544225442354424544255442654427544285442954430544315443254433544345443554436544375443854439544405444154442544435444454445544465444754448544495445054451544525445354454544555445654457544585445954460544615446254463544645446554466544675446854469544705447154472544735447454475544765447754478544795448054481544825448354484544855448654487544885448954490544915449254493544945449554496544975449854499545005450154502545035450454505545065450754508545095451054511545125451354514545155451654517545185451954520545215452254523545245452554526545275452854529545305453154532545335453454535545365453754538545395454054541545425454354544545455454654547545485454954550545515455254553545545455554556545575455854559545605456154562545635456454565545665456754568545695457054571545725457354574545755457654577545785457954580545815458254583545845458554586545875458854589545905459154592545935459454595545965459754598545995460054601546025460354604546055460654607546085460954610546115461254613546145461554616546175461854619546205462154622546235462454625546265462754628546295463054631546325463354634546355463654637546385463954640546415464254643546445464554646546475464854649546505465154652546535465454655546565465754658546595466054661546625466354664546655466654667546685466954670546715467254673546745467554676546775467854679546805468154682546835468454685546865468754688546895469054691546925469354694546955469654697546985469954700547015470254703547045470554706547075470854709547105471154712547135471454715547165471754718547195472054721547225472354724547255472654727547285472954730547315473254733547345473554736547375473854739547405474154742547435474454745547465474754748547495475054751547525475354754547555475654757547585475954760547615476254763547645476554766547675476854769547705477154772547735477454775547765477754778547795478054781547825478354784547855478654787547885478954790547915479254793547945479554796547975479854799548005480154802548035480454805548065480754808548095481054811548125481354814548155481654817548185481954820548215482254823548245482554826548275482854829548305483154832548335483454835548365483754838548395484054841548425484354844548455484654847548485484954850548515485254853548545485554856548575485854859548605486154862548635486454865548665486754868548695487054871548725487354874548755487654877548785487954880548815488254883548845488554886548875488854889548905489154892548935489454895548965489754898548995490054901549025490354904549055490654907549085490954910549115491254913549145491554916549175491854919549205492154922549235492454925549265492754928549295493054931549325493354934549355493654937549385493954940549415494254943549445494554946549475494854949549505495154952549535495454955549565495754958549595496054961549625496354964549655496654967549685496954970549715497254973549745497554976549775497854979549805498154982549835498454985549865498754988549895499054991549925499354994549955499654997549985499955000550015500255003550045500555006550075500855009550105501155012550135501455015550165501755018550195502055021550225502355024550255502655027550285502955030550315503255033550345503555036550375503855039550405504155042550435504455045550465504755048550495505055051550525505355054550555505655057550585505955060550615506255063550645506555066550675506855069550705507155072550735507455075550765507755078550795508055081550825508355084550855508655087550885508955090550915509255093550945509555096550975509855099551005510155102551035510455105551065510755108551095511055111551125511355114551155511655117551185511955120551215512255123551245512555126551275512855129551305513155132551335513455135551365513755138551395514055141551425514355144551455514655147551485514955150551515515255153551545515555156551575515855159551605516155162551635516455165551665516755168551695517055171551725517355174551755517655177551785517955180551815518255183551845518555186551875518855189551905519155192551935519455195551965519755198551995520055201552025520355204552055520655207552085520955210552115521255213552145521555216552175521855219552205522155222552235522455225552265522755228552295523055231552325523355234552355523655237552385523955240552415524255243552445524555246552475524855249552505525155252552535525455255552565525755258552595526055261552625526355264552655526655267552685526955270552715527255273552745527555276552775527855279552805528155282552835528455285552865528755288552895529055291552925529355294552955529655297552985529955300553015530255303553045530555306553075530855309553105531155312553135531455315553165531755318553195532055321553225532355324553255532655327553285532955330553315533255333553345533555336553375533855339553405534155342553435534455345553465534755348553495535055351553525535355354553555535655357553585535955360553615536255363553645536555366553675536855369553705537155372553735537455375553765537755378553795538055381553825538355384553855538655387553885538955390553915539255393553945539555396553975539855399554005540155402554035540455405554065540755408554095541055411554125541355414554155541655417554185541955420554215542255423554245542555426554275542855429554305543155432554335543455435554365543755438554395544055441554425544355444554455544655447554485544955450554515545255453554545545555456554575545855459554605546155462554635546455465554665546755468554695547055471554725547355474554755547655477554785547955480554815548255483554845548555486554875548855489554905549155492554935549455495554965549755498554995550055501555025550355504555055550655507555085550955510555115551255513555145551555516555175551855519555205552155522555235552455525555265552755528555295553055531555325553355534555355553655537555385553955540555415554255543555445554555546555475554855549555505555155552555535555455555555565555755558555595556055561555625556355564555655556655567555685556955570555715557255573555745557555576555775557855579555805558155582555835558455585555865558755588555895559055591555925559355594555955559655597555985559955600556015560255603556045560555606556075560855609556105561155612556135561455615556165561755618556195562055621556225562355624556255562655627556285562955630556315563255633556345563555636556375563855639556405564155642556435564455645556465564755648556495565055651556525565355654556555565655657556585565955660556615566255663556645566555666556675566855669556705567155672556735567455675556765567755678556795568055681556825568355684556855568655687556885568955690556915569255693556945569555696556975569855699557005570155702557035570455705557065570755708557095571055711557125571355714557155571655717557185571955720557215572255723557245572555726557275572855729557305573155732557335573455735557365573755738557395574055741557425574355744557455574655747557485574955750557515575255753557545575555756557575575855759557605576155762557635576455765557665576755768557695577055771557725577355774557755577655777557785577955780557815578255783557845578555786557875578855789557905579155792557935579455795557965579755798557995580055801558025580355804558055580655807558085580955810558115581255813558145581555816558175581855819558205582155822558235582455825558265582755828558295583055831558325583355834558355583655837558385583955840558415584255843558445584555846558475584855849558505585155852558535585455855558565585755858558595586055861558625586355864558655586655867558685586955870558715587255873558745587555876558775587855879558805588155882558835588455885558865588755888558895589055891558925589355894558955589655897558985589955900559015590255903559045590555906559075590855909559105591155912559135591455915559165591755918559195592055921559225592355924559255592655927559285592955930559315593255933559345593555936559375593855939559405594155942559435594455945559465594755948559495595055951559525595355954559555595655957559585595955960559615596255963559645596555966559675596855969559705597155972559735597455975559765597755978559795598055981559825598355984559855598655987559885598955990559915599255993559945599555996559975599855999560005600156002560035600456005560065600756008560095601056011560125601356014560155601656017560185601956020560215602256023560245602556026560275602856029560305603156032560335603456035560365603756038560395604056041560425604356044560455604656047560485604956050560515605256053560545605556056560575605856059560605606156062560635606456065560665606756068560695607056071560725607356074560755607656077560785607956080560815608256083560845608556086560875608856089560905609156092560935609456095560965609756098560995610056101561025610356104561055610656107561085610956110561115611256113561145611556116561175611856119561205612156122561235612456125561265612756128561295613056131561325613356134561355613656137561385613956140561415614256143561445614556146561475614856149561505615156152561535615456155561565615756158561595616056161561625616356164561655616656167561685616956170561715617256173561745617556176561775617856179561805618156182561835618456185561865618756188561895619056191561925619356194561955619656197561985619956200562015620256203562045620556206562075620856209562105621156212562135621456215562165621756218562195622056221562225622356224562255622656227562285622956230562315623256233562345623556236562375623856239562405624156242562435624456245562465624756248562495625056251562525625356254562555625656257562585625956260562615626256263562645626556266562675626856269562705627156272562735627456275562765627756278562795628056281562825628356284562855628656287562885628956290562915629256293562945629556296562975629856299563005630156302563035630456305563065630756308563095631056311563125631356314563155631656317563185631956320563215632256323563245632556326563275632856329563305633156332563335633456335563365633756338563395634056341563425634356344563455634656347563485634956350563515635256353563545635556356563575635856359563605636156362563635636456365563665636756368563695637056371563725637356374563755637656377563785637956380563815638256383563845638556386563875638856389563905639156392563935639456395563965639756398563995640056401564025640356404564055640656407564085640956410564115641256413564145641556416564175641856419564205642156422564235642456425564265642756428564295643056431564325643356434564355643656437564385643956440564415644256443564445644556446564475644856449564505645156452564535645456455564565645756458564595646056461564625646356464564655646656467564685646956470564715647256473564745647556476564775647856479564805648156482564835648456485564865648756488564895649056491564925649356494564955649656497564985649956500565015650256503565045650556506565075650856509565105651156512565135651456515565165651756518565195652056521565225652356524565255652656527565285652956530565315653256533565345653556536565375653856539565405654156542565435654456545565465654756548565495655056551565525655356554565555655656557565585655956560565615656256563565645656556566565675656856569565705657156572565735657456575565765657756578565795658056581565825658356584565855658656587565885658956590565915659256593565945659556596565975659856599566005660156602566035660456605566065660756608566095661056611566125661356614566155661656617566185661956620566215662256623566245662556626566275662856629566305663156632566335663456635566365663756638566395664056641566425664356644566455664656647566485664956650566515665256653566545665556656566575665856659566605666156662566635666456665566665666756668566695667056671566725667356674566755667656677566785667956680566815668256683566845668556686566875668856689566905669156692566935669456695566965669756698566995670056701567025670356704567055670656707567085670956710567115671256713567145671556716567175671856719567205672156722567235672456725567265672756728567295673056731567325673356734567355673656737567385673956740567415674256743567445674556746567475674856749567505675156752567535675456755567565675756758567595676056761567625676356764567655676656767567685676956770567715677256773567745677556776567775677856779567805678156782567835678456785567865678756788567895679056791567925679356794567955679656797567985679956800568015680256803568045680556806568075680856809568105681156812568135681456815568165681756818568195682056821568225682356824568255682656827568285682956830568315683256833568345683556836568375683856839568405684156842568435684456845568465684756848568495685056851568525685356854568555685656857568585685956860568615686256863568645686556866568675686856869568705687156872568735687456875568765687756878568795688056881568825688356884568855688656887568885688956890568915689256893568945689556896568975689856899569005690156902569035690456905569065690756908569095691056911569125691356914569155691656917569185691956920569215692256923569245692556926569275692856929569305693156932569335693456935569365693756938569395694056941569425694356944569455694656947569485694956950569515695256953569545695556956569575695856959569605696156962569635696456965569665696756968569695697056971569725697356974569755697656977569785697956980569815698256983569845698556986569875698856989569905699156992569935699456995569965699756998569995700057001570025700357004570055700657007570085700957010570115701257013570145701557016570175701857019570205702157022570235702457025570265702757028570295703057031570325703357034570355703657037570385703957040570415704257043570445704557046570475704857049570505705157052570535705457055570565705757058570595706057061570625706357064570655706657067570685706957070570715707257073570745707557076570775707857079570805708157082570835708457085570865708757088570895709057091570925709357094570955709657097570985709957100571015710257103571045710557106571075710857109571105711157112571135711457115571165711757118571195712057121571225712357124571255712657127571285712957130571315713257133571345713557136571375713857139571405714157142571435714457145571465714757148571495715057151571525715357154571555715657157571585715957160571615716257163571645716557166571675716857169571705717157172571735717457175571765717757178571795718057181571825718357184571855718657187571885718957190571915719257193571945719557196571975719857199572005720157202572035720457205572065720757208572095721057211572125721357214572155721657217572185721957220572215722257223572245722557226572275722857229572305723157232572335723457235572365723757238572395724057241572425724357244572455724657247572485724957250572515725257253572545725557256572575725857259572605726157262572635726457265572665726757268572695727057271572725727357274572755727657277572785727957280572815728257283572845728557286572875728857289572905729157292572935729457295572965729757298572995730057301573025730357304573055730657307573085730957310573115731257313573145731557316573175731857319573205732157322573235732457325573265732757328573295733057331573325733357334573355733657337573385733957340573415734257343573445734557346573475734857349573505735157352573535735457355573565735757358573595736057361573625736357364573655736657367573685736957370573715737257373573745737557376573775737857379573805738157382573835738457385573865738757388573895739057391573925739357394573955739657397573985739957400574015740257403574045740557406574075740857409574105741157412574135741457415574165741757418574195742057421574225742357424574255742657427574285742957430574315743257433574345743557436574375743857439574405744157442574435744457445574465744757448574495745057451574525745357454574555745657457574585745957460574615746257463574645746557466574675746857469574705747157472574735747457475574765747757478574795748057481574825748357484574855748657487574885748957490574915749257493574945749557496574975749857499575005750157502575035750457505575065750757508575095751057511575125751357514575155751657517575185751957520575215752257523575245752557526575275752857529575305753157532575335753457535575365753757538575395754057541575425754357544575455754657547575485754957550575515755257553575545755557556575575755857559575605756157562575635756457565575665756757568575695757057571575725757357574575755757657577575785757957580575815758257583575845758557586575875758857589575905759157592575935759457595575965759757598575995760057601576025760357604576055760657607576085760957610576115761257613576145761557616576175761857619576205762157622576235762457625576265762757628576295763057631576325763357634576355763657637576385763957640576415764257643576445764557646576475764857649576505765157652576535765457655576565765757658576595766057661576625766357664576655766657667576685766957670576715767257673576745767557676576775767857679576805768157682576835768457685576865768757688576895769057691576925769357694576955769657697576985769957700577015770257703577045770557706577075770857709577105771157712577135771457715577165771757718577195772057721577225772357724577255772657727577285772957730577315773257733577345773557736577375773857739577405774157742577435774457745577465774757748577495775057751577525775357754577555775657757577585775957760577615776257763577645776557766577675776857769577705777157772577735777457775577765777757778577795778057781577825778357784577855778657787577885778957790577915779257793577945779557796577975779857799578005780157802578035780457805578065780757808578095781057811578125781357814578155781657817578185781957820578215782257823578245782557826578275782857829578305783157832578335783457835578365783757838578395784057841578425784357844578455784657847578485784957850578515785257853578545785557856578575785857859578605786157862578635786457865578665786757868578695787057871578725787357874578755787657877578785787957880578815788257883578845788557886578875788857889578905789157892578935789457895578965789757898578995790057901579025790357904579055790657907579085790957910579115791257913579145791557916579175791857919579205792157922579235792457925579265792757928579295793057931579325793357934579355793657937579385793957940579415794257943579445794557946579475794857949579505795157952579535795457955579565795757958579595796057961579625796357964579655796657967579685796957970579715797257973579745797557976579775797857979579805798157982579835798457985579865798757988579895799057991579925799357994579955799657997579985799958000580015800258003580045800558006580075800858009580105801158012580135801458015580165801758018580195802058021580225802358024580255802658027580285802958030580315803258033580345803558036580375803858039580405804158042580435804458045580465804758048580495805058051580525805358054580555805658057580585805958060580615806258063580645806558066580675806858069580705807158072580735807458075580765807758078580795808058081580825808358084580855808658087580885808958090580915809258093580945809558096580975809858099581005810158102581035810458105581065810758108581095811058111581125811358114581155811658117581185811958120581215812258123581245812558126581275812858129581305813158132581335813458135581365813758138581395814058141581425814358144581455814658147581485814958150581515815258153581545815558156581575815858159581605816158162581635816458165581665816758168581695817058171581725817358174581755817658177581785817958180581815818258183581845818558186581875818858189581905819158192581935819458195581965819758198581995820058201582025820358204582055820658207582085820958210582115821258213582145821558216582175821858219582205822158222582235822458225582265822758228582295823058231582325823358234582355823658237582385823958240582415824258243582445824558246582475824858249582505825158252582535825458255582565825758258582595826058261582625826358264582655826658267582685826958270582715827258273582745827558276582775827858279582805828158282582835828458285582865828758288582895829058291582925829358294582955829658297582985829958300583015830258303583045830558306583075830858309583105831158312583135831458315583165831758318583195832058321583225832358324583255832658327583285832958330583315833258333583345833558336583375833858339583405834158342583435834458345583465834758348583495835058351583525835358354583555835658357583585835958360583615836258363583645836558366583675836858369583705837158372583735837458375583765837758378583795838058381583825838358384583855838658387583885838958390583915839258393583945839558396583975839858399584005840158402584035840458405584065840758408584095841058411584125841358414584155841658417584185841958420584215842258423584245842558426584275842858429584305843158432584335843458435584365843758438584395844058441584425844358444584455844658447584485844958450584515845258453584545845558456584575845858459584605846158462584635846458465584665846758468584695847058471584725847358474584755847658477584785847958480584815848258483584845848558486584875848858489584905849158492584935849458495584965849758498584995850058501585025850358504585055850658507585085850958510585115851258513585145851558516585175851858519585205852158522585235852458525585265852758528585295853058531585325853358534585355853658537585385853958540585415854258543585445854558546585475854858549585505855158552585535855458555585565855758558585595856058561585625856358564585655856658567585685856958570585715857258573585745857558576585775857858579585805858158582585835858458585585865858758588585895859058591585925859358594585955859658597585985859958600586015860258603586045860558606586075860858609586105861158612586135861458615586165861758618586195862058621586225862358624586255862658627586285862958630586315863258633586345863558636586375863858639586405864158642586435864458645586465864758648586495865058651586525865358654586555865658657586585865958660586615866258663586645866558666586675866858669586705867158672586735867458675586765867758678586795868058681586825868358684586855868658687586885868958690586915869258693586945869558696586975869858699587005870158702587035870458705587065870758708587095871058711587125871358714587155871658717587185871958720587215872258723587245872558726587275872858729587305873158732587335873458735587365873758738587395874058741587425874358744587455874658747587485874958750587515875258753587545875558756587575875858759587605876158762587635876458765587665876758768587695877058771587725877358774587755877658777587785877958780587815878258783587845878558786587875878858789587905879158792587935879458795587965879758798587995880058801588025880358804588055880658807588085880958810588115881258813588145881558816588175881858819588205882158822588235882458825588265882758828588295883058831588325883358834588355883658837588385883958840588415884258843588445884558846588475884858849588505885158852588535885458855588565885758858588595886058861588625886358864588655886658867588685886958870588715887258873588745887558876588775887858879588805888158882588835888458885588865888758888588895889058891588925889358894588955889658897588985889958900589015890258903589045890558906589075890858909589105891158912589135891458915589165891758918589195892058921589225892358924589255892658927589285892958930589315893258933589345893558936589375893858939589405894158942589435894458945589465894758948589495895058951589525895358954589555895658957589585895958960589615896258963589645896558966589675896858969589705897158972589735897458975589765897758978589795898058981589825898358984589855898658987589885898958990589915899258993589945899558996589975899858999590005900159002590035900459005590065900759008590095901059011590125901359014590155901659017590185901959020590215902259023590245902559026590275902859029590305903159032590335903459035590365903759038590395904059041590425904359044590455904659047590485904959050590515905259053590545905559056590575905859059590605906159062590635906459065590665906759068590695907059071590725907359074590755907659077590785907959080590815908259083590845908559086590875908859089590905909159092590935909459095590965909759098590995910059101591025910359104591055910659107591085910959110591115911259113591145911559116591175911859119591205912159122591235912459125591265912759128591295913059131591325913359134591355913659137591385913959140591415914259143591445914559146591475914859149591505915159152591535915459155591565915759158591595916059161591625916359164591655916659167591685916959170591715917259173591745917559176591775917859179591805918159182591835918459185591865918759188591895919059191591925919359194591955919659197591985919959200592015920259203592045920559206592075920859209592105921159212592135921459215592165921759218592195922059221592225922359224592255922659227592285922959230592315923259233592345923559236592375923859239592405924159242592435924459245592465924759248592495925059251592525925359254592555925659257592585925959260592615926259263592645926559266592675926859269592705927159272592735927459275592765927759278592795928059281592825928359284592855928659287592885928959290592915929259293592945929559296592975929859299593005930159302593035930459305593065930759308593095931059311593125931359314593155931659317593185931959320593215932259323593245932559326593275932859329593305933159332593335933459335593365933759338593395934059341593425934359344593455934659347593485934959350593515935259353593545935559356593575935859359593605936159362593635936459365593665936759368593695937059371593725937359374593755937659377593785937959380593815938259383593845938559386593875938859389593905939159392593935939459395593965939759398593995940059401594025940359404594055940659407594085940959410594115941259413594145941559416594175941859419594205942159422594235942459425594265942759428594295943059431594325943359434594355943659437594385943959440594415944259443594445944559446594475944859449594505945159452594535945459455594565945759458594595946059461594625946359464594655946659467594685946959470594715947259473594745947559476594775947859479594805948159482594835948459485594865948759488594895949059491594925949359494594955949659497594985949959500595015950259503595045950559506595075950859509595105951159512595135951459515595165951759518595195952059521595225952359524595255952659527595285952959530595315953259533595345953559536595375953859539595405954159542595435954459545595465954759548595495955059551595525955359554595555955659557595585955959560595615956259563595645956559566595675956859569595705957159572595735957459575595765957759578595795958059581595825958359584595855958659587595885958959590595915959259593595945959559596595975959859599596005960159602596035960459605596065960759608596095961059611596125961359614596155961659617596185961959620596215962259623596245962559626596275962859629596305963159632596335963459635596365963759638596395964059641596425964359644596455964659647596485964959650596515965259653596545965559656596575965859659596605966159662596635966459665596665966759668596695967059671596725967359674596755967659677596785967959680596815968259683596845968559686596875968859689596905969159692596935969459695596965969759698596995970059701597025970359704597055970659707597085970959710597115971259713597145971559716597175971859719597205972159722597235972459725597265972759728597295973059731597325973359734597355973659737597385973959740597415974259743597445974559746597475974859749597505975159752597535975459755597565975759758597595976059761597625976359764597655976659767597685976959770597715977259773597745977559776597775977859779597805978159782597835978459785597865978759788597895979059791597925979359794597955979659797597985979959800598015980259803598045980559806598075980859809598105981159812598135981459815598165981759818598195982059821598225982359824598255982659827598285982959830598315983259833598345983559836598375983859839598405984159842598435984459845598465984759848598495985059851598525985359854598555985659857598585985959860598615986259863598645986559866598675986859869598705987159872598735987459875598765987759878598795988059881598825988359884598855988659887598885988959890598915989259893598945989559896598975989859899599005990159902599035990459905599065990759908599095991059911599125991359914599155991659917599185991959920599215992259923599245992559926599275992859929599305993159932599335993459935599365993759938599395994059941599425994359944599455994659947599485994959950599515995259953599545995559956599575995859959599605996159962599635996459965599665996759968599695997059971599725997359974599755997659977599785997959980599815998259983599845998559986599875998859989599905999159992599935999459995599965999759998599996000060001600026000360004600056000660007600086000960010600116001260013600146001560016600176001860019600206002160022600236002460025600266002760028600296003060031600326003360034600356003660037600386003960040600416004260043600446004560046600476004860049600506005160052600536005460055600566005760058600596006060061600626006360064600656006660067600686006960070600716007260073600746007560076600776007860079600806008160082600836008460085600866008760088600896009060091600926009360094600956009660097600986009960100601016010260103601046010560106601076010860109601106011160112601136011460115601166011760118601196012060121601226012360124601256012660127601286012960130601316013260133601346013560136601376013860139601406014160142601436014460145601466014760148601496015060151601526015360154601556015660157601586015960160601616016260163601646016560166601676016860169601706017160172601736017460175601766017760178601796018060181601826018360184601856018660187601886018960190601916019260193601946019560196601976019860199602006020160202602036020460205602066020760208602096021060211602126021360214602156021660217602186021960220602216022260223602246022560226602276022860229602306023160232602336023460235602366023760238602396024060241602426024360244602456024660247602486024960250602516025260253602546025560256602576025860259602606026160262602636026460265602666026760268602696027060271602726027360274602756027660277602786027960280602816028260283602846028560286602876028860289602906029160292602936029460295602966029760298602996030060301603026030360304603056030660307603086030960310603116031260313603146031560316603176031860319603206032160322603236032460325603266032760328603296033060331603326033360334603356033660337603386033960340603416034260343603446034560346603476034860349603506035160352603536035460355603566035760358603596036060361603626036360364603656036660367603686036960370603716037260373603746037560376603776037860379603806038160382603836038460385603866038760388603896039060391603926039360394603956039660397603986039960400604016040260403604046040560406604076040860409604106041160412604136041460415604166041760418604196042060421604226042360424604256042660427604286042960430604316043260433604346043560436604376043860439604406044160442604436044460445604466044760448604496045060451604526045360454604556045660457604586045960460604616046260463604646046560466604676046860469604706047160472604736047460475604766047760478604796048060481604826048360484604856048660487604886048960490604916049260493604946049560496604976049860499605006050160502605036050460505605066050760508605096051060511605126051360514605156051660517605186051960520605216052260523605246052560526605276052860529605306053160532605336053460535605366053760538605396054060541605426054360544605456054660547605486054960550605516055260553605546055560556605576055860559605606056160562605636056460565605666056760568605696057060571605726057360574605756057660577605786057960580605816058260583605846058560586605876058860589605906059160592605936059460595605966059760598605996060060601606026060360604606056060660607606086060960610606116061260613606146061560616606176061860619606206062160622606236062460625606266062760628606296063060631606326063360634606356063660637606386063960640606416064260643606446064560646606476064860649606506065160652606536065460655606566065760658606596066060661606626066360664606656066660667606686066960670606716067260673606746067560676606776067860679606806068160682606836068460685606866068760688606896069060691606926069360694606956069660697606986069960700607016070260703607046070560706607076070860709607106071160712607136071460715607166071760718607196072060721607226072360724607256072660727607286072960730607316073260733607346073560736607376073860739607406074160742607436074460745607466074760748607496075060751607526075360754607556075660757607586075960760607616076260763607646076560766607676076860769607706077160772607736077460775607766077760778607796078060781607826078360784607856078660787607886078960790607916079260793607946079560796607976079860799608006080160802608036080460805608066080760808608096081060811608126081360814608156081660817608186081960820608216082260823608246082560826608276082860829608306083160832608336083460835608366083760838608396084060841608426084360844608456084660847608486084960850608516085260853608546085560856608576085860859608606086160862608636086460865608666086760868608696087060871608726087360874608756087660877608786087960880608816088260883608846088560886608876088860889608906089160892608936089460895608966089760898608996090060901609026090360904609056090660907609086090960910609116091260913609146091560916609176091860919609206092160922609236092460925609266092760928609296093060931609326093360934609356093660937609386093960940609416094260943609446094560946609476094860949609506095160952609536095460955609566095760958609596096060961609626096360964609656096660967609686096960970609716097260973609746097560976609776097860979609806098160982609836098460985609866098760988609896099060991609926099360994609956099660997609986099961000610016100261003610046100561006610076100861009610106101161012610136101461015610166101761018610196102061021610226102361024610256102661027610286102961030610316103261033610346103561036610376103861039610406104161042610436104461045610466104761048610496105061051610526105361054610556105661057610586105961060610616106261063610646106561066610676106861069610706107161072610736107461075610766107761078610796108061081610826108361084610856108661087610886108961090610916109261093610946109561096610976109861099611006110161102611036110461105611066110761108611096111061111611126111361114611156111661117611186111961120611216112261123611246112561126611276112861129611306113161132611336113461135611366113761138611396114061141611426114361144611456114661147611486114961150611516115261153611546115561156611576115861159611606116161162611636116461165611666116761168611696117061171611726117361174611756117661177611786117961180611816118261183611846118561186611876118861189611906119161192611936119461195611966119761198611996120061201612026120361204612056120661207612086120961210612116121261213612146121561216612176121861219612206122161222612236122461225612266122761228612296123061231612326123361234612356123661237612386123961240612416124261243612446124561246612476124861249612506125161252612536125461255612566125761258612596126061261612626126361264612656126661267612686126961270612716127261273612746127561276612776127861279612806128161282612836128461285612866128761288612896129061291612926129361294612956129661297612986129961300613016130261303613046130561306613076130861309613106131161312613136131461315613166131761318613196132061321613226132361324613256132661327613286132961330613316133261333613346133561336613376133861339613406134161342613436134461345613466134761348613496135061351613526135361354613556135661357613586135961360613616136261363613646136561366613676136861369613706137161372613736137461375613766137761378613796138061381613826138361384613856138661387613886138961390613916139261393613946139561396613976139861399614006140161402614036140461405614066140761408614096141061411614126141361414614156141661417614186141961420614216142261423614246142561426614276142861429614306143161432614336143461435614366143761438614396144061441614426144361444614456144661447614486144961450614516145261453614546145561456614576145861459614606146161462614636146461465614666146761468614696147061471614726147361474614756147661477614786147961480614816148261483614846148561486614876148861489614906149161492614936149461495614966149761498614996150061501615026150361504615056150661507615086150961510615116151261513615146151561516615176151861519615206152161522615236152461525615266152761528615296153061531615326153361534615356153661537615386153961540615416154261543615446154561546615476154861549615506155161552615536155461555615566155761558615596156061561615626156361564615656156661567615686156961570615716157261573615746157561576615776157861579615806158161582615836158461585615866158761588615896159061591615926159361594615956159661597615986159961600616016160261603616046160561606616076160861609616106161161612616136161461615616166161761618616196162061621616226162361624616256162661627616286162961630616316163261633616346163561636616376163861639616406164161642616436164461645616466164761648616496165061651616526165361654616556165661657616586165961660616616166261663616646166561666616676166861669616706167161672616736167461675616766167761678616796168061681616826168361684616856168661687616886168961690616916169261693616946169561696616976169861699617006170161702617036170461705617066170761708617096171061711617126171361714617156171661717617186171961720617216172261723617246172561726617276172861729617306173161732617336173461735617366173761738617396174061741617426174361744617456174661747617486174961750617516175261753617546175561756617576175861759617606176161762617636176461765617666176761768617696177061771617726177361774617756177661777617786177961780617816178261783617846178561786617876178861789617906179161792617936179461795617966179761798617996180061801618026180361804618056180661807618086180961810618116181261813618146181561816618176181861819618206182161822618236182461825618266182761828618296183061831618326183361834618356183661837618386183961840618416184261843618446184561846618476184861849618506185161852618536185461855618566185761858618596186061861618626186361864618656186661867618686186961870618716187261873618746187561876618776187861879618806188161882618836188461885618866188761888618896189061891618926189361894618956189661897618986189961900619016190261903619046190561906619076190861909619106191161912619136191461915619166191761918619196192061921619226192361924619256192661927619286192961930619316193261933619346193561936619376193861939619406194161942619436194461945619466194761948619496195061951619526195361954619556195661957619586195961960619616196261963619646196561966619676196861969619706197161972619736197461975619766197761978619796198061981619826198361984619856198661987619886198961990619916199261993619946199561996619976199861999620006200162002620036200462005620066200762008620096201062011620126201362014620156201662017620186201962020620216202262023620246202562026620276202862029620306203162032620336203462035620366203762038620396204062041620426204362044620456204662047620486204962050620516205262053620546205562056620576205862059620606206162062620636206462065620666206762068620696207062071620726207362074620756207662077620786207962080620816208262083620846208562086620876208862089620906209162092620936209462095620966209762098620996210062101621026210362104621056210662107621086210962110621116211262113621146211562116621176211862119621206212162122621236212462125621266212762128621296213062131621326213362134621356213662137621386213962140621416214262143621446214562146621476214862149621506215162152621536215462155621566215762158621596216062161621626216362164621656216662167621686216962170621716217262173621746217562176621776217862179621806218162182621836218462185621866218762188621896219062191621926219362194621956219662197621986219962200622016220262203622046220562206622076220862209622106221162212622136221462215622166221762218622196222062221622226222362224622256222662227622286222962230622316223262233622346223562236622376223862239622406224162242622436224462245622466224762248622496225062251622526225362254622556225662257622586225962260622616226262263622646226562266622676226862269622706227162272622736227462275622766227762278622796228062281622826228362284622856228662287622886228962290622916229262293622946229562296622976229862299623006230162302623036230462305623066230762308623096231062311623126231362314623156231662317623186231962320623216232262323623246232562326623276232862329623306233162332623336233462335623366233762338623396234062341623426234362344623456234662347623486234962350623516235262353623546235562356623576235862359623606236162362623636236462365623666236762368623696237062371623726237362374623756237662377623786237962380623816238262383623846238562386623876238862389623906239162392623936239462395623966239762398623996240062401624026240362404624056240662407624086240962410624116241262413624146241562416624176241862419624206242162422624236242462425624266242762428624296243062431624326243362434624356243662437624386243962440624416244262443624446244562446624476244862449624506245162452624536245462455624566245762458624596246062461624626246362464624656246662467624686246962470624716247262473624746247562476624776247862479624806248162482624836248462485624866248762488624896249062491624926249362494624956249662497624986249962500625016250262503625046250562506625076250862509625106251162512625136251462515625166251762518625196252062521625226252362524625256252662527625286252962530625316253262533625346253562536625376253862539625406254162542625436254462545625466254762548625496255062551625526255362554625556255662557625586255962560625616256262563625646256562566625676256862569625706257162572625736257462575625766257762578625796258062581625826258362584625856258662587625886258962590625916259262593625946259562596625976259862599626006260162602626036260462605626066260762608626096261062611626126261362614626156261662617626186261962620626216262262623626246262562626626276262862629626306263162632626336263462635626366263762638626396264062641626426264362644626456264662647626486264962650626516265262653626546265562656626576265862659626606266162662626636266462665626666266762668626696267062671626726267362674626756267662677626786267962680626816268262683626846268562686626876268862689626906269162692626936269462695626966269762698626996270062701627026270362704627056270662707627086270962710627116271262713627146271562716627176271862719627206272162722627236272462725627266272762728627296273062731627326273362734627356273662737627386273962740627416274262743627446274562746627476274862749627506275162752627536275462755627566275762758627596276062761627626276362764627656276662767627686276962770627716277262773627746277562776627776277862779627806278162782627836278462785627866278762788627896279062791627926279362794627956279662797627986279962800628016280262803628046280562806628076280862809628106281162812628136281462815628166281762818628196282062821628226282362824628256282662827628286282962830628316283262833628346283562836628376283862839628406284162842628436284462845628466284762848628496285062851628526285362854628556285662857628586285962860628616286262863628646286562866628676286862869628706287162872628736287462875628766287762878628796288062881628826288362884628856288662887628886288962890628916289262893628946289562896628976289862899629006290162902629036290462905629066290762908629096291062911629126291362914629156291662917629186291962920629216292262923629246292562926629276292862929629306293162932629336293462935629366293762938629396294062941629426294362944629456294662947629486294962950629516295262953629546295562956629576295862959629606296162962629636296462965629666296762968629696297062971629726297362974629756297662977629786297962980629816298262983629846298562986629876298862989629906299162992629936299462995629966299762998629996300063001630026300363004630056300663007630086300963010630116301263013630146301563016630176301863019630206302163022630236302463025630266302763028630296303063031630326303363034630356303663037630386303963040630416304263043630446304563046630476304863049630506305163052630536305463055630566305763058630596306063061630626306363064630656306663067630686306963070630716307263073630746307563076630776307863079630806308163082630836308463085630866308763088630896309063091630926309363094630956309663097630986309963100631016310263103631046310563106631076310863109631106311163112631136311463115631166311763118631196312063121631226312363124631256312663127631286312963130631316313263133631346313563136631376313863139631406314163142631436314463145631466314763148631496315063151631526315363154631556315663157631586315963160631616316263163631646316563166631676316863169631706317163172631736317463175631766317763178631796318063181631826318363184631856318663187631886318963190631916319263193631946319563196631976319863199632006320163202632036320463205632066320763208632096321063211632126321363214632156321663217632186321963220632216322263223632246322563226632276322863229632306323163232632336323463235632366323763238632396324063241632426324363244632456324663247632486324963250632516325263253632546325563256632576325863259632606326163262632636326463265632666326763268632696327063271632726327363274632756327663277632786327963280632816328263283632846328563286632876328863289632906329163292632936329463295632966329763298632996330063301633026330363304633056330663307633086330963310633116331263313633146331563316633176331863319633206332163322633236332463325633266332763328633296333063331633326333363334633356333663337633386333963340633416334263343633446334563346633476334863349633506335163352633536335463355633566335763358633596336063361633626336363364633656336663367633686336963370633716337263373633746337563376633776337863379633806338163382633836338463385633866338763388633896339063391633926339363394633956339663397633986339963400634016340263403634046340563406634076340863409634106341163412634136341463415634166341763418634196342063421634226342363424634256342663427634286342963430634316343263433634346343563436634376343863439634406344163442634436344463445634466344763448634496345063451634526345363454634556345663457634586345963460634616346263463634646346563466634676346863469634706347163472634736347463475634766347763478634796348063481634826348363484634856348663487634886348963490634916349263493634946349563496634976349863499635006350163502635036350463505635066350763508635096351063511635126351363514635156351663517635186351963520635216352263523635246352563526635276352863529635306353163532635336353463535635366353763538635396354063541635426354363544635456354663547635486354963550635516355263553635546355563556635576355863559635606356163562635636356463565635666356763568635696357063571635726357363574635756357663577635786357963580635816358263583635846358563586635876358863589635906359163592635936359463595635966359763598635996360063601636026360363604636056360663607636086360963610636116361263613636146361563616636176361863619636206362163622636236362463625636266362763628636296363063631636326363363634636356363663637636386363963640636416364263643636446364563646636476364863649636506365163652636536365463655636566365763658636596366063661636626366363664636656366663667636686366963670636716367263673636746367563676636776367863679636806368163682636836368463685636866368763688636896369063691636926369363694636956369663697636986369963700637016370263703637046370563706637076370863709637106371163712637136371463715637166371763718637196372063721637226372363724637256372663727637286372963730637316373263733637346373563736637376373863739637406374163742637436374463745637466374763748637496375063751637526375363754637556375663757637586375963760637616376263763637646376563766637676376863769637706377163772637736377463775637766377763778637796378063781637826378363784637856378663787637886378963790637916379263793637946379563796637976379863799638006380163802638036380463805638066380763808638096381063811638126381363814638156381663817638186381963820638216382263823638246382563826638276382863829638306383163832638336383463835638366383763838638396384063841638426384363844638456384663847638486384963850638516385263853638546385563856638576385863859638606386163862638636386463865638666386763868638696387063871638726387363874638756387663877638786387963880638816388263883638846388563886638876388863889638906389163892638936389463895638966389763898638996390063901639026390363904639056390663907639086390963910639116391263913639146391563916639176391863919639206392163922639236392463925639266392763928639296393063931639326393363934639356393663937639386393963940639416394263943639446394563946639476394863949639506395163952639536395463955639566395763958639596396063961639626396363964639656396663967639686396963970639716397263973639746397563976639776397863979639806398163982639836398463985639866398763988639896399063991639926399363994639956399663997639986399964000640016400264003640046400564006640076400864009640106401164012640136401464015640166401764018640196402064021640226402364024640256402664027640286402964030640316403264033640346403564036640376403864039640406404164042640436404464045640466404764048640496405064051640526405364054640556405664057640586405964060640616406264063640646406564066640676406864069640706407164072640736407464075640766407764078640796408064081640826408364084640856408664087640886408964090640916409264093640946409564096640976409864099641006410164102641036410464105641066410764108641096411064111641126411364114641156411664117641186411964120641216412264123641246412564126641276412864129641306413164132641336413464135641366413764138641396414064141641426414364144641456414664147641486414964150641516415264153641546415564156641576415864159641606416164162641636416464165641666416764168641696417064171641726417364174641756417664177641786417964180641816418264183641846418564186641876418864189641906419164192641936419464195641966419764198641996420064201642026420364204642056420664207642086420964210642116421264213642146421564216642176421864219642206422164222642236422464225642266422764228642296423064231642326423364234642356423664237642386423964240642416424264243642446424564246642476424864249642506425164252642536425464255642566425764258642596426064261642626426364264642656426664267642686426964270642716427264273642746427564276642776427864279642806428164282642836428464285642866428764288642896429064291642926429364294642956429664297642986429964300643016430264303643046430564306643076430864309643106431164312643136431464315643166431764318643196432064321643226432364324643256432664327643286432964330643316433264333643346433564336643376433864339643406434164342643436434464345643466434764348643496435064351643526435364354643556435664357643586435964360643616436264363643646436564366643676436864369643706437164372643736437464375643766437764378643796438064381643826438364384643856438664387643886438964390643916439264393643946439564396643976439864399644006440164402644036440464405644066440764408644096441064411644126441364414644156441664417644186441964420644216442264423644246442564426644276442864429644306443164432644336443464435644366443764438644396444064441644426444364444644456444664447644486444964450644516445264453644546445564456644576445864459644606446164462644636446464465644666446764468644696447064471644726447364474644756447664477644786447964480644816448264483644846448564486644876448864489644906449164492644936449464495644966449764498644996450064501645026450364504645056450664507645086450964510645116451264513645146451564516645176451864519645206452164522645236452464525645266452764528645296453064531645326453364534645356453664537645386453964540645416454264543645446454564546645476454864549645506455164552645536455464555645566455764558645596456064561645626456364564645656456664567645686456964570645716457264573645746457564576645776457864579645806458164582645836458464585645866458764588645896459064591645926459364594645956459664597645986459964600646016460264603646046460564606646076460864609646106461164612646136461464615646166461764618646196462064621646226462364624646256462664627646286462964630646316463264633646346463564636646376463864639646406464164642646436464464645646466464764648646496465064651646526465364654646556465664657646586465964660646616466264663646646466564666646676466864669646706467164672646736467464675646766467764678646796468064681646826468364684646856468664687646886468964690646916469264693646946469564696646976469864699647006470164702647036470464705647066470764708647096471064711647126471364714647156471664717647186471964720647216472264723647246472564726647276472864729647306473164732647336473464735647366473764738647396474064741647426474364744647456474664747647486474964750647516475264753647546475564756647576475864759647606476164762647636476464765647666476764768647696477064771647726477364774647756477664777647786477964780647816478264783647846478564786647876478864789647906479164792647936479464795647966479764798647996480064801648026480364804648056480664807648086480964810648116481264813648146481564816648176481864819648206482164822648236482464825648266482764828648296483064831648326483364834648356483664837648386483964840648416484264843648446484564846648476484864849648506485164852648536485464855648566485764858648596486064861648626486364864648656486664867648686486964870648716487264873648746487564876648776487864879648806488164882648836488464885648866488764888648896489064891648926489364894648956489664897648986489964900649016490264903649046490564906649076490864909649106491164912649136491464915649166491764918649196492064921649226492364924649256492664927649286492964930649316493264933649346493564936649376493864939649406494164942649436494464945649466494764948649496495064951649526495364954649556495664957649586495964960649616496264963649646496564966649676496864969649706497164972649736497464975649766497764978649796498064981649826498364984649856498664987649886498964990649916499264993649946499564996649976499864999650006500165002650036500465005650066500765008650096501065011650126501365014650156501665017650186501965020650216502265023650246502565026650276502865029650306503165032650336503465035650366503765038650396504065041650426504365044650456504665047650486504965050650516505265053650546505565056650576505865059650606506165062650636506465065650666506765068650696507065071650726507365074650756507665077650786507965080650816508265083650846508565086650876508865089650906509165092650936509465095650966509765098650996510065101651026510365104651056510665107651086510965110651116511265113651146511565116651176511865119651206512165122651236512465125651266512765128651296513065131651326513365134651356513665137651386513965140651416514265143651446514565146651476514865149651506515165152651536515465155651566515765158651596516065161651626516365164651656516665167651686516965170651716517265173651746517565176651776517865179651806518165182651836518465185651866518765188651896519065191651926519365194651956519665197651986519965200652016520265203652046520565206652076520865209652106521165212652136521465215652166521765218652196522065221652226522365224652256522665227652286522965230652316523265233652346523565236652376523865239652406524165242652436524465245652466524765248652496525065251652526525365254652556525665257652586525965260652616526265263652646526565266652676526865269652706527165272652736527465275652766527765278652796528065281652826528365284652856528665287652886528965290652916529265293652946529565296652976529865299653006530165302653036530465305653066530765308653096531065311653126531365314653156531665317653186531965320653216532265323653246532565326653276532865329653306533165332653336533465335653366533765338653396534065341653426534365344653456534665347653486534965350653516535265353653546535565356653576535865359653606536165362653636536465365653666536765368653696537065371653726537365374653756537665377653786537965380653816538265383653846538565386653876538865389653906539165392653936539465395653966539765398653996540065401654026540365404654056540665407654086540965410654116541265413654146541565416654176541865419654206542165422654236542465425654266542765428654296543065431654326543365434654356543665437654386543965440654416544265443654446544565446654476544865449654506545165452654536545465455654566545765458654596546065461654626546365464654656546665467654686546965470654716547265473654746547565476654776547865479654806548165482654836548465485654866548765488654896549065491654926549365494654956549665497654986549965500655016550265503655046550565506655076550865509655106551165512655136551465515655166551765518655196552065521655226552365524655256552665527655286552965530655316553265533655346553565536655376553865539655406554165542655436554465545655466554765548655496555065551655526555365554655556555665557655586555965560655616556265563655646556565566655676556865569655706557165572655736557465575655766557765578655796558065581655826558365584655856558665587655886558965590655916559265593655946559565596655976559865599656006560165602656036560465605656066560765608656096561065611656126561365614656156561665617656186561965620656216562265623656246562565626656276562865629656306563165632656336563465635656366563765638656396564065641656426564365644656456564665647656486564965650656516565265653656546565565656656576565865659656606566165662656636566465665656666566765668656696567065671656726567365674656756567665677656786567965680656816568265683656846568565686656876568865689656906569165692656936569465695656966569765698656996570065701657026570365704657056570665707657086570965710657116571265713657146571565716657176571865719657206572165722657236572465725657266572765728657296573065731657326573365734657356573665737657386573965740657416574265743657446574565746657476574865749657506575165752657536575465755657566575765758657596576065761657626576365764657656576665767657686576965770657716577265773657746577565776657776577865779657806578165782657836578465785657866578765788657896579065791657926579365794657956579665797657986579965800658016580265803658046580565806658076580865809658106581165812658136581465815658166581765818658196582065821658226582365824658256582665827658286582965830658316583265833658346583565836658376583865839658406584165842658436584465845658466584765848658496585065851658526585365854658556585665857658586585965860658616586265863658646586565866658676586865869658706587165872658736587465875658766587765878658796588065881658826588365884658856588665887658886588965890658916589265893658946589565896658976589865899659006590165902659036590465905659066590765908659096591065911659126591365914659156591665917659186591965920659216592265923659246592565926659276592865929659306593165932659336593465935659366593765938659396594065941659426594365944659456594665947659486594965950659516595265953659546595565956659576595865959659606596165962659636596465965659666596765968659696597065971659726597365974659756597665977659786597965980659816598265983659846598565986659876598865989659906599165992659936599465995659966599765998659996600066001660026600366004660056600666007660086600966010660116601266013660146601566016660176601866019660206602166022660236602466025660266602766028660296603066031660326603366034660356603666037660386603966040660416604266043660446604566046660476604866049660506605166052660536605466055660566605766058660596606066061660626606366064660656606666067660686606966070660716607266073660746607566076660776607866079660806608166082660836608466085660866608766088660896609066091660926609366094660956609666097660986609966100661016610266103661046610566106661076610866109661106611166112661136611466115661166611766118661196612066121661226612366124661256612666127661286612966130661316613266133661346613566136661376613866139661406614166142661436614466145661466614766148661496615066151661526615366154661556615666157661586615966160661616616266163661646616566166661676616866169661706617166172661736617466175661766617766178661796618066181661826618366184661856618666187661886618966190661916619266193661946619566196661976619866199662006620166202662036620466205662066620766208662096621066211662126621366214662156621666217662186621966220662216622266223662246622566226662276622866229662306623166232662336623466235662366623766238662396624066241662426624366244662456624666247662486624966250662516625266253662546625566256662576625866259662606626166262662636626466265662666626766268662696627066271662726627366274662756627666277662786627966280662816628266283662846628566286662876628866289662906629166292662936629466295662966629766298662996630066301663026630366304663056630666307663086630966310663116631266313663146631566316663176631866319663206632166322663236632466325663266632766328663296633066331663326633366334663356633666337663386633966340663416634266343663446634566346663476634866349663506635166352663536635466355663566635766358663596636066361663626636366364663656636666367663686636966370663716637266373663746637566376663776637866379663806638166382663836638466385663866638766388663896639066391663926639366394663956639666397663986639966400664016640266403664046640566406664076640866409664106641166412664136641466415664166641766418664196642066421664226642366424664256642666427664286642966430664316643266433664346643566436664376643866439664406644166442664436644466445664466644766448664496645066451664526645366454664556645666457664586645966460664616646266463664646646566466664676646866469664706647166472664736647466475664766647766478664796648066481664826648366484664856648666487664886648966490664916649266493664946649566496664976649866499665006650166502665036650466505665066650766508665096651066511665126651366514665156651666517665186651966520665216652266523665246652566526665276652866529665306653166532665336653466535665366653766538665396654066541665426654366544665456654666547665486654966550665516655266553665546655566556665576655866559665606656166562665636656466565665666656766568665696657066571665726657366574665756657666577665786657966580665816658266583665846658566586665876658866589665906659166592665936659466595665966659766598665996660066601666026660366604666056660666607666086660966610666116661266613666146661566616666176661866619666206662166622666236662466625666266662766628666296663066631666326663366634666356663666637666386663966640666416664266643666446664566646666476664866649666506665166652666536665466655666566665766658666596666066661666626666366664666656666666667666686666966670666716667266673666746667566676666776667866679666806668166682666836668466685666866668766688666896669066691666926669366694666956669666697666986669966700667016670266703667046670566706667076670866709667106671166712667136671466715667166671766718667196672066721667226672366724667256672666727667286672966730667316673266733667346673566736667376673866739667406674166742667436674466745667466674766748667496675066751667526675366754667556675666757667586675966760667616676266763667646676566766667676676866769667706677166772667736677466775667766677766778667796678066781667826678366784667856678666787667886678966790667916679266793667946679566796667976679866799668006680166802668036680466805668066680766808668096681066811668126681366814668156681666817668186681966820668216682266823668246682566826668276682866829668306683166832668336683466835668366683766838668396684066841668426684366844668456684666847668486684966850668516685266853668546685566856668576685866859668606686166862668636686466865668666686766868668696687066871668726687366874668756687666877668786687966880668816688266883668846688566886668876688866889668906689166892668936689466895668966689766898668996690066901669026690366904669056690666907669086690966910669116691266913669146691566916669176691866919669206692166922669236692466925669266692766928669296693066931669326693366934669356693666937669386693966940669416694266943669446694566946669476694866949669506695166952669536695466955669566695766958669596696066961669626696366964669656696666967669686696966970669716697266973669746697566976669776697866979669806698166982669836698466985669866698766988669896699066991669926699366994669956699666997669986699967000670016700267003670046700567006670076700867009670106701167012670136701467015670166701767018670196702067021670226702367024670256702667027670286702967030670316703267033670346703567036670376703867039670406704167042670436704467045670466704767048670496705067051670526705367054670556705667057670586705967060670616706267063670646706567066670676706867069670706707167072670736707467075670766707767078670796708067081670826708367084670856708667087670886708967090670916709267093670946709567096670976709867099671006710167102671036710467105671066710767108671096711067111671126711367114671156711667117671186711967120671216712267123671246712567126671276712867129671306713167132671336713467135671366713767138671396714067141671426714367144671456714667147671486714967150671516715267153671546715567156671576715867159671606716167162671636716467165671666716767168671696717067171671726717367174671756717667177671786717967180671816718267183671846718567186671876718867189671906719167192671936719467195671966719767198671996720067201672026720367204672056720667207672086720967210672116721267213672146721567216672176721867219672206722167222672236722467225672266722767228672296723067231672326723367234672356723667237672386723967240672416724267243672446724567246672476724867249672506725167252672536725467255672566725767258672596726067261672626726367264672656726667267672686726967270672716727267273672746727567276672776727867279672806728167282672836728467285672866728767288672896729067291672926729367294672956729667297672986729967300673016730267303673046730567306673076730867309673106731167312673136731467315673166731767318673196732067321673226732367324673256732667327673286732967330673316733267333673346733567336673376733867339673406734167342673436734467345673466734767348673496735067351673526735367354673556735667357673586735967360673616736267363673646736567366673676736867369673706737167372673736737467375673766737767378673796738067381673826738367384673856738667387673886738967390673916739267393673946739567396673976739867399674006740167402674036740467405674066740767408674096741067411674126741367414674156741667417674186741967420674216742267423674246742567426674276742867429674306743167432674336743467435674366743767438674396744067441674426744367444674456744667447674486744967450674516745267453674546745567456674576745867459674606746167462674636746467465674666746767468674696747067471674726747367474674756747667477674786747967480674816748267483674846748567486674876748867489674906749167492674936749467495674966749767498674996750067501675026750367504675056750667507675086750967510675116751267513675146751567516675176751867519675206752167522675236752467525675266752767528675296753067531675326753367534675356753667537675386753967540675416754267543675446754567546675476754867549675506755167552675536755467555675566755767558675596756067561675626756367564675656756667567675686756967570675716757267573675746757567576675776757867579675806758167582675836758467585675866758767588675896759067591675926759367594675956759667597675986759967600676016760267603676046760567606676076760867609676106761167612676136761467615676166761767618676196762067621676226762367624676256762667627676286762967630676316763267633676346763567636676376763867639676406764167642676436764467645676466764767648676496765067651676526765367654676556765667657676586765967660676616766267663676646766567666676676766867669676706767167672676736767467675676766767767678676796768067681676826768367684676856768667687676886768967690676916769267693676946769567696676976769867699677006770167702677036770467705677066770767708677096771067711677126771367714677156771667717677186771967720677216772267723677246772567726677276772867729677306773167732677336773467735677366773767738677396774067741677426774367744677456774667747677486774967750677516775267753677546775567756677576775867759677606776167762677636776467765677666776767768677696777067771677726777367774677756777667777677786777967780677816778267783677846778567786677876778867789677906779167792677936779467795677966779767798677996780067801678026780367804678056780667807678086780967810678116781267813678146781567816678176781867819678206782167822678236782467825678266782767828678296783067831678326783367834678356783667837678386783967840678416784267843678446784567846678476784867849678506785167852678536785467855678566785767858678596786067861678626786367864678656786667867678686786967870678716787267873678746787567876678776787867879678806788167882678836788467885678866788767888678896789067891678926789367894678956789667897678986789967900679016790267903679046790567906679076790867909679106791167912679136791467915679166791767918679196792067921679226792367924679256792667927679286792967930679316793267933679346793567936679376793867939679406794167942679436794467945679466794767948679496795067951679526795367954679556795667957679586795967960679616796267963679646796567966679676796867969679706797167972679736797467975679766797767978679796798067981679826798367984679856798667987679886798967990679916799267993679946799567996679976799867999680006800168002680036800468005680066800768008680096801068011680126801368014680156801668017680186801968020680216802268023680246802568026680276802868029680306803168032680336803468035680366803768038680396804068041680426804368044680456804668047680486804968050680516805268053680546805568056680576805868059680606806168062680636806468065680666806768068680696807068071680726807368074680756807668077680786807968080680816808268083680846808568086680876808868089680906809168092680936809468095680966809768098680996810068101681026810368104681056810668107681086810968110681116811268113681146811568116681176811868119681206812168122681236812468125681266812768128681296813068131681326813368134681356813668137681386813968140681416814268143681446814568146681476814868149681506815168152681536815468155681566815768158681596816068161681626816368164681656816668167681686816968170681716817268173681746817568176681776817868179681806818168182681836818468185681866818768188681896819068191681926819368194681956819668197681986819968200682016820268203682046820568206682076820868209682106821168212682136821468215682166821768218682196822068221682226822368224682256822668227682286822968230682316823268233682346823568236682376823868239682406824168242682436824468245682466824768248682496825068251682526825368254682556825668257682586825968260682616826268263682646826568266682676826868269682706827168272682736827468275682766827768278682796828068281682826828368284682856828668287682886828968290682916829268293682946829568296682976829868299683006830168302683036830468305683066830768308683096831068311683126831368314683156831668317683186831968320683216832268323683246832568326683276832868329683306833168332683336833468335683366833768338683396834068341683426834368344683456834668347683486834968350683516835268353683546835568356683576835868359683606836168362683636836468365683666836768368683696837068371683726837368374683756837668377683786837968380683816838268383683846838568386683876838868389683906839168392683936839468395683966839768398683996840068401684026840368404684056840668407684086840968410684116841268413684146841568416684176841868419684206842168422684236842468425684266842768428684296843068431684326843368434684356843668437684386843968440684416844268443684446844568446684476844868449684506845168452684536845468455684566845768458684596846068461684626846368464684656846668467684686846968470684716847268473684746847568476684776847868479684806848168482684836848468485684866848768488684896849068491684926849368494684956849668497684986849968500685016850268503685046850568506685076850868509685106851168512685136851468515685166851768518685196852068521685226852368524685256852668527685286852968530685316853268533685346853568536685376853868539685406854168542685436854468545685466854768548685496855068551685526855368554685556855668557685586855968560685616856268563685646856568566685676856868569685706857168572685736857468575685766857768578685796858068581685826858368584685856858668587685886858968590685916859268593685946859568596685976859868599686006860168602686036860468605686066860768608686096861068611686126861368614686156861668617686186861968620686216862268623686246862568626686276862868629686306863168632686336863468635686366863768638686396864068641686426864368644686456864668647686486864968650686516865268653686546865568656686576865868659686606866168662686636866468665686666866768668686696867068671686726867368674686756867668677686786867968680686816868268683686846868568686686876868868689686906869168692686936869468695686966869768698686996870068701687026870368704687056870668707687086870968710687116871268713687146871568716687176871868719687206872168722687236872468725687266872768728687296873068731687326873368734687356873668737687386873968740687416874268743687446874568746687476874868749687506875168752687536875468755687566875768758687596876068761687626876368764687656876668767687686876968770687716877268773687746877568776687776877868779687806878168782687836878468785687866878768788687896879068791687926879368794687956879668797687986879968800688016880268803688046880568806688076880868809688106881168812688136881468815688166881768818688196882068821688226882368824688256882668827688286882968830688316883268833688346883568836688376883868839688406884168842688436884468845688466884768848688496885068851688526885368854688556885668857688586885968860688616886268863688646886568866688676886868869688706887168872688736887468875688766887768878688796888068881688826888368884688856888668887688886888968890688916889268893688946889568896688976889868899689006890168902689036890468905689066890768908689096891068911689126891368914689156891668917689186891968920689216892268923689246892568926689276892868929689306893168932689336893468935689366893768938689396894068941689426894368944689456894668947689486894968950689516895268953689546895568956689576895868959689606896168962689636896468965689666896768968689696897068971689726897368974689756897668977689786897968980689816898268983689846898568986689876898868989689906899168992689936899468995689966899768998689996900069001690026900369004690056900669007690086900969010690116901269013690146901569016690176901869019690206902169022690236902469025690266902769028690296903069031690326903369034690356903669037690386903969040690416904269043690446904569046690476904869049690506905169052690536905469055690566905769058690596906069061690626906369064690656906669067690686906969070690716907269073690746907569076690776907869079690806908169082690836908469085690866908769088690896909069091690926909369094690956909669097690986909969100691016910269103691046910569106691076910869109691106911169112691136911469115691166911769118691196912069121691226912369124691256912669127691286912969130691316913269133691346913569136691376913869139691406914169142691436914469145691466914769148691496915069151691526915369154691556915669157691586915969160691616916269163691646916569166691676916869169691706917169172691736917469175691766917769178691796918069181691826918369184691856918669187691886918969190691916919269193691946919569196691976919869199692006920169202692036920469205692066920769208692096921069211692126921369214692156921669217692186921969220692216922269223692246922569226692276922869229692306923169232692336923469235692366923769238692396924069241692426924369244692456924669247692486924969250692516925269253692546925569256692576925869259692606926169262692636926469265692666926769268692696927069271692726927369274692756927669277692786927969280692816928269283692846928569286692876928869289692906929169292692936929469295692966929769298692996930069301693026930369304693056930669307693086930969310693116931269313693146931569316693176931869319693206932169322693236932469325693266932769328693296933069331693326933369334693356933669337693386933969340693416934269343693446934569346693476934869349693506935169352693536935469355693566935769358693596936069361693626936369364693656936669367693686936969370693716937269373693746937569376693776937869379693806938169382693836938469385693866938769388693896939069391693926939369394693956939669397693986939969400694016940269403694046940569406694076940869409694106941169412694136941469415694166941769418694196942069421694226942369424694256942669427694286942969430694316943269433694346943569436694376943869439694406944169442694436944469445694466944769448694496945069451694526945369454694556945669457694586945969460694616946269463694646946569466694676946869469694706947169472694736947469475694766947769478694796948069481694826948369484694856948669487694886948969490694916949269493694946949569496694976949869499695006950169502695036950469505695066950769508695096951069511695126951369514695156951669517695186951969520695216952269523695246952569526695276952869529695306953169532695336953469535695366953769538695396954069541695426954369544695456954669547695486954969550695516955269553695546955569556695576955869559695606956169562695636956469565695666956769568695696957069571695726957369574695756957669577695786957969580695816958269583695846958569586695876958869589695906959169592695936959469595695966959769598695996960069601696026960369604696056960669607696086960969610696116961269613696146961569616696176961869619696206962169622696236962469625696266962769628696296963069631696326963369634696356963669637696386963969640696416964269643696446964569646696476964869649696506965169652696536965469655696566965769658696596966069661696626966369664696656966669667696686966969670696716967269673696746967569676696776967869679696806968169682696836968469685696866968769688696896969069691696926969369694696956969669697696986969969700697016970269703697046970569706697076970869709697106971169712697136971469715697166971769718697196972069721697226972369724697256972669727697286972969730697316973269733697346973569736697376973869739697406974169742697436974469745697466974769748697496975069751697526975369754697556975669757697586975969760697616976269763697646976569766697676976869769697706977169772697736977469775697766977769778697796978069781697826978369784697856978669787697886978969790697916979269793697946979569796697976979869799698006980169802698036980469805698066980769808698096981069811698126981369814698156981669817698186981969820698216982269823698246982569826698276982869829698306983169832698336983469835698366983769838698396984069841698426984369844698456984669847698486984969850698516985269853698546985569856698576985869859698606986169862698636986469865698666986769868698696987069871698726987369874698756987669877698786987969880698816988269883698846988569886698876988869889698906989169892698936989469895698966989769898698996990069901699026990369904699056990669907699086990969910699116991269913699146991569916699176991869919699206992169922699236992469925699266992769928699296993069931699326993369934699356993669937699386993969940699416994269943699446994569946699476994869949699506995169952699536995469955699566995769958699596996069961699626996369964699656996669967699686996969970699716997269973699746997569976699776997869979699806998169982699836998469985699866998769988699896999069991699926999369994699956999669997699986999970000700017000270003700047000570006700077000870009700107001170012700137001470015700167001770018700197002070021700227002370024700257002670027700287002970030700317003270033700347003570036700377003870039700407004170042700437004470045700467004770048700497005070051700527005370054700557005670057700587005970060700617006270063700647006570066700677006870069700707007170072700737007470075700767007770078700797008070081700827008370084700857008670087700887008970090700917009270093700947009570096700977009870099701007010170102701037010470105701067010770108701097011070111701127011370114701157011670117701187011970120701217012270123701247012570126701277012870129701307013170132701337013470135701367013770138701397014070141701427014370144701457014670147701487014970150701517015270153701547015570156701577015870159701607016170162701637016470165701667016770168701697017070171701727017370174701757017670177701787017970180701817018270183701847018570186701877018870189701907019170192701937019470195701967019770198701997020070201702027020370204702057020670207702087020970210702117021270213702147021570216702177021870219702207022170222702237022470225702267022770228702297023070231702327023370234702357023670237702387023970240702417024270243702447024570246702477024870249702507025170252702537025470255702567025770258702597026070261702627026370264702657026670267702687026970270702717027270273702747027570276702777027870279702807028170282702837028470285702867028770288702897029070291702927029370294702957029670297702987029970300703017030270303703047030570306703077030870309703107031170312703137031470315703167031770318703197032070321703227032370324703257032670327703287032970330703317033270333703347033570336703377033870339703407034170342703437034470345703467034770348703497035070351703527035370354703557035670357703587035970360703617036270363703647036570366703677036870369703707037170372703737037470375703767037770378703797038070381703827038370384703857038670387703887038970390703917039270393703947039570396703977039870399704007040170402704037040470405704067040770408704097041070411704127041370414704157041670417704187041970420704217042270423704247042570426704277042870429704307043170432704337043470435704367043770438704397044070441704427044370444704457044670447704487044970450704517045270453704547045570456704577045870459704607046170462704637046470465704667046770468704697047070471704727047370474704757047670477704787047970480704817048270483704847048570486704877048870489704907049170492704937049470495704967049770498704997050070501705027050370504705057050670507705087050970510705117051270513705147051570516705177051870519705207052170522705237052470525705267052770528705297053070531705327053370534705357053670537705387053970540705417054270543705447054570546705477054870549705507055170552705537055470555705567055770558705597056070561705627056370564705657056670567705687056970570705717057270573705747057570576705777057870579705807058170582705837058470585705867058770588705897059070591705927059370594705957059670597705987059970600706017060270603706047060570606706077060870609706107061170612706137061470615706167061770618706197062070621706227062370624706257062670627706287062970630706317063270633706347063570636706377063870639706407064170642706437064470645706467064770648706497065070651706527065370654706557065670657706587065970660706617066270663706647066570666706677066870669706707067170672706737067470675706767067770678706797068070681706827068370684706857068670687706887068970690706917069270693706947069570696706977069870699707007070170702707037070470705707067070770708707097071070711707127071370714707157071670717707187071970720707217072270723707247072570726707277072870729707307073170732707337073470735707367073770738707397074070741707427074370744707457074670747707487074970750707517075270753707547075570756707577075870759707607076170762707637076470765707667076770768707697077070771707727077370774707757077670777707787077970780707817078270783707847078570786707877078870789707907079170792707937079470795707967079770798707997080070801708027080370804708057080670807708087080970810708117081270813708147081570816708177081870819708207082170822708237082470825708267082770828708297083070831708327083370834708357083670837708387083970840708417084270843708447084570846708477084870849708507085170852708537085470855708567085770858708597086070861708627086370864708657086670867708687086970870708717087270873708747087570876708777087870879708807088170882708837088470885708867088770888708897089070891708927089370894708957089670897708987089970900709017090270903709047090570906709077090870909709107091170912709137091470915709167091770918709197092070921709227092370924709257092670927709287092970930709317093270933709347093570936709377093870939709407094170942709437094470945709467094770948709497095070951709527095370954709557095670957709587095970960709617096270963709647096570966709677096870969709707097170972709737097470975709767097770978709797098070981709827098370984709857098670987709887098970990709917099270993709947099570996709977099870999710007100171002710037100471005710067100771008710097101071011710127101371014710157101671017710187101971020710217102271023710247102571026710277102871029710307103171032710337103471035710367103771038710397104071041710427104371044710457104671047710487104971050710517105271053710547105571056710577105871059710607106171062710637106471065710667106771068710697107071071710727107371074710757107671077710787107971080710817108271083710847108571086710877108871089710907109171092710937109471095710967109771098710997110071101711027110371104711057110671107711087110971110711117111271113711147111571116711177111871119711207112171122711237112471125711267112771128711297113071131711327113371134711357113671137711387113971140711417114271143711447114571146711477114871149711507115171152711537115471155711567115771158711597116071161711627116371164711657116671167711687116971170711717117271173711747117571176711777117871179711807118171182711837118471185711867118771188711897119071191711927119371194711957119671197711987119971200712017120271203712047120571206712077120871209712107121171212712137121471215712167121771218712197122071221712227122371224712257122671227712287122971230712317123271233712347123571236712377123871239712407124171242712437124471245712467124771248712497125071251712527125371254712557125671257712587125971260712617126271263712647126571266712677126871269712707127171272712737127471275712767127771278712797128071281712827128371284712857128671287712887128971290712917129271293712947129571296712977129871299713007130171302713037130471305713067130771308713097131071311713127131371314713157131671317713187131971320713217132271323713247132571326713277132871329713307133171332713337133471335713367133771338713397134071341713427134371344713457134671347713487134971350713517135271353713547135571356713577135871359713607136171362713637136471365713667136771368713697137071371713727137371374713757137671377713787137971380713817138271383713847138571386713877138871389713907139171392713937139471395713967139771398713997140071401714027140371404714057140671407714087140971410714117141271413714147141571416714177141871419714207142171422714237142471425714267142771428714297143071431714327143371434714357143671437714387143971440714417144271443714447144571446714477144871449714507145171452714537145471455714567145771458714597146071461714627146371464714657146671467714687146971470714717147271473714747147571476714777147871479714807148171482714837148471485714867148771488714897149071491714927149371494714957149671497714987149971500715017150271503715047150571506715077150871509715107151171512715137151471515715167151771518715197152071521715227152371524715257152671527715287152971530715317153271533715347153571536715377153871539715407154171542715437154471545715467154771548715497155071551715527155371554715557155671557715587155971560715617156271563715647156571566715677156871569715707157171572715737157471575715767157771578715797158071581715827158371584715857158671587715887158971590715917159271593715947159571596715977159871599716007160171602716037160471605716067160771608716097161071611716127161371614716157161671617716187161971620716217162271623716247162571626716277162871629716307163171632716337163471635716367163771638716397164071641716427164371644716457164671647716487164971650716517165271653716547165571656716577165871659716607166171662716637166471665716667166771668716697167071671716727167371674716757167671677716787167971680716817168271683716847168571686716877168871689716907169171692716937169471695716967169771698716997170071701717027170371704717057170671707717087170971710717117171271713717147171571716717177171871719717207172171722717237172471725717267172771728717297173071731717327173371734717357173671737717387173971740717417174271743717447174571746717477174871749717507175171752717537175471755717567175771758717597176071761717627176371764717657176671767717687176971770717717177271773717747177571776717777177871779717807178171782717837178471785717867178771788717897179071791717927179371794717957179671797717987179971800718017180271803718047180571806718077180871809718107181171812718137181471815718167181771818718197182071821718227182371824718257182671827718287182971830718317183271833718347183571836718377183871839718407184171842718437184471845718467184771848718497185071851718527185371854718557185671857718587185971860718617186271863718647186571866718677186871869718707187171872718737187471875718767187771878718797188071881718827188371884718857188671887718887188971890718917189271893718947189571896718977189871899719007190171902719037190471905719067190771908719097191071911719127191371914719157191671917719187191971920719217192271923719247192571926719277192871929719307193171932719337193471935719367193771938719397194071941719427194371944719457194671947719487194971950719517195271953719547195571956719577195871959719607196171962719637196471965719667196771968719697197071971719727197371974719757197671977719787197971980719817198271983719847198571986719877198871989719907199171992719937199471995719967199771998719997200072001720027200372004720057200672007720087200972010720117201272013720147201572016720177201872019720207202172022720237202472025720267202772028720297203072031720327203372034720357203672037720387203972040720417204272043720447204572046720477204872049720507205172052720537205472055720567205772058720597206072061720627206372064720657206672067720687206972070720717207272073720747207572076720777207872079720807208172082720837208472085720867208772088720897209072091720927209372094720957209672097720987209972100721017210272103721047210572106721077210872109721107211172112721137211472115721167211772118721197212072121721227212372124721257212672127721287212972130721317213272133721347213572136721377213872139721407214172142721437214472145721467214772148721497215072151721527215372154721557215672157721587215972160721617216272163721647216572166721677216872169721707217172172721737217472175721767217772178721797218072181721827218372184721857218672187721887218972190721917219272193721947219572196721977219872199722007220172202722037220472205722067220772208722097221072211722127221372214722157221672217722187221972220722217222272223722247222572226722277222872229722307223172232722337223472235722367223772238722397224072241722427224372244722457224672247722487224972250722517225272253722547225572256722577225872259722607226172262722637226472265722667226772268722697227072271722727227372274722757227672277722787227972280722817228272283722847228572286722877228872289722907229172292722937229472295722967229772298722997230072301723027230372304723057230672307723087230972310723117231272313723147231572316723177231872319723207232172322723237232472325723267232772328723297233072331723327233372334723357233672337723387233972340723417234272343723447234572346723477234872349723507235172352723537235472355723567235772358723597236072361723627236372364723657236672367723687236972370723717237272373723747237572376723777237872379723807238172382723837238472385723867238772388723897239072391723927239372394723957239672397723987239972400724017240272403724047240572406724077240872409724107241172412724137241472415724167241772418724197242072421724227242372424724257242672427724287242972430724317243272433724347243572436724377243872439724407244172442724437244472445724467244772448724497245072451724527245372454724557245672457724587245972460724617246272463724647246572466724677246872469724707247172472724737247472475724767247772478724797248072481724827248372484724857248672487724887248972490724917249272493724947249572496724977249872499725007250172502725037250472505725067250772508725097251072511725127251372514725157251672517725187251972520725217252272523725247252572526725277252872529725307253172532725337253472535725367253772538725397254072541725427254372544725457254672547725487254972550725517255272553725547255572556725577255872559725607256172562725637256472565725667256772568725697257072571725727257372574725757257672577725787257972580725817258272583725847258572586725877258872589725907259172592725937259472595725967259772598725997260072601726027260372604726057260672607726087260972610726117261272613726147261572616726177261872619726207262172622726237262472625726267262772628726297263072631726327263372634726357263672637726387263972640726417264272643726447264572646726477264872649726507265172652726537265472655726567265772658726597266072661726627266372664726657266672667726687266972670726717267272673726747267572676726777267872679726807268172682726837268472685726867268772688726897269072691726927269372694726957269672697726987269972700727017270272703727047270572706727077270872709727107271172712727137271472715727167271772718727197272072721727227272372724727257272672727727287272972730727317273272733727347273572736727377273872739727407274172742727437274472745727467274772748727497275072751727527275372754727557275672757727587275972760727617276272763727647276572766727677276872769727707277172772727737277472775727767277772778727797278072781727827278372784727857278672787727887278972790727917279272793727947279572796727977279872799728007280172802728037280472805728067280772808728097281072811728127281372814728157281672817728187281972820728217282272823728247282572826728277282872829728307283172832728337283472835728367283772838728397284072841728427284372844728457284672847728487284972850728517285272853728547285572856728577285872859728607286172862728637286472865728667286772868728697287072871728727287372874728757287672877728787287972880728817288272883728847288572886728877288872889728907289172892728937289472895728967289772898728997290072901729027290372904729057290672907729087290972910729117291272913729147291572916729177291872919729207292172922729237292472925729267292772928729297293072931729327293372934729357293672937729387293972940729417294272943729447294572946729477294872949729507295172952729537295472955729567295772958729597296072961729627296372964729657296672967729687296972970729717297272973729747297572976729777297872979729807298172982729837298472985729867298772988729897299072991729927299372994729957299672997729987299973000730017300273003730047300573006730077300873009730107301173012730137301473015730167301773018730197302073021730227302373024730257302673027730287302973030730317303273033730347303573036730377303873039730407304173042730437304473045730467304773048730497305073051730527305373054730557305673057730587305973060730617306273063730647306573066730677306873069730707307173072730737307473075730767307773078730797308073081730827308373084730857308673087730887308973090730917309273093730947309573096730977309873099731007310173102731037310473105731067310773108731097311073111731127311373114731157311673117731187311973120731217312273123731247312573126731277312873129731307313173132731337313473135731367313773138731397314073141731427314373144731457314673147731487314973150731517315273153731547315573156731577315873159731607316173162731637316473165731667316773168731697317073171731727317373174731757317673177731787317973180731817318273183731847318573186731877318873189731907319173192731937319473195731967319773198731997320073201732027320373204732057320673207732087320973210732117321273213732147321573216732177321873219732207322173222732237322473225732267322773228732297323073231732327323373234732357323673237732387323973240732417324273243732447324573246732477324873249732507325173252732537325473255732567325773258732597326073261732627326373264732657326673267732687326973270732717327273273732747327573276732777327873279732807328173282732837328473285732867328773288732897329073291732927329373294732957329673297732987329973300733017330273303733047330573306733077330873309733107331173312733137331473315733167331773318733197332073321733227332373324733257332673327733287332973330733317333273333733347333573336733377333873339733407334173342733437334473345733467334773348733497335073351733527335373354733557335673357733587335973360733617336273363733647336573366733677336873369733707337173372733737337473375733767337773378733797338073381733827338373384733857338673387733887338973390733917339273393733947339573396733977339873399734007340173402734037340473405734067340773408734097341073411734127341373414734157341673417734187341973420734217342273423734247342573426734277342873429734307343173432734337343473435734367343773438734397344073441734427344373444734457344673447734487344973450734517345273453734547345573456734577345873459734607346173462734637346473465734667346773468734697347073471734727347373474734757347673477734787347973480734817348273483734847348573486734877348873489734907349173492734937349473495734967349773498734997350073501735027350373504735057350673507735087350973510735117351273513735147351573516735177351873519735207352173522735237352473525735267352773528735297353073531735327353373534735357353673537735387353973540735417354273543735447354573546735477354873549735507355173552735537355473555735567355773558735597356073561735627356373564735657356673567735687356973570735717357273573735747357573576735777357873579735807358173582735837358473585735867358773588735897359073591735927359373594735957359673597735987359973600736017360273603736047360573606736077360873609736107361173612736137361473615736167361773618736197362073621736227362373624736257362673627736287362973630736317363273633736347363573636736377363873639736407364173642736437364473645736467364773648736497365073651736527365373654736557365673657736587365973660736617366273663736647366573666736677366873669736707367173672736737367473675736767367773678736797368073681736827368373684736857368673687736887368973690736917369273693736947369573696736977369873699737007370173702737037370473705737067370773708737097371073711737127371373714737157371673717737187371973720737217372273723737247372573726737277372873729737307373173732737337373473735737367373773738737397374073741737427374373744737457374673747737487374973750737517375273753737547375573756737577375873759737607376173762737637376473765737667376773768737697377073771737727377373774737757377673777737787377973780737817378273783737847378573786737877378873789737907379173792737937379473795737967379773798737997380073801738027380373804738057380673807738087380973810738117381273813738147381573816738177381873819738207382173822738237382473825738267382773828738297383073831738327383373834738357383673837738387383973840738417384273843738447384573846738477384873849738507385173852738537385473855738567385773858738597386073861738627386373864738657386673867738687386973870738717387273873738747387573876738777387873879738807388173882738837388473885738867388773888738897389073891738927389373894738957389673897738987389973900739017390273903739047390573906739077390873909739107391173912739137391473915739167391773918739197392073921739227392373924739257392673927739287392973930739317393273933739347393573936739377393873939739407394173942739437394473945739467394773948739497395073951739527395373954739557395673957739587395973960739617396273963739647396573966739677396873969739707397173972739737397473975739767397773978739797398073981739827398373984739857398673987739887398973990739917399273993739947399573996739977399873999740007400174002740037400474005740067400774008740097401074011740127401374014740157401674017740187401974020740217402274023740247402574026740277402874029740307403174032740337403474035740367403774038740397404074041740427404374044740457404674047740487404974050740517405274053740547405574056740577405874059740607406174062740637406474065740667406774068740697407074071740727407374074740757407674077740787407974080740817408274083740847408574086740877408874089740907409174092740937409474095740967409774098740997410074101741027410374104741057410674107741087410974110741117411274113741147411574116741177411874119741207412174122741237412474125741267412774128741297413074131741327413374134741357413674137741387413974140741417414274143741447414574146741477414874149741507415174152741537415474155741567415774158741597416074161741627416374164741657416674167741687416974170741717417274173741747417574176741777417874179741807418174182741837418474185741867418774188741897419074191741927419374194741957419674197741987419974200742017420274203742047420574206742077420874209742107421174212742137421474215742167421774218742197422074221742227422374224742257422674227742287422974230742317423274233742347423574236742377423874239742407424174242742437424474245742467424774248742497425074251742527425374254742557425674257742587425974260742617426274263742647426574266742677426874269742707427174272742737427474275742767427774278742797428074281742827428374284742857428674287742887428974290742917429274293742947429574296742977429874299743007430174302743037430474305743067430774308743097431074311743127431374314743157431674317743187431974320743217432274323743247432574326743277432874329743307433174332743337433474335743367433774338743397434074341743427434374344743457434674347743487434974350743517435274353743547435574356743577435874359743607436174362743637436474365743667436774368743697437074371743727437374374743757437674377743787437974380743817438274383743847438574386743877438874389743907439174392743937439474395743967439774398743997440074401744027440374404744057440674407744087440974410744117441274413744147441574416744177441874419744207442174422744237442474425744267442774428744297443074431744327443374434744357443674437744387443974440744417444274443744447444574446744477444874449744507445174452744537445474455744567445774458744597446074461744627446374464744657446674467744687446974470744717447274473744747447574476744777447874479744807448174482744837448474485744867448774488744897449074491744927449374494744957449674497744987449974500745017450274503745047450574506745077450874509745107451174512745137451474515745167451774518745197452074521745227452374524745257452674527745287452974530745317453274533745347453574536745377453874539745407454174542745437454474545745467454774548745497455074551745527455374554745557455674557745587455974560745617456274563745647456574566745677456874569745707457174572745737457474575745767457774578745797458074581745827458374584745857458674587745887458974590745917459274593745947459574596745977459874599746007460174602746037460474605746067460774608746097461074611746127461374614746157461674617746187461974620746217462274623746247462574626746277462874629746307463174632746337463474635746367463774638746397464074641746427464374644746457464674647746487464974650746517465274653746547465574656746577465874659746607466174662746637466474665746667466774668746697467074671746727467374674746757467674677746787467974680746817468274683746847468574686746877468874689746907469174692746937469474695746967469774698746997470074701747027470374704747057470674707747087470974710747117471274713747147471574716747177471874719747207472174722747237472474725747267472774728747297473074731747327473374734747357473674737747387473974740747417474274743747447474574746747477474874749747507475174752747537475474755747567475774758747597476074761747627476374764747657476674767747687476974770747717477274773747747477574776747777477874779747807478174782747837478474785747867478774788747897479074791747927479374794747957479674797747987479974800748017480274803748047480574806748077480874809748107481174812748137481474815748167481774818748197482074821748227482374824748257482674827748287482974830748317483274833748347483574836748377483874839748407484174842748437484474845748467484774848748497485074851748527485374854748557485674857748587485974860748617486274863748647486574866748677486874869748707487174872748737487474875748767487774878748797488074881748827488374884748857488674887748887488974890748917489274893748947489574896748977489874899749007490174902749037490474905749067490774908749097491074911749127491374914749157491674917749187491974920749217492274923749247492574926749277492874929749307493174932749337493474935749367493774938749397494074941749427494374944749457494674947749487494974950749517495274953749547495574956749577495874959749607496174962749637496474965749667496774968749697497074971749727497374974749757497674977749787497974980749817498274983749847498574986749877498874989749907499174992749937499474995749967499774998749997500075001750027500375004750057500675007750087500975010750117501275013750147501575016750177501875019750207502175022750237502475025750267502775028750297503075031750327503375034750357503675037750387503975040750417504275043750447504575046750477504875049750507505175052750537505475055750567505775058750597506075061750627506375064750657506675067750687506975070750717507275073750747507575076750777507875079750807508175082750837508475085750867508775088750897509075091750927509375094750957509675097750987509975100751017510275103751047510575106751077510875109751107511175112751137511475115751167511775118751197512075121751227512375124751257512675127751287512975130751317513275133751347513575136751377513875139751407514175142751437514475145751467514775148751497515075151751527515375154751557515675157751587515975160751617516275163751647516575166751677516875169751707517175172751737517475175751767517775178751797518075181751827518375184751857518675187751887518975190751917519275193751947519575196751977519875199752007520175202752037520475205752067520775208752097521075211752127521375214752157521675217752187521975220752217522275223752247522575226752277522875229752307523175232752337523475235752367523775238752397524075241752427524375244752457524675247752487524975250752517525275253752547525575256752577525875259752607526175262752637526475265752667526775268752697527075271752727527375274752757527675277752787527975280752817528275283752847528575286752877528875289752907529175292752937529475295752967529775298752997530075301753027530375304753057530675307753087530975310753117531275313753147531575316753177531875319753207532175322753237532475325753267532775328753297533075331753327533375334753357533675337753387533975340753417534275343753447534575346753477534875349753507535175352753537535475355753567535775358753597536075361753627536375364753657536675367753687536975370753717537275373753747537575376753777537875379753807538175382753837538475385753867538775388753897539075391753927539375394753957539675397753987539975400754017540275403754047540575406754077540875409754107541175412754137541475415754167541775418754197542075421754227542375424754257542675427754287542975430754317543275433754347543575436754377543875439754407544175442754437544475445754467544775448754497545075451754527545375454754557545675457754587545975460754617546275463754647546575466754677546875469754707547175472754737547475475754767547775478754797548075481754827548375484754857548675487754887548975490754917549275493754947549575496754977549875499755007550175502755037550475505755067550775508755097551075511755127551375514755157551675517755187551975520755217552275523755247552575526755277552875529755307553175532755337553475535755367553775538755397554075541755427554375544755457554675547755487554975550755517555275553755547555575556755577555875559755607556175562755637556475565755667556775568755697557075571755727557375574755757557675577755787557975580755817558275583755847558575586755877558875589755907559175592755937559475595755967559775598755997560075601756027560375604756057560675607756087560975610756117561275613756147561575616756177561875619756207562175622756237562475625756267562775628756297563075631756327563375634756357563675637756387563975640756417564275643756447564575646756477564875649756507565175652756537565475655756567565775658756597566075661756627566375664756657566675667756687566975670756717567275673756747567575676756777567875679756807568175682756837568475685756867568775688756897569075691756927569375694756957569675697756987569975700757017570275703757047570575706757077570875709757107571175712757137571475715757167571775718757197572075721757227572375724757257572675727757287572975730757317573275733757347573575736757377573875739757407574175742757437574475745757467574775748757497575075751757527575375754757557575675757757587575975760757617576275763757647576575766757677576875769757707577175772757737577475775757767577775778757797578075781757827578375784757857578675787757887578975790757917579275793757947579575796757977579875799758007580175802758037580475805758067580775808758097581075811758127581375814758157581675817758187581975820758217582275823758247582575826758277582875829758307583175832758337583475835758367583775838758397584075841758427584375844758457584675847758487584975850758517585275853758547585575856758577585875859758607586175862758637586475865758667586775868758697587075871758727587375874758757587675877758787587975880758817588275883758847588575886758877588875889758907589175892758937589475895758967589775898758997590075901759027590375904759057590675907759087590975910759117591275913759147591575916759177591875919759207592175922759237592475925759267592775928759297593075931759327593375934759357593675937759387593975940759417594275943759447594575946759477594875949759507595175952759537595475955759567595775958759597596075961759627596375964759657596675967759687596975970759717597275973759747597575976759777597875979759807598175982759837598475985759867598775988759897599075991759927599375994759957599675997759987599976000760017600276003760047600576006760077600876009760107601176012760137601476015760167601776018760197602076021760227602376024760257602676027760287602976030760317603276033760347603576036760377603876039760407604176042760437604476045760467604776048760497605076051760527605376054760557605676057760587605976060760617606276063760647606576066760677606876069760707607176072760737607476075760767607776078760797608076081760827608376084760857608676087760887608976090760917609276093760947609576096760977609876099761007610176102761037610476105761067610776108761097611076111761127611376114761157611676117761187611976120761217612276123761247612576126761277612876129761307613176132761337613476135761367613776138761397614076141761427614376144761457614676147761487614976150761517615276153761547615576156761577615876159761607616176162761637616476165761667616776168761697617076171761727617376174761757617676177761787617976180761817618276183761847618576186761877618876189761907619176192761937619476195761967619776198761997620076201762027620376204762057620676207762087620976210762117621276213762147621576216762177621876219762207622176222762237622476225762267622776228762297623076231762327623376234762357623676237762387623976240762417624276243762447624576246762477624876249762507625176252762537625476255762567625776258762597626076261762627626376264762657626676267762687626976270762717627276273762747627576276762777627876279762807628176282762837628476285762867628776288762897629076291762927629376294762957629676297762987629976300763017630276303763047630576306763077630876309763107631176312763137631476315763167631776318763197632076321763227632376324763257632676327763287632976330763317633276333763347633576336763377633876339763407634176342763437634476345763467634776348763497635076351763527635376354763557635676357763587635976360763617636276363763647636576366763677636876369763707637176372763737637476375763767637776378763797638076381763827638376384763857638676387763887638976390763917639276393763947639576396763977639876399764007640176402764037640476405764067640776408764097641076411764127641376414764157641676417764187641976420764217642276423764247642576426764277642876429764307643176432764337643476435764367643776438764397644076441764427644376444764457644676447764487644976450764517645276453764547645576456764577645876459764607646176462764637646476465764667646776468764697647076471764727647376474764757647676477764787647976480764817648276483764847648576486764877648876489764907649176492764937649476495764967649776498764997650076501765027650376504765057650676507765087650976510765117651276513765147651576516765177651876519765207652176522765237652476525765267652776528765297653076531765327653376534765357653676537765387653976540765417654276543765447654576546765477654876549765507655176552765537655476555765567655776558765597656076561765627656376564765657656676567765687656976570765717657276573765747657576576765777657876579765807658176582765837658476585765867658776588765897659076591765927659376594765957659676597765987659976600766017660276603766047660576606766077660876609766107661176612766137661476615766167661776618766197662076621766227662376624766257662676627766287662976630766317663276633766347663576636766377663876639766407664176642766437664476645766467664776648766497665076651766527665376654766557665676657766587665976660766617666276663766647666576666766677666876669766707667176672766737667476675766767667776678766797668076681766827668376684766857668676687766887668976690766917669276693766947669576696766977669876699767007670176702767037670476705767067670776708767097671076711767127671376714767157671676717767187671976720767217672276723767247672576726767277672876729767307673176732767337673476735767367673776738767397674076741767427674376744767457674676747767487674976750767517675276753767547675576756767577675876759767607676176762767637676476765767667676776768767697677076771767727677376774767757677676777767787677976780767817678276783767847678576786767877678876789767907679176792767937679476795767967679776798767997680076801768027680376804768057680676807768087680976810768117681276813768147681576816768177681876819768207682176822768237682476825768267682776828768297683076831768327683376834768357683676837768387683976840768417684276843768447684576846768477684876849768507685176852768537685476855768567685776858768597686076861768627686376864768657686676867768687686976870768717687276873768747687576876768777687876879768807688176882768837688476885768867688776888768897689076891768927689376894768957689676897768987689976900769017690276903769047690576906769077690876909769107691176912769137691476915769167691776918769197692076921769227692376924769257692676927769287692976930769317693276933769347693576936769377693876939769407694176942769437694476945769467694776948769497695076951769527695376954769557695676957769587695976960769617696276963769647696576966769677696876969769707697176972769737697476975769767697776978769797698076981769827698376984769857698676987769887698976990769917699276993769947699576996769977699876999770007700177002770037700477005770067700777008770097701077011770127701377014770157701677017770187701977020770217702277023770247702577026770277702877029770307703177032770337703477035770367703777038770397704077041770427704377044770457704677047770487704977050770517705277053770547705577056770577705877059770607706177062770637706477065770667706777068770697707077071770727707377074770757707677077770787707977080770817708277083770847708577086770877708877089770907709177092770937709477095770967709777098770997710077101771027710377104771057710677107771087710977110771117711277113771147711577116771177711877119771207712177122771237712477125771267712777128771297713077131771327713377134771357713677137771387713977140771417714277143771447714577146771477714877149771507715177152771537715477155771567715777158771597716077161771627716377164771657716677167771687716977170771717717277173771747717577176771777717877179771807718177182771837718477185771867718777188771897719077191771927719377194771957719677197771987719977200772017720277203772047720577206772077720877209772107721177212772137721477215772167721777218772197722077221772227722377224772257722677227772287722977230772317723277233772347723577236772377723877239772407724177242772437724477245772467724777248772497725077251772527725377254772557725677257772587725977260772617726277263772647726577266772677726877269772707727177272772737727477275772767727777278772797728077281772827728377284772857728677287772887728977290772917729277293772947729577296772977729877299773007730177302773037730477305773067730777308773097731077311773127731377314773157731677317773187731977320773217732277323773247732577326773277732877329773307733177332773337733477335773367733777338773397734077341773427734377344773457734677347773487734977350773517735277353773547735577356773577735877359773607736177362773637736477365773667736777368773697737077371773727737377374773757737677377773787737977380773817738277383773847738577386773877738877389773907739177392773937739477395773967739777398773997740077401774027740377404774057740677407774087740977410774117741277413774147741577416774177741877419774207742177422774237742477425774267742777428774297743077431774327743377434774357743677437774387743977440774417744277443774447744577446774477744877449774507745177452774537745477455774567745777458774597746077461774627746377464774657746677467774687746977470774717747277473774747747577476774777747877479774807748177482774837748477485774867748777488774897749077491774927749377494774957749677497774987749977500775017750277503775047750577506775077750877509775107751177512775137751477515775167751777518775197752077521775227752377524775257752677527775287752977530775317753277533775347753577536775377753877539775407754177542775437754477545775467754777548775497755077551775527755377554775557755677557775587755977560775617756277563775647756577566775677756877569775707757177572775737757477575775767757777578775797758077581775827758377584775857758677587775887758977590775917759277593775947759577596775977759877599776007760177602776037760477605776067760777608776097761077611776127761377614776157761677617776187761977620776217762277623776247762577626776277762877629776307763177632776337763477635776367763777638776397764077641776427764377644776457764677647776487764977650776517765277653776547765577656776577765877659776607766177662776637766477665776667766777668776697767077671776727767377674776757767677677776787767977680776817768277683776847768577686776877768877689776907769177692776937769477695776967769777698776997770077701777027770377704777057770677707777087770977710777117771277713777147771577716777177771877719777207772177722777237772477725777267772777728777297773077731777327773377734777357773677737777387773977740777417774277743777447774577746777477774877749777507775177752777537775477755777567775777758777597776077761777627776377764777657776677767777687776977770777717777277773777747777577776777777777877779777807778177782777837778477785777867778777788777897779077791777927779377794777957779677797777987779977800778017780277803778047780577806778077780877809778107781177812778137781477815778167781777818778197782077821778227782377824778257782677827778287782977830778317783277833778347783577836778377783877839778407784177842778437784477845778467784777848778497785077851778527785377854778557785677857778587785977860778617786277863778647786577866778677786877869778707787177872778737787477875778767787777878778797788077881778827788377884778857788677887778887788977890778917789277893778947789577896778977789877899779007790177902779037790477905779067790777908779097791077911779127791377914779157791677917779187791977920779217792277923779247792577926779277792877929779307793177932779337793477935779367793777938779397794077941779427794377944779457794677947779487794977950779517795277953779547795577956779577795877959779607796177962779637796477965779667796777968779697797077971779727797377974779757797677977779787797977980779817798277983779847798577986779877798877989779907799177992779937799477995779967799777998779997800078001780027800378004780057800678007780087800978010780117801278013780147801578016780177801878019780207802178022780237802478025780267802778028780297803078031780327803378034780357803678037780387803978040780417804278043780447804578046780477804878049780507805178052780537805478055780567805778058780597806078061780627806378064780657806678067780687806978070780717807278073780747807578076780777807878079780807808178082780837808478085780867808778088780897809078091780927809378094780957809678097780987809978100781017810278103781047810578106781077810878109781107811178112781137811478115781167811778118781197812078121781227812378124781257812678127781287812978130781317813278133781347813578136781377813878139781407814178142781437814478145781467814778148781497815078151781527815378154781557815678157781587815978160781617816278163781647816578166781677816878169781707817178172781737817478175781767817778178781797818078181781827818378184781857818678187781887818978190781917819278193781947819578196781977819878199782007820178202782037820478205782067820778208782097821078211782127821378214782157821678217782187821978220782217822278223782247822578226782277822878229782307823178232782337823478235782367823778238782397824078241782427824378244782457824678247782487824978250782517825278253782547825578256782577825878259782607826178262782637826478265782667826778268782697827078271782727827378274782757827678277782787827978280782817828278283782847828578286782877828878289782907829178292782937829478295782967829778298782997830078301783027830378304783057830678307783087830978310783117831278313783147831578316783177831878319783207832178322783237832478325783267832778328783297833078331783327833378334783357833678337783387833978340783417834278343783447834578346783477834878349783507835178352783537835478355783567835778358783597836078361783627836378364783657836678367783687836978370783717837278373783747837578376783777837878379783807838178382783837838478385783867838778388783897839078391783927839378394783957839678397783987839978400784017840278403784047840578406784077840878409784107841178412784137841478415784167841778418784197842078421784227842378424784257842678427784287842978430784317843278433784347843578436784377843878439784407844178442784437844478445784467844778448784497845078451784527845378454784557845678457784587845978460784617846278463784647846578466784677846878469784707847178472784737847478475784767847778478784797848078481784827848378484784857848678487784887848978490784917849278493784947849578496784977849878499785007850178502785037850478505785067850778508785097851078511785127851378514785157851678517785187851978520785217852278523785247852578526785277852878529785307853178532785337853478535785367853778538785397854078541785427854378544785457854678547785487854978550785517855278553785547855578556785577855878559785607856178562785637856478565785667856778568785697857078571785727857378574785757857678577785787857978580785817858278583785847858578586785877858878589785907859178592785937859478595785967859778598785997860078601786027860378604786057860678607786087860978610786117861278613786147861578616786177861878619786207862178622786237862478625786267862778628786297863078631786327863378634786357863678637786387863978640786417864278643786447864578646786477864878649786507865178652786537865478655786567865778658786597866078661786627866378664786657866678667786687866978670786717867278673786747867578676786777867878679786807868178682786837868478685786867868778688786897869078691786927869378694786957869678697786987869978700787017870278703787047870578706787077870878709787107871178712787137871478715787167871778718787197872078721787227872378724787257872678727787287872978730787317873278733787347873578736787377873878739787407874178742787437874478745787467874778748787497875078751787527875378754787557875678757787587875978760787617876278763787647876578766787677876878769787707877178772787737877478775787767877778778787797878078781787827878378784787857878678787787887878978790787917879278793787947879578796787977879878799788007880178802788037880478805788067880778808788097881078811788127881378814788157881678817788187881978820788217882278823788247882578826788277882878829788307883178832788337883478835788367883778838788397884078841788427884378844788457884678847788487884978850788517885278853788547885578856788577885878859788607886178862788637886478865788667886778868788697887078871788727887378874788757887678877788787887978880788817888278883788847888578886788877888878889788907889178892788937889478895788967889778898788997890078901789027890378904789057890678907789087890978910789117891278913789147891578916789177891878919789207892178922789237892478925789267892778928789297893078931789327893378934789357893678937789387893978940789417894278943789447894578946789477894878949789507895178952789537895478955789567895778958789597896078961789627896378964789657896678967789687896978970789717897278973789747897578976789777897878979789807898178982789837898478985789867898778988789897899078991789927899378994789957899678997789987899979000790017900279003790047900579006790077900879009790107901179012790137901479015790167901779018790197902079021790227902379024790257902679027790287902979030790317903279033790347903579036790377903879039790407904179042790437904479045790467904779048790497905079051790527905379054790557905679057790587905979060790617906279063790647906579066790677906879069790707907179072790737907479075790767907779078790797908079081790827908379084790857908679087790887908979090790917909279093790947909579096790977909879099791007910179102791037910479105791067910779108791097911079111791127911379114791157911679117791187911979120791217912279123791247912579126791277912879129791307913179132791337913479135791367913779138791397914079141791427914379144791457914679147791487914979150791517915279153791547915579156791577915879159791607916179162791637916479165791667916779168791697917079171791727917379174791757917679177791787917979180791817918279183791847918579186791877918879189791907919179192791937919479195791967919779198791997920079201792027920379204792057920679207792087920979210792117921279213792147921579216792177921879219792207922179222792237922479225792267922779228792297923079231792327923379234792357923679237792387923979240792417924279243792447924579246792477924879249792507925179252792537925479255792567925779258792597926079261792627926379264792657926679267792687926979270792717927279273792747927579276792777927879279792807928179282792837928479285792867928779288792897929079291792927929379294792957929679297792987929979300793017930279303793047930579306793077930879309793107931179312793137931479315793167931779318793197932079321793227932379324793257932679327793287932979330793317933279333793347933579336793377933879339793407934179342793437934479345793467934779348793497935079351793527935379354793557935679357793587935979360793617936279363793647936579366793677936879369793707937179372793737937479375793767937779378793797938079381793827938379384793857938679387793887938979390793917939279393793947939579396793977939879399794007940179402794037940479405794067940779408794097941079411794127941379414794157941679417794187941979420794217942279423794247942579426794277942879429794307943179432794337943479435794367943779438794397944079441794427944379444794457944679447794487944979450794517945279453794547945579456794577945879459794607946179462794637946479465794667946779468794697947079471794727947379474794757947679477794787947979480794817948279483794847948579486794877948879489794907949179492794937949479495794967949779498794997950079501795027950379504795057950679507795087950979510795117951279513795147951579516795177951879519795207952179522795237952479525795267952779528795297953079531795327953379534795357953679537795387953979540795417954279543795447954579546795477954879549795507955179552795537955479555795567955779558795597956079561795627956379564795657956679567795687956979570795717957279573795747957579576795777957879579795807958179582795837958479585795867958779588795897959079591795927959379594795957959679597795987959979600796017960279603796047960579606796077960879609796107961179612796137961479615796167961779618796197962079621796227962379624796257962679627796287962979630796317963279633796347963579636796377963879639796407964179642796437964479645796467964779648796497965079651796527965379654796557965679657796587965979660796617966279663796647966579666796677966879669796707967179672796737967479675796767967779678796797968079681796827968379684796857968679687796887968979690796917969279693796947969579696796977969879699797007970179702797037970479705797067970779708797097971079711797127971379714797157971679717797187971979720797217972279723797247972579726797277972879729797307973179732797337973479735797367973779738797397974079741797427974379744797457974679747797487974979750797517975279753797547975579756797577975879759797607976179762797637976479765797667976779768797697977079771797727977379774797757977679777797787977979780797817978279783797847978579786797877978879789797907979179792797937979479795797967979779798797997980079801798027980379804798057980679807798087980979810798117981279813798147981579816798177981879819798207982179822798237982479825798267982779828798297983079831798327983379834798357983679837798387983979840798417984279843798447984579846798477984879849798507985179852798537985479855798567985779858798597986079861798627986379864798657986679867798687986979870798717987279873798747987579876798777987879879798807988179882798837988479885798867988779888798897989079891798927989379894798957989679897798987989979900799017990279903799047990579906799077990879909799107991179912799137991479915799167991779918799197992079921799227992379924799257992679927799287992979930799317993279933799347993579936799377993879939799407994179942799437994479945799467994779948799497995079951799527995379954799557995679957799587995979960799617996279963799647996579966799677996879969799707997179972799737997479975799767997779978799797998079981799827998379984799857998679987799887998979990799917999279993799947999579996799977999879999800008000180002800038000480005800068000780008800098001080011800128001380014800158001680017800188001980020800218002280023800248002580026800278002880029800308003180032800338003480035800368003780038800398004080041800428004380044800458004680047800488004980050800518005280053800548005580056800578005880059800608006180062800638006480065800668006780068800698007080071800728007380074800758007680077800788007980080800818008280083800848008580086800878008880089800908009180092800938009480095800968009780098800998010080101801028010380104801058010680107801088010980110801118011280113801148011580116801178011880119801208012180122801238012480125801268012780128801298013080131801328013380134801358013680137801388013980140801418014280143801448014580146801478014880149801508015180152801538015480155801568015780158801598016080161801628016380164801658016680167801688016980170801718017280173801748017580176801778017880179801808018180182801838018480185801868018780188801898019080191801928019380194801958019680197801988019980200802018020280203802048020580206802078020880209802108021180212802138021480215802168021780218802198022080221802228022380224802258022680227802288022980230802318023280233802348023580236802378023880239802408024180242802438024480245802468024780248802498025080251802528025380254802558025680257802588025980260802618026280263802648026580266802678026880269802708027180272802738027480275802768027780278802798028080281802828028380284802858028680287802888028980290802918029280293802948029580296802978029880299803008030180302803038030480305803068030780308803098031080311803128031380314803158031680317803188031980320803218032280323803248032580326803278032880329803308033180332803338033480335803368033780338803398034080341803428034380344803458034680347803488034980350803518035280353803548035580356803578035880359803608036180362803638036480365803668036780368803698037080371803728037380374803758037680377803788037980380803818038280383803848038580386803878038880389803908039180392803938039480395803968039780398803998040080401804028040380404804058040680407804088040980410804118041280413804148041580416804178041880419804208042180422804238042480425804268042780428804298043080431804328043380434804358043680437804388043980440804418044280443804448044580446804478044880449804508045180452804538045480455804568045780458804598046080461804628046380464804658046680467804688046980470804718047280473804748047580476804778047880479804808048180482804838048480485804868048780488804898049080491804928049380494804958049680497804988049980500805018050280503805048050580506805078050880509805108051180512805138051480515805168051780518805198052080521805228052380524805258052680527805288052980530805318053280533805348053580536805378053880539805408054180542805438054480545805468054780548805498055080551805528055380554805558055680557805588055980560805618056280563805648056580566805678056880569805708057180572805738057480575805768057780578805798058080581805828058380584805858058680587805888058980590805918059280593805948059580596805978059880599806008060180602806038060480605806068060780608806098061080611806128061380614806158061680617806188061980620806218062280623806248062580626806278062880629806308063180632806338063480635806368063780638806398064080641806428064380644806458064680647806488064980650806518065280653806548065580656806578065880659806608066180662806638066480665806668066780668806698067080671806728067380674806758067680677806788067980680806818068280683806848068580686806878068880689806908069180692806938069480695806968069780698806998070080701807028070380704807058070680707807088070980710807118071280713807148071580716807178071880719807208072180722807238072480725807268072780728807298073080731807328073380734807358073680737807388073980740807418074280743807448074580746807478074880749807508075180752807538075480755807568075780758807598076080761807628076380764807658076680767807688076980770807718077280773807748077580776807778077880779807808078180782807838078480785807868078780788807898079080791807928079380794807958079680797807988079980800808018080280803808048080580806808078080880809808108081180812808138081480815808168081780818808198082080821808228082380824808258082680827808288082980830808318083280833808348083580836808378083880839808408084180842808438084480845808468084780848808498085080851808528085380854808558085680857808588085980860808618086280863808648086580866808678086880869808708087180872808738087480875808768087780878808798088080881808828088380884808858088680887808888088980890808918089280893808948089580896808978089880899809008090180902809038090480905809068090780908809098091080911809128091380914809158091680917809188091980920809218092280923809248092580926809278092880929809308093180932809338093480935809368093780938809398094080941809428094380944809458094680947809488094980950809518095280953809548095580956809578095880959809608096180962809638096480965809668096780968809698097080971809728097380974809758097680977809788097980980809818098280983809848098580986809878098880989809908099180992809938099480995809968099780998809998100081001810028100381004810058100681007810088100981010810118101281013810148101581016810178101881019810208102181022810238102481025810268102781028810298103081031810328103381034810358103681037810388103981040810418104281043810448104581046810478104881049810508105181052810538105481055810568105781058810598106081061810628106381064810658106681067810688106981070810718107281073810748107581076810778107881079810808108181082810838108481085810868108781088810898109081091810928109381094810958109681097810988109981100811018110281103811048110581106811078110881109811108111181112811138111481115811168111781118811198112081121811228112381124811258112681127811288112981130811318113281133811348113581136811378113881139811408114181142811438114481145811468114781148811498115081151811528115381154811558115681157811588115981160811618116281163811648116581166811678116881169811708117181172811738117481175811768117781178811798118081181811828118381184811858118681187811888118981190811918119281193811948119581196811978119881199812008120181202812038120481205812068120781208812098121081211812128121381214812158121681217812188121981220812218122281223812248122581226812278122881229812308123181232812338123481235812368123781238812398124081241812428124381244812458124681247812488124981250812518125281253812548125581256812578125881259812608126181262812638126481265812668126781268812698127081271812728127381274812758127681277812788127981280812818128281283812848128581286812878128881289812908129181292812938129481295812968129781298812998130081301813028130381304813058130681307813088130981310813118131281313813148131581316813178131881319813208132181322813238132481325813268132781328813298133081331813328133381334813358133681337813388133981340813418134281343813448134581346813478134881349813508135181352813538135481355813568135781358813598136081361813628136381364813658136681367813688136981370813718137281373813748137581376813778137881379813808138181382813838138481385813868138781388813898139081391813928139381394813958139681397813988139981400814018140281403814048140581406814078140881409814108141181412814138141481415814168141781418814198142081421814228142381424814258142681427814288142981430814318143281433814348143581436814378143881439814408144181442814438144481445814468144781448814498145081451814528145381454814558145681457814588145981460814618146281463814648146581466814678146881469814708147181472814738147481475814768147781478814798148081481814828148381484814858148681487814888148981490814918149281493814948149581496814978149881499815008150181502815038150481505815068150781508815098151081511815128151381514815158151681517815188151981520815218152281523815248152581526815278152881529815308153181532815338153481535815368153781538815398154081541815428154381544815458154681547815488154981550815518155281553815548155581556815578155881559815608156181562815638156481565815668156781568815698157081571815728157381574815758157681577815788157981580815818158281583815848158581586815878158881589815908159181592815938159481595815968159781598815998160081601816028160381604816058160681607816088160981610816118161281613816148161581616816178161881619816208162181622816238162481625816268162781628816298163081631816328163381634816358163681637816388163981640816418164281643816448164581646816478164881649816508165181652816538165481655816568165781658816598166081661816628166381664816658166681667816688166981670816718167281673816748167581676816778167881679816808168181682816838168481685816868168781688816898169081691816928169381694816958169681697816988169981700817018170281703817048170581706817078170881709817108171181712817138171481715817168171781718817198172081721817228172381724817258172681727817288172981730817318173281733817348173581736817378173881739817408174181742817438174481745817468174781748817498175081751817528175381754817558175681757817588175981760817618176281763817648176581766817678176881769817708177181772817738177481775817768177781778817798178081781817828178381784817858178681787817888178981790817918179281793817948179581796817978179881799818008180181802818038180481805818068180781808818098181081811818128181381814818158181681817818188181981820818218182281823818248182581826818278182881829818308183181832818338183481835818368183781838818398184081841818428184381844818458184681847818488184981850818518185281853818548185581856818578185881859818608186181862818638186481865818668186781868818698187081871818728187381874818758187681877818788187981880818818188281883818848188581886818878188881889818908189181892818938189481895818968189781898818998190081901819028190381904819058190681907819088190981910819118191281913819148191581916819178191881919819208192181922819238192481925819268192781928819298193081931819328193381934819358193681937819388193981940819418194281943819448194581946819478194881949819508195181952819538195481955819568195781958819598196081961819628196381964819658196681967819688196981970819718197281973819748197581976819778197881979819808198181982819838198481985819868198781988819898199081991819928199381994819958199681997819988199982000820018200282003820048200582006820078200882009820108201182012820138201482015820168201782018820198202082021820228202382024820258202682027820288202982030820318203282033820348203582036820378203882039820408204182042820438204482045820468204782048820498205082051820528205382054820558205682057820588205982060820618206282063820648206582066820678206882069820708207182072820738207482075820768207782078820798208082081820828208382084820858208682087820888208982090820918209282093820948209582096820978209882099821008210182102821038210482105821068210782108821098211082111821128211382114821158211682117821188211982120821218212282123821248212582126821278212882129821308213182132821338213482135821368213782138821398214082141821428214382144821458214682147821488214982150821518215282153821548215582156821578215882159821608216182162821638216482165821668216782168821698217082171821728217382174821758217682177821788217982180821818218282183821848218582186821878218882189821908219182192821938219482195821968219782198821998220082201822028220382204822058220682207822088220982210822118221282213822148221582216822178221882219822208222182222822238222482225822268222782228822298223082231822328223382234822358223682237822388223982240822418224282243822448224582246822478224882249822508225182252822538225482255822568225782258822598226082261822628226382264822658226682267822688226982270822718227282273822748227582276822778227882279822808228182282822838228482285822868228782288822898229082291822928229382294822958229682297822988229982300823018230282303823048230582306823078230882309823108231182312823138231482315823168231782318823198232082321823228232382324823258232682327823288232982330823318233282333823348233582336823378233882339823408234182342823438234482345823468234782348823498235082351823528235382354823558235682357823588235982360823618236282363823648236582366823678236882369823708237182372823738237482375823768237782378823798238082381823828238382384823858238682387823888238982390823918239282393823948239582396823978239882399824008240182402824038240482405824068240782408824098241082411824128241382414824158241682417824188241982420824218242282423824248242582426824278242882429824308243182432824338243482435824368243782438824398244082441824428244382444824458244682447824488244982450824518245282453824548245582456824578245882459824608246182462824638246482465824668246782468824698247082471824728247382474824758247682477824788247982480824818248282483824848248582486824878248882489824908249182492824938249482495824968249782498824998250082501825028250382504825058250682507825088250982510825118251282513825148251582516825178251882519825208252182522825238252482525825268252782528825298253082531825328253382534825358253682537825388253982540825418254282543825448254582546825478254882549825508255182552825538255482555825568255782558825598256082561825628256382564825658256682567825688256982570825718257282573825748257582576825778257882579825808258182582825838258482585825868258782588825898259082591825928259382594825958259682597825988259982600826018260282603826048260582606826078260882609826108261182612826138261482615826168261782618826198262082621826228262382624826258262682627826288262982630826318263282633826348263582636826378263882639826408264182642826438264482645826468264782648826498265082651826528265382654826558265682657826588265982660826618266282663826648266582666826678266882669826708267182672826738267482675826768267782678826798268082681826828268382684826858268682687826888268982690826918269282693826948269582696826978269882699827008270182702827038270482705827068270782708827098271082711827128271382714827158271682717827188271982720827218272282723827248272582726827278272882729827308273182732827338273482735827368273782738827398274082741827428274382744827458274682747827488274982750827518275282753827548275582756827578275882759827608276182762827638276482765827668276782768827698277082771827728277382774827758277682777827788277982780827818278282783827848278582786827878278882789827908279182792827938279482795827968279782798827998280082801828028280382804828058280682807828088280982810828118281282813828148281582816828178281882819828208282182822828238282482825828268282782828828298283082831828328283382834828358283682837828388283982840828418284282843828448284582846828478284882849828508285182852828538285482855828568285782858828598286082861828628286382864828658286682867828688286982870828718287282873828748287582876828778287882879828808288182882828838288482885828868288782888828898289082891828928289382894828958289682897828988289982900829018290282903829048290582906829078290882909829108291182912829138291482915829168291782918829198292082921829228292382924829258292682927829288292982930829318293282933829348293582936829378293882939829408294182942829438294482945829468294782948829498295082951829528295382954829558295682957829588295982960829618296282963829648296582966829678296882969829708297182972829738297482975829768297782978829798298082981829828298382984829858298682987829888298982990829918299282993829948299582996829978299882999830008300183002830038300483005830068300783008830098301083011830128301383014830158301683017830188301983020830218302283023830248302583026830278302883029830308303183032830338303483035830368303783038830398304083041830428304383044830458304683047830488304983050830518305283053830548305583056830578305883059830608306183062830638306483065830668306783068830698307083071830728307383074830758307683077830788307983080830818308283083830848308583086830878308883089830908309183092830938309483095830968309783098830998310083101831028310383104831058310683107831088310983110831118311283113831148311583116831178311883119831208312183122831238312483125831268312783128831298313083131831328313383134831358313683137831388313983140831418314283143831448314583146831478314883149831508315183152831538315483155831568315783158831598316083161831628316383164831658316683167831688316983170831718317283173831748317583176831778317883179831808318183182831838318483185831868318783188831898319083191831928319383194831958319683197831988319983200832018320283203832048320583206832078320883209832108321183212832138321483215832168321783218832198322083221832228322383224832258322683227832288322983230832318323283233832348323583236832378323883239832408324183242832438324483245832468324783248832498325083251832528325383254832558325683257832588325983260832618326283263832648326583266832678326883269832708327183272832738327483275832768327783278832798328083281832828328383284832858328683287832888328983290832918329283293832948329583296832978329883299833008330183302833038330483305833068330783308833098331083311833128331383314833158331683317833188331983320833218332283323833248332583326833278332883329833308333183332833338333483335833368333783338833398334083341833428334383344833458334683347833488334983350833518335283353833548335583356833578335883359833608336183362833638336483365833668336783368833698337083371833728337383374833758337683377833788337983380833818338283383833848338583386833878338883389833908339183392833938339483395833968339783398833998340083401834028340383404834058340683407834088340983410834118341283413834148341583416834178341883419834208342183422834238342483425834268342783428834298343083431834328343383434834358343683437834388343983440834418344283443834448344583446834478344883449834508345183452834538345483455834568345783458834598346083461834628346383464834658346683467834688346983470834718347283473834748347583476834778347883479834808348183482834838348483485834868348783488834898349083491834928349383494834958349683497834988349983500835018350283503835048350583506835078350883509835108351183512835138351483515835168351783518835198352083521835228352383524835258352683527835288352983530835318353283533835348353583536835378353883539835408354183542835438354483545835468354783548835498355083551835528355383554835558355683557835588355983560835618356283563835648356583566835678356883569835708357183572835738357483575835768357783578835798358083581835828358383584835858358683587835888358983590835918359283593835948359583596835978359883599836008360183602836038360483605836068360783608836098361083611836128361383614836158361683617836188361983620836218362283623836248362583626836278362883629836308363183632836338363483635836368363783638836398364083641836428364383644836458364683647836488364983650836518365283653836548365583656836578365883659836608366183662836638366483665836668366783668836698367083671836728367383674836758367683677836788367983680836818368283683836848368583686836878368883689836908369183692836938369483695836968369783698836998370083701837028370383704837058370683707837088370983710837118371283713837148371583716837178371883719837208372183722837238372483725837268372783728837298373083731837328373383734837358373683737837388373983740837418374283743837448374583746837478374883749837508375183752837538375483755837568375783758837598376083761837628376383764837658376683767837688376983770837718377283773837748377583776837778377883779837808378183782837838378483785837868378783788837898379083791837928379383794837958379683797837988379983800838018380283803838048380583806838078380883809838108381183812838138381483815838168381783818838198382083821838228382383824838258382683827838288382983830838318383283833838348383583836838378383883839838408384183842838438384483845838468384783848838498385083851838528385383854838558385683857838588385983860838618386283863838648386583866838678386883869838708387183872838738387483875838768387783878838798388083881838828388383884838858388683887838888388983890838918389283893838948389583896838978389883899839008390183902839038390483905839068390783908839098391083911839128391383914839158391683917839188391983920839218392283923839248392583926839278392883929839308393183932839338393483935839368393783938839398394083941839428394383944839458394683947839488394983950839518395283953839548395583956839578395883959839608396183962839638396483965839668396783968839698397083971839728397383974839758397683977839788397983980839818398283983839848398583986839878398883989839908399183992839938399483995839968399783998839998400084001840028400384004840058400684007840088400984010840118401284013840148401584016840178401884019840208402184022840238402484025840268402784028840298403084031840328403384034840358403684037840388403984040840418404284043840448404584046840478404884049840508405184052840538405484055840568405784058840598406084061840628406384064840658406684067840688406984070840718407284073840748407584076840778407884079840808408184082840838408484085840868408784088840898409084091840928409384094840958409684097840988409984100841018410284103841048410584106841078410884109841108411184112841138411484115841168411784118841198412084121841228412384124841258412684127841288412984130841318413284133841348413584136841378413884139841408414184142841438414484145841468414784148841498415084151841528415384154841558415684157841588415984160841618416284163841648416584166841678416884169841708417184172841738417484175841768417784178841798418084181841828418384184841858418684187841888418984190841918419284193841948419584196841978419884199842008420184202842038420484205842068420784208842098421084211842128421384214842158421684217842188421984220842218422284223842248422584226842278422884229842308423184232842338423484235842368423784238842398424084241842428424384244842458424684247842488424984250842518425284253842548425584256842578425884259842608426184262842638426484265842668426784268842698427084271842728427384274842758427684277842788427984280842818428284283842848428584286842878428884289842908429184292842938429484295842968429784298842998430084301843028430384304843058430684307843088430984310843118431284313843148431584316843178431884319843208432184322843238432484325843268432784328843298433084331843328433384334843358433684337843388433984340843418434284343843448434584346843478434884349843508435184352843538435484355843568435784358843598436084361843628436384364843658436684367843688436984370843718437284373843748437584376843778437884379843808438184382843838438484385843868438784388843898439084391843928439384394843958439684397843988439984400844018440284403844048440584406844078440884409844108441184412844138441484415844168441784418844198442084421844228442384424844258442684427844288442984430844318443284433844348443584436844378443884439844408444184442844438444484445844468444784448844498445084451844528445384454844558445684457844588445984460844618446284463844648446584466844678446884469844708447184472844738447484475844768447784478844798448084481844828448384484844858448684487844888448984490844918449284493844948449584496844978449884499845008450184502845038450484505845068450784508845098451084511845128451384514845158451684517845188451984520845218452284523845248452584526845278452884529845308453184532845338453484535845368453784538845398454084541845428454384544845458454684547845488454984550845518455284553845548455584556845578455884559845608456184562845638456484565845668456784568845698457084571845728457384574845758457684577845788457984580845818458284583845848458584586845878458884589845908459184592845938459484595845968459784598845998460084601846028460384604846058460684607846088460984610846118461284613846148461584616846178461884619846208462184622846238462484625846268462784628846298463084631846328463384634846358463684637846388463984640846418464284643846448464584646846478464884649846508465184652846538465484655846568465784658846598466084661846628466384664846658466684667846688466984670846718467284673846748467584676846778467884679846808468184682846838468484685846868468784688846898469084691846928469384694846958469684697846988469984700847018470284703847048470584706847078470884709847108471184712847138471484715847168471784718847198472084721847228472384724847258472684727847288472984730847318473284733847348473584736847378473884739847408474184742847438474484745847468474784748847498475084751847528475384754847558475684757847588475984760847618476284763847648476584766847678476884769847708477184772847738477484775847768477784778847798478084781847828478384784847858478684787847888478984790847918479284793847948479584796847978479884799848008480184802848038480484805848068480784808848098481084811848128481384814848158481684817848188481984820848218482284823848248482584826848278482884829848308483184832848338483484835848368483784838848398484084841848428484384844848458484684847848488484984850848518485284853848548485584856848578485884859848608486184862848638486484865848668486784868848698487084871848728487384874848758487684877848788487984880848818488284883848848488584886848878488884889848908489184892848938489484895848968489784898848998490084901849028490384904849058490684907849088490984910849118491284913849148491584916849178491884919849208492184922849238492484925849268492784928849298493084931849328493384934849358493684937849388493984940849418494284943849448494584946849478494884949849508495184952849538495484955849568495784958849598496084961849628496384964849658496684967849688496984970849718497284973849748497584976849778497884979849808498184982849838498484985849868498784988849898499084991849928499384994849958499684997849988499985000850018500285003850048500585006850078500885009850108501185012850138501485015850168501785018850198502085021850228502385024850258502685027850288502985030850318503285033850348503585036850378503885039850408504185042850438504485045850468504785048850498505085051850528505385054850558505685057850588505985060850618506285063850648506585066850678506885069850708507185072850738507485075850768507785078850798508085081850828508385084850858508685087850888508985090850918509285093850948509585096850978509885099851008510185102851038510485105851068510785108851098511085111851128511385114851158511685117851188511985120851218512285123851248512585126851278512885129851308513185132851338513485135851368513785138851398514085141851428514385144851458514685147851488514985150851518515285153851548515585156851578515885159851608516185162851638516485165851668516785168851698517085171851728517385174851758517685177851788517985180851818518285183851848518585186851878518885189851908519185192851938519485195851968519785198851998520085201852028520385204852058520685207852088520985210852118521285213852148521585216852178521885219852208522185222852238522485225852268522785228852298523085231852328523385234852358523685237852388523985240852418524285243852448524585246852478524885249852508525185252852538525485255852568525785258852598526085261852628526385264852658526685267852688526985270852718527285273852748527585276852778527885279852808528185282852838528485285852868528785288852898529085291852928529385294852958529685297852988529985300853018530285303853048530585306853078530885309853108531185312853138531485315853168531785318853198532085321853228532385324853258532685327853288532985330853318533285333853348533585336853378533885339853408534185342853438534485345853468534785348853498535085351853528535385354853558535685357853588535985360853618536285363853648536585366853678536885369853708537185372853738537485375853768537785378853798538085381853828538385384853858538685387853888538985390853918539285393853948539585396853978539885399854008540185402854038540485405854068540785408854098541085411854128541385414854158541685417854188541985420854218542285423854248542585426854278542885429854308543185432854338543485435854368543785438854398544085441854428544385444854458544685447854488544985450854518545285453854548545585456854578545885459854608546185462854638546485465854668546785468854698547085471854728547385474854758547685477854788547985480854818548285483854848548585486854878548885489854908549185492854938549485495854968549785498854998550085501855028550385504855058550685507855088550985510855118551285513855148551585516855178551885519855208552185522855238552485525855268552785528855298553085531855328553385534855358553685537855388553985540855418554285543855448554585546855478554885549855508555185552855538555485555855568555785558855598556085561855628556385564855658556685567855688556985570855718557285573855748557585576855778557885579855808558185582855838558485585855868558785588855898559085591855928559385594855958559685597855988559985600856018560285603856048560585606856078560885609856108561185612856138561485615856168561785618856198562085621856228562385624856258562685627856288562985630856318563285633856348563585636856378563885639856408564185642856438564485645856468564785648856498565085651856528565385654856558565685657856588565985660856618566285663856648566585666856678566885669856708567185672856738567485675856768567785678856798568085681856828568385684856858568685687856888568985690856918569285693856948569585696856978569885699857008570185702857038570485705857068570785708857098571085711857128571385714857158571685717857188571985720857218572285723857248572585726857278572885729857308573185732857338573485735857368573785738857398574085741857428574385744857458574685747857488574985750857518575285753857548575585756857578575885759857608576185762857638576485765857668576785768857698577085771857728577385774857758577685777857788577985780857818578285783857848578585786857878578885789857908579185792857938579485795857968579785798857998580085801858028580385804858058580685807858088580985810858118581285813858148581585816858178581885819858208582185822858238582485825858268582785828858298583085831858328583385834858358583685837858388583985840858418584285843858448584585846858478584885849858508585185852858538585485855858568585785858858598586085861858628586385864858658586685867858688586985870858718587285873858748587585876858778587885879858808588185882858838588485885858868588785888858898589085891858928589385894858958589685897858988589985900859018590285903859048590585906859078590885909859108591185912859138591485915859168591785918859198592085921859228592385924859258592685927859288592985930859318593285933859348593585936859378593885939859408594185942859438594485945859468594785948859498595085951859528595385954859558595685957859588595985960859618596285963859648596585966859678596885969859708597185972859738597485975859768597785978859798598085981859828598385984859858598685987859888598985990859918599285993859948599585996859978599885999860008600186002860038600486005860068600786008860098601086011860128601386014860158601686017860188601986020860218602286023860248602586026860278602886029860308603186032860338603486035860368603786038860398604086041860428604386044860458604686047860488604986050860518605286053860548605586056860578605886059860608606186062860638606486065860668606786068860698607086071860728607386074860758607686077860788607986080860818608286083860848608586086860878608886089860908609186092860938609486095860968609786098860998610086101861028610386104861058610686107861088610986110861118611286113861148611586116861178611886119861208612186122861238612486125861268612786128861298613086131861328613386134861358613686137861388613986140861418614286143861448614586146861478614886149861508615186152861538615486155861568615786158861598616086161861628616386164861658616686167861688616986170861718617286173861748617586176861778617886179861808618186182861838618486185861868618786188861898619086191861928619386194861958619686197861988619986200862018620286203862048620586206862078620886209862108621186212862138621486215862168621786218862198622086221862228622386224862258622686227862288622986230862318623286233862348623586236862378623886239862408624186242862438624486245862468624786248862498625086251862528625386254862558625686257862588625986260862618626286263862648626586266862678626886269862708627186272862738627486275862768627786278862798628086281862828628386284862858628686287862888628986290862918629286293862948629586296862978629886299863008630186302863038630486305863068630786308863098631086311863128631386314863158631686317863188631986320863218632286323863248632586326863278632886329863308633186332863338633486335863368633786338863398634086341863428634386344863458634686347863488634986350863518635286353863548635586356863578635886359863608636186362863638636486365863668636786368863698637086371863728637386374863758637686377863788637986380863818638286383863848638586386863878638886389863908639186392863938639486395863968639786398863998640086401864028640386404864058640686407864088640986410864118641286413864148641586416864178641886419864208642186422864238642486425864268642786428864298643086431864328643386434864358643686437864388643986440864418644286443864448644586446864478644886449864508645186452864538645486455864568645786458864598646086461864628646386464864658646686467864688646986470864718647286473864748647586476864778647886479864808648186482864838648486485864868648786488864898649086491864928649386494864958649686497864988649986500865018650286503865048650586506865078650886509865108651186512865138651486515865168651786518865198652086521865228652386524865258652686527865288652986530865318653286533865348653586536865378653886539865408654186542865438654486545865468654786548865498655086551865528655386554865558655686557865588655986560865618656286563865648656586566865678656886569865708657186572865738657486575865768657786578865798658086581865828658386584865858658686587865888658986590865918659286593865948659586596865978659886599866008660186602866038660486605866068660786608866098661086611866128661386614866158661686617866188661986620866218662286623866248662586626866278662886629866308663186632866338663486635866368663786638866398664086641866428664386644866458664686647866488664986650866518665286653866548665586656866578665886659866608666186662866638666486665866668666786668866698667086671866728667386674866758667686677866788667986680866818668286683866848668586686866878668886689866908669186692866938669486695866968669786698866998670086701867028670386704867058670686707867088670986710867118671286713867148671586716867178671886719867208672186722867238672486725867268672786728867298673086731867328673386734867358673686737867388673986740867418674286743867448674586746867478674886749867508675186752867538675486755867568675786758867598676086761867628676386764867658676686767867688676986770867718677286773867748677586776867778677886779867808678186782867838678486785867868678786788867898679086791867928679386794867958679686797867988679986800868018680286803868048680586806868078680886809868108681186812868138681486815868168681786818868198682086821868228682386824868258682686827868288682986830868318683286833868348683586836868378683886839868408684186842868438684486845868468684786848868498685086851868528685386854868558685686857868588685986860868618686286863868648686586866868678686886869868708687186872868738687486875868768687786878868798688086881868828688386884868858688686887868888688986890868918689286893868948689586896868978689886899869008690186902869038690486905869068690786908869098691086911869128691386914869158691686917869188691986920869218692286923869248692586926869278692886929869308693186932869338693486935869368693786938869398694086941869428694386944869458694686947869488694986950869518695286953869548695586956869578695886959869608696186962869638696486965869668696786968869698697086971869728697386974869758697686977869788697986980869818698286983869848698586986869878698886989869908699186992869938699486995869968699786998869998700087001870028700387004870058700687007870088700987010870118701287013870148701587016870178701887019870208702187022870238702487025870268702787028870298703087031870328703387034870358703687037870388703987040870418704287043870448704587046870478704887049870508705187052870538705487055870568705787058870598706087061870628706387064870658706687067870688706987070870718707287073870748707587076870778707887079870808708187082870838708487085870868708787088870898709087091870928709387094870958709687097870988709987100871018710287103871048710587106871078710887109871108711187112871138711487115871168711787118871198712087121871228712387124871258712687127871288712987130871318713287133871348713587136871378713887139871408714187142871438714487145871468714787148871498715087151871528715387154871558715687157871588715987160871618716287163871648716587166871678716887169871708717187172871738717487175871768717787178871798718087181871828718387184871858718687187871888718987190871918719287193871948719587196871978719887199872008720187202872038720487205872068720787208872098721087211872128721387214872158721687217872188721987220872218722287223872248722587226872278722887229872308723187232872338723487235872368723787238872398724087241872428724387244872458724687247872488724987250872518725287253872548725587256872578725887259872608726187262872638726487265872668726787268872698727087271872728727387274872758727687277872788727987280872818728287283872848728587286872878728887289872908729187292872938729487295872968729787298872998730087301873028730387304873058730687307873088730987310873118731287313873148731587316873178731887319873208732187322873238732487325873268732787328873298733087331873328733387334873358733687337873388733987340873418734287343873448734587346873478734887349873508735187352873538735487355873568735787358873598736087361873628736387364873658736687367873688736987370873718737287373873748737587376873778737887379873808738187382873838738487385873868738787388873898739087391873928739387394873958739687397873988739987400874018740287403874048740587406874078740887409874108741187412874138741487415874168741787418874198742087421874228742387424874258742687427874288742987430874318743287433874348743587436874378743887439874408744187442874438744487445874468744787448874498745087451874528745387454874558745687457874588745987460874618746287463874648746587466874678746887469874708747187472874738747487475874768747787478874798748087481874828748387484874858748687487874888748987490874918749287493874948749587496874978749887499875008750187502875038750487505875068750787508875098751087511875128751387514875158751687517875188751987520875218752287523875248752587526875278752887529875308753187532875338753487535875368753787538875398754087541875428754387544875458754687547875488754987550875518755287553875548755587556875578755887559875608756187562875638756487565875668756787568875698757087571875728757387574875758757687577875788757987580875818758287583875848758587586875878758887589875908759187592875938759487595875968759787598875998760087601876028760387604876058760687607876088760987610876118761287613876148761587616876178761887619876208762187622876238762487625876268762787628876298763087631876328763387634876358763687637876388763987640876418764287643876448764587646876478764887649876508765187652876538765487655876568765787658876598766087661876628766387664876658766687667876688766987670876718767287673876748767587676876778767887679876808768187682876838768487685876868768787688876898769087691876928769387694876958769687697876988769987700877018770287703877048770587706877078770887709877108771187712877138771487715877168771787718877198772087721877228772387724877258772687727877288772987730877318773287733877348773587736877378773887739877408774187742877438774487745877468774787748877498775087751877528775387754877558775687757877588775987760877618776287763877648776587766877678776887769877708777187772877738777487775877768777787778877798778087781877828778387784877858778687787877888778987790877918779287793877948779587796877978779887799878008780187802878038780487805878068780787808878098781087811878128781387814878158781687817878188781987820878218782287823878248782587826878278782887829878308783187832878338783487835878368783787838878398784087841878428784387844878458784687847878488784987850878518785287853878548785587856878578785887859878608786187862878638786487865878668786787868878698787087871878728787387874878758787687877878788787987880878818788287883878848788587886878878788887889878908789187892878938789487895878968789787898878998790087901879028790387904879058790687907879088790987910879118791287913879148791587916879178791887919879208792187922879238792487925879268792787928879298793087931879328793387934879358793687937879388793987940879418794287943879448794587946879478794887949879508795187952879538795487955879568795787958879598796087961879628796387964879658796687967879688796987970879718797287973879748797587976879778797887979879808798187982879838798487985879868798787988879898799087991879928799387994879958799687997879988799988000880018800288003880048800588006880078800888009880108801188012880138801488015880168801788018880198802088021880228802388024880258802688027880288802988030880318803288033880348803588036880378803888039880408804188042880438804488045880468804788048880498805088051880528805388054880558805688057880588805988060880618806288063880648806588066880678806888069880708807188072880738807488075880768807788078880798808088081880828808388084880858808688087880888808988090880918809288093880948809588096880978809888099881008810188102881038810488105881068810788108881098811088111881128811388114881158811688117881188811988120881218812288123881248812588126881278812888129881308813188132881338813488135881368813788138881398814088141881428814388144881458814688147881488814988150881518815288153881548815588156881578815888159881608816188162881638816488165881668816788168881698817088171881728817388174881758817688177881788817988180881818818288183881848818588186881878818888189881908819188192881938819488195881968819788198881998820088201882028820388204882058820688207882088820988210882118821288213882148821588216882178821888219882208822188222882238822488225882268822788228882298823088231882328823388234882358823688237882388823988240882418824288243882448824588246882478824888249882508825188252882538825488255882568825788258882598826088261882628826388264882658826688267882688826988270882718827288273882748827588276882778827888279882808828188282882838828488285882868828788288882898829088291882928829388294882958829688297882988829988300883018830288303883048830588306883078830888309883108831188312883138831488315883168831788318883198832088321883228832388324883258832688327883288832988330883318833288333883348833588336883378833888339883408834188342883438834488345883468834788348883498835088351883528835388354883558835688357883588835988360883618836288363883648836588366883678836888369883708837188372883738837488375883768837788378883798838088381883828838388384883858838688387883888838988390883918839288393883948839588396883978839888399884008840188402884038840488405884068840788408884098841088411884128841388414884158841688417884188841988420884218842288423884248842588426884278842888429884308843188432884338843488435884368843788438884398844088441884428844388444884458844688447884488844988450884518845288453884548845588456884578845888459884608846188462884638846488465884668846788468884698847088471884728847388474884758847688477884788847988480884818848288483884848848588486884878848888489884908849188492884938849488495884968849788498884998850088501885028850388504885058850688507885088850988510885118851288513885148851588516885178851888519885208852188522885238852488525885268852788528885298853088531885328853388534885358853688537885388853988540885418854288543885448854588546885478854888549885508855188552885538855488555885568855788558885598856088561885628856388564885658856688567885688856988570885718857288573885748857588576885778857888579885808858188582885838858488585885868858788588885898859088591885928859388594885958859688597885988859988600886018860288603886048860588606886078860888609886108861188612886138861488615886168861788618886198862088621886228862388624886258862688627886288862988630886318863288633886348863588636886378863888639886408864188642886438864488645886468864788648886498865088651886528865388654886558865688657886588865988660886618866288663886648866588666886678866888669886708867188672886738867488675886768867788678886798868088681886828868388684886858868688687886888868988690886918869288693886948869588696886978869888699887008870188702887038870488705887068870788708887098871088711887128871388714887158871688717887188871988720887218872288723887248872588726887278872888729887308873188732887338873488735887368873788738887398874088741887428874388744887458874688747887488874988750887518875288753887548875588756887578875888759887608876188762887638876488765887668876788768887698877088771887728877388774887758877688777887788877988780887818878288783887848878588786887878878888789887908879188792887938879488795887968879788798887998880088801888028880388804888058880688807888088880988810888118881288813888148881588816888178881888819888208882188822888238882488825888268882788828888298883088831888328883388834888358883688837888388883988840888418884288843888448884588846888478884888849888508885188852888538885488855888568885788858888598886088861888628886388864888658886688867888688886988870888718887288873888748887588876888778887888879888808888188882888838888488885888868888788888888898889088891888928889388894888958889688897888988889988900889018890288903889048890588906889078890888909889108891188912889138891488915889168891788918889198892088921889228892388924889258892688927889288892988930889318893288933889348893588936889378893888939889408894188942889438894488945889468894788948889498895088951889528895388954889558895688957889588895988960889618896288963889648896588966889678896888969889708897188972889738897488975889768897788978889798898088981889828898388984889858898688987889888898988990889918899288993889948899588996889978899888999890008900189002890038900489005890068900789008890098901089011890128901389014890158901689017890188901989020890218902289023890248902589026890278902889029890308903189032890338903489035890368903789038890398904089041890428904389044890458904689047890488904989050890518905289053890548905589056890578905889059890608906189062890638906489065890668906789068890698907089071890728907389074890758907689077890788907989080890818908289083890848908589086890878908889089890908909189092890938909489095890968909789098890998910089101891028910389104891058910689107891088910989110891118911289113891148911589116891178911889119891208912189122891238912489125891268912789128891298913089131891328913389134891358913689137891388913989140891418914289143891448914589146891478914889149891508915189152891538915489155891568915789158891598916089161891628916389164891658916689167891688916989170891718917289173891748917589176891778917889179891808918189182891838918489185891868918789188891898919089191891928919389194891958919689197891988919989200892018920289203892048920589206892078920889209892108921189212892138921489215892168921789218892198922089221892228922389224892258922689227892288922989230892318923289233892348923589236892378923889239892408924189242892438924489245892468924789248892498925089251892528925389254892558925689257892588925989260892618926289263892648926589266892678926889269892708927189272892738927489275892768927789278892798928089281892828928389284892858928689287892888928989290892918929289293892948929589296892978929889299893008930189302893038930489305893068930789308893098931089311893128931389314893158931689317893188931989320893218932289323893248932589326893278932889329893308933189332893338933489335893368933789338893398934089341893428934389344893458934689347893488934989350893518935289353893548935589356893578935889359893608936189362893638936489365893668936789368893698937089371893728937389374893758937689377893788937989380893818938289383893848938589386893878938889389893908939189392893938939489395893968939789398893998940089401894028940389404894058940689407894088940989410894118941289413894148941589416894178941889419894208942189422894238942489425894268942789428894298943089431894328943389434894358943689437894388943989440894418944289443894448944589446894478944889449894508945189452894538945489455894568945789458894598946089461894628946389464894658946689467894688946989470894718947289473894748947589476894778947889479894808948189482894838948489485894868948789488894898949089491894928949389494894958949689497894988949989500895018950289503895048950589506895078950889509895108951189512895138951489515895168951789518895198952089521895228952389524895258952689527895288952989530895318953289533895348953589536895378953889539895408954189542895438954489545895468954789548895498955089551895528955389554895558955689557895588955989560895618956289563895648956589566895678956889569895708957189572895738957489575895768957789578895798958089581895828958389584895858958689587895888958989590895918959289593895948959589596895978959889599896008960189602896038960489605896068960789608896098961089611896128961389614896158961689617896188961989620896218962289623896248962589626896278962889629896308963189632896338963489635896368963789638896398964089641896428964389644896458964689647896488964989650896518965289653896548965589656896578965889659896608966189662896638966489665896668966789668896698967089671896728967389674896758967689677896788967989680896818968289683896848968589686896878968889689896908969189692896938969489695896968969789698896998970089701897028970389704897058970689707897088970989710897118971289713897148971589716897178971889719897208972189722897238972489725897268972789728897298973089731897328973389734897358973689737897388973989740897418974289743897448974589746897478974889749897508975189752897538975489755897568975789758897598976089761897628976389764897658976689767897688976989770897718977289773897748977589776897778977889779897808978189782897838978489785897868978789788897898979089791897928979389794897958979689797897988979989800898018980289803898048980589806898078980889809898108981189812898138981489815898168981789818898198982089821898228982389824898258982689827898288982989830898318983289833898348983589836898378983889839898408984189842898438984489845898468984789848898498985089851898528985389854898558985689857898588985989860898618986289863898648986589866898678986889869898708987189872898738987489875898768987789878898798988089881898828988389884898858988689887898888988989890898918989289893898948989589896898978989889899899008990189902899038990489905899068990789908899098991089911899128991389914899158991689917899188991989920899218992289923899248992589926899278992889929899308993189932899338993489935899368993789938899398994089941899428994389944899458994689947899488994989950899518995289953899548995589956899578995889959899608996189962899638996489965899668996789968899698997089971899728997389974899758997689977899788997989980899818998289983899848998589986899878998889989899908999189992899938999489995899968999789998899999000090001900029000390004900059000690007900089000990010900119001290013900149001590016900179001890019900209002190022900239002490025900269002790028900299003090031900329003390034900359003690037900389003990040900419004290043900449004590046900479004890049900509005190052900539005490055900569005790058900599006090061900629006390064900659006690067900689006990070900719007290073900749007590076900779007890079900809008190082900839008490085900869008790088900899009090091900929009390094900959009690097900989009990100901019010290103901049010590106901079010890109901109011190112901139011490115901169011790118901199012090121901229012390124901259012690127901289012990130901319013290133901349013590136901379013890139901409014190142901439014490145901469014790148901499015090151901529015390154901559015690157901589015990160901619016290163901649016590166901679016890169901709017190172901739017490175901769017790178901799018090181901829018390184901859018690187901889018990190901919019290193901949019590196901979019890199902009020190202902039020490205902069020790208902099021090211902129021390214902159021690217902189021990220902219022290223902249022590226902279022890229902309023190232902339023490235902369023790238902399024090241902429024390244902459024690247902489024990250902519025290253902549025590256902579025890259902609026190262902639026490265902669026790268902699027090271902729027390274902759027690277902789027990280902819028290283902849028590286902879028890289902909029190292902939029490295902969029790298902999030090301903029030390304903059030690307903089030990310903119031290313903149031590316903179031890319903209032190322903239032490325903269032790328903299033090331903329033390334903359033690337903389033990340903419034290343903449034590346903479034890349903509035190352903539035490355903569035790358903599036090361
  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. };
  70. }
  71. else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  72. // In worker
  73. env = {
  74. browser: {},
  75. os: {},
  76. node: false,
  77. worker: true,
  78. canvasSupported: true
  79. };
  80. }
  81. else if (typeof navigator === 'undefined') {
  82. // In node
  83. env = {
  84. browser: {},
  85. os: {},
  86. node: true,
  87. worker: false,
  88. // Assume canvas is supported
  89. canvasSupported: true,
  90. svgSupported: true
  91. };
  92. }
  93. else {
  94. env = detect(navigator.userAgent);
  95. }
  96. var env$1 = env;
  97. // Zepto.js
  98. // (c) 2010-2013 Thomas Fuchs
  99. // Zepto.js may be freely distributed under the MIT license.
  100. function detect(ua) {
  101. var os = {};
  102. var browser = {};
  103. // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  104. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  105. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  106. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  107. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  108. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  109. // var touchpad = webos && ua.match(/TouchPad/);
  110. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  111. // var silk = ua.match(/Silk\/([\d._]+)/);
  112. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  113. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  114. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  115. // var playbook = ua.match(/PlayBook/);
  116. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  117. var firefox = ua.match(/Firefox\/([\d.]+)/);
  118. // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  119. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  120. var ie = ua.match(/MSIE\s([\d.]+)/)
  121. // IE 11 Trident/7.0; rv:11.0
  122. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  123. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  124. var weChat = (/micromessenger/i).test(ua);
  125. // Todo: clean this up with a better OS/browser seperation:
  126. // - discern (more) between multiple browsers on android
  127. // - decide if kindle fire in silk mode is android or not
  128. // - Firefox on Android doesn't specify the Android version
  129. // - possibly devide in os, device and browser hashes
  130. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  131. // if (android) os.android = true, os.version = android[2];
  132. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  133. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  134. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  135. // if (webos) os.webos = true, os.version = webos[2];
  136. // if (touchpad) os.touchpad = true;
  137. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  138. // if (bb10) os.bb10 = true, os.version = bb10[2];
  139. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  140. // if (playbook) browser.playbook = true;
  141. // if (kindle) os.kindle = true, os.version = kindle[1];
  142. // if (silk) browser.silk = true, browser.version = silk[1];
  143. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  144. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  145. if (firefox) {
  146. browser.firefox = true;
  147. browser.version = firefox[1];
  148. }
  149. // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  150. // if (webview) browser.webview = true;
  151. if (ie) {
  152. browser.ie = true;
  153. browser.version = ie[1];
  154. }
  155. if (edge) {
  156. browser.edge = true;
  157. browser.version = edge[1];
  158. }
  159. // It is difficult to detect WeChat in Win Phone precisely, because ua can
  160. // not be set on win phone. So we do not consider Win Phone.
  161. if (weChat) {
  162. browser.weChat = true;
  163. }
  164. // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  165. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  166. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  167. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  168. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  169. return {
  170. browser: browser,
  171. os: os,
  172. node: false,
  173. // 原生canvas支持,改极端点了
  174. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  175. canvasSupported: !!document.createElement('canvas').getContext,
  176. svgSupported: typeof SVGRect !== 'undefined',
  177. // works on most browsers
  178. // IE10/11 does not support touch event, and MS Edge supports them but not by
  179. // default, so we dont check navigator.maxTouchPoints for them here.
  180. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  181. // <http://caniuse.com/#search=pointer%20event>.
  182. pointerEventsSupported: 'onpointerdown' in window
  183. // Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  184. // events currently. So we dont use that on other browsers unless tested sufficiently.
  185. // Although IE 10 supports pointer event, it use old style and is different from the
  186. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  187. && (browser.edge || (browser.ie && browser.version >= 11))
  188. // passiveSupported: detectPassiveSupport()
  189. };
  190. }
  191. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  192. // function detectPassiveSupport() {
  193. // // Test via a getter in the options object to see if the passive property is accessed
  194. // var supportsPassive = false;
  195. // try {
  196. // var opts = Object.defineProperty({}, 'passive', {
  197. // get: function() {
  198. // supportsPassive = true;
  199. // }
  200. // });
  201. // window.addEventListener('testPassive', function() {}, opts);
  202. // } catch (e) {
  203. // }
  204. // return supportsPassive;
  205. // }
  206. /**
  207. * @module zrender/core/util
  208. */
  209. // 用于处理merge时无法遍历Date等对象的问题
  210. var BUILTIN_OBJECT = {
  211. '[object Function]': 1,
  212. '[object RegExp]': 1,
  213. '[object Date]': 1,
  214. '[object Error]': 1,
  215. '[object CanvasGradient]': 1,
  216. '[object CanvasPattern]': 1,
  217. // For node-canvas
  218. '[object Image]': 1,
  219. '[object Canvas]': 1
  220. };
  221. var TYPED_ARRAY = {
  222. '[object Int8Array]': 1,
  223. '[object Uint8Array]': 1,
  224. '[object Uint8ClampedArray]': 1,
  225. '[object Int16Array]': 1,
  226. '[object Uint16Array]': 1,
  227. '[object Int32Array]': 1,
  228. '[object Uint32Array]': 1,
  229. '[object Float32Array]': 1,
  230. '[object Float64Array]': 1
  231. };
  232. var objToString = Object.prototype.toString;
  233. var arrayProto = Array.prototype;
  234. var nativeForEach = arrayProto.forEach;
  235. var nativeFilter = arrayProto.filter;
  236. var nativeSlice = arrayProto.slice;
  237. var nativeMap = arrayProto.map;
  238. var nativeReduce = arrayProto.reduce;
  239. // Avoid assign to an exported variable, for transforming to cjs.
  240. var methods = {};
  241. function $override(name, fn) {
  242. // Clear ctx instance for different environment
  243. if (name === 'createCanvas') {
  244. _ctx = null;
  245. }
  246. methods[name] = fn;
  247. }
  248. /**
  249. * Those data types can be cloned:
  250. * Plain object, Array, TypedArray, number, string, null, undefined.
  251. * Those data types will be assgined using the orginal data:
  252. * BUILTIN_OBJECT
  253. * Instance of user defined class will be cloned to a plain object, without
  254. * properties in prototype.
  255. * Other data types is not supported (not sure what will happen).
  256. *
  257. * Caution: do not support clone Date, for performance consideration.
  258. * (There might be a large number of date in `series.data`).
  259. * So date should not be modified in and out of echarts.
  260. *
  261. * @param {*} source
  262. * @return {*} new
  263. */
  264. function clone(source) {
  265. if (source == null || typeof source != 'object') {
  266. return source;
  267. }
  268. var result = source;
  269. var typeStr = objToString.call(source);
  270. if (typeStr === '[object Array]') {
  271. if (!isPrimitive(source)) {
  272. result = [];
  273. for (var i = 0, len = source.length; i < len; i++) {
  274. result[i] = clone(source[i]);
  275. }
  276. }
  277. }
  278. else if (TYPED_ARRAY[typeStr]) {
  279. if (!isPrimitive(source)) {
  280. var Ctor = source.constructor;
  281. if (source.constructor.from) {
  282. result = Ctor.from(source);
  283. }
  284. else {
  285. result = new Ctor(source.length);
  286. for (var i = 0, len = source.length; i < len; i++) {
  287. result[i] = clone(source[i]);
  288. }
  289. }
  290. }
  291. }
  292. else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  293. result = {};
  294. for (var key in source) {
  295. if (source.hasOwnProperty(key)) {
  296. result[key] = clone(source[key]);
  297. }
  298. }
  299. }
  300. return result;
  301. }
  302. /**
  303. * @memberOf module:zrender/core/util
  304. * @param {*} target
  305. * @param {*} source
  306. * @param {boolean} [overwrite=false]
  307. */
  308. function merge(target, source, overwrite) {
  309. // We should escapse that source is string
  310. // and enter for ... in ...
  311. if (!isObject$1(source) || !isObject$1(target)) {
  312. return overwrite ? clone(source) : target;
  313. }
  314. for (var key in source) {
  315. if (source.hasOwnProperty(key)) {
  316. var targetProp = target[key];
  317. var sourceProp = source[key];
  318. if (isObject$1(sourceProp)
  319. && isObject$1(targetProp)
  320. && !isArray(sourceProp)
  321. && !isArray(targetProp)
  322. && !isDom(sourceProp)
  323. && !isDom(targetProp)
  324. && !isBuiltInObject(sourceProp)
  325. && !isBuiltInObject(targetProp)
  326. && !isPrimitive(sourceProp)
  327. && !isPrimitive(targetProp)
  328. ) {
  329. // 如果需要递归覆盖,就递归调用merge
  330. merge(targetProp, sourceProp, overwrite);
  331. }
  332. else if (overwrite || !(key in target)) {
  333. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  334. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  335. target[key] = clone(source[key], true);
  336. }
  337. }
  338. }
  339. return target;
  340. }
  341. /**
  342. * @param {Array} targetAndSources The first item is target, and the rests are source.
  343. * @param {boolean} [overwrite=false]
  344. * @return {*} target
  345. */
  346. function mergeAll(targetAndSources, overwrite) {
  347. var result = targetAndSources[0];
  348. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  349. result = merge(result, targetAndSources[i], overwrite);
  350. }
  351. return result;
  352. }
  353. /**
  354. * @param {*} target
  355. * @param {*} source
  356. * @memberOf module:zrender/core/util
  357. */
  358. function extend(target, source) {
  359. for (var key in source) {
  360. if (source.hasOwnProperty(key)) {
  361. target[key] = source[key];
  362. }
  363. }
  364. return target;
  365. }
  366. /**
  367. * @param {*} target
  368. * @param {*} source
  369. * @param {boolean} [overlay=false]
  370. * @memberOf module:zrender/core/util
  371. */
  372. function defaults(target, source, overlay) {
  373. for (var key in source) {
  374. if (source.hasOwnProperty(key)
  375. && (overlay ? source[key] != null : target[key] == null)
  376. ) {
  377. target[key] = source[key];
  378. }
  379. }
  380. return target;
  381. }
  382. var createCanvas = function () {
  383. return methods.createCanvas();
  384. };
  385. methods.createCanvas = function () {
  386. return document.createElement('canvas');
  387. };
  388. // FIXME
  389. var _ctx;
  390. function getContext() {
  391. if (!_ctx) {
  392. // Use util.createCanvas instead of createCanvas
  393. // because createCanvas may be overwritten in different environment
  394. _ctx = createCanvas().getContext('2d');
  395. }
  396. return _ctx;
  397. }
  398. /**
  399. * 查询数组中元素的index
  400. * @memberOf module:zrender/core/util
  401. */
  402. function indexOf(array, value) {
  403. if (array) {
  404. if (array.indexOf) {
  405. return array.indexOf(value);
  406. }
  407. for (var i = 0, len = array.length; i < len; i++) {
  408. if (array[i] === value) {
  409. return i;
  410. }
  411. }
  412. }
  413. return -1;
  414. }
  415. /**
  416. * 构造类继承关系
  417. *
  418. * @memberOf module:zrender/core/util
  419. * @param {Function} clazz 源类
  420. * @param {Function} baseClazz 基类
  421. */
  422. function inherits(clazz, baseClazz) {
  423. var clazzPrototype = clazz.prototype;
  424. function F() {}
  425. F.prototype = baseClazz.prototype;
  426. clazz.prototype = new F();
  427. for (var prop in clazzPrototype) {
  428. clazz.prototype[prop] = clazzPrototype[prop];
  429. }
  430. clazz.prototype.constructor = clazz;
  431. clazz.superClass = baseClazz;
  432. }
  433. /**
  434. * @memberOf module:zrender/core/util
  435. * @param {Object|Function} target
  436. * @param {Object|Function} sorce
  437. * @param {boolean} overlay
  438. */
  439. function mixin(target, source, overlay) {
  440. target = 'prototype' in target ? target.prototype : target;
  441. source = 'prototype' in source ? source.prototype : source;
  442. defaults(target, source, overlay);
  443. }
  444. /**
  445. * Consider typed array.
  446. * @param {Array|TypedArray} data
  447. */
  448. function isArrayLike(data) {
  449. if (! data) {
  450. return;
  451. }
  452. if (typeof data == 'string') {
  453. return false;
  454. }
  455. return typeof data.length == 'number';
  456. }
  457. /**
  458. * 数组或对象遍历
  459. * @memberOf module:zrender/core/util
  460. * @param {Object|Array} obj
  461. * @param {Function} cb
  462. * @param {*} [context]
  463. */
  464. function each$1(obj, cb, context) {
  465. if (!(obj && cb)) {
  466. return;
  467. }
  468. if (obj.forEach && obj.forEach === nativeForEach) {
  469. obj.forEach(cb, context);
  470. }
  471. else if (obj.length === +obj.length) {
  472. for (var i = 0, len = obj.length; i < len; i++) {
  473. cb.call(context, obj[i], i, obj);
  474. }
  475. }
  476. else {
  477. for (var key in obj) {
  478. if (obj.hasOwnProperty(key)) {
  479. cb.call(context, obj[key], key, obj);
  480. }
  481. }
  482. }
  483. }
  484. /**
  485. * 数组映射
  486. * @memberOf module:zrender/core/util
  487. * @param {Array} obj
  488. * @param {Function} cb
  489. * @param {*} [context]
  490. * @return {Array}
  491. */
  492. function map(obj, cb, context) {
  493. if (!(obj && cb)) {
  494. return;
  495. }
  496. if (obj.map && obj.map === nativeMap) {
  497. return obj.map(cb, context);
  498. }
  499. else {
  500. var result = [];
  501. for (var i = 0, len = obj.length; i < len; i++) {
  502. result.push(cb.call(context, obj[i], i, obj));
  503. }
  504. return result;
  505. }
  506. }
  507. /**
  508. * @memberOf module:zrender/core/util
  509. * @param {Array} obj
  510. * @param {Function} cb
  511. * @param {Object} [memo]
  512. * @param {*} [context]
  513. * @return {Array}
  514. */
  515. function reduce(obj, cb, memo, context) {
  516. if (!(obj && cb)) {
  517. return;
  518. }
  519. if (obj.reduce && obj.reduce === nativeReduce) {
  520. return obj.reduce(cb, memo, context);
  521. }
  522. else {
  523. for (var i = 0, len = obj.length; i < len; i++) {
  524. memo = cb.call(context, memo, obj[i], i, obj);
  525. }
  526. return memo;
  527. }
  528. }
  529. /**
  530. * 数组过滤
  531. * @memberOf module:zrender/core/util
  532. * @param {Array} obj
  533. * @param {Function} cb
  534. * @param {*} [context]
  535. * @return {Array}
  536. */
  537. function filter(obj, cb, context) {
  538. if (!(obj && cb)) {
  539. return;
  540. }
  541. if (obj.filter && obj.filter === nativeFilter) {
  542. return obj.filter(cb, context);
  543. }
  544. else {
  545. var result = [];
  546. for (var i = 0, len = obj.length; i < len; i++) {
  547. if (cb.call(context, obj[i], i, obj)) {
  548. result.push(obj[i]);
  549. }
  550. }
  551. return result;
  552. }
  553. }
  554. /**
  555. * 数组项查找
  556. * @memberOf module:zrender/core/util
  557. * @param {Array} obj
  558. * @param {Function} cb
  559. * @param {*} [context]
  560. * @return {*}
  561. */
  562. function find(obj, cb, context) {
  563. if (!(obj && cb)) {
  564. return;
  565. }
  566. for (var i = 0, len = obj.length; i < len; i++) {
  567. if (cb.call(context, obj[i], i, obj)) {
  568. return obj[i];
  569. }
  570. }
  571. }
  572. /**
  573. * @memberOf module:zrender/core/util
  574. * @param {Function} func
  575. * @param {*} context
  576. * @return {Function}
  577. */
  578. function bind(func, context) {
  579. var args = nativeSlice.call(arguments, 2);
  580. return function () {
  581. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  582. };
  583. }
  584. /**
  585. * @memberOf module:zrender/core/util
  586. * @param {Function} func
  587. * @return {Function}
  588. */
  589. function curry(func) {
  590. var args = nativeSlice.call(arguments, 1);
  591. return function () {
  592. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  593. };
  594. }
  595. /**
  596. * @memberOf module:zrender/core/util
  597. * @param {*} value
  598. * @return {boolean}
  599. */
  600. function isArray(value) {
  601. return objToString.call(value) === '[object Array]';
  602. }
  603. /**
  604. * @memberOf module:zrender/core/util
  605. * @param {*} value
  606. * @return {boolean}
  607. */
  608. function isFunction$1(value) {
  609. return typeof value === 'function';
  610. }
  611. /**
  612. * @memberOf module:zrender/core/util
  613. * @param {*} value
  614. * @return {boolean}
  615. */
  616. function isString(value) {
  617. return objToString.call(value) === '[object String]';
  618. }
  619. /**
  620. * @memberOf module:zrender/core/util
  621. * @param {*} value
  622. * @return {boolean}
  623. */
  624. function isObject$1(value) {
  625. // Avoid a V8 JIT bug in Chrome 19-20.
  626. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  627. var type = typeof value;
  628. return type === 'function' || (!!value && type == 'object');
  629. }
  630. /**
  631. * @memberOf module:zrender/core/util
  632. * @param {*} value
  633. * @return {boolean}
  634. */
  635. function isBuiltInObject(value) {
  636. return !!BUILTIN_OBJECT[objToString.call(value)];
  637. }
  638. /**
  639. * @memberOf module:zrender/core/util
  640. * @param {*} value
  641. * @return {boolean}
  642. */
  643. function isTypedArray(value) {
  644. return !!TYPED_ARRAY[objToString.call(value)];
  645. }
  646. /**
  647. * @memberOf module:zrender/core/util
  648. * @param {*} value
  649. * @return {boolean}
  650. */
  651. function isDom(value) {
  652. return typeof value === 'object'
  653. && typeof value.nodeType === 'number'
  654. && typeof value.ownerDocument === 'object';
  655. }
  656. /**
  657. * Whether is exactly NaN. Notice isNaN('a') returns true.
  658. * @param {*} value
  659. * @return {boolean}
  660. */
  661. function eqNaN(value) {
  662. return value !== value;
  663. }
  664. /**
  665. * If value1 is not null, then return value1, otherwise judget rest of values.
  666. * Low performance.
  667. * @memberOf module:zrender/core/util
  668. * @return {*} Final value
  669. */
  670. function retrieve(values) {
  671. for (var i = 0, len = arguments.length; i < len; i++) {
  672. if (arguments[i] != null) {
  673. return arguments[i];
  674. }
  675. }
  676. }
  677. function retrieve2(value0, value1) {
  678. return value0 != null
  679. ? value0
  680. : value1;
  681. }
  682. function retrieve3(value0, value1, value2) {
  683. return value0 != null
  684. ? value0
  685. : value1 != null
  686. ? value1
  687. : value2;
  688. }
  689. /**
  690. * @memberOf module:zrender/core/util
  691. * @param {Array} arr
  692. * @param {number} startIndex
  693. * @param {number} endIndex
  694. * @return {Array}
  695. */
  696. function slice() {
  697. return Function.call.apply(nativeSlice, arguments);
  698. }
  699. /**
  700. * Normalize css liked array configuration
  701. * e.g.
  702. * 3 => [3, 3, 3, 3]
  703. * [4, 2] => [4, 2, 4, 2]
  704. * [4, 3, 2] => [4, 3, 2, 3]
  705. * @param {number|Array.<number>} val
  706. * @return {Array.<number>}
  707. */
  708. function normalizeCssArray(val) {
  709. if (typeof (val) === 'number') {
  710. return [val, val, val, val];
  711. }
  712. var len = val.length;
  713. if (len === 2) {
  714. // vertical | horizontal
  715. return [val[0], val[1], val[0], val[1]];
  716. }
  717. else if (len === 3) {
  718. // top | horizontal | bottom
  719. return [val[0], val[1], val[2], val[1]];
  720. }
  721. return val;
  722. }
  723. /**
  724. * @memberOf module:zrender/core/util
  725. * @param {boolean} condition
  726. * @param {string} message
  727. */
  728. function assert$1(condition, message) {
  729. if (!condition) {
  730. throw new Error(message);
  731. }
  732. }
  733. /**
  734. * @memberOf module:zrender/core/util
  735. * @param {string} str string to be trimed
  736. * @return {string} trimed string
  737. */
  738. function trim(str) {
  739. if (str == null) {
  740. return null;
  741. }
  742. else if (typeof str.trim === 'function') {
  743. return str.trim();
  744. }
  745. else {
  746. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  747. }
  748. }
  749. var primitiveKey = '__ec_primitive__';
  750. /**
  751. * Set an object as primitive to be ignored traversing children in clone or merge
  752. */
  753. function setAsPrimitive(obj) {
  754. obj[primitiveKey] = true;
  755. }
  756. function isPrimitive(obj) {
  757. return obj[primitiveKey];
  758. }
  759. /**
  760. * @constructor
  761. * @param {Object} obj Only apply `ownProperty`.
  762. */
  763. function HashMap(obj) {
  764. var isArr = isArray(obj);
  765. var thisMap = this;
  766. (obj instanceof HashMap)
  767. ? obj.each(visit)
  768. : (obj && each$1(obj, visit));
  769. function visit(value, key) {
  770. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  771. }
  772. }
  773. // Add prefix to avoid conflict with Object.prototype.
  774. HashMap.prototype = {
  775. constructor: HashMap,
  776. // Do not provide `has` method to avoid defining what is `has`.
  777. // (We usually treat `null` and `undefined` as the same, different
  778. // from ES6 Map).
  779. get: function (key) {
  780. return this.hasOwnProperty(key) ? this[key] : null;
  781. },
  782. set: function (key, value) {
  783. // Comparing with invocation chaining, `return value` is more commonly
  784. // used in this case: `var someVal = map.set('a', genVal());`
  785. return (this[key] = value);
  786. },
  787. // Although util.each can be performed on this hashMap directly, user
  788. // should not use the exposed keys, who are prefixed.
  789. each: function (cb, context) {
  790. context !== void 0 && (cb = bind(cb, context));
  791. for (var key in this) {
  792. this.hasOwnProperty(key) && cb(this[key], key);
  793. }
  794. },
  795. // Do not use this method if performance sensitive.
  796. removeKey: function (key) {
  797. delete this[key];
  798. }
  799. };
  800. function createHashMap(obj) {
  801. return new HashMap(obj);
  802. }
  803. function concatArray(a, b) {
  804. var newArray = new a.constructor(a.length + b.length);
  805. for (var i = 0; i < a.length; i++) {
  806. newArray[i] = a[i];
  807. }
  808. var offset = a.length;
  809. for (i = 0; i < b.length; i++) {
  810. newArray[i + offset] = b[i];
  811. }
  812. return newArray;
  813. }
  814. function noop() {}
  815. var zrUtil = (Object.freeze || Object)({
  816. $override: $override,
  817. clone: clone,
  818. merge: merge,
  819. mergeAll: mergeAll,
  820. extend: extend,
  821. defaults: defaults,
  822. createCanvas: createCanvas,
  823. getContext: getContext,
  824. indexOf: indexOf,
  825. inherits: inherits,
  826. mixin: mixin,
  827. isArrayLike: isArrayLike,
  828. each: each$1,
  829. map: map,
  830. reduce: reduce,
  831. filter: filter,
  832. find: find,
  833. bind: bind,
  834. curry: curry,
  835. isArray: isArray,
  836. isFunction: isFunction$1,
  837. isString: isString,
  838. isObject: isObject$1,
  839. isBuiltInObject: isBuiltInObject,
  840. isTypedArray: isTypedArray,
  841. isDom: isDom,
  842. eqNaN: eqNaN,
  843. retrieve: retrieve,
  844. retrieve2: retrieve2,
  845. retrieve3: retrieve3,
  846. slice: slice,
  847. normalizeCssArray: normalizeCssArray,
  848. assert: assert$1,
  849. trim: trim,
  850. setAsPrimitive: setAsPrimitive,
  851. isPrimitive: isPrimitive,
  852. createHashMap: createHashMap,
  853. concatArray: concatArray,
  854. noop: noop
  855. });
  856. var ArrayCtor = typeof Float32Array === 'undefined'
  857. ? Array
  858. : Float32Array;
  859. /**
  860. * 创建一个向量
  861. * @param {number} [x=0]
  862. * @param {number} [y=0]
  863. * @return {Vector2}
  864. */
  865. function create(x, y) {
  866. var out = new ArrayCtor(2);
  867. if (x == null) {
  868. x = 0;
  869. }
  870. if (y == null) {
  871. y = 0;
  872. }
  873. out[0] = x;
  874. out[1] = y;
  875. return out;
  876. }
  877. /**
  878. * 复制向量数据
  879. * @param {Vector2} out
  880. * @param {Vector2} v
  881. * @return {Vector2}
  882. */
  883. function copy(out, v) {
  884. out[0] = v[0];
  885. out[1] = v[1];
  886. return out;
  887. }
  888. /**
  889. * 克隆一个向量
  890. * @param {Vector2} v
  891. * @return {Vector2}
  892. */
  893. function clone$1(v) {
  894. var out = new ArrayCtor(2);
  895. out[0] = v[0];
  896. out[1] = v[1];
  897. return out;
  898. }
  899. /**
  900. * 设置向量的两个项
  901. * @param {Vector2} out
  902. * @param {number} a
  903. * @param {number} b
  904. * @return {Vector2} 结果
  905. */
  906. function set(out, a, b) {
  907. out[0] = a;
  908. out[1] = b;
  909. return out;
  910. }
  911. /**
  912. * 向量相加
  913. * @param {Vector2} out
  914. * @param {Vector2} v1
  915. * @param {Vector2} v2
  916. */
  917. function add(out, v1, v2) {
  918. out[0] = v1[0] + v2[0];
  919. out[1] = v1[1] + v2[1];
  920. return out;
  921. }
  922. /**
  923. * 向量缩放后相加
  924. * @param {Vector2} out
  925. * @param {Vector2} v1
  926. * @param {Vector2} v2
  927. * @param {number} a
  928. */
  929. function scaleAndAdd(out, v1, v2, a) {
  930. out[0] = v1[0] + v2[0] * a;
  931. out[1] = v1[1] + v2[1] * a;
  932. return out;
  933. }
  934. /**
  935. * 向量相减
  936. * @param {Vector2} out
  937. * @param {Vector2} v1
  938. * @param {Vector2} v2
  939. */
  940. function sub(out, v1, v2) {
  941. out[0] = v1[0] - v2[0];
  942. out[1] = v1[1] - v2[1];
  943. return out;
  944. }
  945. /**
  946. * 向量长度
  947. * @param {Vector2} v
  948. * @return {number}
  949. */
  950. function len(v) {
  951. return Math.sqrt(lenSquare(v));
  952. }
  953. var length = len; // jshint ignore:line
  954. /**
  955. * 向量长度平方
  956. * @param {Vector2} v
  957. * @return {number}
  958. */
  959. function lenSquare(v) {
  960. return v[0] * v[0] + v[1] * v[1];
  961. }
  962. var lengthSquare = lenSquare;
  963. /**
  964. * 向量乘法
  965. * @param {Vector2} out
  966. * @param {Vector2} v1
  967. * @param {Vector2} v2
  968. */
  969. function mul(out, v1, v2) {
  970. out[0] = v1[0] * v2[0];
  971. out[1] = v1[1] * v2[1];
  972. return out;
  973. }
  974. /**
  975. * 向量除法
  976. * @param {Vector2} out
  977. * @param {Vector2} v1
  978. * @param {Vector2} v2
  979. */
  980. function div(out, v1, v2) {
  981. out[0] = v1[0] / v2[0];
  982. out[1] = v1[1] / v2[1];
  983. return out;
  984. }
  985. /**
  986. * 向量点乘
  987. * @param {Vector2} v1
  988. * @param {Vector2} v2
  989. * @return {number}
  990. */
  991. function dot(v1, v2) {
  992. return v1[0] * v2[0] + v1[1] * v2[1];
  993. }
  994. /**
  995. * 向量缩放
  996. * @param {Vector2} out
  997. * @param {Vector2} v
  998. * @param {number} s
  999. */
  1000. function scale(out, v, s) {
  1001. out[0] = v[0] * s;
  1002. out[1] = v[1] * s;
  1003. return out;
  1004. }
  1005. /**
  1006. * 向量归一化
  1007. * @param {Vector2} out
  1008. * @param {Vector2} v
  1009. */
  1010. function normalize(out, v) {
  1011. var d = len(v);
  1012. if (d === 0) {
  1013. out[0] = 0;
  1014. out[1] = 0;
  1015. }
  1016. else {
  1017. out[0] = v[0] / d;
  1018. out[1] = v[1] / d;
  1019. }
  1020. return out;
  1021. }
  1022. /**
  1023. * 计算向量间距离
  1024. * @param {Vector2} v1
  1025. * @param {Vector2} v2
  1026. * @return {number}
  1027. */
  1028. function distance(v1, v2) {
  1029. return Math.sqrt(
  1030. (v1[0] - v2[0]) * (v1[0] - v2[0])
  1031. + (v1[1] - v2[1]) * (v1[1] - v2[1])
  1032. );
  1033. }
  1034. var dist = distance;
  1035. /**
  1036. * 向量距离平方
  1037. * @param {Vector2} v1
  1038. * @param {Vector2} v2
  1039. * @return {number}
  1040. */
  1041. function distanceSquare(v1, v2) {
  1042. return (v1[0] - v2[0]) * (v1[0] - v2[0])
  1043. + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  1044. }
  1045. var distSquare = distanceSquare;
  1046. /**
  1047. * 求负向量
  1048. * @param {Vector2} out
  1049. * @param {Vector2} v
  1050. */
  1051. function negate(out, v) {
  1052. out[0] = -v[0];
  1053. out[1] = -v[1];
  1054. return out;
  1055. }
  1056. /**
  1057. * 插值两个点
  1058. * @param {Vector2} out
  1059. * @param {Vector2} v1
  1060. * @param {Vector2} v2
  1061. * @param {number} t
  1062. */
  1063. function lerp(out, v1, v2, t) {
  1064. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1065. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1066. return out;
  1067. }
  1068. /**
  1069. * 矩阵左乘向量
  1070. * @param {Vector2} out
  1071. * @param {Vector2} v
  1072. * @param {Vector2} m
  1073. */
  1074. function applyTransform(out, v, m) {
  1075. var x = v[0];
  1076. var y = v[1];
  1077. out[0] = m[0] * x + m[2] * y + m[4];
  1078. out[1] = m[1] * x + m[3] * y + m[5];
  1079. return out;
  1080. }
  1081. /**
  1082. * 求两个向量最小值
  1083. * @param {Vector2} out
  1084. * @param {Vector2} v1
  1085. * @param {Vector2} v2
  1086. */
  1087. function min(out, v1, v2) {
  1088. out[0] = Math.min(v1[0], v2[0]);
  1089. out[1] = Math.min(v1[1], v2[1]);
  1090. return out;
  1091. }
  1092. /**
  1093. * 求两个向量最大值
  1094. * @param {Vector2} out
  1095. * @param {Vector2} v1
  1096. * @param {Vector2} v2
  1097. */
  1098. function max(out, v1, v2) {
  1099. out[0] = Math.max(v1[0], v2[0]);
  1100. out[1] = Math.max(v1[1], v2[1]);
  1101. return out;
  1102. }
  1103. var vector = (Object.freeze || Object)({
  1104. create: create,
  1105. copy: copy,
  1106. clone: clone$1,
  1107. set: set,
  1108. add: add,
  1109. scaleAndAdd: scaleAndAdd,
  1110. sub: sub,
  1111. len: len,
  1112. length: length,
  1113. lenSquare: lenSquare,
  1114. lengthSquare: lengthSquare,
  1115. mul: mul,
  1116. div: div,
  1117. dot: dot,
  1118. scale: scale,
  1119. normalize: normalize,
  1120. distance: distance,
  1121. dist: dist,
  1122. distanceSquare: distanceSquare,
  1123. distSquare: distSquare,
  1124. negate: negate,
  1125. lerp: lerp,
  1126. applyTransform: applyTransform,
  1127. min: min,
  1128. max: max
  1129. });
  1130. // TODO Draggable for group
  1131. // FIXME Draggable on element which has parent rotation or scale
  1132. function Draggable() {
  1133. this.on('mousedown', this._dragStart, this);
  1134. this.on('mousemove', this._drag, this);
  1135. this.on('mouseup', this._dragEnd, this);
  1136. this.on('globalout', this._dragEnd, this);
  1137. // this._dropTarget = null;
  1138. // this._draggingTarget = null;
  1139. // this._x = 0;
  1140. // this._y = 0;
  1141. }
  1142. Draggable.prototype = {
  1143. constructor: Draggable,
  1144. _dragStart: function (e) {
  1145. var draggingTarget = e.target;
  1146. if (draggingTarget && draggingTarget.draggable) {
  1147. this._draggingTarget = draggingTarget;
  1148. draggingTarget.dragging = true;
  1149. this._x = e.offsetX;
  1150. this._y = e.offsetY;
  1151. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1152. }
  1153. },
  1154. _drag: function (e) {
  1155. var draggingTarget = this._draggingTarget;
  1156. if (draggingTarget) {
  1157. var x = e.offsetX;
  1158. var y = e.offsetY;
  1159. var dx = x - this._x;
  1160. var dy = y - this._y;
  1161. this._x = x;
  1162. this._y = y;
  1163. draggingTarget.drift(dx, dy, e);
  1164. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1165. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1166. var lastDropTarget = this._dropTarget;
  1167. this._dropTarget = dropTarget;
  1168. if (draggingTarget !== dropTarget) {
  1169. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1170. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1171. }
  1172. if (dropTarget && dropTarget !== lastDropTarget) {
  1173. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1174. }
  1175. }
  1176. }
  1177. },
  1178. _dragEnd: function (e) {
  1179. var draggingTarget = this._draggingTarget;
  1180. if (draggingTarget) {
  1181. draggingTarget.dragging = false;
  1182. }
  1183. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1184. if (this._dropTarget) {
  1185. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1186. }
  1187. this._draggingTarget = null;
  1188. this._dropTarget = null;
  1189. }
  1190. };
  1191. function param(target, e) {
  1192. return {target: target, topTarget: e && e.topTarget};
  1193. }
  1194. /**
  1195. * 事件扩展
  1196. * @module zrender/mixin/Eventful
  1197. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1198. * pissang (https://www.github.com/pissang)
  1199. */
  1200. var arrySlice = Array.prototype.slice;
  1201. /**
  1202. * 事件分发器
  1203. * @alias module:zrender/mixin/Eventful
  1204. * @constructor
  1205. */
  1206. var Eventful = function () {
  1207. this._$handlers = {};
  1208. };
  1209. Eventful.prototype = {
  1210. constructor: Eventful,
  1211. /**
  1212. * 单次触发绑定,trigger后销毁
  1213. *
  1214. * @param {string} event 事件名
  1215. * @param {Function} handler 响应函数
  1216. * @param {Object} context
  1217. */
  1218. one: function (event, handler, context) {
  1219. var _h = this._$handlers;
  1220. if (!handler || !event) {
  1221. return this;
  1222. }
  1223. if (!_h[event]) {
  1224. _h[event] = [];
  1225. }
  1226. for (var i = 0; i < _h[event].length; i++) {
  1227. if (_h[event][i].h === handler) {
  1228. return this;
  1229. }
  1230. }
  1231. _h[event].push({
  1232. h: handler,
  1233. one: true,
  1234. ctx: context || this
  1235. });
  1236. return this;
  1237. },
  1238. /**
  1239. * 绑定事件
  1240. * @param {string} event 事件名
  1241. * @param {Function} handler 事件处理函数
  1242. * @param {Object} [context]
  1243. */
  1244. on: function (event, handler, context) {
  1245. var _h = this._$handlers;
  1246. if (!handler || !event) {
  1247. return this;
  1248. }
  1249. if (!_h[event]) {
  1250. _h[event] = [];
  1251. }
  1252. for (var i = 0; i < _h[event].length; i++) {
  1253. if (_h[event][i].h === handler) {
  1254. return this;
  1255. }
  1256. }
  1257. _h[event].push({
  1258. h: handler,
  1259. one: false,
  1260. ctx: context || this
  1261. });
  1262. return this;
  1263. },
  1264. /**
  1265. * 是否绑定了事件
  1266. * @param {string} event
  1267. * @return {boolean}
  1268. */
  1269. isSilent: function (event) {
  1270. var _h = this._$handlers;
  1271. return _h[event] && _h[event].length;
  1272. },
  1273. /**
  1274. * 解绑事件
  1275. * @param {string} event 事件名
  1276. * @param {Function} [handler] 事件处理函数
  1277. */
  1278. off: function (event, handler) {
  1279. var _h = this._$handlers;
  1280. if (!event) {
  1281. this._$handlers = {};
  1282. return this;
  1283. }
  1284. if (handler) {
  1285. if (_h[event]) {
  1286. var newList = [];
  1287. for (var i = 0, l = _h[event].length; i < l; i++) {
  1288. if (_h[event][i]['h'] != handler) {
  1289. newList.push(_h[event][i]);
  1290. }
  1291. }
  1292. _h[event] = newList;
  1293. }
  1294. if (_h[event] && _h[event].length === 0) {
  1295. delete _h[event];
  1296. }
  1297. }
  1298. else {
  1299. delete _h[event];
  1300. }
  1301. return this;
  1302. },
  1303. /**
  1304. * 事件分发
  1305. *
  1306. * @param {string} type 事件类型
  1307. */
  1308. trigger: function (type) {
  1309. if (this._$handlers[type]) {
  1310. var args = arguments;
  1311. var argLen = args.length;
  1312. if (argLen > 3) {
  1313. args = arrySlice.call(args, 1);
  1314. }
  1315. var _h = this._$handlers[type];
  1316. var len = _h.length;
  1317. for (var i = 0; i < len;) {
  1318. // Optimize advise from backbone
  1319. switch (argLen) {
  1320. case 1:
  1321. _h[i]['h'].call(_h[i]['ctx']);
  1322. break;
  1323. case 2:
  1324. _h[i]['h'].call(_h[i]['ctx'], args[1]);
  1325. break;
  1326. case 3:
  1327. _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]);
  1328. break;
  1329. default:
  1330. // have more than 2 given arguments
  1331. _h[i]['h'].apply(_h[i]['ctx'], args);
  1332. break;
  1333. }
  1334. if (_h[i]['one']) {
  1335. _h.splice(i, 1);
  1336. len--;
  1337. }
  1338. else {
  1339. i++;
  1340. }
  1341. }
  1342. }
  1343. return this;
  1344. },
  1345. /**
  1346. * 带有context的事件分发, 最后一个参数是事件回调的context
  1347. * @param {string} type 事件类型
  1348. */
  1349. triggerWithContext: function (type) {
  1350. if (this._$handlers[type]) {
  1351. var args = arguments;
  1352. var argLen = args.length;
  1353. if (argLen > 4) {
  1354. args = arrySlice.call(args, 1, args.length - 1);
  1355. }
  1356. var ctx = args[args.length - 1];
  1357. var _h = this._$handlers[type];
  1358. var len = _h.length;
  1359. for (var i = 0; i < len;) {
  1360. // Optimize advise from backbone
  1361. switch (argLen) {
  1362. case 1:
  1363. _h[i]['h'].call(ctx);
  1364. break;
  1365. case 2:
  1366. _h[i]['h'].call(ctx, args[1]);
  1367. break;
  1368. case 3:
  1369. _h[i]['h'].call(ctx, args[1], args[2]);
  1370. break;
  1371. default:
  1372. // have more than 2 given arguments
  1373. _h[i]['h'].apply(ctx, args);
  1374. break;
  1375. }
  1376. if (_h[i]['one']) {
  1377. _h.splice(i, 1);
  1378. len--;
  1379. }
  1380. else {
  1381. i++;
  1382. }
  1383. }
  1384. }
  1385. return this;
  1386. }
  1387. };
  1388. var SILENT = 'silent';
  1389. function makeEventPacket(eveType, targetInfo, event) {
  1390. return {
  1391. type: eveType,
  1392. event: event,
  1393. // target can only be an element that is not silent.
  1394. target: targetInfo.target,
  1395. // topTarget can be a silent element.
  1396. topTarget: targetInfo.topTarget,
  1397. cancelBubble: false,
  1398. offsetX: event.zrX,
  1399. offsetY: event.zrY,
  1400. gestureEvent: event.gestureEvent,
  1401. pinchX: event.pinchX,
  1402. pinchY: event.pinchY,
  1403. pinchScale: event.pinchScale,
  1404. wheelDelta: event.zrDelta,
  1405. zrByTouch: event.zrByTouch,
  1406. which: event.which
  1407. };
  1408. }
  1409. function EmptyProxy () {}
  1410. EmptyProxy.prototype.dispose = function () {};
  1411. var handlerNames = [
  1412. 'click', 'dblclick', 'mousewheel', 'mouseout',
  1413. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  1414. ];
  1415. /**
  1416. * @alias module:zrender/Handler
  1417. * @constructor
  1418. * @extends module:zrender/mixin/Eventful
  1419. * @param {module:zrender/Storage} storage Storage instance.
  1420. * @param {module:zrender/Painter} painter Painter instance.
  1421. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1422. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1423. */
  1424. var Handler = function(storage, painter, proxy, painterRoot) {
  1425. Eventful.call(this);
  1426. this.storage = storage;
  1427. this.painter = painter;
  1428. this.painterRoot = painterRoot;
  1429. proxy = proxy || new EmptyProxy();
  1430. /**
  1431. * Proxy of event. can be Dom, WebGLSurface, etc.
  1432. */
  1433. this.proxy = null;
  1434. /**
  1435. * {target, topTarget, x, y}
  1436. * @private
  1437. * @type {Object}
  1438. */
  1439. this._hovered = {};
  1440. /**
  1441. * @private
  1442. * @type {Date}
  1443. */
  1444. this._lastTouchMoment;
  1445. /**
  1446. * @private
  1447. * @type {number}
  1448. */
  1449. this._lastX;
  1450. /**
  1451. * @private
  1452. * @type {number}
  1453. */
  1454. this._lastY;
  1455. Draggable.call(this);
  1456. this.setHandlerProxy(proxy);
  1457. };
  1458. Handler.prototype = {
  1459. constructor: Handler,
  1460. setHandlerProxy: function (proxy) {
  1461. if (this.proxy) {
  1462. this.proxy.dispose();
  1463. }
  1464. if (proxy) {
  1465. each$1(handlerNames, function (name) {
  1466. proxy.on && proxy.on(name, this[name], this);
  1467. }, this);
  1468. // Attach handler
  1469. proxy.handler = this;
  1470. }
  1471. this.proxy = proxy;
  1472. },
  1473. mousemove: function (event) {
  1474. var x = event.zrX;
  1475. var y = event.zrY;
  1476. var lastHovered = this._hovered;
  1477. var lastHoveredTarget = lastHovered.target;
  1478. // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  1479. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  1480. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  1481. // See #6198.
  1482. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  1483. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  1484. lastHoveredTarget = lastHovered.target;
  1485. }
  1486. var hovered = this._hovered = this.findHover(x, y);
  1487. var hoveredTarget = hovered.target;
  1488. var proxy = this.proxy;
  1489. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default');
  1490. // Mouse out on previous hovered element
  1491. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1492. this.dispatchToElement(lastHovered, 'mouseout', event);
  1493. }
  1494. // Mouse moving on one element
  1495. this.dispatchToElement(hovered, 'mousemove', event);
  1496. // Mouse over on a new element
  1497. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  1498. this.dispatchToElement(hovered, 'mouseover', event);
  1499. }
  1500. },
  1501. mouseout: function (event) {
  1502. this.dispatchToElement(this._hovered, 'mouseout', event);
  1503. // There might be some doms created by upper layer application
  1504. // at the same level of painter.getViewportRoot() (e.g., tooltip
  1505. // dom created by echarts), where 'globalout' event should not
  1506. // be triggered when mouse enters these doms. (But 'mouseout'
  1507. // should be triggered at the original hovered element as usual).
  1508. var element = event.toElement || event.relatedTarget;
  1509. var innerDom;
  1510. do {
  1511. element = element && element.parentNode;
  1512. }
  1513. while (element && element.nodeType != 9 && !(
  1514. innerDom = element === this.painterRoot
  1515. ));
  1516. !innerDom && this.trigger('globalout', {event: event});
  1517. },
  1518. /**
  1519. * Resize
  1520. */
  1521. resize: function (event) {
  1522. this._hovered = {};
  1523. },
  1524. /**
  1525. * Dispatch event
  1526. * @param {string} eventName
  1527. * @param {event=} eventArgs
  1528. */
  1529. dispatch: function (eventName, eventArgs) {
  1530. var handler = this[eventName];
  1531. handler && handler.call(this, eventArgs);
  1532. },
  1533. /**
  1534. * Dispose
  1535. */
  1536. dispose: function () {
  1537. this.proxy.dispose();
  1538. this.storage =
  1539. this.proxy =
  1540. this.painter = null;
  1541. },
  1542. /**
  1543. * 设置默认的cursor style
  1544. * @param {string} [cursorStyle='default'] 例如 crosshair
  1545. */
  1546. setCursorStyle: function (cursorStyle) {
  1547. var proxy = this.proxy;
  1548. proxy.setCursor && proxy.setCursor(cursorStyle);
  1549. },
  1550. /**
  1551. * 事件分发代理
  1552. *
  1553. * @private
  1554. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  1555. * @param {string} eventName 事件名称
  1556. * @param {Object} event 事件对象
  1557. */
  1558. dispatchToElement: function (targetInfo, eventName, event) {
  1559. targetInfo = targetInfo || {};
  1560. var el = targetInfo.target;
  1561. if (el && el.silent) {
  1562. return;
  1563. }
  1564. var eventHandler = 'on' + eventName;
  1565. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  1566. while (el) {
  1567. el[eventHandler]
  1568. && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  1569. el.trigger(eventName, eventPacket);
  1570. el = el.parent;
  1571. if (eventPacket.cancelBubble) {
  1572. break;
  1573. }
  1574. }
  1575. if (!eventPacket.cancelBubble) {
  1576. // 冒泡到顶级 zrender 对象
  1577. this.trigger(eventName, eventPacket);
  1578. // 分发事件到用户自定义层
  1579. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  1580. this.painter && this.painter.eachOtherLayer(function (layer) {
  1581. if (typeof(layer[eventHandler]) == 'function') {
  1582. layer[eventHandler].call(layer, eventPacket);
  1583. }
  1584. if (layer.trigger) {
  1585. layer.trigger(eventName, eventPacket);
  1586. }
  1587. });
  1588. }
  1589. },
  1590. /**
  1591. * @private
  1592. * @param {number} x
  1593. * @param {number} y
  1594. * @param {module:zrender/graphic/Displayable} exclude
  1595. * @return {model:zrender/Element}
  1596. * @method
  1597. */
  1598. findHover: function(x, y, exclude) {
  1599. var list = this.storage.getDisplayList();
  1600. var out = {x: x, y: y};
  1601. for (var i = list.length - 1; i >= 0 ; i--) {
  1602. var hoverCheckResult;
  1603. if (list[i] !== exclude
  1604. // getDisplayList may include ignored item in VML mode
  1605. && !list[i].ignore
  1606. && (hoverCheckResult = isHover(list[i], x, y))
  1607. ) {
  1608. !out.topTarget && (out.topTarget = list[i]);
  1609. if (hoverCheckResult !== SILENT) {
  1610. out.target = list[i];
  1611. break;
  1612. }
  1613. }
  1614. }
  1615. return out;
  1616. }
  1617. };
  1618. // Common handlers
  1619. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  1620. Handler.prototype[name] = function (event) {
  1621. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  1622. var hovered = this.findHover(event.zrX, event.zrY);
  1623. var hoveredTarget = hovered.target;
  1624. if (name === 'mousedown') {
  1625. this._downEl = hoveredTarget;
  1626. this._downPoint = [event.zrX, event.zrY];
  1627. // In case click triggered before mouseup
  1628. this._upEl = hoveredTarget;
  1629. }
  1630. else if (name === 'mouseup') {
  1631. this._upEl = hoveredTarget;
  1632. }
  1633. else if (name === 'click') {
  1634. if (this._downEl !== this._upEl
  1635. // Original click event is triggered on the whole canvas element,
  1636. // including the case that `mousedown` - `mousemove` - `mouseup`,
  1637. // which should be filtered, otherwise it will bring trouble to
  1638. // pan and zoom.
  1639. || !this._downPoint
  1640. // Arbitrary value
  1641. || dist(this._downPoint, [event.zrX, event.zrY]) > 4
  1642. ) {
  1643. return;
  1644. }
  1645. this._downPoint = null;
  1646. }
  1647. this.dispatchToElement(hovered, name, event);
  1648. };
  1649. });
  1650. function isHover(displayable, x, y) {
  1651. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  1652. var el = displayable;
  1653. var isSilent;
  1654. while (el) {
  1655. // If clipped by ancestor.
  1656. // FIXME: If clipPath has neither stroke nor fill,
  1657. // el.clipPath.contain(x, y) will always return false.
  1658. if (el.clipPath && !el.clipPath.contain(x, y)) {
  1659. return false;
  1660. }
  1661. if (el.silent) {
  1662. isSilent = true;
  1663. }
  1664. el = el.parent;
  1665. }
  1666. return isSilent ? SILENT : true;
  1667. }
  1668. return false;
  1669. }
  1670. mixin(Handler, Eventful);
  1671. mixin(Handler, Draggable);
  1672. /**
  1673. * 3x2矩阵操作类
  1674. * @exports zrender/tool/matrix
  1675. */
  1676. var ArrayCtor$1 = typeof Float32Array === 'undefined'
  1677. ? Array
  1678. : Float32Array;
  1679. /**
  1680. * Create a identity matrix.
  1681. * @return {Float32Array|Array.<number>}
  1682. */
  1683. function create$1() {
  1684. var out = new ArrayCtor$1(6);
  1685. identity(out);
  1686. return out;
  1687. }
  1688. /**
  1689. * 设置矩阵为单位矩阵
  1690. * @param {Float32Array|Array.<number>} out
  1691. */
  1692. function identity(out) {
  1693. out[0] = 1;
  1694. out[1] = 0;
  1695. out[2] = 0;
  1696. out[3] = 1;
  1697. out[4] = 0;
  1698. out[5] = 0;
  1699. return out;
  1700. }
  1701. /**
  1702. * 复制矩阵
  1703. * @param {Float32Array|Array.<number>} out
  1704. * @param {Float32Array|Array.<number>} m
  1705. */
  1706. function copy$1(out, m) {
  1707. out[0] = m[0];
  1708. out[1] = m[1];
  1709. out[2] = m[2];
  1710. out[3] = m[3];
  1711. out[4] = m[4];
  1712. out[5] = m[5];
  1713. return out;
  1714. }
  1715. /**
  1716. * 矩阵相乘
  1717. * @param {Float32Array|Array.<number>} out
  1718. * @param {Float32Array|Array.<number>} m1
  1719. * @param {Float32Array|Array.<number>} m2
  1720. */
  1721. function mul$1(out, m1, m2) {
  1722. // Consider matrix.mul(m, m2, m);
  1723. // where out is the same as m2.
  1724. // So use temp variable to escape error.
  1725. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  1726. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  1727. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  1728. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  1729. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  1730. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  1731. out[0] = out0;
  1732. out[1] = out1;
  1733. out[2] = out2;
  1734. out[3] = out3;
  1735. out[4] = out4;
  1736. out[5] = out5;
  1737. return out;
  1738. }
  1739. /**
  1740. * 平移变换
  1741. * @param {Float32Array|Array.<number>} out
  1742. * @param {Float32Array|Array.<number>} a
  1743. * @param {Float32Array|Array.<number>} v
  1744. */
  1745. function translate(out, a, v) {
  1746. out[0] = a[0];
  1747. out[1] = a[1];
  1748. out[2] = a[2];
  1749. out[3] = a[3];
  1750. out[4] = a[4] + v[0];
  1751. out[5] = a[5] + v[1];
  1752. return out;
  1753. }
  1754. /**
  1755. * 旋转变换
  1756. * @param {Float32Array|Array.<number>} out
  1757. * @param {Float32Array|Array.<number>} a
  1758. * @param {number} rad
  1759. */
  1760. function rotate(out, a, rad) {
  1761. var aa = a[0];
  1762. var ac = a[2];
  1763. var atx = a[4];
  1764. var ab = a[1];
  1765. var ad = a[3];
  1766. var aty = a[5];
  1767. var st = Math.sin(rad);
  1768. var ct = Math.cos(rad);
  1769. out[0] = aa * ct + ab * st;
  1770. out[1] = -aa * st + ab * ct;
  1771. out[2] = ac * ct + ad * st;
  1772. out[3] = -ac * st + ct * ad;
  1773. out[4] = ct * atx + st * aty;
  1774. out[5] = ct * aty - st * atx;
  1775. return out;
  1776. }
  1777. /**
  1778. * 缩放变换
  1779. * @param {Float32Array|Array.<number>} out
  1780. * @param {Float32Array|Array.<number>} a
  1781. * @param {Float32Array|Array.<number>} v
  1782. */
  1783. function scale$1(out, a, v) {
  1784. var vx = v[0];
  1785. var vy = v[1];
  1786. out[0] = a[0] * vx;
  1787. out[1] = a[1] * vy;
  1788. out[2] = a[2] * vx;
  1789. out[3] = a[3] * vy;
  1790. out[4] = a[4] * vx;
  1791. out[5] = a[5] * vy;
  1792. return out;
  1793. }
  1794. /**
  1795. * 求逆矩阵
  1796. * @param {Float32Array|Array.<number>} out
  1797. * @param {Float32Array|Array.<number>} a
  1798. */
  1799. function invert(out, a) {
  1800. var aa = a[0];
  1801. var ac = a[2];
  1802. var atx = a[4];
  1803. var ab = a[1];
  1804. var ad = a[3];
  1805. var aty = a[5];
  1806. var det = aa * ad - ab * ac;
  1807. if (!det) {
  1808. return null;
  1809. }
  1810. det = 1.0 / det;
  1811. out[0] = ad * det;
  1812. out[1] = -ab * det;
  1813. out[2] = -ac * det;
  1814. out[3] = aa * det;
  1815. out[4] = (ac * aty - ad * atx) * det;
  1816. out[5] = (ab * atx - aa * aty) * det;
  1817. return out;
  1818. }
  1819. /**
  1820. * Clone a new matrix.
  1821. * @param {Float32Array|Array.<number>} a
  1822. */
  1823. function clone$2(a) {
  1824. var b = create$1();
  1825. copy$1(b, a);
  1826. return b;
  1827. }
  1828. var matrix = (Object.freeze || Object)({
  1829. create: create$1,
  1830. identity: identity,
  1831. copy: copy$1,
  1832. mul: mul$1,
  1833. translate: translate,
  1834. rotate: rotate,
  1835. scale: scale$1,
  1836. invert: invert,
  1837. clone: clone$2
  1838. });
  1839. /**
  1840. * 提供变换扩展
  1841. * @module zrender/mixin/Transformable
  1842. * @author pissang (https://www.github.com/pissang)
  1843. */
  1844. var mIdentity = identity;
  1845. var EPSILON = 5e-5;
  1846. function isNotAroundZero(val) {
  1847. return val > EPSILON || val < -EPSILON;
  1848. }
  1849. /**
  1850. * @alias module:zrender/mixin/Transformable
  1851. * @constructor
  1852. */
  1853. var Transformable = function (opts) {
  1854. opts = opts || {};
  1855. // If there are no given position, rotation, scale
  1856. if (!opts.position) {
  1857. /**
  1858. * 平移
  1859. * @type {Array.<number>}
  1860. * @default [0, 0]
  1861. */
  1862. this.position = [0, 0];
  1863. }
  1864. if (opts.rotation == null) {
  1865. /**
  1866. * 旋转
  1867. * @type {Array.<number>}
  1868. * @default 0
  1869. */
  1870. this.rotation = 0;
  1871. }
  1872. if (!opts.scale) {
  1873. /**
  1874. * 缩放
  1875. * @type {Array.<number>}
  1876. * @default [1, 1]
  1877. */
  1878. this.scale = [1, 1];
  1879. }
  1880. /**
  1881. * 旋转和缩放的原点
  1882. * @type {Array.<number>}
  1883. * @default null
  1884. */
  1885. this.origin = this.origin || null;
  1886. };
  1887. var transformableProto = Transformable.prototype;
  1888. transformableProto.transform = null;
  1889. /**
  1890. * 判断是否需要有坐标变换
  1891. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  1892. */
  1893. transformableProto.needLocalTransform = function () {
  1894. return isNotAroundZero(this.rotation)
  1895. || isNotAroundZero(this.position[0])
  1896. || isNotAroundZero(this.position[1])
  1897. || isNotAroundZero(this.scale[0] - 1)
  1898. || isNotAroundZero(this.scale[1] - 1);
  1899. };
  1900. transformableProto.updateTransform = function () {
  1901. var parent = this.parent;
  1902. var parentHasTransform = parent && parent.transform;
  1903. var needLocalTransform = this.needLocalTransform();
  1904. var m = this.transform;
  1905. if (!(needLocalTransform || parentHasTransform)) {
  1906. m && mIdentity(m);
  1907. return;
  1908. }
  1909. m = m || create$1();
  1910. if (needLocalTransform) {
  1911. this.getLocalTransform(m);
  1912. }
  1913. else {
  1914. mIdentity(m);
  1915. }
  1916. // 应用父节点变换
  1917. if (parentHasTransform) {
  1918. if (needLocalTransform) {
  1919. mul$1(m, parent.transform, m);
  1920. }
  1921. else {
  1922. copy$1(m, parent.transform);
  1923. }
  1924. }
  1925. // 保存这个变换矩阵
  1926. this.transform = m;
  1927. this.invTransform = this.invTransform || create$1();
  1928. invert(this.invTransform, m);
  1929. };
  1930. transformableProto.getLocalTransform = function (m) {
  1931. return Transformable.getLocalTransform(this, m);
  1932. };
  1933. /**
  1934. * 将自己的transform应用到context上
  1935. * @param {CanvasRenderingContext2D} ctx
  1936. */
  1937. transformableProto.setTransform = function (ctx) {
  1938. var m = this.transform;
  1939. var dpr = ctx.dpr || 1;
  1940. if (m) {
  1941. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  1942. }
  1943. else {
  1944. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1945. }
  1946. };
  1947. transformableProto.restoreTransform = function (ctx) {
  1948. var dpr = ctx.dpr || 1;
  1949. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  1950. };
  1951. var tmpTransform = [];
  1952. /**
  1953. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  1954. */
  1955. transformableProto.decomposeTransform = function () {
  1956. if (!this.transform) {
  1957. return;
  1958. }
  1959. var parent = this.parent;
  1960. var m = this.transform;
  1961. if (parent && parent.transform) {
  1962. // Get local transform and decompose them to position, scale, rotation
  1963. mul$1(tmpTransform, parent.invTransform, m);
  1964. m = tmpTransform;
  1965. }
  1966. var sx = m[0] * m[0] + m[1] * m[1];
  1967. var sy = m[2] * m[2] + m[3] * m[3];
  1968. var position = this.position;
  1969. var scale$$1 = this.scale;
  1970. if (isNotAroundZero(sx - 1)) {
  1971. sx = Math.sqrt(sx);
  1972. }
  1973. if (isNotAroundZero(sy - 1)) {
  1974. sy = Math.sqrt(sy);
  1975. }
  1976. if (m[0] < 0) {
  1977. sx = -sx;
  1978. }
  1979. if (m[3] < 0) {
  1980. sy = -sy;
  1981. }
  1982. position[0] = m[4];
  1983. position[1] = m[5];
  1984. scale$$1[0] = sx;
  1985. scale$$1[1] = sy;
  1986. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  1987. };
  1988. /**
  1989. * Get global scale
  1990. * @return {Array.<number>}
  1991. */
  1992. transformableProto.getGlobalScale = function () {
  1993. var m = this.transform;
  1994. if (!m) {
  1995. return [1, 1];
  1996. }
  1997. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  1998. var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  1999. if (m[0] < 0) {
  2000. sx = -sx;
  2001. }
  2002. if (m[3] < 0) {
  2003. sy = -sy;
  2004. }
  2005. return [sx, sy];
  2006. };
  2007. /**
  2008. * 变换坐标位置到 shape 的局部坐标空间
  2009. * @method
  2010. * @param {number} x
  2011. * @param {number} y
  2012. * @return {Array.<number>}
  2013. */
  2014. transformableProto.transformCoordToLocal = function (x, y) {
  2015. var v2 = [x, y];
  2016. var invTransform = this.invTransform;
  2017. if (invTransform) {
  2018. applyTransform(v2, v2, invTransform);
  2019. }
  2020. return v2;
  2021. };
  2022. /**
  2023. * 变换局部坐标位置到全局坐标空间
  2024. * @method
  2025. * @param {number} x
  2026. * @param {number} y
  2027. * @return {Array.<number>}
  2028. */
  2029. transformableProto.transformCoordToGlobal = function (x, y) {
  2030. var v2 = [x, y];
  2031. var transform = this.transform;
  2032. if (transform) {
  2033. applyTransform(v2, v2, transform);
  2034. }
  2035. return v2;
  2036. };
  2037. /**
  2038. * @static
  2039. * @param {Object} target
  2040. * @param {Array.<number>} target.origin
  2041. * @param {number} target.rotation
  2042. * @param {Array.<number>} target.position
  2043. * @param {Array.<number>} [m]
  2044. */
  2045. Transformable.getLocalTransform = function (target, m) {
  2046. m = m || [];
  2047. mIdentity(m);
  2048. var origin = target.origin;
  2049. var scale$$1 = target.scale || [1, 1];
  2050. var rotation = target.rotation || 0;
  2051. var position = target.position || [0, 0];
  2052. if (origin) {
  2053. // Translate to origin
  2054. m[4] -= origin[0];
  2055. m[5] -= origin[1];
  2056. }
  2057. scale$1(m, m, scale$$1);
  2058. if (rotation) {
  2059. rotate(m, m, rotation);
  2060. }
  2061. if (origin) {
  2062. // Translate back from origin
  2063. m[4] += origin[0];
  2064. m[5] += origin[1];
  2065. }
  2066. m[4] += position[0];
  2067. m[5] += position[1];
  2068. return m;
  2069. };
  2070. /**
  2071. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2072. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2073. * @exports zrender/animation/easing
  2074. */
  2075. var easing = {
  2076. /**
  2077. * @param {number} k
  2078. * @return {number}
  2079. */
  2080. linear: function (k) {
  2081. return k;
  2082. },
  2083. /**
  2084. * @param {number} k
  2085. * @return {number}
  2086. */
  2087. quadraticIn: function (k) {
  2088. return k * k;
  2089. },
  2090. /**
  2091. * @param {number} k
  2092. * @return {number}
  2093. */
  2094. quadraticOut: function (k) {
  2095. return k * (2 - k);
  2096. },
  2097. /**
  2098. * @param {number} k
  2099. * @return {number}
  2100. */
  2101. quadraticInOut: function (k) {
  2102. if ((k *= 2) < 1) {
  2103. return 0.5 * k * k;
  2104. }
  2105. return -0.5 * (--k * (k - 2) - 1);
  2106. },
  2107. // 三次方的缓动(t^3)
  2108. /**
  2109. * @param {number} k
  2110. * @return {number}
  2111. */
  2112. cubicIn: function (k) {
  2113. return k * k * k;
  2114. },
  2115. /**
  2116. * @param {number} k
  2117. * @return {number}
  2118. */
  2119. cubicOut: function (k) {
  2120. return --k * k * k + 1;
  2121. },
  2122. /**
  2123. * @param {number} k
  2124. * @return {number}
  2125. */
  2126. cubicInOut: function (k) {
  2127. if ((k *= 2) < 1) {
  2128. return 0.5 * k * k * k;
  2129. }
  2130. return 0.5 * ((k -= 2) * k * k + 2);
  2131. },
  2132. // 四次方的缓动(t^4)
  2133. /**
  2134. * @param {number} k
  2135. * @return {number}
  2136. */
  2137. quarticIn: function (k) {
  2138. return k * k * k * k;
  2139. },
  2140. /**
  2141. * @param {number} k
  2142. * @return {number}
  2143. */
  2144. quarticOut: function (k) {
  2145. return 1 - (--k * k * k * k);
  2146. },
  2147. /**
  2148. * @param {number} k
  2149. * @return {number}
  2150. */
  2151. quarticInOut: function (k) {
  2152. if ((k *= 2) < 1) {
  2153. return 0.5 * k * k * k * k;
  2154. }
  2155. return -0.5 * ((k -= 2) * k * k * k - 2);
  2156. },
  2157. // 五次方的缓动(t^5)
  2158. /**
  2159. * @param {number} k
  2160. * @return {number}
  2161. */
  2162. quinticIn: function (k) {
  2163. return k * k * k * k * k;
  2164. },
  2165. /**
  2166. * @param {number} k
  2167. * @return {number}
  2168. */
  2169. quinticOut: function (k) {
  2170. return --k * k * k * k * k + 1;
  2171. },
  2172. /**
  2173. * @param {number} k
  2174. * @return {number}
  2175. */
  2176. quinticInOut: function (k) {
  2177. if ((k *= 2) < 1) {
  2178. return 0.5 * k * k * k * k * k;
  2179. }
  2180. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2181. },
  2182. // 正弦曲线的缓动(sin(t))
  2183. /**
  2184. * @param {number} k
  2185. * @return {number}
  2186. */
  2187. sinusoidalIn: function (k) {
  2188. return 1 - Math.cos(k * Math.PI / 2);
  2189. },
  2190. /**
  2191. * @param {number} k
  2192. * @return {number}
  2193. */
  2194. sinusoidalOut: function (k) {
  2195. return Math.sin(k * Math.PI / 2);
  2196. },
  2197. /**
  2198. * @param {number} k
  2199. * @return {number}
  2200. */
  2201. sinusoidalInOut: function (k) {
  2202. return 0.5 * (1 - Math.cos(Math.PI * k));
  2203. },
  2204. // 指数曲线的缓动(2^t)
  2205. /**
  2206. * @param {number} k
  2207. * @return {number}
  2208. */
  2209. exponentialIn: function (k) {
  2210. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2211. },
  2212. /**
  2213. * @param {number} k
  2214. * @return {number}
  2215. */
  2216. exponentialOut: function (k) {
  2217. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2218. },
  2219. /**
  2220. * @param {number} k
  2221. * @return {number}
  2222. */
  2223. exponentialInOut: function (k) {
  2224. if (k === 0) {
  2225. return 0;
  2226. }
  2227. if (k === 1) {
  2228. return 1;
  2229. }
  2230. if ((k *= 2) < 1) {
  2231. return 0.5 * Math.pow(1024, k - 1);
  2232. }
  2233. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2234. },
  2235. // 圆形曲线的缓动(sqrt(1-t^2))
  2236. /**
  2237. * @param {number} k
  2238. * @return {number}
  2239. */
  2240. circularIn: function (k) {
  2241. return 1 - Math.sqrt(1 - k * k);
  2242. },
  2243. /**
  2244. * @param {number} k
  2245. * @return {number}
  2246. */
  2247. circularOut: function (k) {
  2248. return Math.sqrt(1 - (--k * k));
  2249. },
  2250. /**
  2251. * @param {number} k
  2252. * @return {number}
  2253. */
  2254. circularInOut: function (k) {
  2255. if ((k *= 2) < 1) {
  2256. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2257. }
  2258. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2259. },
  2260. // 创建类似于弹簧在停止前来回振荡的动画
  2261. /**
  2262. * @param {number} k
  2263. * @return {number}
  2264. */
  2265. elasticIn: function (k) {
  2266. var s;
  2267. var a = 0.1;
  2268. var p = 0.4;
  2269. if (k === 0) {
  2270. return 0;
  2271. }
  2272. if (k === 1) {
  2273. return 1;
  2274. }
  2275. if (!a || a < 1) {
  2276. a = 1; s = p / 4;
  2277. }
  2278. else {
  2279. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2280. }
  2281. return -(a * Math.pow(2, 10 * (k -= 1)) *
  2282. Math.sin((k - s) * (2 * Math.PI) / p));
  2283. },
  2284. /**
  2285. * @param {number} k
  2286. * @return {number}
  2287. */
  2288. elasticOut: function (k) {
  2289. var s;
  2290. var a = 0.1;
  2291. var p = 0.4;
  2292. if (k === 0) {
  2293. return 0;
  2294. }
  2295. if (k === 1) {
  2296. return 1;
  2297. }
  2298. if (!a || a < 1) {
  2299. a = 1; s = p / 4;
  2300. }
  2301. else {
  2302. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2303. }
  2304. return (a * Math.pow(2, -10 * k) *
  2305. Math.sin((k - s) * (2 * Math.PI) / p) + 1);
  2306. },
  2307. /**
  2308. * @param {number} k
  2309. * @return {number}
  2310. */
  2311. elasticInOut: function (k) {
  2312. var s;
  2313. var a = 0.1;
  2314. var p = 0.4;
  2315. if (k === 0) {
  2316. return 0;
  2317. }
  2318. if (k === 1) {
  2319. return 1;
  2320. }
  2321. if (!a || a < 1) {
  2322. a = 1; s = p / 4;
  2323. }
  2324. else {
  2325. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2326. }
  2327. if ((k *= 2) < 1) {
  2328. return -0.5 * (a * Math.pow(2, 10 * (k -= 1))
  2329. * Math.sin((k - s) * (2 * Math.PI) / p));
  2330. }
  2331. return a * Math.pow(2, -10 * (k -= 1))
  2332. * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2333. },
  2334. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2335. /**
  2336. * @param {number} k
  2337. * @return {number}
  2338. */
  2339. backIn: function (k) {
  2340. var s = 1.70158;
  2341. return k * k * ((s + 1) * k - s);
  2342. },
  2343. /**
  2344. * @param {number} k
  2345. * @return {number}
  2346. */
  2347. backOut: function (k) {
  2348. var s = 1.70158;
  2349. return --k * k * ((s + 1) * k + s) + 1;
  2350. },
  2351. /**
  2352. * @param {number} k
  2353. * @return {number}
  2354. */
  2355. backInOut: function (k) {
  2356. var s = 1.70158 * 1.525;
  2357. if ((k *= 2) < 1) {
  2358. return 0.5 * (k * k * ((s + 1) * k - s));
  2359. }
  2360. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2361. },
  2362. // 创建弹跳效果
  2363. /**
  2364. * @param {number} k
  2365. * @return {number}
  2366. */
  2367. bounceIn: function (k) {
  2368. return 1 - easing.bounceOut(1 - k);
  2369. },
  2370. /**
  2371. * @param {number} k
  2372. * @return {number}
  2373. */
  2374. bounceOut: function (k) {
  2375. if (k < (1 / 2.75)) {
  2376. return 7.5625 * k * k;
  2377. }
  2378. else if (k < (2 / 2.75)) {
  2379. return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75;
  2380. }
  2381. else if (k < (2.5 / 2.75)) {
  2382. return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375;
  2383. }
  2384. else {
  2385. return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375;
  2386. }
  2387. },
  2388. /**
  2389. * @param {number} k
  2390. * @return {number}
  2391. */
  2392. bounceInOut: function (k) {
  2393. if (k < 0.5) {
  2394. return easing.bounceIn(k * 2) * 0.5;
  2395. }
  2396. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2397. }
  2398. };
  2399. /**
  2400. * 动画主控制器
  2401. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2402. * @config life(1000) 动画时长
  2403. * @config delay(0) 动画延迟时间
  2404. * @config loop(true)
  2405. * @config gap(0) 循环的间隔时间
  2406. * @config onframe
  2407. * @config easing(optional)
  2408. * @config ondestroy(optional)
  2409. * @config onrestart(optional)
  2410. *
  2411. * TODO pause
  2412. */
  2413. function Clip(options) {
  2414. this._target = options.target;
  2415. // 生命周期
  2416. this._life = options.life || 1000;
  2417. // 延时
  2418. this._delay = options.delay || 0;
  2419. // 开始时间
  2420. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2421. this._initialized = false;
  2422. // 是否循环
  2423. this.loop = options.loop == null ? false : options.loop;
  2424. this.gap = options.gap || 0;
  2425. this.easing = options.easing || 'Linear';
  2426. this.onframe = options.onframe;
  2427. this.ondestroy = options.ondestroy;
  2428. this.onrestart = options.onrestart;
  2429. this._pausedTime = 0;
  2430. this._paused = false;
  2431. }
  2432. Clip.prototype = {
  2433. constructor: Clip,
  2434. step: function (globalTime, deltaTime) {
  2435. // Set startTime on first step, or _startTime may has milleseconds different between clips
  2436. // PENDING
  2437. if (!this._initialized) {
  2438. this._startTime = globalTime + this._delay;
  2439. this._initialized = true;
  2440. }
  2441. if (this._paused) {
  2442. this._pausedTime += deltaTime;
  2443. return;
  2444. }
  2445. var percent = (globalTime - this._startTime - this._pausedTime) / this._life;
  2446. // 还没开始
  2447. if (percent < 0) {
  2448. return;
  2449. }
  2450. percent = Math.min(percent, 1);
  2451. var easing$$1 = this.easing;
  2452. var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1;
  2453. var schedule = typeof easingFunc === 'function'
  2454. ? easingFunc(percent)
  2455. : percent;
  2456. this.fire('frame', schedule);
  2457. // 结束
  2458. if (percent == 1) {
  2459. if (this.loop) {
  2460. this.restart (globalTime);
  2461. // 重新开始周期
  2462. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  2463. return 'restart';
  2464. }
  2465. // 动画完成将这个控制器标识为待删除
  2466. // 在Animation.update中进行批量删除
  2467. this._needsRemove = true;
  2468. return 'destroy';
  2469. }
  2470. return null;
  2471. },
  2472. restart: function (globalTime) {
  2473. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  2474. this._startTime = globalTime - remainder + this.gap;
  2475. this._pausedTime = 0;
  2476. this._needsRemove = false;
  2477. },
  2478. fire: function (eventType, arg) {
  2479. eventType = 'on' + eventType;
  2480. if (this[eventType]) {
  2481. this[eventType](this._target, arg);
  2482. }
  2483. },
  2484. pause: function () {
  2485. this._paused = true;
  2486. },
  2487. resume: function () {
  2488. this._paused = false;
  2489. }
  2490. };
  2491. // Simple LRU cache use doubly linked list
  2492. // @module zrender/core/LRU
  2493. /**
  2494. * Simple double linked list. Compared with array, it has O(1) remove operation.
  2495. * @constructor
  2496. */
  2497. var LinkedList = function () {
  2498. /**
  2499. * @type {module:zrender/core/LRU~Entry}
  2500. */
  2501. this.head = null;
  2502. /**
  2503. * @type {module:zrender/core/LRU~Entry}
  2504. */
  2505. this.tail = null;
  2506. this._len = 0;
  2507. };
  2508. var linkedListProto = LinkedList.prototype;
  2509. /**
  2510. * Insert a new value at the tail
  2511. * @param {} val
  2512. * @return {module:zrender/core/LRU~Entry}
  2513. */
  2514. linkedListProto.insert = function (val) {
  2515. var entry = new Entry(val);
  2516. this.insertEntry(entry);
  2517. return entry;
  2518. };
  2519. /**
  2520. * Insert an entry at the tail
  2521. * @param {module:zrender/core/LRU~Entry} entry
  2522. */
  2523. linkedListProto.insertEntry = function (entry) {
  2524. if (!this.head) {
  2525. this.head = this.tail = entry;
  2526. }
  2527. else {
  2528. this.tail.next = entry;
  2529. entry.prev = this.tail;
  2530. entry.next = null;
  2531. this.tail = entry;
  2532. }
  2533. this._len++;
  2534. };
  2535. /**
  2536. * Remove entry.
  2537. * @param {module:zrender/core/LRU~Entry} entry
  2538. */
  2539. linkedListProto.remove = function (entry) {
  2540. var prev = entry.prev;
  2541. var next = entry.next;
  2542. if (prev) {
  2543. prev.next = next;
  2544. }
  2545. else {
  2546. // Is head
  2547. this.head = next;
  2548. }
  2549. if (next) {
  2550. next.prev = prev;
  2551. }
  2552. else {
  2553. // Is tail
  2554. this.tail = prev;
  2555. }
  2556. entry.next = entry.prev = null;
  2557. this._len--;
  2558. };
  2559. /**
  2560. * @return {number}
  2561. */
  2562. linkedListProto.len = function () {
  2563. return this._len;
  2564. };
  2565. /**
  2566. * Clear list
  2567. */
  2568. linkedListProto.clear = function () {
  2569. this.head = this.tail = null;
  2570. this._len = 0;
  2571. };
  2572. /**
  2573. * @constructor
  2574. * @param {} val
  2575. */
  2576. var Entry = function (val) {
  2577. /**
  2578. * @type {}
  2579. */
  2580. this.value = val;
  2581. /**
  2582. * @type {module:zrender/core/LRU~Entry}
  2583. */
  2584. this.next;
  2585. /**
  2586. * @type {module:zrender/core/LRU~Entry}
  2587. */
  2588. this.prev;
  2589. };
  2590. /**
  2591. * LRU Cache
  2592. * @constructor
  2593. * @alias module:zrender/core/LRU
  2594. */
  2595. var LRU = function (maxSize) {
  2596. this._list = new LinkedList();
  2597. this._map = {};
  2598. this._maxSize = maxSize || 10;
  2599. this._lastRemovedEntry = null;
  2600. };
  2601. var LRUProto = LRU.prototype;
  2602. /**
  2603. * @param {string} key
  2604. * @param {} value
  2605. * @return {} Removed value
  2606. */
  2607. LRUProto.put = function (key, value) {
  2608. var list = this._list;
  2609. var map = this._map;
  2610. var removed = null;
  2611. if (map[key] == null) {
  2612. var len = list.len();
  2613. // Reuse last removed entry
  2614. var entry = this._lastRemovedEntry;
  2615. if (len >= this._maxSize && len > 0) {
  2616. // Remove the least recently used
  2617. var leastUsedEntry = list.head;
  2618. list.remove(leastUsedEntry);
  2619. delete map[leastUsedEntry.key];
  2620. removed = leastUsedEntry.value;
  2621. this._lastRemovedEntry = leastUsedEntry;
  2622. }
  2623. if (entry) {
  2624. entry.value = value;
  2625. }
  2626. else {
  2627. entry = new Entry(value);
  2628. }
  2629. entry.key = key;
  2630. list.insertEntry(entry);
  2631. map[key] = entry;
  2632. }
  2633. return removed;
  2634. };
  2635. /**
  2636. * @param {string} key
  2637. * @return {}
  2638. */
  2639. LRUProto.get = function (key) {
  2640. var entry = this._map[key];
  2641. var list = this._list;
  2642. if (entry != null) {
  2643. // Put the latest used entry in the tail
  2644. if (entry !== list.tail) {
  2645. list.remove(entry);
  2646. list.insertEntry(entry);
  2647. }
  2648. return entry.value;
  2649. }
  2650. };
  2651. /**
  2652. * Clear the cache
  2653. */
  2654. LRUProto.clear = function () {
  2655. this._list.clear();
  2656. this._map = {};
  2657. };
  2658. var kCSSColorTable = {
  2659. 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1],
  2660. 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1],
  2661. 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1],
  2662. 'beige': [245,245,220,1], 'bisque': [255,228,196,1],
  2663. 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1],
  2664. 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1],
  2665. 'brown': [165,42,42,1], 'burlywood': [222,184,135,1],
  2666. 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1],
  2667. 'chocolate': [210,105,30,1], 'coral': [255,127,80,1],
  2668. 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1],
  2669. 'crimson': [220,20,60,1], 'cyan': [0,255,255,1],
  2670. 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1],
  2671. 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1],
  2672. 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1],
  2673. 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1],
  2674. 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1],
  2675. 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1],
  2676. 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1],
  2677. 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1],
  2678. 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1],
  2679. 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1],
  2680. 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1],
  2681. 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1],
  2682. 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1],
  2683. 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1],
  2684. 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1],
  2685. 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1],
  2686. 'gray': [128,128,128,1], 'green': [0,128,0,1],
  2687. 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1],
  2688. 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1],
  2689. 'indianred': [205,92,92,1], 'indigo': [75,0,130,1],
  2690. 'ivory': [255,255,240,1], 'khaki': [240,230,140,1],
  2691. 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1],
  2692. 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1],
  2693. 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1],
  2694. 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1],
  2695. 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1],
  2696. 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1],
  2697. 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1],
  2698. 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1],
  2699. 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1],
  2700. 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1],
  2701. 'limegreen': [50,205,50,1], 'linen': [250,240,230,1],
  2702. 'magenta': [255,0,255,1], 'maroon': [128,0,0,1],
  2703. 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1],
  2704. 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1],
  2705. 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1],
  2706. 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1],
  2707. 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1],
  2708. 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1],
  2709. 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1],
  2710. 'navy': [0,0,128,1], 'oldlace': [253,245,230,1],
  2711. 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1],
  2712. 'orange': [255,165,0,1], 'orangered': [255,69,0,1],
  2713. 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1],
  2714. 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1],
  2715. 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1],
  2716. 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1],
  2717. 'pink': [255,192,203,1], 'plum': [221,160,221,1],
  2718. 'powderblue': [176,224,230,1], 'purple': [128,0,128,1],
  2719. 'red': [255,0,0,1], 'rosybrown': [188,143,143,1],
  2720. 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1],
  2721. 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1],
  2722. 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1],
  2723. 'sienna': [160,82,45,1], 'silver': [192,192,192,1],
  2724. 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1],
  2725. 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1],
  2726. 'snow': [255,250,250,1], 'springgreen': [0,255,127,1],
  2727. 'steelblue': [70,130,180,1], 'tan': [210,180,140,1],
  2728. 'teal': [0,128,128,1], 'thistle': [216,191,216,1],
  2729. 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1],
  2730. 'violet': [238,130,238,1], 'wheat': [245,222,179,1],
  2731. 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1],
  2732. 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1]
  2733. };
  2734. function clampCssByte(i) { // Clamp to integer 0 .. 255.
  2735. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2736. return i < 0 ? 0 : i > 255 ? 255 : i;
  2737. }
  2738. function clampCssAngle(i) { // Clamp to integer 0 .. 360.
  2739. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  2740. return i < 0 ? 0 : i > 360 ? 360 : i;
  2741. }
  2742. function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0.
  2743. return f < 0 ? 0 : f > 1 ? 1 : f;
  2744. }
  2745. function parseCssInt(str) { // int or percentage.
  2746. if (str.length && str.charAt(str.length - 1) === '%') {
  2747. return clampCssByte(parseFloat(str) / 100 * 255);
  2748. }
  2749. return clampCssByte(parseInt(str, 10));
  2750. }
  2751. function parseCssFloat(str) { // float or percentage.
  2752. if (str.length && str.charAt(str.length - 1) === '%') {
  2753. return clampCssFloat(parseFloat(str) / 100);
  2754. }
  2755. return clampCssFloat(parseFloat(str));
  2756. }
  2757. function cssHueToRgb(m1, m2, h) {
  2758. if (h < 0) {
  2759. h += 1;
  2760. }
  2761. else if (h > 1) {
  2762. h -= 1;
  2763. }
  2764. if (h * 6 < 1) {
  2765. return m1 + (m2 - m1) * h * 6;
  2766. }
  2767. if (h * 2 < 1) {
  2768. return m2;
  2769. }
  2770. if (h * 3 < 2) {
  2771. return m1 + (m2 - m1) * (2/3 - h) * 6;
  2772. }
  2773. return m1;
  2774. }
  2775. function lerpNumber(a, b, p) {
  2776. return a + (b - a) * p;
  2777. }
  2778. function setRgba(out, r, g, b, a) {
  2779. out[0] = r; out[1] = g; out[2] = b; out[3] = a;
  2780. return out;
  2781. }
  2782. function copyRgba(out, a) {
  2783. out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3];
  2784. return out;
  2785. }
  2786. var colorCache = new LRU(20);
  2787. var lastRemovedArr = null;
  2788. function putToCache(colorStr, rgbaArr) {
  2789. // Reuse removed array
  2790. if (lastRemovedArr) {
  2791. copyRgba(lastRemovedArr, rgbaArr);
  2792. }
  2793. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice()));
  2794. }
  2795. /**
  2796. * @param {string} colorStr
  2797. * @param {Array.<number>} out
  2798. * @return {Array.<number>}
  2799. * @memberOf module:zrender/util/color
  2800. */
  2801. function parse(colorStr, rgbaArr) {
  2802. if (!colorStr) {
  2803. return;
  2804. }
  2805. rgbaArr = rgbaArr || [];
  2806. var cached = colorCache.get(colorStr);
  2807. if (cached) {
  2808. return copyRgba(rgbaArr, cached);
  2809. }
  2810. // colorStr may be not string
  2811. colorStr = colorStr + '';
  2812. // Remove all whitespace, not compliant, but should just be more accepting.
  2813. var str = colorStr.replace(/ /g, '').toLowerCase();
  2814. // Color keywords (and transparent) lookup.
  2815. if (str in kCSSColorTable) {
  2816. copyRgba(rgbaArr, kCSSColorTable[str]);
  2817. putToCache(colorStr, rgbaArr);
  2818. return rgbaArr;
  2819. }
  2820. // #abc and #abc123 syntax.
  2821. if (str.charAt(0) === '#') {
  2822. if (str.length === 4) {
  2823. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2824. if (!(iv >= 0 && iv <= 0xfff)) {
  2825. setRgba(rgbaArr, 0, 0, 0, 1);
  2826. return; // Covers NaN.
  2827. }
  2828. setRgba(rgbaArr,
  2829. ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8),
  2830. (iv & 0xf0) | ((iv & 0xf0) >> 4),
  2831. (iv & 0xf) | ((iv & 0xf) << 4),
  2832. 1
  2833. );
  2834. putToCache(colorStr, rgbaArr);
  2835. return rgbaArr;
  2836. }
  2837. else if (str.length === 7) {
  2838. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  2839. if (!(iv >= 0 && iv <= 0xffffff)) {
  2840. setRgba(rgbaArr, 0, 0, 0, 1);
  2841. return; // Covers NaN.
  2842. }
  2843. setRgba(rgbaArr,
  2844. (iv & 0xff0000) >> 16,
  2845. (iv & 0xff00) >> 8,
  2846. iv & 0xff,
  2847. 1
  2848. );
  2849. putToCache(colorStr, rgbaArr);
  2850. return rgbaArr;
  2851. }
  2852. return;
  2853. }
  2854. var op = str.indexOf('('), ep = str.indexOf(')');
  2855. if (op !== -1 && ep + 1 === str.length) {
  2856. var fname = str.substr(0, op);
  2857. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  2858. var alpha = 1; // To allow case fallthrough.
  2859. switch (fname) {
  2860. case 'rgba':
  2861. if (params.length !== 4) {
  2862. setRgba(rgbaArr, 0, 0, 0, 1);
  2863. return;
  2864. }
  2865. alpha = parseCssFloat(params.pop()); // jshint ignore:line
  2866. // Fall through.
  2867. case 'rgb':
  2868. if (params.length !== 3) {
  2869. setRgba(rgbaArr, 0, 0, 0, 1);
  2870. return;
  2871. }
  2872. setRgba(rgbaArr,
  2873. parseCssInt(params[0]),
  2874. parseCssInt(params[1]),
  2875. parseCssInt(params[2]),
  2876. alpha
  2877. );
  2878. putToCache(colorStr, rgbaArr);
  2879. return rgbaArr;
  2880. case 'hsla':
  2881. if (params.length !== 4) {
  2882. setRgba(rgbaArr, 0, 0, 0, 1);
  2883. return;
  2884. }
  2885. params[3] = parseCssFloat(params[3]);
  2886. hsla2rgba(params, rgbaArr);
  2887. putToCache(colorStr, rgbaArr);
  2888. return rgbaArr;
  2889. case 'hsl':
  2890. if (params.length !== 3) {
  2891. setRgba(rgbaArr, 0, 0, 0, 1);
  2892. return;
  2893. }
  2894. hsla2rgba(params, rgbaArr);
  2895. putToCache(colorStr, rgbaArr);
  2896. return rgbaArr;
  2897. default:
  2898. return;
  2899. }
  2900. }
  2901. setRgba(rgbaArr, 0, 0, 0, 1);
  2902. return;
  2903. }
  2904. /**
  2905. * @param {Array.<number>} hsla
  2906. * @param {Array.<number>} rgba
  2907. * @return {Array.<number>} rgba
  2908. */
  2909. function hsla2rgba(hsla, rgba) {
  2910. var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1
  2911. // NOTE(deanm): According to the CSS spec s/l should only be
  2912. // percentages, but we don't bother and let float or percentage.
  2913. var s = parseCssFloat(hsla[1]);
  2914. var l = parseCssFloat(hsla[2]);
  2915. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  2916. var m1 = l * 2 - m2;
  2917. rgba = rgba || [];
  2918. setRgba(rgba,
  2919. clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255),
  2920. clampCssByte(cssHueToRgb(m1, m2, h) * 255),
  2921. clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255),
  2922. 1
  2923. );
  2924. if (hsla.length === 4) {
  2925. rgba[3] = hsla[3];
  2926. }
  2927. return rgba;
  2928. }
  2929. /**
  2930. * @param {Array.<number>} rgba
  2931. * @return {Array.<number>} hsla
  2932. */
  2933. function rgba2hsla(rgba) {
  2934. if (!rgba) {
  2935. return;
  2936. }
  2937. // RGB from 0 to 255
  2938. var R = rgba[0] / 255;
  2939. var G = rgba[1] / 255;
  2940. var B = rgba[2] / 255;
  2941. var vMin = Math.min(R, G, B); // Min. value of RGB
  2942. var vMax = Math.max(R, G, B); // Max. value of RGB
  2943. var delta = vMax - vMin; // Delta RGB value
  2944. var L = (vMax + vMin) / 2;
  2945. var H;
  2946. var S;
  2947. // HSL results from 0 to 1
  2948. if (delta === 0) {
  2949. H = 0;
  2950. S = 0;
  2951. }
  2952. else {
  2953. if (L < 0.5) {
  2954. S = delta / (vMax + vMin);
  2955. }
  2956. else {
  2957. S = delta / (2 - vMax - vMin);
  2958. }
  2959. var deltaR = (((vMax - R) / 6) + (delta / 2)) / delta;
  2960. var deltaG = (((vMax - G) / 6) + (delta / 2)) / delta;
  2961. var deltaB = (((vMax - B) / 6) + (delta / 2)) / delta;
  2962. if (R === vMax) {
  2963. H = deltaB - deltaG;
  2964. }
  2965. else if (G === vMax) {
  2966. H = (1 / 3) + deltaR - deltaB;
  2967. }
  2968. else if (B === vMax) {
  2969. H = (2 / 3) + deltaG - deltaR;
  2970. }
  2971. if (H < 0) {
  2972. H += 1;
  2973. }
  2974. if (H > 1) {
  2975. H -= 1;
  2976. }
  2977. }
  2978. var hsla = [H * 360, S, L];
  2979. if (rgba[3] != null) {
  2980. hsla.push(rgba[3]);
  2981. }
  2982. return hsla;
  2983. }
  2984. /**
  2985. * @param {string} color
  2986. * @param {number} level
  2987. * @return {string}
  2988. * @memberOf module:zrender/util/color
  2989. */
  2990. function lift(color, level) {
  2991. var colorArr = parse(color);
  2992. if (colorArr) {
  2993. for (var i = 0; i < 3; i++) {
  2994. if (level < 0) {
  2995. colorArr[i] = colorArr[i] * (1 - level) | 0;
  2996. }
  2997. else {
  2998. colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0;
  2999. }
  3000. if (colorArr[i] > 255) {
  3001. colorArr[i] = 255;
  3002. }
  3003. else if (color[i] < 0) {
  3004. colorArr[i] = 0;
  3005. }
  3006. }
  3007. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3008. }
  3009. }
  3010. /**
  3011. * @param {string} color
  3012. * @return {string}
  3013. * @memberOf module:zrender/util/color
  3014. */
  3015. function toHex(color) {
  3016. var colorArr = parse(color);
  3017. if (colorArr) {
  3018. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + (+colorArr[2])).toString(16).slice(1);
  3019. }
  3020. }
  3021. /**
  3022. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3023. * @param {number} normalizedValue A float between 0 and 1.
  3024. * @param {Array.<Array.<number>>} colors List of rgba color array
  3025. * @param {Array.<number>} [out] Mapped gba color array
  3026. * @return {Array.<number>} will be null/undefined if input illegal.
  3027. */
  3028. function fastLerp(normalizedValue, colors, out) {
  3029. if (!(colors && colors.length)
  3030. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3031. ) {
  3032. return;
  3033. }
  3034. out = out || [];
  3035. var value = normalizedValue * (colors.length - 1);
  3036. var leftIndex = Math.floor(value);
  3037. var rightIndex = Math.ceil(value);
  3038. var leftColor = colors[leftIndex];
  3039. var rightColor = colors[rightIndex];
  3040. var dv = value - leftIndex;
  3041. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3042. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3043. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3044. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3045. return out;
  3046. }
  3047. /**
  3048. * @deprecated
  3049. */
  3050. var fastMapToColor = fastLerp;
  3051. /**
  3052. * @param {number} normalizedValue A float between 0 and 1.
  3053. * @param {Array.<string>} colors Color list.
  3054. * @param {boolean=} fullOutput Default false.
  3055. * @return {(string|Object)} Result color. If fullOutput,
  3056. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3057. * @memberOf module:zrender/util/color
  3058. */
  3059. function lerp$1(normalizedValue, colors, fullOutput) {
  3060. if (!(colors && colors.length)
  3061. || !(normalizedValue >= 0 && normalizedValue <= 1)
  3062. ) {
  3063. return;
  3064. }
  3065. var value = normalizedValue * (colors.length - 1);
  3066. var leftIndex = Math.floor(value);
  3067. var rightIndex = Math.ceil(value);
  3068. var leftColor = parse(colors[leftIndex]);
  3069. var rightColor = parse(colors[rightIndex]);
  3070. var dv = value - leftIndex;
  3071. var color = stringify(
  3072. [
  3073. clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)),
  3074. clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)),
  3075. clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)),
  3076. clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))
  3077. ],
  3078. 'rgba'
  3079. );
  3080. return fullOutput
  3081. ? {
  3082. color: color,
  3083. leftIndex: leftIndex,
  3084. rightIndex: rightIndex,
  3085. value: value
  3086. }
  3087. : color;
  3088. }
  3089. /**
  3090. * @deprecated
  3091. */
  3092. var mapToColor = lerp$1;
  3093. /**
  3094. * @param {string} color
  3095. * @param {number=} h 0 ~ 360, ignore when null.
  3096. * @param {number=} s 0 ~ 1, ignore when null.
  3097. * @param {number=} l 0 ~ 1, ignore when null.
  3098. * @return {string} Color string in rgba format.
  3099. * @memberOf module:zrender/util/color
  3100. */
  3101. function modifyHSL(color, h, s, l) {
  3102. color = parse(color);
  3103. if (color) {
  3104. color = rgba2hsla(color);
  3105. h != null && (color[0] = clampCssAngle(h));
  3106. s != null && (color[1] = parseCssFloat(s));
  3107. l != null && (color[2] = parseCssFloat(l));
  3108. return stringify(hsla2rgba(color), 'rgba');
  3109. }
  3110. }
  3111. /**
  3112. * @param {string} color
  3113. * @param {number=} alpha 0 ~ 1
  3114. * @return {string} Color string in rgba format.
  3115. * @memberOf module:zrender/util/color
  3116. */
  3117. function modifyAlpha(color, alpha) {
  3118. color = parse(color);
  3119. if (color && alpha != null) {
  3120. color[3] = clampCssFloat(alpha);
  3121. return stringify(color, 'rgba');
  3122. }
  3123. }
  3124. /**
  3125. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3126. * @param {string} type 'rgba', 'hsva', ...
  3127. * @return {string} Result color. (If input illegal, return undefined).
  3128. */
  3129. function stringify(arrColor, type) {
  3130. if (!arrColor || !arrColor.length) {
  3131. return;
  3132. }
  3133. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3134. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3135. colorStr += ',' + arrColor[3];
  3136. }
  3137. return type + '(' + colorStr + ')';
  3138. }
  3139. var color = (Object.freeze || Object)({
  3140. parse: parse,
  3141. lift: lift,
  3142. toHex: toHex,
  3143. fastLerp: fastLerp,
  3144. fastMapToColor: fastMapToColor,
  3145. lerp: lerp$1,
  3146. mapToColor: mapToColor,
  3147. modifyHSL: modifyHSL,
  3148. modifyAlpha: modifyAlpha,
  3149. stringify: stringify
  3150. });
  3151. /**
  3152. * @module echarts/animation/Animator
  3153. */
  3154. var arraySlice = Array.prototype.slice;
  3155. function defaultGetter(target, key) {
  3156. return target[key];
  3157. }
  3158. function defaultSetter(target, key, value) {
  3159. target[key] = value;
  3160. }
  3161. /**
  3162. * @param {number} p0
  3163. * @param {number} p1
  3164. * @param {number} percent
  3165. * @return {number}
  3166. */
  3167. function interpolateNumber(p0, p1, percent) {
  3168. return (p1 - p0) * percent + p0;
  3169. }
  3170. /**
  3171. * @param {string} p0
  3172. * @param {string} p1
  3173. * @param {number} percent
  3174. * @return {string}
  3175. */
  3176. function interpolateString(p0, p1, percent) {
  3177. return percent > 0.5 ? p1 : p0;
  3178. }
  3179. /**
  3180. * @param {Array} p0
  3181. * @param {Array} p1
  3182. * @param {number} percent
  3183. * @param {Array} out
  3184. * @param {number} arrDim
  3185. */
  3186. function interpolateArray(p0, p1, percent, out, arrDim) {
  3187. var len = p0.length;
  3188. if (arrDim == 1) {
  3189. for (var i = 0; i < len; i++) {
  3190. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3191. }
  3192. }
  3193. else {
  3194. var len2 = len && p0[0].length;
  3195. for (var i = 0; i < len; i++) {
  3196. for (var j = 0; j < len2; j++) {
  3197. out[i][j] = interpolateNumber(
  3198. p0[i][j], p1[i][j], percent
  3199. );
  3200. }
  3201. }
  3202. }
  3203. }
  3204. // arr0 is source array, arr1 is target array.
  3205. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3206. function fillArr(arr0, arr1, arrDim) {
  3207. var arr0Len = arr0.length;
  3208. var arr1Len = arr1.length;
  3209. if (arr0Len !== arr1Len) {
  3210. // FIXME Not work for TypedArray
  3211. var isPreviousLarger = arr0Len > arr1Len;
  3212. if (isPreviousLarger) {
  3213. // Cut the previous
  3214. arr0.length = arr1Len;
  3215. }
  3216. else {
  3217. // Fill the previous
  3218. for (var i = arr0Len; i < arr1Len; i++) {
  3219. arr0.push(
  3220. arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i])
  3221. );
  3222. }
  3223. }
  3224. }
  3225. // Handling NaN value
  3226. var len2 = arr0[0] && arr0[0].length;
  3227. for (var i = 0; i < arr0.length; i++) {
  3228. if (arrDim === 1) {
  3229. if (isNaN(arr0[i])) {
  3230. arr0[i] = arr1[i];
  3231. }
  3232. }
  3233. else {
  3234. for (var j = 0; j < len2; j++) {
  3235. if (isNaN(arr0[i][j])) {
  3236. arr0[i][j] = arr1[i][j];
  3237. }
  3238. }
  3239. }
  3240. }
  3241. }
  3242. /**
  3243. * @param {Array} arr0
  3244. * @param {Array} arr1
  3245. * @param {number} arrDim
  3246. * @return {boolean}
  3247. */
  3248. function isArraySame(arr0, arr1, arrDim) {
  3249. if (arr0 === arr1) {
  3250. return true;
  3251. }
  3252. var len = arr0.length;
  3253. if (len !== arr1.length) {
  3254. return false;
  3255. }
  3256. if (arrDim === 1) {
  3257. for (var i = 0; i < len; i++) {
  3258. if (arr0[i] !== arr1[i]) {
  3259. return false;
  3260. }
  3261. }
  3262. }
  3263. else {
  3264. var len2 = arr0[0].length;
  3265. for (var i = 0; i < len; i++) {
  3266. for (var j = 0; j < len2; j++) {
  3267. if (arr0[i][j] !== arr1[i][j]) {
  3268. return false;
  3269. }
  3270. }
  3271. }
  3272. }
  3273. return true;
  3274. }
  3275. /**
  3276. * Catmull Rom interpolate array
  3277. * @param {Array} p0
  3278. * @param {Array} p1
  3279. * @param {Array} p2
  3280. * @param {Array} p3
  3281. * @param {number} t
  3282. * @param {number} t2
  3283. * @param {number} t3
  3284. * @param {Array} out
  3285. * @param {number} arrDim
  3286. */
  3287. function catmullRomInterpolateArray(
  3288. p0, p1, p2, p3, t, t2, t3, out, arrDim
  3289. ) {
  3290. var len = p0.length;
  3291. if (arrDim == 1) {
  3292. for (var i = 0; i < len; i++) {
  3293. out[i] = catmullRomInterpolate(
  3294. p0[i], p1[i], p2[i], p3[i], t, t2, t3
  3295. );
  3296. }
  3297. }
  3298. else {
  3299. var len2 = p0[0].length;
  3300. for (var i = 0; i < len; i++) {
  3301. for (var j = 0; j < len2; j++) {
  3302. out[i][j] = catmullRomInterpolate(
  3303. p0[i][j], p1[i][j], p2[i][j], p3[i][j],
  3304. t, t2, t3
  3305. );
  3306. }
  3307. }
  3308. }
  3309. }
  3310. /**
  3311. * Catmull Rom interpolate number
  3312. * @param {number} p0
  3313. * @param {number} p1
  3314. * @param {number} p2
  3315. * @param {number} p3
  3316. * @param {number} t
  3317. * @param {number} t2
  3318. * @param {number} t3
  3319. * @return {number}
  3320. */
  3321. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3322. var v0 = (p2 - p0) * 0.5;
  3323. var v1 = (p3 - p1) * 0.5;
  3324. return (2 * (p1 - p2) + v0 + v1) * t3
  3325. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  3326. + v0 * t + p1;
  3327. }
  3328. function cloneValue(value) {
  3329. if (isArrayLike(value)) {
  3330. var len = value.length;
  3331. if (isArrayLike(value[0])) {
  3332. var ret = [];
  3333. for (var i = 0; i < len; i++) {
  3334. ret.push(arraySlice.call(value[i]));
  3335. }
  3336. return ret;
  3337. }
  3338. return arraySlice.call(value);
  3339. }
  3340. return value;
  3341. }
  3342. function rgba2String(rgba) {
  3343. rgba[0] = Math.floor(rgba[0]);
  3344. rgba[1] = Math.floor(rgba[1]);
  3345. rgba[2] = Math.floor(rgba[2]);
  3346. return 'rgba(' + rgba.join(',') + ')';
  3347. }
  3348. function getArrayDim(keyframes) {
  3349. var lastValue = keyframes[keyframes.length - 1].value;
  3350. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3351. }
  3352. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3353. var getter = animator._getter;
  3354. var setter = animator._setter;
  3355. var useSpline = easing === 'spline';
  3356. var trackLen = keyframes.length;
  3357. if (!trackLen) {
  3358. return;
  3359. }
  3360. // Guess data type
  3361. var firstVal = keyframes[0].value;
  3362. var isValueArray = isArrayLike(firstVal);
  3363. var isValueColor = false;
  3364. var isValueString = false;
  3365. // For vertices morphing
  3366. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3367. var trackMaxTime;
  3368. // Sort keyframe as ascending
  3369. keyframes.sort(function(a, b) {
  3370. return a.time - b.time;
  3371. });
  3372. trackMaxTime = keyframes[trackLen - 1].time;
  3373. // Percents of each keyframe
  3374. var kfPercents = [];
  3375. // Value of each keyframe
  3376. var kfValues = [];
  3377. var prevValue = keyframes[0].value;
  3378. var isAllValueEqual = true;
  3379. for (var i = 0; i < trackLen; i++) {
  3380. kfPercents.push(keyframes[i].time / trackMaxTime);
  3381. // Assume value is a color when it is a string
  3382. var value = keyframes[i].value;
  3383. // Check if value is equal, deep check if value is array
  3384. if (!((isValueArray && isArraySame(value, prevValue, arrDim))
  3385. || (!isValueArray && value === prevValue))) {
  3386. isAllValueEqual = false;
  3387. }
  3388. prevValue = value;
  3389. // Try converting a string to a color array
  3390. if (typeof value == 'string') {
  3391. var colorArray = parse(value);
  3392. if (colorArray) {
  3393. value = colorArray;
  3394. isValueColor = true;
  3395. }
  3396. else {
  3397. isValueString = true;
  3398. }
  3399. }
  3400. kfValues.push(value);
  3401. }
  3402. if (!forceAnimate && isAllValueEqual) {
  3403. return;
  3404. }
  3405. var lastValue = kfValues[trackLen - 1];
  3406. // Polyfill array and NaN value
  3407. for (var i = 0; i < trackLen - 1; i++) {
  3408. if (isValueArray) {
  3409. fillArr(kfValues[i], lastValue, arrDim);
  3410. }
  3411. else {
  3412. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3413. kfValues[i] = lastValue;
  3414. }
  3415. }
  3416. }
  3417. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim);
  3418. // Cache the key of last frame to speed up when
  3419. // animation playback is sequency
  3420. var lastFrame = 0;
  3421. var lastFramePercent = 0;
  3422. var start;
  3423. var w;
  3424. var p0;
  3425. var p1;
  3426. var p2;
  3427. var p3;
  3428. if (isValueColor) {
  3429. var rgba = [0, 0, 0, 0];
  3430. }
  3431. var onframe = function (target, percent) {
  3432. // Find the range keyframes
  3433. // kf1-----kf2---------current--------kf3
  3434. // find kf2 and kf3 and do interpolation
  3435. var frame;
  3436. // In the easing function like elasticOut, percent may less than 0
  3437. if (percent < 0) {
  3438. frame = 0;
  3439. }
  3440. else if (percent < lastFramePercent) {
  3441. // Start from next key
  3442. // PENDING start from lastFrame ?
  3443. start = Math.min(lastFrame + 1, trackLen - 1);
  3444. for (frame = start; frame >= 0; frame--) {
  3445. if (kfPercents[frame] <= percent) {
  3446. break;
  3447. }
  3448. }
  3449. // PENDING really need to do this ?
  3450. frame = Math.min(frame, trackLen - 2);
  3451. }
  3452. else {
  3453. for (frame = lastFrame; frame < trackLen; frame++) {
  3454. if (kfPercents[frame] > percent) {
  3455. break;
  3456. }
  3457. }
  3458. frame = Math.min(frame - 1, trackLen - 2);
  3459. }
  3460. lastFrame = frame;
  3461. lastFramePercent = percent;
  3462. var range = (kfPercents[frame + 1] - kfPercents[frame]);
  3463. if (range === 0) {
  3464. return;
  3465. }
  3466. else {
  3467. w = (percent - kfPercents[frame]) / range;
  3468. }
  3469. if (useSpline) {
  3470. p1 = kfValues[frame];
  3471. p0 = kfValues[frame === 0 ? frame : frame - 1];
  3472. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  3473. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  3474. if (isValueArray) {
  3475. catmullRomInterpolateArray(
  3476. p0, p1, p2, p3, w, w * w, w * w * w,
  3477. getter(target, propName),
  3478. arrDim
  3479. );
  3480. }
  3481. else {
  3482. var value;
  3483. if (isValueColor) {
  3484. value = catmullRomInterpolateArray(
  3485. p0, p1, p2, p3, w, w * w, w * w * w,
  3486. rgba, 1
  3487. );
  3488. value = rgba2String(rgba);
  3489. }
  3490. else if (isValueString) {
  3491. // String is step(0.5)
  3492. return interpolateString(p1, p2, w);
  3493. }
  3494. else {
  3495. value = catmullRomInterpolate(
  3496. p0, p1, p2, p3, w, w * w, w * w * w
  3497. );
  3498. }
  3499. setter(
  3500. target,
  3501. propName,
  3502. value
  3503. );
  3504. }
  3505. }
  3506. else {
  3507. if (isValueArray) {
  3508. interpolateArray(
  3509. kfValues[frame], kfValues[frame + 1], w,
  3510. getter(target, propName),
  3511. arrDim
  3512. );
  3513. }
  3514. else {
  3515. var value;
  3516. if (isValueColor) {
  3517. interpolateArray(
  3518. kfValues[frame], kfValues[frame + 1], w,
  3519. rgba, 1
  3520. );
  3521. value = rgba2String(rgba);
  3522. }
  3523. else if (isValueString) {
  3524. // String is step(0.5)
  3525. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  3526. }
  3527. else {
  3528. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  3529. }
  3530. setter(
  3531. target,
  3532. propName,
  3533. value
  3534. );
  3535. }
  3536. }
  3537. };
  3538. var clip = new Clip({
  3539. target: animator._target,
  3540. life: trackMaxTime,
  3541. loop: animator._loop,
  3542. delay: animator._delay,
  3543. onframe: onframe,
  3544. ondestroy: oneTrackDone
  3545. });
  3546. if (easing && easing !== 'spline') {
  3547. clip.easing = easing;
  3548. }
  3549. return clip;
  3550. }
  3551. /**
  3552. * @alias module:zrender/animation/Animator
  3553. * @constructor
  3554. * @param {Object} target
  3555. * @param {boolean} loop
  3556. * @param {Function} getter
  3557. * @param {Function} setter
  3558. */
  3559. var Animator = function(target, loop, getter, setter) {
  3560. this._tracks = {};
  3561. this._target = target;
  3562. this._loop = loop || false;
  3563. this._getter = getter || defaultGetter;
  3564. this._setter = setter || defaultSetter;
  3565. this._clipCount = 0;
  3566. this._delay = 0;
  3567. this._doneList = [];
  3568. this._onframeList = [];
  3569. this._clipList = [];
  3570. };
  3571. Animator.prototype = {
  3572. /**
  3573. * 设置动画关键帧
  3574. * @param {number} time 关键帧时间,单位是ms
  3575. * @param {Object} props 关键帧的属性值,key-value表示
  3576. * @return {module:zrender/animation/Animator}
  3577. */
  3578. when: function(time /* ms */, props) {
  3579. var tracks = this._tracks;
  3580. for (var propName in props) {
  3581. if (!props.hasOwnProperty(propName)) {
  3582. continue;
  3583. }
  3584. if (!tracks[propName]) {
  3585. tracks[propName] = [];
  3586. // Invalid value
  3587. var value = this._getter(this._target, propName);
  3588. if (value == null) {
  3589. // zrLog('Invalid property ' + propName);
  3590. continue;
  3591. }
  3592. // If time is 0
  3593. // Then props is given initialize value
  3594. // Else
  3595. // Initialize value from current prop value
  3596. if (time !== 0) {
  3597. tracks[propName].push({
  3598. time: 0,
  3599. value: cloneValue(value)
  3600. });
  3601. }
  3602. }
  3603. tracks[propName].push({
  3604. time: time,
  3605. value: props[propName]
  3606. });
  3607. }
  3608. return this;
  3609. },
  3610. /**
  3611. * 添加动画每一帧的回调函数
  3612. * @param {Function} callback
  3613. * @return {module:zrender/animation/Animator}
  3614. */
  3615. during: function (callback) {
  3616. this._onframeList.push(callback);
  3617. return this;
  3618. },
  3619. pause: function () {
  3620. for (var i = 0; i < this._clipList.length; i++) {
  3621. this._clipList[i].pause();
  3622. }
  3623. this._paused = true;
  3624. },
  3625. resume: function () {
  3626. for (var i = 0; i < this._clipList.length; i++) {
  3627. this._clipList[i].resume();
  3628. }
  3629. this._paused = false;
  3630. },
  3631. isPaused: function () {
  3632. return !!this._paused;
  3633. },
  3634. _doneCallback: function () {
  3635. // Clear all tracks
  3636. this._tracks = {};
  3637. // Clear all clips
  3638. this._clipList.length = 0;
  3639. var doneList = this._doneList;
  3640. var len = doneList.length;
  3641. for (var i = 0; i < len; i++) {
  3642. doneList[i].call(this);
  3643. }
  3644. },
  3645. /**
  3646. * 开始执行动画
  3647. * @param {string|Function} [easing]
  3648. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  3649. * @param {boolean} forceAnimate
  3650. * @return {module:zrender/animation/Animator}
  3651. */
  3652. start: function (easing, forceAnimate) {
  3653. var self = this;
  3654. var clipCount = 0;
  3655. var oneTrackDone = function() {
  3656. clipCount--;
  3657. if (!clipCount) {
  3658. self._doneCallback();
  3659. }
  3660. };
  3661. var lastClip;
  3662. for (var propName in this._tracks) {
  3663. if (!this._tracks.hasOwnProperty(propName)) {
  3664. continue;
  3665. }
  3666. var clip = createTrackClip(
  3667. this, easing, oneTrackDone,
  3668. this._tracks[propName], propName, forceAnimate
  3669. );
  3670. if (clip) {
  3671. this._clipList.push(clip);
  3672. clipCount++;
  3673. // If start after added to animation
  3674. if (this.animation) {
  3675. this.animation.addClip(clip);
  3676. }
  3677. lastClip = clip;
  3678. }
  3679. }
  3680. // Add during callback on the last clip
  3681. if (lastClip) {
  3682. var oldOnFrame = lastClip.onframe;
  3683. lastClip.onframe = function (target, percent) {
  3684. oldOnFrame(target, percent);
  3685. for (var i = 0; i < self._onframeList.length; i++) {
  3686. self._onframeList[i](target, percent);
  3687. }
  3688. };
  3689. }
  3690. // This optimization will help the case that in the upper application
  3691. // the view may be refreshed frequently, where animation will be
  3692. // called repeatly but nothing changed.
  3693. if (!clipCount) {
  3694. this._doneCallback();
  3695. }
  3696. return this;
  3697. },
  3698. /**
  3699. * 停止动画
  3700. * @param {boolean} forwardToLast If move to last frame before stop
  3701. */
  3702. stop: function (forwardToLast) {
  3703. var clipList = this._clipList;
  3704. var animation = this.animation;
  3705. for (var i = 0; i < clipList.length; i++) {
  3706. var clip = clipList[i];
  3707. if (forwardToLast) {
  3708. // Move to last frame before stop
  3709. clip.onframe(this._target, 1);
  3710. }
  3711. animation && animation.removeClip(clip);
  3712. }
  3713. clipList.length = 0;
  3714. },
  3715. /**
  3716. * 设置动画延迟开始的时间
  3717. * @param {number} time 单位ms
  3718. * @return {module:zrender/animation/Animator}
  3719. */
  3720. delay: function (time) {
  3721. this._delay = time;
  3722. return this;
  3723. },
  3724. /**
  3725. * 添加动画结束的回调
  3726. * @param {Function} cb
  3727. * @return {module:zrender/animation/Animator}
  3728. */
  3729. done: function(cb) {
  3730. if (cb) {
  3731. this._doneList.push(cb);
  3732. }
  3733. return this;
  3734. },
  3735. /**
  3736. * @return {Array.<module:zrender/animation/Clip>}
  3737. */
  3738. getClips: function () {
  3739. return this._clipList;
  3740. }
  3741. };
  3742. var dpr = 1;
  3743. // If in browser environment
  3744. if (typeof window !== 'undefined') {
  3745. dpr = Math.max(window.devicePixelRatio || 1, 1);
  3746. }
  3747. /**
  3748. * config默认配置项
  3749. * @exports zrender/config
  3750. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  3751. */
  3752. /**
  3753. * debug日志选项:catchBrushException为true下有效
  3754. * 0 : 不生成debug数据,发布用
  3755. * 1 : 异常抛出,调试用
  3756. * 2 : 控制台输出,调试用
  3757. */
  3758. var debugMode = 0;
  3759. // retina 屏幕优化
  3760. var devicePixelRatio = dpr;
  3761. var log = function () {
  3762. };
  3763. if (debugMode === 1) {
  3764. log = function () {
  3765. for (var k in arguments) {
  3766. throw new Error(arguments[k]);
  3767. }
  3768. };
  3769. }
  3770. else if (debugMode > 1) {
  3771. log = function () {
  3772. for (var k in arguments) {
  3773. console.log(arguments[k]);
  3774. }
  3775. };
  3776. }
  3777. var zrLog = log;
  3778. /**
  3779. * @alias modue:zrender/mixin/Animatable
  3780. * @constructor
  3781. */
  3782. var Animatable = function () {
  3783. /**
  3784. * @type {Array.<module:zrender/animation/Animator>}
  3785. * @readOnly
  3786. */
  3787. this.animators = [];
  3788. };
  3789. Animatable.prototype = {
  3790. constructor: Animatable,
  3791. /**
  3792. * 动画
  3793. *
  3794. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  3795. * @param {boolean} [loop] Whether to loop animation.
  3796. * @return {module:zrender/animation/Animator}
  3797. * @example:
  3798. * el.animate('style', false)
  3799. * .when(1000, {x: 10} )
  3800. * .done(function(){ // Animation done })
  3801. * .start()
  3802. */
  3803. animate: function (path, loop) {
  3804. var target;
  3805. var animatingShape = false;
  3806. var el = this;
  3807. var zr = this.__zr;
  3808. if (path) {
  3809. var pathSplitted = path.split('.');
  3810. var prop = el;
  3811. // If animating shape
  3812. animatingShape = pathSplitted[0] === 'shape';
  3813. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  3814. if (!prop) {
  3815. continue;
  3816. }
  3817. prop = prop[pathSplitted[i]];
  3818. }
  3819. if (prop) {
  3820. target = prop;
  3821. }
  3822. }
  3823. else {
  3824. target = el;
  3825. }
  3826. if (!target) {
  3827. zrLog(
  3828. 'Property "'
  3829. + path
  3830. + '" is not existed in element '
  3831. + el.id
  3832. );
  3833. return;
  3834. }
  3835. var animators = el.animators;
  3836. var animator = new Animator(target, loop);
  3837. animator.during(function (target) {
  3838. el.dirty(animatingShape);
  3839. })
  3840. .done(function () {
  3841. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  3842. animators.splice(indexOf(animators, animator), 1);
  3843. });
  3844. animators.push(animator);
  3845. // If animate after added to the zrender
  3846. if (zr) {
  3847. zr.animation.addAnimator(animator);
  3848. }
  3849. return animator;
  3850. },
  3851. /**
  3852. * 停止动画
  3853. * @param {boolean} forwardToLast If move to last frame before stop
  3854. */
  3855. stopAnimation: function (forwardToLast) {
  3856. var animators = this.animators;
  3857. var len = animators.length;
  3858. for (var i = 0; i < len; i++) {
  3859. animators[i].stop(forwardToLast);
  3860. }
  3861. animators.length = 0;
  3862. return this;
  3863. },
  3864. /**
  3865. * Caution: this method will stop previous animation.
  3866. * So do not use this method to one element twice before
  3867. * animation starts, unless you know what you are doing.
  3868. * @param {Object} target
  3869. * @param {number} [time=500] Time in ms
  3870. * @param {string} [easing='linear']
  3871. * @param {number} [delay=0]
  3872. * @param {Function} [callback]
  3873. * @param {Function} [forceAnimate] Prevent stop animation and callback
  3874. * immediently when target values are the same as current values.
  3875. *
  3876. * @example
  3877. * // Animate position
  3878. * el.animateTo({
  3879. * position: [10, 10]
  3880. * }, function () { // done })
  3881. *
  3882. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  3883. * el.animateTo({
  3884. * shape: {
  3885. * width: 500
  3886. * },
  3887. * style: {
  3888. * fill: 'red'
  3889. * }
  3890. * position: [10, 10]
  3891. * }, 100, 100, 'cubicOut', function () { // done })
  3892. */
  3893. // TODO Return animation key
  3894. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  3895. // animateTo(target, time, easing, callback);
  3896. if (isString(delay)) {
  3897. callback = easing;
  3898. easing = delay;
  3899. delay = 0;
  3900. }
  3901. // animateTo(target, time, delay, callback);
  3902. else if (isFunction$1(easing)) {
  3903. callback = easing;
  3904. easing = 'linear';
  3905. delay = 0;
  3906. }
  3907. // animateTo(target, time, callback);
  3908. else if (isFunction$1(delay)) {
  3909. callback = delay;
  3910. delay = 0;
  3911. }
  3912. // animateTo(target, callback)
  3913. else if (isFunction$1(time)) {
  3914. callback = time;
  3915. time = 500;
  3916. }
  3917. // animateTo(target)
  3918. else if (!time) {
  3919. time = 500;
  3920. }
  3921. // Stop all previous animations
  3922. this.stopAnimation();
  3923. this._animateToShallow('', this, target, time, delay);
  3924. // Animators may be removed immediately after start
  3925. // if there is nothing to animate
  3926. var animators = this.animators.slice();
  3927. var count = animators.length;
  3928. function done() {
  3929. count--;
  3930. if (!count) {
  3931. callback && callback();
  3932. }
  3933. }
  3934. // No animators. This should be checked before animators[i].start(),
  3935. // because 'done' may be executed immediately if no need to animate.
  3936. if (!count) {
  3937. callback && callback();
  3938. }
  3939. // Start after all animators created
  3940. // Incase any animator is done immediately when all animation properties are not changed
  3941. for (var i = 0; i < animators.length; i++) {
  3942. animators[i]
  3943. .done(done)
  3944. .start(easing, forceAnimate);
  3945. }
  3946. },
  3947. /**
  3948. * @private
  3949. * @param {string} path=''
  3950. * @param {Object} source=this
  3951. * @param {Object} target
  3952. * @param {number} [time=500]
  3953. * @param {number} [delay=0]
  3954. *
  3955. * @example
  3956. * // Animate position
  3957. * el._animateToShallow({
  3958. * position: [10, 10]
  3959. * })
  3960. *
  3961. * // Animate shape, style and position in 100ms, delayed 100ms
  3962. * el._animateToShallow({
  3963. * shape: {
  3964. * width: 500
  3965. * },
  3966. * style: {
  3967. * fill: 'red'
  3968. * }
  3969. * position: [10, 10]
  3970. * }, 100, 100)
  3971. */
  3972. _animateToShallow: function (path, source, target, time, delay) {
  3973. var objShallow = {};
  3974. var propertyCount = 0;
  3975. for (var name in target) {
  3976. if (!target.hasOwnProperty(name)) {
  3977. continue;
  3978. }
  3979. if (source[name] != null) {
  3980. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  3981. this._animateToShallow(
  3982. path ? path + '.' + name : name,
  3983. source[name],
  3984. target[name],
  3985. time,
  3986. delay
  3987. );
  3988. }
  3989. else {
  3990. objShallow[name] = target[name];
  3991. propertyCount++;
  3992. }
  3993. }
  3994. else if (target[name] != null) {
  3995. // Attr directly if not has property
  3996. // FIXME, if some property not needed for element ?
  3997. if (!path) {
  3998. this.attr(name, target[name]);
  3999. }
  4000. else { // Shape or style
  4001. var props = {};
  4002. props[path] = {};
  4003. props[path][name] = target[name];
  4004. this.attr(props);
  4005. }
  4006. }
  4007. }
  4008. if (propertyCount > 0) {
  4009. this.animate(path, false)
  4010. .when(time == null ? 500 : time, objShallow)
  4011. .delay(delay || 0);
  4012. }
  4013. return this;
  4014. }
  4015. };
  4016. /**
  4017. * @alias module:zrender/Element
  4018. * @constructor
  4019. * @extends {module:zrender/mixin/Animatable}
  4020. * @extends {module:zrender/mixin/Transformable}
  4021. * @extends {module:zrender/mixin/Eventful}
  4022. */
  4023. var Element = function (opts) { // jshint ignore:line
  4024. Transformable.call(this, opts);
  4025. Eventful.call(this, opts);
  4026. Animatable.call(this, opts);
  4027. /**
  4028. * 画布元素ID
  4029. * @type {string}
  4030. */
  4031. this.id = opts.id || guid();
  4032. };
  4033. Element.prototype = {
  4034. /**
  4035. * 元素类型
  4036. * Element type
  4037. * @type {string}
  4038. */
  4039. type: 'element',
  4040. /**
  4041. * 元素名字
  4042. * Element name
  4043. * @type {string}
  4044. */
  4045. name: '',
  4046. /**
  4047. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4048. * ZRender instance will be assigned when element is associated with zrender
  4049. * @name module:/zrender/Element#__zr
  4050. * @type {module:zrender/ZRender}
  4051. */
  4052. __zr: null,
  4053. /**
  4054. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4055. * If ignore drawing and events of the element object
  4056. * @name module:/zrender/Element#ignore
  4057. * @type {boolean}
  4058. * @default false
  4059. */
  4060. ignore: false,
  4061. /**
  4062. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4063. * 该路径会继承被裁减对象的变换
  4064. * @type {module:zrender/graphic/Path}
  4065. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4066. * @readOnly
  4067. */
  4068. clipPath: null,
  4069. /**
  4070. * 是否是 Group
  4071. * @type {boolean}
  4072. */
  4073. isGroup: false,
  4074. /**
  4075. * Drift element
  4076. * @param {number} dx dx on the global space
  4077. * @param {number} dy dy on the global space
  4078. */
  4079. drift: function (dx, dy) {
  4080. switch (this.draggable) {
  4081. case 'horizontal':
  4082. dy = 0;
  4083. break;
  4084. case 'vertical':
  4085. dx = 0;
  4086. break;
  4087. }
  4088. var m = this.transform;
  4089. if (!m) {
  4090. m = this.transform = [1, 0, 0, 1, 0, 0];
  4091. }
  4092. m[4] += dx;
  4093. m[5] += dy;
  4094. this.decomposeTransform();
  4095. this.dirty(false);
  4096. },
  4097. /**
  4098. * Hook before update
  4099. */
  4100. beforeUpdate: function () {},
  4101. /**
  4102. * Hook after update
  4103. */
  4104. afterUpdate: function () {},
  4105. /**
  4106. * Update each frame
  4107. */
  4108. update: function () {
  4109. this.updateTransform();
  4110. },
  4111. /**
  4112. * @param {Function} cb
  4113. * @param {} context
  4114. */
  4115. traverse: function (cb, context) {},
  4116. /**
  4117. * @protected
  4118. */
  4119. attrKV: function (key, value) {
  4120. if (key === 'position' || key === 'scale' || key === 'origin') {
  4121. // Copy the array
  4122. if (value) {
  4123. var target = this[key];
  4124. if (!target) {
  4125. target = this[key] = [];
  4126. }
  4127. target[0] = value[0];
  4128. target[1] = value[1];
  4129. }
  4130. }
  4131. else {
  4132. this[key] = value;
  4133. }
  4134. },
  4135. /**
  4136. * Hide the element
  4137. */
  4138. hide: function () {
  4139. this.ignore = true;
  4140. this.__zr && this.__zr.refresh();
  4141. },
  4142. /**
  4143. * Show the element
  4144. */
  4145. show: function () {
  4146. this.ignore = false;
  4147. this.__zr && this.__zr.refresh();
  4148. },
  4149. /**
  4150. * @param {string|Object} key
  4151. * @param {*} value
  4152. */
  4153. attr: function (key, value) {
  4154. if (typeof key === 'string') {
  4155. this.attrKV(key, value);
  4156. }
  4157. else if (isObject$1(key)) {
  4158. for (var name in key) {
  4159. if (key.hasOwnProperty(name)) {
  4160. this.attrKV(name, key[name]);
  4161. }
  4162. }
  4163. }
  4164. this.dirty(false);
  4165. return this;
  4166. },
  4167. /**
  4168. * @param {module:zrender/graphic/Path} clipPath
  4169. */
  4170. setClipPath: function (clipPath) {
  4171. var zr = this.__zr;
  4172. if (zr) {
  4173. clipPath.addSelfToZr(zr);
  4174. }
  4175. // Remove previous clip path
  4176. if (this.clipPath && this.clipPath !== clipPath) {
  4177. this.removeClipPath();
  4178. }
  4179. this.clipPath = clipPath;
  4180. clipPath.__zr = zr;
  4181. clipPath.__clipTarget = this;
  4182. this.dirty(false);
  4183. },
  4184. /**
  4185. */
  4186. removeClipPath: function () {
  4187. var clipPath = this.clipPath;
  4188. if (clipPath) {
  4189. if (clipPath.__zr) {
  4190. clipPath.removeSelfFromZr(clipPath.__zr);
  4191. }
  4192. clipPath.__zr = null;
  4193. clipPath.__clipTarget = null;
  4194. this.clipPath = null;
  4195. this.dirty(false);
  4196. }
  4197. },
  4198. /**
  4199. * Add self from zrender instance.
  4200. * Not recursively because it will be invoked when element added to storage.
  4201. * @param {module:zrender/ZRender} zr
  4202. */
  4203. addSelfToZr: function (zr) {
  4204. this.__zr = zr;
  4205. // 添加动画
  4206. var animators = this.animators;
  4207. if (animators) {
  4208. for (var i = 0; i < animators.length; i++) {
  4209. zr.animation.addAnimator(animators[i]);
  4210. }
  4211. }
  4212. if (this.clipPath) {
  4213. this.clipPath.addSelfToZr(zr);
  4214. }
  4215. },
  4216. /**
  4217. * Remove self from zrender instance.
  4218. * Not recursively because it will be invoked when element added to storage.
  4219. * @param {module:zrender/ZRender} zr
  4220. */
  4221. removeSelfFromZr: function (zr) {
  4222. this.__zr = null;
  4223. // 移除动画
  4224. var animators = this.animators;
  4225. if (animators) {
  4226. for (var i = 0; i < animators.length; i++) {
  4227. zr.animation.removeAnimator(animators[i]);
  4228. }
  4229. }
  4230. if (this.clipPath) {
  4231. this.clipPath.removeSelfFromZr(zr);
  4232. }
  4233. }
  4234. };
  4235. mixin(Element, Animatable);
  4236. mixin(Element, Transformable);
  4237. mixin(Element, Eventful);
  4238. /**
  4239. * @module echarts/core/BoundingRect
  4240. */
  4241. var v2ApplyTransform = applyTransform;
  4242. var mathMin = Math.min;
  4243. var mathMax = Math.max;
  4244. /**
  4245. * @alias module:echarts/core/BoundingRect
  4246. */
  4247. function BoundingRect(x, y, width, height) {
  4248. if (width < 0) {
  4249. x = x + width;
  4250. width = -width;
  4251. }
  4252. if (height < 0) {
  4253. y = y + height;
  4254. height = -height;
  4255. }
  4256. /**
  4257. * @type {number}
  4258. */
  4259. this.x = x;
  4260. /**
  4261. * @type {number}
  4262. */
  4263. this.y = y;
  4264. /**
  4265. * @type {number}
  4266. */
  4267. this.width = width;
  4268. /**
  4269. * @type {number}
  4270. */
  4271. this.height = height;
  4272. }
  4273. BoundingRect.prototype = {
  4274. constructor: BoundingRect,
  4275. /**
  4276. * @param {module:echarts/core/BoundingRect} other
  4277. */
  4278. union: function (other) {
  4279. var x = mathMin(other.x, this.x);
  4280. var y = mathMin(other.y, this.y);
  4281. this.width = mathMax(
  4282. other.x + other.width,
  4283. this.x + this.width
  4284. ) - x;
  4285. this.height = mathMax(
  4286. other.y + other.height,
  4287. this.y + this.height
  4288. ) - y;
  4289. this.x = x;
  4290. this.y = y;
  4291. },
  4292. /**
  4293. * @param {Array.<number>} m
  4294. * @methods
  4295. */
  4296. applyTransform: (function () {
  4297. var lt = [];
  4298. var rb = [];
  4299. var lb = [];
  4300. var rt = [];
  4301. return function (m) {
  4302. // In case usage like this
  4303. // el.getBoundingRect().applyTransform(el.transform)
  4304. // And element has no transform
  4305. if (!m) {
  4306. return;
  4307. }
  4308. lt[0] = lb[0] = this.x;
  4309. lt[1] = rt[1] = this.y;
  4310. rb[0] = rt[0] = this.x + this.width;
  4311. rb[1] = lb[1] = this.y + this.height;
  4312. v2ApplyTransform(lt, lt, m);
  4313. v2ApplyTransform(rb, rb, m);
  4314. v2ApplyTransform(lb, lb, m);
  4315. v2ApplyTransform(rt, rt, m);
  4316. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4317. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4318. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4319. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4320. this.width = maxX - this.x;
  4321. this.height = maxY - this.y;
  4322. };
  4323. })(),
  4324. /**
  4325. * Calculate matrix of transforming from self to target rect
  4326. * @param {module:zrender/core/BoundingRect} b
  4327. * @return {Array.<number>}
  4328. */
  4329. calculateTransform: function (b) {
  4330. var a = this;
  4331. var sx = b.width / a.width;
  4332. var sy = b.height / a.height;
  4333. var m = create$1();
  4334. // 矩阵右乘
  4335. translate(m, m, [-a.x, -a.y]);
  4336. scale$1(m, m, [sx, sy]);
  4337. translate(m, m, [b.x, b.y]);
  4338. return m;
  4339. },
  4340. /**
  4341. * @param {(module:echarts/core/BoundingRect|Object)} b
  4342. * @return {boolean}
  4343. */
  4344. intersect: function (b) {
  4345. if (!b) {
  4346. return false;
  4347. }
  4348. if (!(b instanceof BoundingRect)) {
  4349. // Normalize negative width/height.
  4350. b = BoundingRect.create(b);
  4351. }
  4352. var a = this;
  4353. var ax0 = a.x;
  4354. var ax1 = a.x + a.width;
  4355. var ay0 = a.y;
  4356. var ay1 = a.y + a.height;
  4357. var bx0 = b.x;
  4358. var bx1 = b.x + b.width;
  4359. var by0 = b.y;
  4360. var by1 = b.y + b.height;
  4361. return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4362. },
  4363. contain: function (x, y) {
  4364. var rect = this;
  4365. return x >= rect.x
  4366. && x <= (rect.x + rect.width)
  4367. && y >= rect.y
  4368. && y <= (rect.y + rect.height);
  4369. },
  4370. /**
  4371. * @return {module:echarts/core/BoundingRect}
  4372. */
  4373. clone: function () {
  4374. return new BoundingRect(this.x, this.y, this.width, this.height);
  4375. },
  4376. /**
  4377. * Copy from another rect
  4378. */
  4379. copy: function (other) {
  4380. this.x = other.x;
  4381. this.y = other.y;
  4382. this.width = other.width;
  4383. this.height = other.height;
  4384. },
  4385. plain: function () {
  4386. return {
  4387. x: this.x,
  4388. y: this.y,
  4389. width: this.width,
  4390. height: this.height
  4391. };
  4392. }
  4393. };
  4394. /**
  4395. * @param {Object|module:zrender/core/BoundingRect} rect
  4396. * @param {number} rect.x
  4397. * @param {number} rect.y
  4398. * @param {number} rect.width
  4399. * @param {number} rect.height
  4400. * @return {module:zrender/core/BoundingRect}
  4401. */
  4402. BoundingRect.create = function (rect) {
  4403. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4404. };
  4405. /**
  4406. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4407. * @module zrender/graphic/Group
  4408. * @example
  4409. * var Group = require('zrender/container/Group');
  4410. * var Circle = require('zrender/graphic/shape/Circle');
  4411. * var g = new Group();
  4412. * g.position[0] = 100;
  4413. * g.position[1] = 100;
  4414. * g.add(new Circle({
  4415. * style: {
  4416. * x: 100,
  4417. * y: 100,
  4418. * r: 20,
  4419. * }
  4420. * }));
  4421. * zr.add(g);
  4422. */
  4423. /**
  4424. * @alias module:zrender/graphic/Group
  4425. * @constructor
  4426. * @extends module:zrender/mixin/Transformable
  4427. * @extends module:zrender/mixin/Eventful
  4428. */
  4429. var Group = function (opts) {
  4430. opts = opts || {};
  4431. Element.call(this, opts);
  4432. for (var key in opts) {
  4433. if (opts.hasOwnProperty(key)) {
  4434. this[key] = opts[key];
  4435. }
  4436. }
  4437. this._children = [];
  4438. this.__storage = null;
  4439. this.__dirty = true;
  4440. };
  4441. Group.prototype = {
  4442. constructor: Group,
  4443. isGroup: true,
  4444. /**
  4445. * @type {string}
  4446. */
  4447. type: 'group',
  4448. /**
  4449. * 所有子孙元素是否响应鼠标事件
  4450. * @name module:/zrender/container/Group#silent
  4451. * @type {boolean}
  4452. * @default false
  4453. */
  4454. silent: false,
  4455. /**
  4456. * @return {Array.<module:zrender/Element>}
  4457. */
  4458. children: function () {
  4459. return this._children.slice();
  4460. },
  4461. /**
  4462. * 获取指定 index 的儿子节点
  4463. * @param {number} idx
  4464. * @return {module:zrender/Element}
  4465. */
  4466. childAt: function (idx) {
  4467. return this._children[idx];
  4468. },
  4469. /**
  4470. * 获取指定名字的儿子节点
  4471. * @param {string} name
  4472. * @return {module:zrender/Element}
  4473. */
  4474. childOfName: function (name) {
  4475. var children = this._children;
  4476. for (var i = 0; i < children.length; i++) {
  4477. if (children[i].name === name) {
  4478. return children[i];
  4479. }
  4480. }
  4481. },
  4482. /**
  4483. * @return {number}
  4484. */
  4485. childCount: function () {
  4486. return this._children.length;
  4487. },
  4488. /**
  4489. * 添加子节点到最后
  4490. * @param {module:zrender/Element} child
  4491. */
  4492. add: function (child) {
  4493. if (child && child !== this && child.parent !== this) {
  4494. this._children.push(child);
  4495. this._doAdd(child);
  4496. }
  4497. return this;
  4498. },
  4499. /**
  4500. * 添加子节点在 nextSibling 之前
  4501. * @param {module:zrender/Element} child
  4502. * @param {module:zrender/Element} nextSibling
  4503. */
  4504. addBefore: function (child, nextSibling) {
  4505. if (child && child !== this && child.parent !== this
  4506. && nextSibling && nextSibling.parent === this) {
  4507. var children = this._children;
  4508. var idx = children.indexOf(nextSibling);
  4509. if (idx >= 0) {
  4510. children.splice(idx, 0, child);
  4511. this._doAdd(child);
  4512. }
  4513. }
  4514. return this;
  4515. },
  4516. _doAdd: function (child) {
  4517. if (child.parent) {
  4518. child.parent.remove(child);
  4519. }
  4520. child.parent = this;
  4521. var storage = this.__storage;
  4522. var zr = this.__zr;
  4523. if (storage && storage !== child.__storage) {
  4524. storage.addToStorage(child);
  4525. if (child instanceof Group) {
  4526. child.addChildrenToStorage(storage);
  4527. }
  4528. }
  4529. zr && zr.refresh();
  4530. },
  4531. /**
  4532. * 移除子节点
  4533. * @param {module:zrender/Element} child
  4534. */
  4535. remove: function (child) {
  4536. var zr = this.__zr;
  4537. var storage = this.__storage;
  4538. var children = this._children;
  4539. var idx = indexOf(children, child);
  4540. if (idx < 0) {
  4541. return this;
  4542. }
  4543. children.splice(idx, 1);
  4544. child.parent = null;
  4545. if (storage) {
  4546. storage.delFromStorage(child);
  4547. if (child instanceof Group) {
  4548. child.delChildrenFromStorage(storage);
  4549. }
  4550. }
  4551. zr && zr.refresh();
  4552. return this;
  4553. },
  4554. /**
  4555. * 移除所有子节点
  4556. */
  4557. removeAll: function () {
  4558. var children = this._children;
  4559. var storage = this.__storage;
  4560. var child;
  4561. var i;
  4562. for (i = 0; i < children.length; i++) {
  4563. child = children[i];
  4564. if (storage) {
  4565. storage.delFromStorage(child);
  4566. if (child instanceof Group) {
  4567. child.delChildrenFromStorage(storage);
  4568. }
  4569. }
  4570. child.parent = null;
  4571. }
  4572. children.length = 0;
  4573. return this;
  4574. },
  4575. /**
  4576. * 遍历所有子节点
  4577. * @param {Function} cb
  4578. * @param {} context
  4579. */
  4580. eachChild: function (cb, context) {
  4581. var children = this._children;
  4582. for (var i = 0; i < children.length; i++) {
  4583. var child = children[i];
  4584. cb.call(context, child, i);
  4585. }
  4586. return this;
  4587. },
  4588. /**
  4589. * 深度优先遍历所有子孙节点
  4590. * @param {Function} cb
  4591. * @param {} context
  4592. */
  4593. traverse: function (cb, context) {
  4594. for (var i = 0; i < this._children.length; i++) {
  4595. var child = this._children[i];
  4596. cb.call(context, child);
  4597. if (child.type === 'group') {
  4598. child.traverse(cb, context);
  4599. }
  4600. }
  4601. return this;
  4602. },
  4603. addChildrenToStorage: function (storage) {
  4604. for (var i = 0; i < this._children.length; i++) {
  4605. var child = this._children[i];
  4606. storage.addToStorage(child);
  4607. if (child instanceof Group) {
  4608. child.addChildrenToStorage(storage);
  4609. }
  4610. }
  4611. },
  4612. delChildrenFromStorage: function (storage) {
  4613. for (var i = 0; i < this._children.length; i++) {
  4614. var child = this._children[i];
  4615. storage.delFromStorage(child);
  4616. if (child instanceof Group) {
  4617. child.delChildrenFromStorage(storage);
  4618. }
  4619. }
  4620. },
  4621. dirty: function () {
  4622. this.__dirty = true;
  4623. this.__zr && this.__zr.refresh();
  4624. return this;
  4625. },
  4626. /**
  4627. * @return {module:zrender/core/BoundingRect}
  4628. */
  4629. getBoundingRect: function (includeChildren) {
  4630. // TODO Caching
  4631. var rect = null;
  4632. var tmpRect = new BoundingRect(0, 0, 0, 0);
  4633. var children = includeChildren || this._children;
  4634. var tmpMat = [];
  4635. for (var i = 0; i < children.length; i++) {
  4636. var child = children[i];
  4637. if (child.ignore || child.invisible) {
  4638. continue;
  4639. }
  4640. var childRect = child.getBoundingRect();
  4641. var transform = child.getLocalTransform(tmpMat);
  4642. // TODO
  4643. // The boundingRect cacluated by transforming original
  4644. // rect may be bigger than the actual bundingRect when rotation
  4645. // is used. (Consider a circle rotated aginst its center, where
  4646. // the actual boundingRect should be the same as that not be
  4647. // rotated.) But we can not find better approach to calculate
  4648. // actual boundingRect yet, considering performance.
  4649. if (transform) {
  4650. tmpRect.copy(childRect);
  4651. tmpRect.applyTransform(transform);
  4652. rect = rect || tmpRect.clone();
  4653. rect.union(tmpRect);
  4654. }
  4655. else {
  4656. rect = rect || childRect.clone();
  4657. rect.union(childRect);
  4658. }
  4659. }
  4660. return rect || tmpRect;
  4661. }
  4662. };
  4663. inherits(Group, Element);
  4664. // https://github.com/mziccard/node-timsort
  4665. var DEFAULT_MIN_MERGE = 32;
  4666. var DEFAULT_MIN_GALLOPING = 7;
  4667. function minRunLength(n) {
  4668. var r = 0;
  4669. while (n >= DEFAULT_MIN_MERGE) {
  4670. r |= n & 1;
  4671. n >>= 1;
  4672. }
  4673. return n + r;
  4674. }
  4675. function makeAscendingRun(array, lo, hi, compare) {
  4676. var runHi = lo + 1;
  4677. if (runHi === hi) {
  4678. return 1;
  4679. }
  4680. if (compare(array[runHi++], array[lo]) < 0) {
  4681. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  4682. runHi++;
  4683. }
  4684. reverseRun(array, lo, runHi);
  4685. }
  4686. else {
  4687. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  4688. runHi++;
  4689. }
  4690. }
  4691. return runHi - lo;
  4692. }
  4693. function reverseRun(array, lo, hi) {
  4694. hi--;
  4695. while (lo < hi) {
  4696. var t = array[lo];
  4697. array[lo++] = array[hi];
  4698. array[hi--] = t;
  4699. }
  4700. }
  4701. function binaryInsertionSort(array, lo, hi, start, compare) {
  4702. if (start === lo) {
  4703. start++;
  4704. }
  4705. for (; start < hi; start++) {
  4706. var pivot = array[start];
  4707. var left = lo;
  4708. var right = start;
  4709. var mid;
  4710. while (left < right) {
  4711. mid = left + right >>> 1;
  4712. if (compare(pivot, array[mid]) < 0) {
  4713. right = mid;
  4714. }
  4715. else {
  4716. left = mid + 1;
  4717. }
  4718. }
  4719. var n = start - left;
  4720. switch (n) {
  4721. case 3:
  4722. array[left + 3] = array[left + 2];
  4723. case 2:
  4724. array[left + 2] = array[left + 1];
  4725. case 1:
  4726. array[left + 1] = array[left];
  4727. break;
  4728. default:
  4729. while (n > 0) {
  4730. array[left + n] = array[left + n - 1];
  4731. n--;
  4732. }
  4733. }
  4734. array[left] = pivot;
  4735. }
  4736. }
  4737. function gallopLeft(value, array, start, length, hint, compare) {
  4738. var lastOffset = 0;
  4739. var maxOffset = 0;
  4740. var offset = 1;
  4741. if (compare(value, array[start + hint]) > 0) {
  4742. maxOffset = length - hint;
  4743. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  4744. lastOffset = offset;
  4745. offset = (offset << 1) + 1;
  4746. if (offset <= 0) {
  4747. offset = maxOffset;
  4748. }
  4749. }
  4750. if (offset > maxOffset) {
  4751. offset = maxOffset;
  4752. }
  4753. lastOffset += hint;
  4754. offset += hint;
  4755. }
  4756. else {
  4757. maxOffset = hint + 1;
  4758. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  4759. lastOffset = offset;
  4760. offset = (offset << 1) + 1;
  4761. if (offset <= 0) {
  4762. offset = maxOffset;
  4763. }
  4764. }
  4765. if (offset > maxOffset) {
  4766. offset = maxOffset;
  4767. }
  4768. var tmp = lastOffset;
  4769. lastOffset = hint - offset;
  4770. offset = hint - tmp;
  4771. }
  4772. lastOffset++;
  4773. while (lastOffset < offset) {
  4774. var m = lastOffset + (offset - lastOffset >>> 1);
  4775. if (compare(value, array[start + m]) > 0) {
  4776. lastOffset = m + 1;
  4777. }
  4778. else {
  4779. offset = m;
  4780. }
  4781. }
  4782. return offset;
  4783. }
  4784. function gallopRight(value, array, start, length, hint, compare) {
  4785. var lastOffset = 0;
  4786. var maxOffset = 0;
  4787. var offset = 1;
  4788. if (compare(value, array[start + hint]) < 0) {
  4789. maxOffset = hint + 1;
  4790. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  4791. lastOffset = offset;
  4792. offset = (offset << 1) + 1;
  4793. if (offset <= 0) {
  4794. offset = maxOffset;
  4795. }
  4796. }
  4797. if (offset > maxOffset) {
  4798. offset = maxOffset;
  4799. }
  4800. var tmp = lastOffset;
  4801. lastOffset = hint - offset;
  4802. offset = hint - tmp;
  4803. }
  4804. else {
  4805. maxOffset = length - hint;
  4806. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  4807. lastOffset = offset;
  4808. offset = (offset << 1) + 1;
  4809. if (offset <= 0) {
  4810. offset = maxOffset;
  4811. }
  4812. }
  4813. if (offset > maxOffset) {
  4814. offset = maxOffset;
  4815. }
  4816. lastOffset += hint;
  4817. offset += hint;
  4818. }
  4819. lastOffset++;
  4820. while (lastOffset < offset) {
  4821. var m = lastOffset + (offset - lastOffset >>> 1);
  4822. if (compare(value, array[start + m]) < 0) {
  4823. offset = m;
  4824. }
  4825. else {
  4826. lastOffset = m + 1;
  4827. }
  4828. }
  4829. return offset;
  4830. }
  4831. function TimSort(array, compare) {
  4832. var minGallop = DEFAULT_MIN_GALLOPING;
  4833. var runStart;
  4834. var runLength;
  4835. var stackSize = 0;
  4836. var tmp = [];
  4837. runStart = [];
  4838. runLength = [];
  4839. function pushRun(_runStart, _runLength) {
  4840. runStart[stackSize] = _runStart;
  4841. runLength[stackSize] = _runLength;
  4842. stackSize += 1;
  4843. }
  4844. function mergeRuns() {
  4845. while (stackSize > 1) {
  4846. var n = stackSize - 2;
  4847. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  4848. if (runLength[n - 1] < runLength[n + 1]) {
  4849. n--;
  4850. }
  4851. }
  4852. else if (runLength[n] > runLength[n + 1]) {
  4853. break;
  4854. }
  4855. mergeAt(n);
  4856. }
  4857. }
  4858. function forceMergeRuns() {
  4859. while (stackSize > 1) {
  4860. var n = stackSize - 2;
  4861. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  4862. n--;
  4863. }
  4864. mergeAt(n);
  4865. }
  4866. }
  4867. function mergeAt(i) {
  4868. var start1 = runStart[i];
  4869. var length1 = runLength[i];
  4870. var start2 = runStart[i + 1];
  4871. var length2 = runLength[i + 1];
  4872. runLength[i] = length1 + length2;
  4873. if (i === stackSize - 3) {
  4874. runStart[i + 1] = runStart[i + 2];
  4875. runLength[i + 1] = runLength[i + 2];
  4876. }
  4877. stackSize--;
  4878. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  4879. start1 += k;
  4880. length1 -= k;
  4881. if (length1 === 0) {
  4882. return;
  4883. }
  4884. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  4885. if (length2 === 0) {
  4886. return;
  4887. }
  4888. if (length1 <= length2) {
  4889. mergeLow(start1, length1, start2, length2);
  4890. }
  4891. else {
  4892. mergeHigh(start1, length1, start2, length2);
  4893. }
  4894. }
  4895. function mergeLow(start1, length1, start2, length2) {
  4896. var i = 0;
  4897. for (i = 0; i < length1; i++) {
  4898. tmp[i] = array[start1 + i];
  4899. }
  4900. var cursor1 = 0;
  4901. var cursor2 = start2;
  4902. var dest = start1;
  4903. array[dest++] = array[cursor2++];
  4904. if (--length2 === 0) {
  4905. for (i = 0; i < length1; i++) {
  4906. array[dest + i] = tmp[cursor1 + i];
  4907. }
  4908. return;
  4909. }
  4910. if (length1 === 1) {
  4911. for (i = 0; i < length2; i++) {
  4912. array[dest + i] = array[cursor2 + i];
  4913. }
  4914. array[dest + length2] = tmp[cursor1];
  4915. return;
  4916. }
  4917. var _minGallop = minGallop;
  4918. var count1, count2, exit;
  4919. while (1) {
  4920. count1 = 0;
  4921. count2 = 0;
  4922. exit = false;
  4923. do {
  4924. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  4925. array[dest++] = array[cursor2++];
  4926. count2++;
  4927. count1 = 0;
  4928. if (--length2 === 0) {
  4929. exit = true;
  4930. break;
  4931. }
  4932. }
  4933. else {
  4934. array[dest++] = tmp[cursor1++];
  4935. count1++;
  4936. count2 = 0;
  4937. if (--length1 === 1) {
  4938. exit = true;
  4939. break;
  4940. }
  4941. }
  4942. } while ((count1 | count2) < _minGallop);
  4943. if (exit) {
  4944. break;
  4945. }
  4946. do {
  4947. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  4948. if (count1 !== 0) {
  4949. for (i = 0; i < count1; i++) {
  4950. array[dest + i] = tmp[cursor1 + i];
  4951. }
  4952. dest += count1;
  4953. cursor1 += count1;
  4954. length1 -= count1;
  4955. if (length1 <= 1) {
  4956. exit = true;
  4957. break;
  4958. }
  4959. }
  4960. array[dest++] = array[cursor2++];
  4961. if (--length2 === 0) {
  4962. exit = true;
  4963. break;
  4964. }
  4965. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  4966. if (count2 !== 0) {
  4967. for (i = 0; i < count2; i++) {
  4968. array[dest + i] = array[cursor2 + i];
  4969. }
  4970. dest += count2;
  4971. cursor2 += count2;
  4972. length2 -= count2;
  4973. if (length2 === 0) {
  4974. exit = true;
  4975. break;
  4976. }
  4977. }
  4978. array[dest++] = tmp[cursor1++];
  4979. if (--length1 === 1) {
  4980. exit = true;
  4981. break;
  4982. }
  4983. _minGallop--;
  4984. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  4985. if (exit) {
  4986. break;
  4987. }
  4988. if (_minGallop < 0) {
  4989. _minGallop = 0;
  4990. }
  4991. _minGallop += 2;
  4992. }
  4993. minGallop = _minGallop;
  4994. minGallop < 1 && (minGallop = 1);
  4995. if (length1 === 1) {
  4996. for (i = 0; i < length2; i++) {
  4997. array[dest + i] = array[cursor2 + i];
  4998. }
  4999. array[dest + length2] = tmp[cursor1];
  5000. }
  5001. else if (length1 === 0) {
  5002. throw new Error();
  5003. // throw new Error('mergeLow preconditions were not respected');
  5004. }
  5005. else {
  5006. for (i = 0; i < length1; i++) {
  5007. array[dest + i] = tmp[cursor1 + i];
  5008. }
  5009. }
  5010. }
  5011. function mergeHigh (start1, length1, start2, length2) {
  5012. var i = 0;
  5013. for (i = 0; i < length2; i++) {
  5014. tmp[i] = array[start2 + i];
  5015. }
  5016. var cursor1 = start1 + length1 - 1;
  5017. var cursor2 = length2 - 1;
  5018. var dest = start2 + length2 - 1;
  5019. var customCursor = 0;
  5020. var customDest = 0;
  5021. array[dest--] = array[cursor1--];
  5022. if (--length1 === 0) {
  5023. customCursor = dest - (length2 - 1);
  5024. for (i = 0; i < length2; i++) {
  5025. array[customCursor + i] = tmp[i];
  5026. }
  5027. return;
  5028. }
  5029. if (length2 === 1) {
  5030. dest -= length1;
  5031. cursor1 -= length1;
  5032. customDest = dest + 1;
  5033. customCursor = cursor1 + 1;
  5034. for (i = length1 - 1; i >= 0; i--) {
  5035. array[customDest + i] = array[customCursor + i];
  5036. }
  5037. array[dest] = tmp[cursor2];
  5038. return;
  5039. }
  5040. var _minGallop = minGallop;
  5041. while (true) {
  5042. var count1 = 0;
  5043. var count2 = 0;
  5044. var exit = false;
  5045. do {
  5046. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5047. array[dest--] = array[cursor1--];
  5048. count1++;
  5049. count2 = 0;
  5050. if (--length1 === 0) {
  5051. exit = true;
  5052. break;
  5053. }
  5054. }
  5055. else {
  5056. array[dest--] = tmp[cursor2--];
  5057. count2++;
  5058. count1 = 0;
  5059. if (--length2 === 1) {
  5060. exit = true;
  5061. break;
  5062. }
  5063. }
  5064. } while ((count1 | count2) < _minGallop);
  5065. if (exit) {
  5066. break;
  5067. }
  5068. do {
  5069. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5070. if (count1 !== 0) {
  5071. dest -= count1;
  5072. cursor1 -= count1;
  5073. length1 -= count1;
  5074. customDest = dest + 1;
  5075. customCursor = cursor1 + 1;
  5076. for (i = count1 - 1; i >= 0; i--) {
  5077. array[customDest + i] = array[customCursor + i];
  5078. }
  5079. if (length1 === 0) {
  5080. exit = true;
  5081. break;
  5082. }
  5083. }
  5084. array[dest--] = tmp[cursor2--];
  5085. if (--length2 === 1) {
  5086. exit = true;
  5087. break;
  5088. }
  5089. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5090. if (count2 !== 0) {
  5091. dest -= count2;
  5092. cursor2 -= count2;
  5093. length2 -= count2;
  5094. customDest = dest + 1;
  5095. customCursor = cursor2 + 1;
  5096. for (i = 0; i < count2; i++) {
  5097. array[customDest + i] = tmp[customCursor + i];
  5098. }
  5099. if (length2 <= 1) {
  5100. exit = true;
  5101. break;
  5102. }
  5103. }
  5104. array[dest--] = array[cursor1--];
  5105. if (--length1 === 0) {
  5106. exit = true;
  5107. break;
  5108. }
  5109. _minGallop--;
  5110. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5111. if (exit) {
  5112. break;
  5113. }
  5114. if (_minGallop < 0) {
  5115. _minGallop = 0;
  5116. }
  5117. _minGallop += 2;
  5118. }
  5119. minGallop = _minGallop;
  5120. if (minGallop < 1) {
  5121. minGallop = 1;
  5122. }
  5123. if (length2 === 1) {
  5124. dest -= length1;
  5125. cursor1 -= length1;
  5126. customDest = dest + 1;
  5127. customCursor = cursor1 + 1;
  5128. for (i = length1 - 1; i >= 0; i--) {
  5129. array[customDest + i] = array[customCursor + i];
  5130. }
  5131. array[dest] = tmp[cursor2];
  5132. }
  5133. else if (length2 === 0) {
  5134. throw new Error();
  5135. // throw new Error('mergeHigh preconditions were not respected');
  5136. }
  5137. else {
  5138. customCursor = dest - (length2 - 1);
  5139. for (i = 0; i < length2; i++) {
  5140. array[customCursor + i] = tmp[i];
  5141. }
  5142. }
  5143. }
  5144. this.mergeRuns = mergeRuns;
  5145. this.forceMergeRuns = forceMergeRuns;
  5146. this.pushRun = pushRun;
  5147. }
  5148. function sort(array, compare, lo, hi) {
  5149. if (!lo) {
  5150. lo = 0;
  5151. }
  5152. if (!hi) {
  5153. hi = array.length;
  5154. }
  5155. var remaining = hi - lo;
  5156. if (remaining < 2) {
  5157. return;
  5158. }
  5159. var runLength = 0;
  5160. if (remaining < DEFAULT_MIN_MERGE) {
  5161. runLength = makeAscendingRun(array, lo, hi, compare);
  5162. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5163. return;
  5164. }
  5165. var ts = new TimSort(array, compare);
  5166. var minRun = minRunLength(remaining);
  5167. do {
  5168. runLength = makeAscendingRun(array, lo, hi, compare);
  5169. if (runLength < minRun) {
  5170. var force = remaining;
  5171. if (force > minRun) {
  5172. force = minRun;
  5173. }
  5174. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5175. runLength = force;
  5176. }
  5177. ts.pushRun(lo, runLength);
  5178. ts.mergeRuns();
  5179. remaining -= runLength;
  5180. lo += runLength;
  5181. } while (remaining !== 0);
  5182. ts.forceMergeRuns();
  5183. }
  5184. // Use timsort because in most case elements are partially sorted
  5185. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5186. function shapeCompareFunc(a, b) {
  5187. if (a.zlevel === b.zlevel) {
  5188. if (a.z === b.z) {
  5189. // if (a.z2 === b.z2) {
  5190. // // FIXME Slow has renderidx compare
  5191. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5192. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5193. // return a.__renderidx - b.__renderidx;
  5194. // }
  5195. return a.z2 - b.z2;
  5196. }
  5197. return a.z - b.z;
  5198. }
  5199. return a.zlevel - b.zlevel;
  5200. }
  5201. /**
  5202. * 内容仓库 (M)
  5203. * @alias module:zrender/Storage
  5204. * @constructor
  5205. */
  5206. var Storage = function () { // jshint ignore:line
  5207. this._roots = [];
  5208. this._displayList = [];
  5209. this._displayListLen = 0;
  5210. };
  5211. Storage.prototype = {
  5212. constructor: Storage,
  5213. /**
  5214. * @param {Function} cb
  5215. *
  5216. */
  5217. traverse: function (cb, context) {
  5218. for (var i = 0; i < this._roots.length; i++) {
  5219. this._roots[i].traverse(cb, context);
  5220. }
  5221. },
  5222. /**
  5223. * 返回所有图形的绘制队列
  5224. * @param {boolean} [update=false] 是否在返回前更新该数组
  5225. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5226. *
  5227. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5228. * @return {Array.<module:zrender/graphic/Displayable>}
  5229. */
  5230. getDisplayList: function (update, includeIgnore) {
  5231. includeIgnore = includeIgnore || false;
  5232. if (update) {
  5233. this.updateDisplayList(includeIgnore);
  5234. }
  5235. return this._displayList;
  5236. },
  5237. /**
  5238. * 更新图形的绘制队列。
  5239. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5240. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5241. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5242. */
  5243. updateDisplayList: function (includeIgnore) {
  5244. this._displayListLen = 0;
  5245. var roots = this._roots;
  5246. var displayList = this._displayList;
  5247. for (var i = 0, len = roots.length; i < len; i++) {
  5248. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5249. }
  5250. displayList.length = this._displayListLen;
  5251. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5252. },
  5253. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5254. if (el.ignore && !includeIgnore) {
  5255. return;
  5256. }
  5257. el.beforeUpdate();
  5258. if (el.__dirty) {
  5259. el.update();
  5260. }
  5261. el.afterUpdate();
  5262. var userSetClipPath = el.clipPath;
  5263. if (userSetClipPath) {
  5264. // FIXME 效率影响
  5265. if (clipPaths) {
  5266. clipPaths = clipPaths.slice();
  5267. }
  5268. else {
  5269. clipPaths = [];
  5270. }
  5271. var currentClipPath = userSetClipPath;
  5272. var parentClipPath = el;
  5273. // Recursively add clip path
  5274. while (currentClipPath) {
  5275. // clipPath 的变换是基于使用这个 clipPath 的元素
  5276. currentClipPath.parent = parentClipPath;
  5277. currentClipPath.updateTransform();
  5278. clipPaths.push(currentClipPath);
  5279. parentClipPath = currentClipPath;
  5280. currentClipPath = currentClipPath.clipPath;
  5281. }
  5282. }
  5283. if (el.isGroup) {
  5284. var children = el._children;
  5285. for (var i = 0; i < children.length; i++) {
  5286. var child = children[i];
  5287. // Force to mark as dirty if group is dirty
  5288. // FIXME __dirtyPath ?
  5289. if (el.__dirty) {
  5290. child.__dirty = true;
  5291. }
  5292. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5293. }
  5294. // Mark group clean here
  5295. el.__dirty = false;
  5296. }
  5297. else {
  5298. el.__clipPaths = clipPaths;
  5299. this._displayList[this._displayListLen++] = el;
  5300. }
  5301. },
  5302. /**
  5303. * 添加图形(Shape)或者组(Group)到根节点
  5304. * @param {module:zrender/Element} el
  5305. */
  5306. addRoot: function (el) {
  5307. if (el.__storage === this) {
  5308. return;
  5309. }
  5310. if (el instanceof Group) {
  5311. el.addChildrenToStorage(this);
  5312. }
  5313. this.addToStorage(el);
  5314. this._roots.push(el);
  5315. },
  5316. /**
  5317. * 删除指定的图形(Shape)或者组(Group)
  5318. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5319. */
  5320. delRoot: function (el) {
  5321. if (el == null) {
  5322. // 不指定el清空
  5323. for (var i = 0; i < this._roots.length; i++) {
  5324. var root = this._roots[i];
  5325. if (root instanceof Group) {
  5326. root.delChildrenFromStorage(this);
  5327. }
  5328. }
  5329. this._roots = [];
  5330. this._displayList = [];
  5331. this._displayListLen = 0;
  5332. return;
  5333. }
  5334. if (el instanceof Array) {
  5335. for (var i = 0, l = el.length; i < l; i++) {
  5336. this.delRoot(el[i]);
  5337. }
  5338. return;
  5339. }
  5340. var idx = indexOf(this._roots, el);
  5341. if (idx >= 0) {
  5342. this.delFromStorage(el);
  5343. this._roots.splice(idx, 1);
  5344. if (el instanceof Group) {
  5345. el.delChildrenFromStorage(this);
  5346. }
  5347. }
  5348. },
  5349. addToStorage: function (el) {
  5350. if (el) {
  5351. el.__storage = this;
  5352. el.dirty(false);
  5353. }
  5354. return this;
  5355. },
  5356. delFromStorage: function (el) {
  5357. if (el) {
  5358. el.__storage = null;
  5359. }
  5360. return this;
  5361. },
  5362. /**
  5363. * 清空并且释放Storage
  5364. */
  5365. dispose: function () {
  5366. this._renderList =
  5367. this._roots = null;
  5368. },
  5369. displayableSortFunc: shapeCompareFunc
  5370. };
  5371. var SHADOW_PROPS = {
  5372. 'shadowBlur': 1,
  5373. 'shadowOffsetX': 1,
  5374. 'shadowOffsetY': 1,
  5375. 'textShadowBlur': 1,
  5376. 'textShadowOffsetX': 1,
  5377. 'textShadowOffsetY': 1,
  5378. 'textBoxShadowBlur': 1,
  5379. 'textBoxShadowOffsetX': 1,
  5380. 'textBoxShadowOffsetY': 1
  5381. };
  5382. var fixShadow = function (ctx, propName, value) {
  5383. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5384. return value *= ctx.dpr;
  5385. }
  5386. return value;
  5387. };
  5388. var STYLE_COMMON_PROPS = [
  5389. ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'],
  5390. ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]
  5391. ];
  5392. // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5393. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5394. var Style = function (opts, host) {
  5395. this.extendFrom(opts, false);
  5396. this.host = host;
  5397. };
  5398. function createLinearGradient(ctx, obj, rect) {
  5399. var x = obj.x == null ? 0 : obj.x;
  5400. var x2 = obj.x2 == null ? 1 : obj.x2;
  5401. var y = obj.y == null ? 0 : obj.y;
  5402. var y2 = obj.y2 == null ? 0 : obj.y2;
  5403. if (!obj.global) {
  5404. x = x * rect.width + rect.x;
  5405. x2 = x2 * rect.width + rect.x;
  5406. y = y * rect.height + rect.y;
  5407. y2 = y2 * rect.height + rect.y;
  5408. }
  5409. // Fix NaN when rect is Infinity
  5410. x = isNaN(x) ? 0 : x;
  5411. x2 = isNaN(x2) ? 1 : x2;
  5412. y = isNaN(y) ? 0 : y;
  5413. y2 = isNaN(y2) ? 0 : y2;
  5414. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5415. return canvasGradient;
  5416. }
  5417. function createRadialGradient(ctx, obj, rect) {
  5418. var width = rect.width;
  5419. var height = rect.height;
  5420. var min = Math.min(width, height);
  5421. var x = obj.x == null ? 0.5 : obj.x;
  5422. var y = obj.y == null ? 0.5 : obj.y;
  5423. var r = obj.r == null ? 0.5 : obj.r;
  5424. if (!obj.global) {
  5425. x = x * width + rect.x;
  5426. y = y * height + rect.y;
  5427. r = r * min;
  5428. }
  5429. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5430. return canvasGradient;
  5431. }
  5432. Style.prototype = {
  5433. constructor: Style,
  5434. /**
  5435. * @type {module:zrender/graphic/Displayable}
  5436. */
  5437. host: null,
  5438. /**
  5439. * @type {string}
  5440. */
  5441. fill: '#000',
  5442. /**
  5443. * @type {string}
  5444. */
  5445. stroke: null,
  5446. /**
  5447. * @type {number}
  5448. */
  5449. opacity: 1,
  5450. /**
  5451. * @type {Array.<number>}
  5452. */
  5453. lineDash: null,
  5454. /**
  5455. * @type {number}
  5456. */
  5457. lineDashOffset: 0,
  5458. /**
  5459. * @type {number}
  5460. */
  5461. shadowBlur: 0,
  5462. /**
  5463. * @type {number}
  5464. */
  5465. shadowOffsetX: 0,
  5466. /**
  5467. * @type {number}
  5468. */
  5469. shadowOffsetY: 0,
  5470. /**
  5471. * @type {number}
  5472. */
  5473. lineWidth: 1,
  5474. /**
  5475. * If stroke ignore scale
  5476. * @type {Boolean}
  5477. */
  5478. strokeNoScale: false,
  5479. // Bounding rect text configuration
  5480. // Not affected by element transform
  5481. /**
  5482. * @type {string}
  5483. */
  5484. text: null,
  5485. /**
  5486. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5487. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5488. * So do not visit it directly in upper application (like echarts),
  5489. * but use `contain/text#makeFont` instead.
  5490. * @type {string}
  5491. */
  5492. font: null,
  5493. /**
  5494. * The same as font. Use font please.
  5495. * @deprecated
  5496. * @type {string}
  5497. */
  5498. textFont: null,
  5499. /**
  5500. * It helps merging respectively, rather than parsing an entire font string.
  5501. * @type {string}
  5502. */
  5503. fontStyle: null,
  5504. /**
  5505. * It helps merging respectively, rather than parsing an entire font string.
  5506. * @type {string}
  5507. */
  5508. fontWeight: null,
  5509. /**
  5510. * It helps merging respectively, rather than parsing an entire font string.
  5511. * Should be 12 but not '12px'.
  5512. * @type {number}
  5513. */
  5514. fontSize: null,
  5515. /**
  5516. * It helps merging respectively, rather than parsing an entire font string.
  5517. * @type {string}
  5518. */
  5519. fontFamily: null,
  5520. /**
  5521. * Reserved for special functinality, like 'hr'.
  5522. * @type {string}
  5523. */
  5524. textTag: null,
  5525. /**
  5526. * @type {string}
  5527. */
  5528. textFill: '#000',
  5529. /**
  5530. * @type {string}
  5531. */
  5532. textStroke: null,
  5533. /**
  5534. * @type {number}
  5535. */
  5536. textWidth: null,
  5537. /**
  5538. * Only for textBackground.
  5539. * @type {number}
  5540. */
  5541. textHeight: null,
  5542. /**
  5543. * textStroke may be set as some color as a default
  5544. * value in upper applicaion, where the default value
  5545. * of textStrokeWidth should be 0 to make sure that
  5546. * user can choose to do not use text stroke.
  5547. * @type {number}
  5548. */
  5549. textStrokeWidth: 0,
  5550. /**
  5551. * @type {number}
  5552. */
  5553. textLineHeight: null,
  5554. /**
  5555. * 'inside', 'left', 'right', 'top', 'bottom'
  5556. * [x, y]
  5557. * Based on x, y of rect.
  5558. * @type {string|Array.<number>}
  5559. * @default 'inside'
  5560. */
  5561. textPosition: 'inside',
  5562. /**
  5563. * If not specified, use the boundingRect of a `displayable`.
  5564. * @type {Object}
  5565. */
  5566. textRect: null,
  5567. /**
  5568. * [x, y]
  5569. * @type {Array.<number>}
  5570. */
  5571. textOffset: null,
  5572. /**
  5573. * @type {string}
  5574. */
  5575. textAlign: null,
  5576. /**
  5577. * @type {string}
  5578. */
  5579. textVerticalAlign: null,
  5580. /**
  5581. * @type {number}
  5582. */
  5583. textDistance: 5,
  5584. /**
  5585. * @type {string}
  5586. */
  5587. textShadowColor: 'transparent',
  5588. /**
  5589. * @type {number}
  5590. */
  5591. textShadowBlur: 0,
  5592. /**
  5593. * @type {number}
  5594. */
  5595. textShadowOffsetX: 0,
  5596. /**
  5597. * @type {number}
  5598. */
  5599. textShadowOffsetY: 0,
  5600. /**
  5601. * @type {string}
  5602. */
  5603. textBoxShadowColor: 'transparent',
  5604. /**
  5605. * @type {number}
  5606. */
  5607. textBoxShadowBlur: 0,
  5608. /**
  5609. * @type {number}
  5610. */
  5611. textBoxShadowOffsetX: 0,
  5612. /**
  5613. * @type {number}
  5614. */
  5615. textBoxShadowOffsetY: 0,
  5616. /**
  5617. * Whether transform text.
  5618. * Only useful in Path and Image element
  5619. * @type {boolean}
  5620. */
  5621. transformText: false,
  5622. /**
  5623. * Text rotate around position of Path or Image
  5624. * Only useful in Path and Image element and transformText is false.
  5625. */
  5626. textRotation: 0,
  5627. /**
  5628. * Text origin of text rotation, like [10, 40].
  5629. * Based on x, y of rect.
  5630. * Useful in label rotation of circular symbol.
  5631. * By default, this origin is textPosition.
  5632. * Can be 'center'.
  5633. * @type {string|Array.<number>}
  5634. */
  5635. textOrigin: null,
  5636. /**
  5637. * @type {string}
  5638. */
  5639. textBackgroundColor: null,
  5640. /**
  5641. * @type {string}
  5642. */
  5643. textBorderColor: null,
  5644. /**
  5645. * @type {number}
  5646. */
  5647. textBorderWidth: 0,
  5648. /**
  5649. * @type {number}
  5650. */
  5651. textBorderRadius: 0,
  5652. /**
  5653. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  5654. * @type {number|Array.<number>}
  5655. */
  5656. textPadding: null,
  5657. /**
  5658. * Text styles for rich text.
  5659. * @type {Object}
  5660. */
  5661. rich: null,
  5662. /**
  5663. * {outerWidth, outerHeight, ellipsis, placeholder}
  5664. * @type {Object}
  5665. */
  5666. truncate: null,
  5667. /**
  5668. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  5669. * @type {string}
  5670. */
  5671. blend: null,
  5672. /**
  5673. * @param {CanvasRenderingContext2D} ctx
  5674. */
  5675. bind: function (ctx, el, prevEl) {
  5676. var style = this;
  5677. var prevStyle = prevEl && prevEl.style;
  5678. var firstDraw = !prevStyle;
  5679. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5680. var prop = STYLE_COMMON_PROPS[i];
  5681. var styleName = prop[0];
  5682. if (firstDraw || style[styleName] !== prevStyle[styleName]) {
  5683. // FIXME Invalid property value will cause style leak from previous element.
  5684. ctx[styleName] =
  5685. fixShadow(ctx, styleName, style[styleName] || prop[1]);
  5686. }
  5687. }
  5688. if ((firstDraw || style.fill !== prevStyle.fill)) {
  5689. ctx.fillStyle = style.fill;
  5690. }
  5691. if ((firstDraw || style.stroke !== prevStyle.stroke)) {
  5692. ctx.strokeStyle = style.stroke;
  5693. }
  5694. if ((firstDraw || style.opacity !== prevStyle.opacity)) {
  5695. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  5696. }
  5697. if ((firstDraw || style.blend !== prevStyle.blend)) {
  5698. ctx.globalCompositeOperation = style.blend || 'source-over';
  5699. }
  5700. if (this.hasStroke()) {
  5701. var lineWidth = style.lineWidth;
  5702. ctx.lineWidth = lineWidth / (
  5703. (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1
  5704. );
  5705. }
  5706. },
  5707. hasFill: function () {
  5708. var fill = this.fill;
  5709. return fill != null && fill !== 'none';
  5710. },
  5711. hasStroke: function () {
  5712. var stroke = this.stroke;
  5713. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  5714. },
  5715. /**
  5716. * Extend from other style
  5717. * @param {zrender/graphic/Style} otherStyle
  5718. * @param {boolean} overwrite true: overwrirte any way.
  5719. * false: overwrite only when !target.hasOwnProperty
  5720. * others: overwrite when property is not null/undefined.
  5721. */
  5722. extendFrom: function (otherStyle, overwrite) {
  5723. if (otherStyle) {
  5724. for (var name in otherStyle) {
  5725. if (otherStyle.hasOwnProperty(name)
  5726. && (overwrite === true
  5727. || (
  5728. overwrite === false
  5729. ? !this.hasOwnProperty(name)
  5730. : otherStyle[name] != null
  5731. )
  5732. )
  5733. ) {
  5734. this[name] = otherStyle[name];
  5735. }
  5736. }
  5737. }
  5738. },
  5739. /**
  5740. * Batch setting style with a given object
  5741. * @param {Object|string} obj
  5742. * @param {*} [obj]
  5743. */
  5744. set: function (obj, value) {
  5745. if (typeof obj === 'string') {
  5746. this[obj] = value;
  5747. }
  5748. else {
  5749. this.extendFrom(obj, true);
  5750. }
  5751. },
  5752. /**
  5753. * Clone
  5754. * @return {zrender/graphic/Style} [description]
  5755. */
  5756. clone: function () {
  5757. var newStyle = new this.constructor();
  5758. newStyle.extendFrom(this, true);
  5759. return newStyle;
  5760. },
  5761. getGradient: function (ctx, obj, rect) {
  5762. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  5763. var canvasGradient = method(ctx, obj, rect);
  5764. var colorStops = obj.colorStops;
  5765. for (var i = 0; i < colorStops.length; i++) {
  5766. canvasGradient.addColorStop(
  5767. colorStops[i].offset, colorStops[i].color
  5768. );
  5769. }
  5770. return canvasGradient;
  5771. }
  5772. };
  5773. var styleProto = Style.prototype;
  5774. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  5775. var prop = STYLE_COMMON_PROPS[i];
  5776. if (!(prop[0] in styleProto)) {
  5777. styleProto[prop[0]] = prop[1];
  5778. }
  5779. }
  5780. // Provide for others
  5781. Style.getGradient = styleProto.getGradient;
  5782. var Pattern = function (image, repeat) {
  5783. // Should do nothing more in this constructor. Because gradient can be
  5784. // declard by `color: {image: ...}`, where this constructor will not be called.
  5785. this.image = image;
  5786. this.repeat = repeat;
  5787. // Can be cloned
  5788. this.type = 'pattern';
  5789. };
  5790. Pattern.prototype.getCanvasPattern = function (ctx) {
  5791. return ctx.createPattern(this.image, this.repeat || 'repeat');
  5792. };
  5793. /**
  5794. * @module zrender/Layer
  5795. * @author pissang(https://www.github.com/pissang)
  5796. */
  5797. function returnFalse() {
  5798. return false;
  5799. }
  5800. /**
  5801. * 创建dom
  5802. *
  5803. * @inner
  5804. * @param {string} id dom id 待用
  5805. * @param {Painter} painter painter instance
  5806. * @param {number} number
  5807. */
  5808. function createDom(id, painter, dpr) {
  5809. var newDom = createCanvas();
  5810. var width = painter.getWidth();
  5811. var height = painter.getHeight();
  5812. var newDomStyle = newDom.style;
  5813. if (newDomStyle) { // In node or some other non-browser environment
  5814. newDomStyle.position = 'absolute';
  5815. newDomStyle.left = 0;
  5816. newDomStyle.top = 0;
  5817. newDomStyle.width = width + 'px';
  5818. newDomStyle.height = height + 'px';
  5819. newDom.setAttribute('data-zr-dom-id', id);
  5820. }
  5821. newDom.width = width * dpr;
  5822. newDom.height = height * dpr;
  5823. return newDom;
  5824. }
  5825. /**
  5826. * @alias module:zrender/Layer
  5827. * @constructor
  5828. * @extends module:zrender/mixin/Transformable
  5829. * @param {string} id
  5830. * @param {module:zrender/Painter} painter
  5831. * @param {number} [dpr]
  5832. */
  5833. var Layer = function(id, painter, dpr) {
  5834. var dom;
  5835. dpr = dpr || devicePixelRatio;
  5836. if (typeof id === 'string') {
  5837. dom = createDom(id, painter, dpr);
  5838. }
  5839. // Not using isDom because in node it will return false
  5840. else if (isObject$1(id)) {
  5841. dom = id;
  5842. id = dom.id;
  5843. }
  5844. this.id = id;
  5845. this.dom = dom;
  5846. var domStyle = dom.style;
  5847. if (domStyle) { // Not in node
  5848. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  5849. domStyle['-webkit-user-select'] = 'none';
  5850. domStyle['user-select'] = 'none';
  5851. domStyle['-webkit-touch-callout'] = 'none';
  5852. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  5853. domStyle['padding'] = 0;
  5854. domStyle['margin'] = 0;
  5855. domStyle['border-width'] = 0;
  5856. }
  5857. this.domBack = null;
  5858. this.ctxBack = null;
  5859. this.painter = painter;
  5860. this.config = null;
  5861. // Configs
  5862. /**
  5863. * 每次清空画布的颜色
  5864. * @type {string}
  5865. * @default 0
  5866. */
  5867. this.clearColor = 0;
  5868. /**
  5869. * 是否开启动态模糊
  5870. * @type {boolean}
  5871. * @default false
  5872. */
  5873. this.motionBlur = false;
  5874. /**
  5875. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  5876. * @type {number}
  5877. * @default 0.7
  5878. */
  5879. this.lastFrameAlpha = 0.7;
  5880. /**
  5881. * Layer dpr
  5882. * @type {number}
  5883. */
  5884. this.dpr = dpr;
  5885. };
  5886. Layer.prototype = {
  5887. constructor: Layer,
  5888. __dirty: true,
  5889. __used: false,
  5890. __drawIndex: 0,
  5891. __startIndex: 0,
  5892. __endIndex: 0,
  5893. incremental: false,
  5894. getElementCount: function () {
  5895. return this.__endIndex - this.__startIndex;
  5896. },
  5897. initContext: function () {
  5898. this.ctx = this.dom.getContext('2d');
  5899. this.ctx.dpr = this.dpr;
  5900. },
  5901. createBackBuffer: function () {
  5902. var dpr = this.dpr;
  5903. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  5904. this.ctxBack = this.domBack.getContext('2d');
  5905. if (dpr != 1) {
  5906. this.ctxBack.scale(dpr, dpr);
  5907. }
  5908. },
  5909. /**
  5910. * @param {number} width
  5911. * @param {number} height
  5912. */
  5913. resize: function (width, height) {
  5914. var dpr = this.dpr;
  5915. var dom = this.dom;
  5916. var domStyle = dom.style;
  5917. var domBack = this.domBack;
  5918. if (domStyle) {
  5919. domStyle.width = width + 'px';
  5920. domStyle.height = height + 'px';
  5921. }
  5922. dom.width = width * dpr;
  5923. dom.height = height * dpr;
  5924. if (domBack) {
  5925. domBack.width = width * dpr;
  5926. domBack.height = height * dpr;
  5927. if (dpr != 1) {
  5928. this.ctxBack.scale(dpr, dpr);
  5929. }
  5930. }
  5931. },
  5932. /**
  5933. * 清空该层画布
  5934. * @param {boolean} [clearAll]=false Clear all with out motion blur
  5935. * @param {Color} [clearColor]
  5936. */
  5937. clear: function (clearAll, clearColor) {
  5938. var dom = this.dom;
  5939. var ctx = this.ctx;
  5940. var width = dom.width;
  5941. var height = dom.height;
  5942. var clearColor = clearColor || this.clearColor;
  5943. var haveMotionBLur = this.motionBlur && !clearAll;
  5944. var lastFrameAlpha = this.lastFrameAlpha;
  5945. var dpr = this.dpr;
  5946. if (haveMotionBLur) {
  5947. if (!this.domBack) {
  5948. this.createBackBuffer();
  5949. }
  5950. this.ctxBack.globalCompositeOperation = 'copy';
  5951. this.ctxBack.drawImage(
  5952. dom, 0, 0,
  5953. width / dpr,
  5954. height / dpr
  5955. );
  5956. }
  5957. ctx.clearRect(0, 0, width, height);
  5958. if (clearColor && clearColor !== 'transparent') {
  5959. var clearColorGradientOrPattern;
  5960. // Gradient
  5961. if (clearColor.colorStops) {
  5962. // Cache canvas gradient
  5963. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  5964. x: 0,
  5965. y: 0,
  5966. width: width,
  5967. height: height
  5968. });
  5969. clearColor.__canvasGradient = clearColorGradientOrPattern;
  5970. }
  5971. // Pattern
  5972. else if (clearColor.image) {
  5973. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  5974. }
  5975. ctx.save();
  5976. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  5977. ctx.fillRect(0, 0, width, height);
  5978. ctx.restore();
  5979. }
  5980. if (haveMotionBLur) {
  5981. var domBack = this.domBack;
  5982. ctx.save();
  5983. ctx.globalAlpha = lastFrameAlpha;
  5984. ctx.drawImage(domBack, 0, 0, width, height);
  5985. ctx.restore();
  5986. }
  5987. }
  5988. };
  5989. var requestAnimationFrame = (
  5990. typeof window !== 'undefined'
  5991. && (
  5992. (window.requestAnimationFrame && window.requestAnimationFrame.bind(window))
  5993. // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  5994. || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window))
  5995. || window.mozRequestAnimationFrame
  5996. || window.webkitRequestAnimationFrame
  5997. )
  5998. ) || function (func) {
  5999. setTimeout(func, 16);
  6000. };
  6001. var globalImageCache = new LRU(50);
  6002. /**
  6003. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6004. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6005. */
  6006. function findExistImage(newImageOrSrc) {
  6007. if (typeof newImageOrSrc === 'string') {
  6008. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6009. return cachedImgObj && cachedImgObj.image;
  6010. }
  6011. else {
  6012. return newImageOrSrc;
  6013. }
  6014. }
  6015. /**
  6016. * Caution: User should cache loaded images, but not just count on LRU.
  6017. * Consider if required images more than LRU size, will dead loop occur?
  6018. *
  6019. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6020. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6021. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6022. * @param {Function} [cb] params: (image, cbPayload)
  6023. * @param {Object} [cbPayload] Payload on cb calling.
  6024. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6025. */
  6026. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6027. if (!newImageOrSrc) {
  6028. return image;
  6029. }
  6030. else if (typeof newImageOrSrc === 'string') {
  6031. // Image should not be loaded repeatly.
  6032. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) {
  6033. return image;
  6034. }
  6035. // Only when there is no existent image or existent image src
  6036. // is different, this method is responsible for load.
  6037. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6038. var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload};
  6039. if (cachedImgObj) {
  6040. image = cachedImgObj.image;
  6041. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6042. }
  6043. else {
  6044. !image && (image = new Image());
  6045. image.onload = imageOnLoad;
  6046. globalImageCache.put(
  6047. newImageOrSrc,
  6048. image.__cachedImgObj = {
  6049. image: image,
  6050. pending: [pendingWrap]
  6051. }
  6052. );
  6053. image.src = image.__zrImageSrc = newImageOrSrc;
  6054. }
  6055. return image;
  6056. }
  6057. // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6058. else {
  6059. return newImageOrSrc;
  6060. }
  6061. }
  6062. function imageOnLoad() {
  6063. var cachedImgObj = this.__cachedImgObj;
  6064. this.onload = this.__cachedImgObj = null;
  6065. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6066. var pendingWrap = cachedImgObj.pending[i];
  6067. var cb = pendingWrap.cb;
  6068. cb && cb(this, pendingWrap.cbPayload);
  6069. pendingWrap.hostEl.dirty();
  6070. }
  6071. cachedImgObj.pending.length = 0;
  6072. }
  6073. function isImageReady(image) {
  6074. return image && image.width && image.height;
  6075. }
  6076. var textWidthCache = {};
  6077. var textWidthCacheCounter = 0;
  6078. var TEXT_CACHE_MAX = 5000;
  6079. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6080. var DEFAULT_FONT = '12px sans-serif';
  6081. // Avoid assign to an exported variable, for transforming to cjs.
  6082. var methods$1 = {};
  6083. function $override$1(name, fn) {
  6084. methods$1[name] = fn;
  6085. }
  6086. /**
  6087. * @public
  6088. * @param {string} text
  6089. * @param {string} font
  6090. * @return {number} width
  6091. */
  6092. function getWidth(text, font) {
  6093. font = font || DEFAULT_FONT;
  6094. var key = text + ':' + font;
  6095. if (textWidthCache[key]) {
  6096. return textWidthCache[key];
  6097. }
  6098. var textLines = (text + '').split('\n');
  6099. var width = 0;
  6100. for (var i = 0, l = textLines.length; i < l; i++) {
  6101. // textContain.measureText may be overrided in SVG or VML
  6102. width = Math.max(measureText(textLines[i], font).width, width);
  6103. }
  6104. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6105. textWidthCacheCounter = 0;
  6106. textWidthCache = {};
  6107. }
  6108. textWidthCacheCounter++;
  6109. textWidthCache[key] = width;
  6110. return width;
  6111. }
  6112. /**
  6113. * @public
  6114. * @param {string} text
  6115. * @param {string} font
  6116. * @param {string} [textAlign='left']
  6117. * @param {string} [textVerticalAlign='top']
  6118. * @param {Array.<number>} [textPadding]
  6119. * @param {Object} [rich]
  6120. * @param {Object} [truncate]
  6121. * @return {Object} {x, y, width, height, lineHeight}
  6122. */
  6123. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6124. return rich
  6125. ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate)
  6126. : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate);
  6127. }
  6128. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) {
  6129. var contentBlock = parsePlainText(text, font, textPadding, truncate);
  6130. var outerWidth = getWidth(text, font);
  6131. if (textPadding) {
  6132. outerWidth += textPadding[1] + textPadding[3];
  6133. }
  6134. var outerHeight = contentBlock.outerHeight;
  6135. var x = adjustTextX(0, outerWidth, textAlign);
  6136. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6137. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6138. rect.lineHeight = contentBlock.lineHeight;
  6139. return rect;
  6140. }
  6141. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) {
  6142. var contentBlock = parseRichText(text, {
  6143. rich: rich,
  6144. truncate: truncate,
  6145. font: font,
  6146. textAlign: textAlign,
  6147. textPadding: textPadding
  6148. });
  6149. var outerWidth = contentBlock.outerWidth;
  6150. var outerHeight = contentBlock.outerHeight;
  6151. var x = adjustTextX(0, outerWidth, textAlign);
  6152. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6153. return new BoundingRect(x, y, outerWidth, outerHeight);
  6154. }
  6155. /**
  6156. * @public
  6157. * @param {number} x
  6158. * @param {number} width
  6159. * @param {string} [textAlign='left']
  6160. * @return {number} Adjusted x.
  6161. */
  6162. function adjustTextX(x, width, textAlign) {
  6163. // FIXME Right to left language
  6164. if (textAlign === 'right') {
  6165. x -= width;
  6166. }
  6167. else if (textAlign === 'center') {
  6168. x -= width / 2;
  6169. }
  6170. return x;
  6171. }
  6172. /**
  6173. * @public
  6174. * @param {number} y
  6175. * @param {number} height
  6176. * @param {string} [textVerticalAlign='top']
  6177. * @return {number} Adjusted y.
  6178. */
  6179. function adjustTextY(y, height, textVerticalAlign) {
  6180. if (textVerticalAlign === 'middle') {
  6181. y -= height / 2;
  6182. }
  6183. else if (textVerticalAlign === 'bottom') {
  6184. y -= height;
  6185. }
  6186. return y;
  6187. }
  6188. /**
  6189. * @public
  6190. * @param {stirng} textPosition
  6191. * @param {Object} rect {x, y, width, height}
  6192. * @param {number} distance
  6193. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6194. */
  6195. function adjustTextPositionOnRect(textPosition, rect, distance) {
  6196. var x = rect.x;
  6197. var y = rect.y;
  6198. var height = rect.height;
  6199. var width = rect.width;
  6200. var halfHeight = height / 2;
  6201. var textAlign = 'left';
  6202. var textVerticalAlign = 'top';
  6203. switch (textPosition) {
  6204. case 'left':
  6205. x -= distance;
  6206. y += halfHeight;
  6207. textAlign = 'right';
  6208. textVerticalAlign = 'middle';
  6209. break;
  6210. case 'right':
  6211. x += distance + width;
  6212. y += halfHeight;
  6213. textVerticalAlign = 'middle';
  6214. break;
  6215. case 'top':
  6216. x += width / 2;
  6217. y -= distance;
  6218. textAlign = 'center';
  6219. textVerticalAlign = 'bottom';
  6220. break;
  6221. case 'bottom':
  6222. x += width / 2;
  6223. y += height + distance;
  6224. textAlign = 'center';
  6225. break;
  6226. case 'inside':
  6227. x += width / 2;
  6228. y += halfHeight;
  6229. textAlign = 'center';
  6230. textVerticalAlign = 'middle';
  6231. break;
  6232. case 'insideLeft':
  6233. x += distance;
  6234. y += halfHeight;
  6235. textVerticalAlign = 'middle';
  6236. break;
  6237. case 'insideRight':
  6238. x += width - distance;
  6239. y += halfHeight;
  6240. textAlign = 'right';
  6241. textVerticalAlign = 'middle';
  6242. break;
  6243. case 'insideTop':
  6244. x += width / 2;
  6245. y += distance;
  6246. textAlign = 'center';
  6247. break;
  6248. case 'insideBottom':
  6249. x += width / 2;
  6250. y += height - distance;
  6251. textAlign = 'center';
  6252. textVerticalAlign = 'bottom';
  6253. break;
  6254. case 'insideTopLeft':
  6255. x += distance;
  6256. y += distance;
  6257. break;
  6258. case 'insideTopRight':
  6259. x += width - distance;
  6260. y += distance;
  6261. textAlign = 'right';
  6262. break;
  6263. case 'insideBottomLeft':
  6264. x += distance;
  6265. y += height - distance;
  6266. textVerticalAlign = 'bottom';
  6267. break;
  6268. case 'insideBottomRight':
  6269. x += width - distance;
  6270. y += height - distance;
  6271. textAlign = 'right';
  6272. textVerticalAlign = 'bottom';
  6273. break;
  6274. }
  6275. return {
  6276. x: x,
  6277. y: y,
  6278. textAlign: textAlign,
  6279. textVerticalAlign: textVerticalAlign
  6280. };
  6281. }
  6282. /**
  6283. * Show ellipsis if overflow.
  6284. *
  6285. * @public
  6286. * @param {string} text
  6287. * @param {string} containerWidth
  6288. * @param {string} font
  6289. * @param {number} [ellipsis='...']
  6290. * @param {Object} [options]
  6291. * @param {number} [options.maxIterations=3]
  6292. * @param {number} [options.minChar=0] If truncate result are less
  6293. * then minChar, ellipsis will not show, which is
  6294. * better for user hint in some cases.
  6295. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6296. * @return {string}
  6297. */
  6298. function truncateText(text, containerWidth, font, ellipsis, options) {
  6299. if (!containerWidth) {
  6300. return '';
  6301. }
  6302. var textLines = (text + '').split('\n');
  6303. options = prepareTruncateOptions(containerWidth, font, ellipsis, options);
  6304. // FIXME
  6305. // It is not appropriate that every line has '...' when truncate multiple lines.
  6306. for (var i = 0, len = textLines.length; i < len; i++) {
  6307. textLines[i] = truncateSingleLine(textLines[i], options);
  6308. }
  6309. return textLines.join('\n');
  6310. }
  6311. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6312. options = extend({}, options);
  6313. options.font = font;
  6314. var ellipsis = retrieve2(ellipsis, '...');
  6315. options.maxIterations = retrieve2(options.maxIterations, 2);
  6316. var minChar = options.minChar = retrieve2(options.minChar, 0);
  6317. // FIXME
  6318. // Other languages?
  6319. options.cnCharWidth = getWidth('国', font);
  6320. // FIXME
  6321. // Consider proportional font?
  6322. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6323. options.placeholder = retrieve2(options.placeholder, '');
  6324. // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6325. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6326. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6327. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6328. contentWidth -= ascCharWidth;
  6329. }
  6330. var ellipsisWidth = getWidth(ellipsis);
  6331. if (ellipsisWidth > contentWidth) {
  6332. ellipsis = '';
  6333. ellipsisWidth = 0;
  6334. }
  6335. contentWidth = containerWidth - ellipsisWidth;
  6336. options.ellipsis = ellipsis;
  6337. options.ellipsisWidth = ellipsisWidth;
  6338. options.contentWidth = contentWidth;
  6339. options.containerWidth = containerWidth;
  6340. return options;
  6341. }
  6342. function truncateSingleLine(textLine, options) {
  6343. var containerWidth = options.containerWidth;
  6344. var font = options.font;
  6345. var contentWidth = options.contentWidth;
  6346. if (!containerWidth) {
  6347. return '';
  6348. }
  6349. var lineWidth = getWidth(textLine, font);
  6350. if (lineWidth <= containerWidth) {
  6351. return textLine;
  6352. }
  6353. for (var j = 0;; j++) {
  6354. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6355. textLine += options.ellipsis;
  6356. break;
  6357. }
  6358. var subLength = j === 0
  6359. ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth)
  6360. : lineWidth > 0
  6361. ? Math.floor(textLine.length * contentWidth / lineWidth)
  6362. : 0;
  6363. textLine = textLine.substr(0, subLength);
  6364. lineWidth = getWidth(textLine, font);
  6365. }
  6366. if (textLine === '') {
  6367. textLine = options.placeholder;
  6368. }
  6369. return textLine;
  6370. }
  6371. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6372. var width = 0;
  6373. var i = 0;
  6374. for (var len = text.length; i < len && width < contentWidth; i++) {
  6375. var charCode = text.charCodeAt(i);
  6376. width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth;
  6377. }
  6378. return i;
  6379. }
  6380. /**
  6381. * @public
  6382. * @param {string} font
  6383. * @return {number} line height
  6384. */
  6385. function getLineHeight(font) {
  6386. // FIXME A rough approach.
  6387. return getWidth('国', font);
  6388. }
  6389. /**
  6390. * @public
  6391. * @param {string} text
  6392. * @param {string} font
  6393. * @return {Object} width
  6394. */
  6395. function measureText(text, font) {
  6396. return methods$1.measureText(text, font);
  6397. }
  6398. // Avoid assign to an exported variable, for transforming to cjs.
  6399. methods$1.measureText = function (text, font) {
  6400. var ctx = getContext();
  6401. ctx.font = font || DEFAULT_FONT;
  6402. return ctx.measureText(text);
  6403. };
  6404. /**
  6405. * @public
  6406. * @param {string} text
  6407. * @param {string} font
  6408. * @param {Object} [truncate]
  6409. * @return {Object} block: {lineHeight, lines, height, outerHeight}
  6410. * Notice: for performance, do not calculate outerWidth util needed.
  6411. */
  6412. function parsePlainText(text, font, padding, truncate) {
  6413. text != null && (text += '');
  6414. var lineHeight = getLineHeight(font);
  6415. var lines = text ? text.split('\n') : [];
  6416. var height = lines.length * lineHeight;
  6417. var outerHeight = height;
  6418. if (padding) {
  6419. outerHeight += padding[0] + padding[2];
  6420. }
  6421. if (text && truncate) {
  6422. var truncOuterHeight = truncate.outerHeight;
  6423. var truncOuterWidth = truncate.outerWidth;
  6424. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6425. text = '';
  6426. lines = [];
  6427. }
  6428. else if (truncOuterWidth != null) {
  6429. var options = prepareTruncateOptions(
  6430. truncOuterWidth - (padding ? padding[1] + padding[3] : 0),
  6431. font,
  6432. truncate.ellipsis,
  6433. {minChar: truncate.minChar, placeholder: truncate.placeholder}
  6434. );
  6435. // FIXME
  6436. // It is not appropriate that every line has '...' when truncate multiple lines.
  6437. for (var i = 0, len = lines.length; i < len; i++) {
  6438. lines[i] = truncateSingleLine(lines[i], options);
  6439. }
  6440. }
  6441. }
  6442. return {
  6443. lines: lines,
  6444. height: height,
  6445. outerHeight: outerHeight,
  6446. lineHeight: lineHeight
  6447. };
  6448. }
  6449. /**
  6450. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6451. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6452. *
  6453. * @public
  6454. * @param {string} text
  6455. * @param {Object} style
  6456. * @return {Object} block
  6457. * {
  6458. * width,
  6459. * height,
  6460. * lines: [{
  6461. * lineHeight,
  6462. * width,
  6463. * tokens: [[{
  6464. * styleName,
  6465. * text,
  6466. * width, // include textPadding
  6467. * height, // include textPadding
  6468. * textWidth, // pure text width
  6469. * textHeight, // pure text height
  6470. * lineHeihgt,
  6471. * font,
  6472. * textAlign,
  6473. * textVerticalAlign
  6474. * }], [...], ...]
  6475. * }, ...]
  6476. * }
  6477. * If styleName is undefined, it is plain text.
  6478. */
  6479. function parseRichText(text, style) {
  6480. var contentBlock = {lines: [], width: 0, height: 0};
  6481. text != null && (text += '');
  6482. if (!text) {
  6483. return contentBlock;
  6484. }
  6485. var lastIndex = STYLE_REG.lastIndex = 0;
  6486. var result;
  6487. while ((result = STYLE_REG.exec(text)) != null) {
  6488. var matchedIndex = result.index;
  6489. if (matchedIndex > lastIndex) {
  6490. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6491. }
  6492. pushTokens(contentBlock, result[2], result[1]);
  6493. lastIndex = STYLE_REG.lastIndex;
  6494. }
  6495. if (lastIndex < text.length) {
  6496. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6497. }
  6498. var lines = contentBlock.lines;
  6499. var contentHeight = 0;
  6500. var contentWidth = 0;
  6501. // For `textWidth: 100%`
  6502. var pendingList = [];
  6503. var stlPadding = style.textPadding;
  6504. var truncate = style.truncate;
  6505. var truncateWidth = truncate && truncate.outerWidth;
  6506. var truncateHeight = truncate && truncate.outerHeight;
  6507. if (stlPadding) {
  6508. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6509. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6510. }
  6511. // Calculate layout info of tokens.
  6512. for (var i = 0; i < lines.length; i++) {
  6513. var line = lines[i];
  6514. var lineHeight = 0;
  6515. var lineWidth = 0;
  6516. for (var j = 0; j < line.tokens.length; j++) {
  6517. var token = line.tokens[j];
  6518. var tokenStyle = token.styleName && style.rich[token.styleName] || {};
  6519. // textPadding should not inherit from style.
  6520. var textPadding = token.textPadding = tokenStyle.textPadding;
  6521. // textFont has been asigned to font by `normalizeStyle`.
  6522. var font = token.font = tokenStyle.font || style.font;
  6523. // textHeight can be used when textVerticalAlign is specified in token.
  6524. var tokenHeight = token.textHeight = retrieve2(
  6525. // textHeight should not be inherited, consider it can be specified
  6526. // as box height of the block.
  6527. tokenStyle.textHeight, getLineHeight(font)
  6528. );
  6529. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6530. token.height = tokenHeight;
  6531. token.lineHeight = retrieve3(
  6532. tokenStyle.textLineHeight, style.textLineHeight, tokenHeight
  6533. );
  6534. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6535. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6536. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6537. return {lines: [], width: 0, height: 0};
  6538. }
  6539. token.textWidth = getWidth(token.text, font);
  6540. var tokenWidth = tokenStyle.textWidth;
  6541. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto';
  6542. // Percent width, can be `100%`, can be used in drawing separate
  6543. // line when box width is needed to be auto.
  6544. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6545. token.percentWidth = tokenWidth;
  6546. pendingList.push(token);
  6547. tokenWidth = 0;
  6548. // Do not truncate in this case, because there is no user case
  6549. // and it is too complicated.
  6550. }
  6551. else {
  6552. if (tokenWidthNotSpecified) {
  6553. tokenWidth = token.textWidth;
  6554. // FIXME: If image is not loaded and textWidth is not specified, calling
  6555. // `getBoundingRect()` will not get correct result.
  6556. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6557. var bgImg = textBackgroundColor && textBackgroundColor.image;
  6558. // Use cases:
  6559. // (1) If image is not loaded, it will be loaded at render phase and call
  6560. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  6561. // image, and then the right size will be calculated here at the next tick.
  6562. // See `graphic/helper/text.js`.
  6563. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  6564. // use `imageHelper.findExistImage` to find cached image.
  6565. // `imageHelper.findExistImage` will always be called here before
  6566. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  6567. // which ensures that image will not be rendered before correct size calcualted.
  6568. if (bgImg) {
  6569. bgImg = findExistImage(bgImg);
  6570. if (isImageReady(bgImg)) {
  6571. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  6572. }
  6573. }
  6574. }
  6575. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  6576. tokenWidth += paddingW;
  6577. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  6578. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  6579. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  6580. token.text = '';
  6581. token.textWidth = tokenWidth = 0;
  6582. }
  6583. else {
  6584. token.text = truncateText(
  6585. token.text, remianTruncWidth - paddingW, font, truncate.ellipsis,
  6586. {minChar: truncate.minChar}
  6587. );
  6588. token.textWidth = getWidth(token.text, font);
  6589. tokenWidth = token.textWidth + paddingW;
  6590. }
  6591. }
  6592. }
  6593. lineWidth += (token.width = tokenWidth);
  6594. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  6595. }
  6596. line.width = lineWidth;
  6597. line.lineHeight = lineHeight;
  6598. contentHeight += lineHeight;
  6599. contentWidth = Math.max(contentWidth, lineWidth);
  6600. }
  6601. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  6602. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  6603. if (stlPadding) {
  6604. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  6605. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  6606. }
  6607. for (var i = 0; i < pendingList.length; i++) {
  6608. var token = pendingList[i];
  6609. var percentWidth = token.percentWidth;
  6610. // Should not base on outerWidth, because token can not be placed out of padding.
  6611. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  6612. }
  6613. return contentBlock;
  6614. }
  6615. function pushTokens(block, str, styleName) {
  6616. var isEmptyStr = str === '';
  6617. var strs = str.split('\n');
  6618. var lines = block.lines;
  6619. for (var i = 0; i < strs.length; i++) {
  6620. var text = strs[i];
  6621. var token = {
  6622. styleName: styleName,
  6623. text: text,
  6624. isLineHolder: !text && !isEmptyStr
  6625. };
  6626. // The first token should be appended to the last line.
  6627. if (!i) {
  6628. var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens;
  6629. // Consider cases:
  6630. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  6631. // (which is a placeholder) should be replaced by new token.
  6632. // (2) A image backage, where token likes {a|}.
  6633. // (3) A redundant '' will affect textAlign in line.
  6634. // (4) tokens with the same tplName should not be merged, because
  6635. // they should be displayed in different box (with border and padding).
  6636. var tokensLen = tokens.length;
  6637. (tokensLen === 1 && tokens[0].isLineHolder)
  6638. ? (tokens[0] = token)
  6639. // Consider text is '', only insert when it is the "lineHolder" or
  6640. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  6641. : ((text || !tokensLen || isEmptyStr) && tokens.push(token));
  6642. }
  6643. // Other tokens always start a new line.
  6644. else {
  6645. // If there is '', insert it as a placeholder.
  6646. lines.push({tokens: [token]});
  6647. }
  6648. }
  6649. }
  6650. function makeFont(style) {
  6651. // FIXME in node-canvas fontWeight is before fontStyle
  6652. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  6653. var font = (style.fontSize || style.fontFamily) && [
  6654. style.fontStyle,
  6655. style.fontWeight,
  6656. (style.fontSize || 12) + 'px',
  6657. // If font properties are defined, `fontFamily` should not be ignored.
  6658. style.fontFamily || 'sans-serif'
  6659. ].join(' ');
  6660. return font && trim(font) || style.textFont || style.font;
  6661. }
  6662. function buildPath(ctx, shape) {
  6663. var x = shape.x;
  6664. var y = shape.y;
  6665. var width = shape.width;
  6666. var height = shape.height;
  6667. var r = shape.r;
  6668. var r1;
  6669. var r2;
  6670. var r3;
  6671. var r4;
  6672. // Convert width and height to positive for better borderRadius
  6673. if (width < 0) {
  6674. x = x + width;
  6675. width = -width;
  6676. }
  6677. if (height < 0) {
  6678. y = y + height;
  6679. height = -height;
  6680. }
  6681. if (typeof r === 'number') {
  6682. r1 = r2 = r3 = r4 = r;
  6683. }
  6684. else if (r instanceof Array) {
  6685. if (r.length === 1) {
  6686. r1 = r2 = r3 = r4 = r[0];
  6687. }
  6688. else if (r.length === 2) {
  6689. r1 = r3 = r[0];
  6690. r2 = r4 = r[1];
  6691. }
  6692. else if (r.length === 3) {
  6693. r1 = r[0];
  6694. r2 = r4 = r[1];
  6695. r3 = r[2];
  6696. }
  6697. else {
  6698. r1 = r[0];
  6699. r2 = r[1];
  6700. r3 = r[2];
  6701. r4 = r[3];
  6702. }
  6703. }
  6704. else {
  6705. r1 = r2 = r3 = r4 = 0;
  6706. }
  6707. var total;
  6708. if (r1 + r2 > width) {
  6709. total = r1 + r2;
  6710. r1 *= width / total;
  6711. r2 *= width / total;
  6712. }
  6713. if (r3 + r4 > width) {
  6714. total = r3 + r4;
  6715. r3 *= width / total;
  6716. r4 *= width / total;
  6717. }
  6718. if (r2 + r3 > height) {
  6719. total = r2 + r3;
  6720. r2 *= height / total;
  6721. r3 *= height / total;
  6722. }
  6723. if (r1 + r4 > height) {
  6724. total = r1 + r4;
  6725. r1 *= height / total;
  6726. r4 *= height / total;
  6727. }
  6728. ctx.moveTo(x + r1, y);
  6729. ctx.lineTo(x + width - r2, y);
  6730. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  6731. ctx.lineTo(x + width, y + height - r3);
  6732. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  6733. ctx.lineTo(x + r4, y + height);
  6734. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  6735. ctx.lineTo(x, y + r1);
  6736. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  6737. }
  6738. // TODO: Have not support 'start', 'end' yet.
  6739. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1};
  6740. var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1};
  6741. /**
  6742. * @param {module:zrender/graphic/Style} style
  6743. * @return {module:zrender/graphic/Style} The input style.
  6744. */
  6745. function normalizeTextStyle(style) {
  6746. normalizeStyle(style);
  6747. each$1(style.rich, normalizeStyle);
  6748. return style;
  6749. }
  6750. function normalizeStyle(style) {
  6751. if (style) {
  6752. style.font = makeFont(style);
  6753. var textAlign = style.textAlign;
  6754. textAlign === 'middle' && (textAlign = 'center');
  6755. style.textAlign = (
  6756. textAlign == null || VALID_TEXT_ALIGN[textAlign]
  6757. ) ? textAlign : 'left';
  6758. // Compatible with textBaseline.
  6759. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  6760. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  6761. style.textVerticalAlign = (
  6762. textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign]
  6763. ) ? textVerticalAlign : 'top';
  6764. var textPadding = style.textPadding;
  6765. if (textPadding) {
  6766. style.textPadding = normalizeCssArray(style.textPadding);
  6767. }
  6768. }
  6769. }
  6770. /**
  6771. * @param {CanvasRenderingContext2D} ctx
  6772. * @param {string} text
  6773. * @param {module:zrender/graphic/Style} style
  6774. * @param {Object|boolean} [rect] {x, y, width, height}
  6775. * If set false, rect text is not used.
  6776. */
  6777. function renderText(hostEl, ctx, text, style, rect) {
  6778. style.rich
  6779. ? renderRichText(hostEl, ctx, text, style, rect)
  6780. : renderPlainText(hostEl, ctx, text, style, rect);
  6781. }
  6782. function renderPlainText(hostEl, ctx, text, style, rect) {
  6783. var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT);
  6784. var textPadding = style.textPadding;
  6785. var contentBlock = hostEl.__textCotentBlock;
  6786. if (!contentBlock || hostEl.__dirty) {
  6787. contentBlock = hostEl.__textCotentBlock = parsePlainText(
  6788. text, font, textPadding, style.truncate
  6789. );
  6790. }
  6791. var outerHeight = contentBlock.outerHeight;
  6792. var textLines = contentBlock.lines;
  6793. var lineHeight = contentBlock.lineHeight;
  6794. var boxPos = getBoxPosition(outerHeight, style, rect);
  6795. var baseX = boxPos.baseX;
  6796. var baseY = boxPos.baseY;
  6797. var textAlign = boxPos.textAlign;
  6798. var textVerticalAlign = boxPos.textVerticalAlign;
  6799. // Origin of textRotation should be the base point of text drawing.
  6800. applyTextRotation(ctx, style, rect, baseX, baseY);
  6801. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6802. var textX = baseX;
  6803. var textY = boxY;
  6804. var needDrawBg = needDrawBackground(style);
  6805. if (needDrawBg || textPadding) {
  6806. // Consider performance, do not call getTextWidth util necessary.
  6807. var textWidth = getWidth(text, font);
  6808. var outerWidth = textWidth;
  6809. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  6810. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6811. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  6812. if (textPadding) {
  6813. textX = getTextXForPadding(baseX, textAlign, textPadding);
  6814. textY += textPadding[0];
  6815. }
  6816. }
  6817. setCtx(ctx, 'textAlign', textAlign || 'left');
  6818. // Force baseline to be "middle". Otherwise, if using "top", the
  6819. // text will offset downward a little bit in font "Microsoft YaHei".
  6820. setCtx(ctx, 'textBaseline', 'middle');
  6821. // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  6822. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0);
  6823. setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent');
  6824. setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0);
  6825. setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0);
  6826. // `textBaseline` is set as 'middle'.
  6827. textY += lineHeight / 2;
  6828. var textStrokeWidth = style.textStrokeWidth;
  6829. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  6830. var textFill = getFill(style.textFill);
  6831. if (textStroke) {
  6832. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6833. setCtx(ctx, 'strokeStyle', textStroke);
  6834. }
  6835. if (textFill) {
  6836. setCtx(ctx, 'fillStyle', textFill);
  6837. }
  6838. for (var i = 0; i < textLines.length; i++) {
  6839. // Fill after stroke so the outline will not cover the main part.
  6840. textStroke && ctx.strokeText(textLines[i], textX, textY);
  6841. textFill && ctx.fillText(textLines[i], textX, textY);
  6842. textY += lineHeight;
  6843. }
  6844. }
  6845. function renderRichText(hostEl, ctx, text, style, rect) {
  6846. var contentBlock = hostEl.__textCotentBlock;
  6847. if (!contentBlock || hostEl.__dirty) {
  6848. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  6849. }
  6850. drawRichText(hostEl, ctx, contentBlock, style, rect);
  6851. }
  6852. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  6853. var contentWidth = contentBlock.width;
  6854. var outerWidth = contentBlock.outerWidth;
  6855. var outerHeight = contentBlock.outerHeight;
  6856. var textPadding = style.textPadding;
  6857. var boxPos = getBoxPosition(outerHeight, style, rect);
  6858. var baseX = boxPos.baseX;
  6859. var baseY = boxPos.baseY;
  6860. var textAlign = boxPos.textAlign;
  6861. var textVerticalAlign = boxPos.textVerticalAlign;
  6862. // Origin of textRotation should be the base point of text drawing.
  6863. applyTextRotation(ctx, style, rect, baseX, baseY);
  6864. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  6865. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  6866. var xLeft = boxX;
  6867. var lineTop = boxY;
  6868. if (textPadding) {
  6869. xLeft += textPadding[3];
  6870. lineTop += textPadding[0];
  6871. }
  6872. var xRight = xLeft + contentWidth;
  6873. needDrawBackground(style) && drawBackground(
  6874. hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight
  6875. );
  6876. for (var i = 0; i < contentBlock.lines.length; i++) {
  6877. var line = contentBlock.lines[i];
  6878. var tokens = line.tokens;
  6879. var tokenCount = tokens.length;
  6880. var lineHeight = line.lineHeight;
  6881. var usedWidth = line.width;
  6882. var leftIndex = 0;
  6883. var lineXLeft = xLeft;
  6884. var lineXRight = xRight;
  6885. var rightIndex = tokenCount - 1;
  6886. var token;
  6887. while (
  6888. leftIndex < tokenCount
  6889. && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')
  6890. ) {
  6891. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  6892. usedWidth -= token.width;
  6893. lineXLeft += token.width;
  6894. leftIndex++;
  6895. }
  6896. while (
  6897. rightIndex >= 0
  6898. && (token = tokens[rightIndex], token.textAlign === 'right')
  6899. ) {
  6900. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  6901. usedWidth -= token.width;
  6902. lineXRight -= token.width;
  6903. rightIndex--;
  6904. }
  6905. // The other tokens are placed as textAlign 'center' if there is enough space.
  6906. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  6907. while (leftIndex <= rightIndex) {
  6908. token = tokens[leftIndex];
  6909. // Consider width specified by user, use 'center' rather than 'left'.
  6910. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  6911. lineXLeft += token.width;
  6912. leftIndex++;
  6913. }
  6914. lineTop += lineHeight;
  6915. }
  6916. }
  6917. function applyTextRotation(ctx, style, rect, x, y) {
  6918. // textRotation only apply in RectText.
  6919. if (rect && style.textRotation) {
  6920. var origin = style.textOrigin;
  6921. if (origin === 'center') {
  6922. x = rect.width / 2 + rect.x;
  6923. y = rect.height / 2 + rect.y;
  6924. }
  6925. else if (origin) {
  6926. x = origin[0] + rect.x;
  6927. y = origin[1] + rect.y;
  6928. }
  6929. ctx.translate(x, y);
  6930. // Positive: anticlockwise
  6931. ctx.rotate(-style.textRotation);
  6932. ctx.translate(-x, -y);
  6933. }
  6934. }
  6935. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  6936. var tokenStyle = style.rich[token.styleName] || {};
  6937. // 'ctx.textBaseline' is always set as 'middle', for sake of
  6938. // the bias of "Microsoft YaHei".
  6939. var textVerticalAlign = token.textVerticalAlign;
  6940. var y = lineTop + lineHeight / 2;
  6941. if (textVerticalAlign === 'top') {
  6942. y = lineTop + token.height / 2;
  6943. }
  6944. else if (textVerticalAlign === 'bottom') {
  6945. y = lineTop + lineHeight - token.height / 2;
  6946. }
  6947. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(
  6948. hostEl,
  6949. ctx,
  6950. tokenStyle,
  6951. textAlign === 'right'
  6952. ? x - token.width
  6953. : textAlign === 'center'
  6954. ? x - token.width / 2
  6955. : x,
  6956. y - token.height / 2,
  6957. token.width,
  6958. token.height
  6959. );
  6960. var textPadding = token.textPadding;
  6961. if (textPadding) {
  6962. x = getTextXForPadding(x, textAlign, textPadding);
  6963. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  6964. }
  6965. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  6966. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  6967. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  6968. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  6969. setCtx(ctx, 'textAlign', textAlign);
  6970. // Force baseline to be "middle". Otherwise, if using "top", the
  6971. // text will offset downward a little bit in font "Microsoft YaHei".
  6972. setCtx(ctx, 'textBaseline', 'middle');
  6973. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  6974. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  6975. var textFill = getFill(tokenStyle.textFill || style.textFill);
  6976. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth);
  6977. // Fill after stroke so the outline will not cover the main part.
  6978. if (textStroke) {
  6979. setCtx(ctx, 'lineWidth', textStrokeWidth);
  6980. setCtx(ctx, 'strokeStyle', textStroke);
  6981. ctx.strokeText(token.text, x, y);
  6982. }
  6983. if (textFill) {
  6984. setCtx(ctx, 'fillStyle', textFill);
  6985. ctx.fillText(token.text, x, y);
  6986. }
  6987. }
  6988. function needDrawBackground(style) {
  6989. return style.textBackgroundColor
  6990. || (style.textBorderWidth && style.textBorderColor);
  6991. }
  6992. // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius}
  6993. // shape: {x, y, width, height}
  6994. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  6995. var textBackgroundColor = style.textBackgroundColor;
  6996. var textBorderWidth = style.textBorderWidth;
  6997. var textBorderColor = style.textBorderColor;
  6998. var isPlainBg = isString(textBackgroundColor);
  6999. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7000. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7001. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7002. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7003. if (isPlainBg || (textBorderWidth && textBorderColor)) {
  7004. ctx.beginPath();
  7005. var textBorderRadius = style.textBorderRadius;
  7006. if (!textBorderRadius) {
  7007. ctx.rect(x, y, width, height);
  7008. }
  7009. else {
  7010. buildPath(ctx, {
  7011. x: x, y: y, width: width, height: height, r: textBorderRadius
  7012. });
  7013. }
  7014. ctx.closePath();
  7015. }
  7016. if (isPlainBg) {
  7017. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7018. ctx.fill();
  7019. }
  7020. else if (isObject$1(textBackgroundColor)) {
  7021. var image = textBackgroundColor.image;
  7022. image = createOrUpdateImage(
  7023. image, null, hostEl, onBgImageLoaded, textBackgroundColor
  7024. );
  7025. if (image && isImageReady(image)) {
  7026. ctx.drawImage(image, x, y, width, height);
  7027. }
  7028. }
  7029. if (textBorderWidth && textBorderColor) {
  7030. setCtx(ctx, 'lineWidth', textBorderWidth);
  7031. setCtx(ctx, 'strokeStyle', textBorderColor);
  7032. ctx.stroke();
  7033. }
  7034. }
  7035. function onBgImageLoaded(image, textBackgroundColor) {
  7036. // Replace image, so that `contain/text.js#parseRichText`
  7037. // will get correct result in next tick.
  7038. textBackgroundColor.image = image;
  7039. }
  7040. function getBoxPosition(blockHeiht, style, rect) {
  7041. var baseX = style.x || 0;
  7042. var baseY = style.y || 0;
  7043. var textAlign = style.textAlign;
  7044. var textVerticalAlign = style.textVerticalAlign;
  7045. // Text position represented by coord
  7046. if (rect) {
  7047. var textPosition = style.textPosition;
  7048. if (textPosition instanceof Array) {
  7049. // Percent
  7050. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7051. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7052. }
  7053. else {
  7054. var res = adjustTextPositionOnRect(
  7055. textPosition, rect, style.textDistance
  7056. );
  7057. baseX = res.x;
  7058. baseY = res.y;
  7059. // Default align and baseline when has textPosition
  7060. textAlign = textAlign || res.textAlign;
  7061. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7062. }
  7063. // textOffset is only support in RectText, otherwise
  7064. // we have to adjust boundingRect for textOffset.
  7065. var textOffset = style.textOffset;
  7066. if (textOffset) {
  7067. baseX += textOffset[0];
  7068. baseY += textOffset[1];
  7069. }
  7070. }
  7071. return {
  7072. baseX: baseX,
  7073. baseY: baseY,
  7074. textAlign: textAlign,
  7075. textVerticalAlign: textVerticalAlign
  7076. };
  7077. }
  7078. function setCtx(ctx, prop, value) {
  7079. ctx[prop] = fixShadow(ctx, prop, value);
  7080. return ctx[prop];
  7081. }
  7082. /**
  7083. * @param {string} [stroke] If specified, do not check style.textStroke.
  7084. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7085. * @param {number} style
  7086. */
  7087. function getStroke(stroke, lineWidth) {
  7088. return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none')
  7089. ? null
  7090. // TODO pattern and gradient?
  7091. : (stroke.image || stroke.colorStops)
  7092. ? '#000'
  7093. : stroke;
  7094. }
  7095. function getFill(fill) {
  7096. return (fill == null || fill === 'none')
  7097. ? null
  7098. // TODO pattern and gradient?
  7099. : (fill.image || fill.colorStops)
  7100. ? '#000'
  7101. : fill;
  7102. }
  7103. function parsePercent(value, maxValue) {
  7104. if (typeof value === 'string') {
  7105. if (value.lastIndexOf('%') >= 0) {
  7106. return parseFloat(value) / 100 * maxValue;
  7107. }
  7108. return parseFloat(value);
  7109. }
  7110. return value;
  7111. }
  7112. function getTextXForPadding(x, textAlign, textPadding) {
  7113. return textAlign === 'right'
  7114. ? (x - textPadding[1])
  7115. : textAlign === 'center'
  7116. ? (x + textPadding[3] / 2 - textPadding[1] / 2)
  7117. : (x + textPadding[3]);
  7118. }
  7119. /**
  7120. * @param {string} text
  7121. * @param {module:zrender/Style} style
  7122. * @return {boolean}
  7123. */
  7124. function needDrawText(text, style) {
  7125. return text != null
  7126. && (text
  7127. || style.textBackgroundColor
  7128. || (style.textBorderWidth && style.textBorderColor)
  7129. || style.textPadding
  7130. );
  7131. }
  7132. /**
  7133. * Mixin for drawing text in a element bounding rect
  7134. * @module zrender/mixin/RectText
  7135. */
  7136. var tmpRect$1 = new BoundingRect();
  7137. var RectText = function () {};
  7138. RectText.prototype = {
  7139. constructor: RectText,
  7140. /**
  7141. * Draw text in a rect with specified position.
  7142. * @param {CanvasRenderingContext2D} ctx
  7143. * @param {Object} rect Displayable rect
  7144. */
  7145. drawRectText: function (ctx, rect) {
  7146. var style = this.style;
  7147. rect = style.textRect || rect;
  7148. // Optimize, avoid normalize every time.
  7149. this.__dirty && normalizeTextStyle(style, true);
  7150. var text = style.text;
  7151. // Convert to string
  7152. text != null && (text += '');
  7153. if (!needDrawText(text, style)) {
  7154. return;
  7155. }
  7156. // FIXME
  7157. ctx.save();
  7158. // Transform rect to view space
  7159. var transform = this.transform;
  7160. if (!style.transformText) {
  7161. if (transform) {
  7162. tmpRect$1.copy(rect);
  7163. tmpRect$1.applyTransform(transform);
  7164. rect = tmpRect$1;
  7165. }
  7166. }
  7167. else {
  7168. this.setTransform(ctx);
  7169. }
  7170. // transformText and textRotation can not be used at the same time.
  7171. renderText(this, ctx, text, style, rect);
  7172. ctx.restore();
  7173. }
  7174. };
  7175. /**
  7176. * 可绘制的图形基类
  7177. * Base class of all displayable graphic objects
  7178. * @module zrender/graphic/Displayable
  7179. */
  7180. /**
  7181. * @alias module:zrender/graphic/Displayable
  7182. * @extends module:zrender/Element
  7183. * @extends module:zrender/graphic/mixin/RectText
  7184. */
  7185. function Displayable(opts) {
  7186. opts = opts || {};
  7187. Element.call(this, opts);
  7188. // Extend properties
  7189. for (var name in opts) {
  7190. if (
  7191. opts.hasOwnProperty(name) &&
  7192. name !== 'style'
  7193. ) {
  7194. this[name] = opts[name];
  7195. }
  7196. }
  7197. /**
  7198. * @type {module:zrender/graphic/Style}
  7199. */
  7200. this.style = new Style(opts.style, this);
  7201. this._rect = null;
  7202. // Shapes for cascade clipping.
  7203. this.__clipPaths = [];
  7204. // FIXME Stateful must be mixined after style is setted
  7205. // Stateful.call(this, opts);
  7206. }
  7207. Displayable.prototype = {
  7208. constructor: Displayable,
  7209. type: 'displayable',
  7210. /**
  7211. * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制
  7212. * Dirty flag. From which painter will determine if this displayable object needs brush
  7213. * @name module:zrender/graphic/Displayable#__dirty
  7214. * @type {boolean}
  7215. */
  7216. __dirty: true,
  7217. /**
  7218. * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件
  7219. * If ignore drawing of the displayable object. Mouse event will still be triggered
  7220. * @name module:/zrender/graphic/Displayable#invisible
  7221. * @type {boolean}
  7222. * @default false
  7223. */
  7224. invisible: false,
  7225. /**
  7226. * @name module:/zrender/graphic/Displayable#z
  7227. * @type {number}
  7228. * @default 0
  7229. */
  7230. z: 0,
  7231. /**
  7232. * @name module:/zrender/graphic/Displayable#z
  7233. * @type {number}
  7234. * @default 0
  7235. */
  7236. z2: 0,
  7237. /**
  7238. * z层level,决定绘画在哪层canvas中
  7239. * @name module:/zrender/graphic/Displayable#zlevel
  7240. * @type {number}
  7241. * @default 0
  7242. */
  7243. zlevel: 0,
  7244. /**
  7245. * 是否可拖拽
  7246. * @name module:/zrender/graphic/Displayable#draggable
  7247. * @type {boolean}
  7248. * @default false
  7249. */
  7250. draggable: false,
  7251. /**
  7252. * 是否正在拖拽
  7253. * @name module:/zrender/graphic/Displayable#draggable
  7254. * @type {boolean}
  7255. * @default false
  7256. */
  7257. dragging: false,
  7258. /**
  7259. * 是否相应鼠标事件
  7260. * @name module:/zrender/graphic/Displayable#silent
  7261. * @type {boolean}
  7262. * @default false
  7263. */
  7264. silent: false,
  7265. /**
  7266. * If enable culling
  7267. * @type {boolean}
  7268. * @default false
  7269. */
  7270. culling: false,
  7271. /**
  7272. * Mouse cursor when hovered
  7273. * @name module:/zrender/graphic/Displayable#cursor
  7274. * @type {string}
  7275. */
  7276. cursor: 'pointer',
  7277. /**
  7278. * If hover area is bounding rect
  7279. * @name module:/zrender/graphic/Displayable#rectHover
  7280. * @type {string}
  7281. */
  7282. rectHover: false,
  7283. /**
  7284. * Render the element progressively when the value >= 0,
  7285. * usefull for large data.
  7286. * @type {boolean}
  7287. */
  7288. progressive: false,
  7289. /**
  7290. * @type {boolean}
  7291. */
  7292. incremental: false,
  7293. // inplace is used with incremental
  7294. inplace: false,
  7295. beforeBrush: function (ctx) {},
  7296. afterBrush: function (ctx) {},
  7297. /**
  7298. * 图形绘制方法
  7299. * @param {CanvasRenderingContext2D} ctx
  7300. */
  7301. // Interface
  7302. brush: function (ctx, prevEl) {},
  7303. /**
  7304. * 获取最小包围盒
  7305. * @return {module:zrender/core/BoundingRect}
  7306. */
  7307. // Interface
  7308. getBoundingRect: function () {},
  7309. /**
  7310. * 判断坐标 x, y 是否在图形上
  7311. * If displayable element contain coord x, y
  7312. * @param {number} x
  7313. * @param {number} y
  7314. * @return {boolean}
  7315. */
  7316. contain: function (x, y) {
  7317. return this.rectContain(x, y);
  7318. },
  7319. /**
  7320. * @param {Function} cb
  7321. * @param {} context
  7322. */
  7323. traverse: function (cb, context) {
  7324. cb.call(context, this);
  7325. },
  7326. /**
  7327. * 判断坐标 x, y 是否在图形的包围盒上
  7328. * If bounding rect of element contain coord x, y
  7329. * @param {number} x
  7330. * @param {number} y
  7331. * @return {boolean}
  7332. */
  7333. rectContain: function (x, y) {
  7334. var coord = this.transformCoordToLocal(x, y);
  7335. var rect = this.getBoundingRect();
  7336. return rect.contain(coord[0], coord[1]);
  7337. },
  7338. /**
  7339. * 标记图形元素为脏,并且在下一帧重绘
  7340. * Mark displayable element dirty and refresh next frame
  7341. */
  7342. dirty: function () {
  7343. this.__dirty = true;
  7344. this._rect = null;
  7345. this.__zr && this.__zr.refresh();
  7346. },
  7347. /**
  7348. * 图形是否会触发事件
  7349. * If displayable object binded any event
  7350. * @return {boolean}
  7351. */
  7352. // TODO, 通过 bind 绑定的事件
  7353. // isSilent: function () {
  7354. // return !(
  7355. // this.hoverable || this.draggable
  7356. // || this.onmousemove || this.onmouseover || this.onmouseout
  7357. // || this.onmousedown || this.onmouseup || this.onclick
  7358. // || this.ondragenter || this.ondragover || this.ondragleave
  7359. // || this.ondrop
  7360. // );
  7361. // },
  7362. /**
  7363. * Alias for animate('style')
  7364. * @param {boolean} loop
  7365. */
  7366. animateStyle: function (loop) {
  7367. return this.animate('style', loop);
  7368. },
  7369. attrKV: function (key, value) {
  7370. if (key !== 'style') {
  7371. Element.prototype.attrKV.call(this, key, value);
  7372. }
  7373. else {
  7374. this.style.set(value);
  7375. }
  7376. },
  7377. /**
  7378. * @param {Object|string} key
  7379. * @param {*} value
  7380. */
  7381. setStyle: function (key, value) {
  7382. this.style.set(key, value);
  7383. this.dirty(false);
  7384. return this;
  7385. },
  7386. /**
  7387. * Use given style object
  7388. * @param {Object} obj
  7389. */
  7390. useStyle: function (obj) {
  7391. this.style = new Style(obj, this);
  7392. this.dirty(false);
  7393. return this;
  7394. }
  7395. };
  7396. inherits(Displayable, Element);
  7397. mixin(Displayable, RectText);
  7398. /**
  7399. * @alias zrender/graphic/Image
  7400. * @extends module:zrender/graphic/Displayable
  7401. * @constructor
  7402. * @param {Object} opts
  7403. */
  7404. function ZImage(opts) {
  7405. Displayable.call(this, opts);
  7406. }
  7407. ZImage.prototype = {
  7408. constructor: ZImage,
  7409. type: 'image',
  7410. brush: function (ctx, prevEl) {
  7411. var style = this.style;
  7412. var src = style.image;
  7413. // Must bind each time
  7414. style.bind(ctx, this, prevEl);
  7415. var image = this._image = createOrUpdateImage(
  7416. src,
  7417. this._image,
  7418. this,
  7419. this.onload
  7420. );
  7421. if (!image || !isImageReady(image)) {
  7422. return;
  7423. }
  7424. // 图片已经加载完成
  7425. // if (image.nodeName.toUpperCase() == 'IMG') {
  7426. // if (!image.complete) {
  7427. // return;
  7428. // }
  7429. // }
  7430. // Else is canvas
  7431. var x = style.x || 0;
  7432. var y = style.y || 0;
  7433. var width = style.width;
  7434. var height = style.height;
  7435. var aspect = image.width / image.height;
  7436. if (width == null && height != null) {
  7437. // Keep image/height ratio
  7438. width = height * aspect;
  7439. }
  7440. else if (height == null && width != null) {
  7441. height = width / aspect;
  7442. }
  7443. else if (width == null && height == null) {
  7444. width = image.width;
  7445. height = image.height;
  7446. }
  7447. // 设置transform
  7448. this.setTransform(ctx);
  7449. if (style.sWidth && style.sHeight) {
  7450. var sx = style.sx || 0;
  7451. var sy = style.sy || 0;
  7452. ctx.drawImage(
  7453. image,
  7454. sx, sy, style.sWidth, style.sHeight,
  7455. x, y, width, height
  7456. );
  7457. }
  7458. else if (style.sx && style.sy) {
  7459. var sx = style.sx;
  7460. var sy = style.sy;
  7461. var sWidth = width - sx;
  7462. var sHeight = height - sy;
  7463. ctx.drawImage(
  7464. image,
  7465. sx, sy, sWidth, sHeight,
  7466. x, y, width, height
  7467. );
  7468. }
  7469. else {
  7470. ctx.drawImage(image, x, y, width, height);
  7471. }
  7472. // Draw rect text
  7473. if (style.text != null) {
  7474. // Only restore transform when needs draw text.
  7475. this.restoreTransform(ctx);
  7476. this.drawRectText(ctx, this.getBoundingRect());
  7477. }
  7478. },
  7479. getBoundingRect: function () {
  7480. var style = this.style;
  7481. if (! this._rect) {
  7482. this._rect = new BoundingRect(
  7483. style.x || 0, style.y || 0, style.width || 0, style.height || 0
  7484. );
  7485. }
  7486. return this._rect;
  7487. }
  7488. };
  7489. inherits(ZImage, Displayable);
  7490. var HOVER_LAYER_ZLEVEL = 1e5;
  7491. var CANVAS_ZLEVEL = 314159;
  7492. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7493. var INCREMENTAL_INC = 0.001;
  7494. function parseInt10(val) {
  7495. return parseInt(val, 10);
  7496. }
  7497. function isLayerValid(layer) {
  7498. if (!layer) {
  7499. return false;
  7500. }
  7501. if (layer.__builtin__) {
  7502. return true;
  7503. }
  7504. if (typeof(layer.resize) !== 'function'
  7505. || typeof(layer.refresh) !== 'function'
  7506. ) {
  7507. return false;
  7508. }
  7509. return true;
  7510. }
  7511. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7512. var viewRect = new BoundingRect(0, 0, 0, 0);
  7513. function isDisplayableCulled(el, width, height) {
  7514. tmpRect.copy(el.getBoundingRect());
  7515. if (el.transform) {
  7516. tmpRect.applyTransform(el.transform);
  7517. }
  7518. viewRect.width = width;
  7519. viewRect.height = height;
  7520. return !tmpRect.intersect(viewRect);
  7521. }
  7522. function isClipPathChanged(clipPaths, prevClipPaths) {
  7523. if (clipPaths == prevClipPaths) { // Can both be null or undefined
  7524. return false;
  7525. }
  7526. if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) {
  7527. return true;
  7528. }
  7529. for (var i = 0; i < clipPaths.length; i++) {
  7530. if (clipPaths[i] !== prevClipPaths[i]) {
  7531. return true;
  7532. }
  7533. }
  7534. }
  7535. function doClip(clipPaths, ctx) {
  7536. for (var i = 0; i < clipPaths.length; i++) {
  7537. var clipPath = clipPaths[i];
  7538. clipPath.setTransform(ctx);
  7539. ctx.beginPath();
  7540. clipPath.buildPath(ctx, clipPath.shape);
  7541. ctx.clip();
  7542. // Transform back
  7543. clipPath.restoreTransform(ctx);
  7544. }
  7545. }
  7546. function createRoot(width, height) {
  7547. var domRoot = document.createElement('div');
  7548. // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬
  7549. domRoot.style.cssText = [
  7550. 'position:relative',
  7551. 'overflow:hidden',
  7552. 'width:' + width + 'px',
  7553. 'height:' + height + 'px',
  7554. 'padding:0',
  7555. 'margin:0',
  7556. 'border-width:0'
  7557. ].join(';') + ';';
  7558. return domRoot;
  7559. }
  7560. /**
  7561. * @alias module:zrender/Painter
  7562. * @constructor
  7563. * @param {HTMLElement} root 绘图容器
  7564. * @param {module:zrender/Storage} storage
  7565. * @param {Object} opts
  7566. */
  7567. var Painter = function (root, storage, opts) {
  7568. this.type = 'canvas';
  7569. // In node environment using node-canvas
  7570. var singleCanvas = !root.nodeName // In node ?
  7571. || root.nodeName.toUpperCase() === 'CANVAS';
  7572. this._opts = opts = extend({}, opts || {});
  7573. /**
  7574. * @type {number}
  7575. */
  7576. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  7577. /**
  7578. * @type {boolean}
  7579. * @private
  7580. */
  7581. this._singleCanvas = singleCanvas;
  7582. /**
  7583. * 绘图容器
  7584. * @type {HTMLElement}
  7585. */
  7586. this.root = root;
  7587. var rootStyle = root.style;
  7588. if (rootStyle) {
  7589. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  7590. rootStyle['-webkit-user-select'] =
  7591. rootStyle['user-select'] =
  7592. rootStyle['-webkit-touch-callout'] = 'none';
  7593. root.innerHTML = '';
  7594. }
  7595. /**
  7596. * @type {module:zrender/Storage}
  7597. */
  7598. this.storage = storage;
  7599. /**
  7600. * @type {Array.<number>}
  7601. * @private
  7602. */
  7603. var zlevelList = this._zlevelList = [];
  7604. /**
  7605. * @type {Object.<string, module:zrender/Layer>}
  7606. * @private
  7607. */
  7608. var layers = this._layers = {};
  7609. /**
  7610. * @type {Object.<string, Object>}
  7611. * @private
  7612. */
  7613. this._layerConfig = {};
  7614. /**
  7615. * zrender will do compositing when root is a canvas and have multiple zlevels.
  7616. */
  7617. this._needsManuallyCompositing = false;
  7618. if (!singleCanvas) {
  7619. this._width = this._getSize(0);
  7620. this._height = this._getSize(1);
  7621. var domRoot = this._domRoot = createRoot(
  7622. this._width, this._height
  7623. );
  7624. root.appendChild(domRoot);
  7625. }
  7626. else {
  7627. var width = root.width;
  7628. var height = root.height;
  7629. if (opts.width != null) {
  7630. width = opts.width;
  7631. }
  7632. if (opts.height != null) {
  7633. height = opts.height;
  7634. }
  7635. this.dpr = opts.devicePixelRatio || 1;
  7636. // Use canvas width and height directly
  7637. root.width = width * this.dpr;
  7638. root.height = height * this.dpr;
  7639. this._width = width;
  7640. this._height = height;
  7641. // Create layer if only one given canvas
  7642. // Device can be specified to create a high dpi image.
  7643. var mainLayer = new Layer(root, this, this.dpr);
  7644. mainLayer.__builtin__ = true;
  7645. mainLayer.initContext();
  7646. // FIXME Use canvas width and height
  7647. // mainLayer.resize(width, height);
  7648. layers[CANVAS_ZLEVEL] = mainLayer;
  7649. mainLayer.zlevel = CANVAS_ZLEVEL;
  7650. // Not use common zlevel.
  7651. zlevelList.push(CANVAS_ZLEVEL);
  7652. this._domRoot = root;
  7653. }
  7654. /**
  7655. * @type {module:zrender/Layer}
  7656. * @private
  7657. */
  7658. this._hoverlayer = null;
  7659. this._hoverElements = [];
  7660. };
  7661. Painter.prototype = {
  7662. constructor: Painter,
  7663. getType: function () {
  7664. return 'canvas';
  7665. },
  7666. /**
  7667. * If painter use a single canvas
  7668. * @return {boolean}
  7669. */
  7670. isSingleCanvas: function () {
  7671. return this._singleCanvas;
  7672. },
  7673. /**
  7674. * @return {HTMLDivElement}
  7675. */
  7676. getViewportRoot: function () {
  7677. return this._domRoot;
  7678. },
  7679. getViewportRootOffset: function () {
  7680. var viewportRoot = this.getViewportRoot();
  7681. if (viewportRoot) {
  7682. return {
  7683. offsetLeft: viewportRoot.offsetLeft || 0,
  7684. offsetTop: viewportRoot.offsetTop || 0
  7685. };
  7686. }
  7687. },
  7688. /**
  7689. * 刷新
  7690. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  7691. */
  7692. refresh: function (paintAll) {
  7693. var list = this.storage.getDisplayList(true);
  7694. var zlevelList = this._zlevelList;
  7695. this._redrawId = Math.random();
  7696. this._paintList(list, paintAll, this._redrawId);
  7697. // Paint custum layers
  7698. for (var i = 0; i < zlevelList.length; i++) {
  7699. var z = zlevelList[i];
  7700. var layer = this._layers[z];
  7701. if (!layer.__builtin__ && layer.refresh) {
  7702. var clearColor = i === 0 ? this._backgroundColor : null;
  7703. layer.refresh(clearColor);
  7704. }
  7705. }
  7706. this.refreshHover();
  7707. return this;
  7708. },
  7709. addHover: function (el, hoverStyle) {
  7710. if (el.__hoverMir) {
  7711. return;
  7712. }
  7713. var elMirror = new el.constructor({
  7714. style: el.style,
  7715. shape: el.shape
  7716. });
  7717. elMirror.__from = el;
  7718. el.__hoverMir = elMirror;
  7719. elMirror.setStyle(hoverStyle);
  7720. this._hoverElements.push(elMirror);
  7721. },
  7722. removeHover: function (el) {
  7723. var elMirror = el.__hoverMir;
  7724. var hoverElements = this._hoverElements;
  7725. var idx = indexOf(hoverElements, elMirror);
  7726. if (idx >= 0) {
  7727. hoverElements.splice(idx, 1);
  7728. }
  7729. el.__hoverMir = null;
  7730. },
  7731. clearHover: function (el) {
  7732. var hoverElements = this._hoverElements;
  7733. for (var i = 0; i < hoverElements.length; i++) {
  7734. var from = hoverElements[i].__from;
  7735. if (from) {
  7736. from.__hoverMir = null;
  7737. }
  7738. }
  7739. hoverElements.length = 0;
  7740. },
  7741. refreshHover: function () {
  7742. var hoverElements = this._hoverElements;
  7743. var len = hoverElements.length;
  7744. var hoverLayer = this._hoverlayer;
  7745. hoverLayer && hoverLayer.clear();
  7746. if (!len) {
  7747. return;
  7748. }
  7749. sort(hoverElements, this.storage.displayableSortFunc);
  7750. // Use a extream large zlevel
  7751. // FIXME?
  7752. if (!hoverLayer) {
  7753. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  7754. }
  7755. var scope = {};
  7756. hoverLayer.ctx.save();
  7757. for (var i = 0; i < len;) {
  7758. var el = hoverElements[i];
  7759. var originalEl = el.__from;
  7760. // Original el is removed
  7761. // PENDING
  7762. if (!(originalEl && originalEl.__zr)) {
  7763. hoverElements.splice(i, 1);
  7764. originalEl.__hoverMir = null;
  7765. len--;
  7766. continue;
  7767. }
  7768. i++;
  7769. // Use transform
  7770. // FIXME style and shape ?
  7771. if (!originalEl.invisible) {
  7772. el.transform = originalEl.transform;
  7773. el.invTransform = originalEl.invTransform;
  7774. el.__clipPaths = originalEl.__clipPaths;
  7775. // el.
  7776. this._doPaintEl(el, hoverLayer, true, scope);
  7777. }
  7778. }
  7779. hoverLayer.ctx.restore();
  7780. },
  7781. getHoverLayer: function () {
  7782. return this.getLayer(HOVER_LAYER_ZLEVEL);
  7783. },
  7784. _paintList: function (list, paintAll, redrawId) {
  7785. if (this._redrawId !== redrawId) {
  7786. return;
  7787. }
  7788. paintAll = paintAll || false;
  7789. this._updateLayerStatus(list);
  7790. var finished = this._doPaintList(list, paintAll);
  7791. if (this._needsManuallyCompositing) {
  7792. this._compositeManually();
  7793. }
  7794. if (!finished) {
  7795. var self = this;
  7796. requestAnimationFrame(function () {
  7797. self._paintList(list, paintAll, redrawId);
  7798. });
  7799. }
  7800. },
  7801. _compositeManually: function () {
  7802. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  7803. var width = this._domRoot.width;
  7804. var height = this._domRoot.height;
  7805. ctx.clearRect(0, 0, width, height);
  7806. // PENDING, If only builtin layer?
  7807. this.eachBuiltinLayer(function (layer) {
  7808. if (layer.virtual) {
  7809. ctx.drawImage(layer.dom, 0, 0, width, height);
  7810. }
  7811. });
  7812. },
  7813. _doPaintList: function (list, paintAll) {
  7814. var layerList = [];
  7815. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  7816. var zlevel = this._zlevelList[zi];
  7817. var layer = this._layers[zlevel];
  7818. if (layer.__builtin__
  7819. && layer !== this._hoverlayer
  7820. && (layer.__dirty || paintAll)
  7821. ) {
  7822. layerList.push(layer);
  7823. }
  7824. }
  7825. var finished = true;
  7826. for (var k = 0; k < layerList.length; k++) {
  7827. var layer = layerList[k];
  7828. var ctx = layer.ctx;
  7829. var scope = {};
  7830. ctx.save();
  7831. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  7832. var useTimer = !paintAll && layer.incremental && Date.now;
  7833. var startTime = useTimer && Date.now();
  7834. var clearColor = layer.zlevel === this._zlevelList[0]
  7835. ? this._backgroundColor : null;
  7836. // All elements in this layer are cleared.
  7837. if (layer.__startIndex === layer.__endIndex) {
  7838. layer.clear(false, clearColor);
  7839. }
  7840. else if (start === layer.__startIndex) {
  7841. var firstEl = list[start];
  7842. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  7843. layer.clear(false, clearColor);
  7844. }
  7845. }
  7846. if (start === -1) {
  7847. console.error('For some unknown reason. drawIndex is -1');
  7848. start = layer.__startIndex;
  7849. }
  7850. for (var i = start; i < layer.__endIndex; i++) {
  7851. var el = list[i];
  7852. this._doPaintEl(el, layer, paintAll, scope);
  7853. el.__dirty = false;
  7854. if (useTimer) {
  7855. // Date.now can be executed in 13,025,305 ops/second.
  7856. var dTime = Date.now() - startTime;
  7857. // Give 15 millisecond to draw.
  7858. // The rest elements will be drawn in the next frame.
  7859. if (dTime > 15) {
  7860. break;
  7861. }
  7862. }
  7863. }
  7864. layer.__drawIndex = i;
  7865. if (layer.__drawIndex < layer.__endIndex) {
  7866. finished = false;
  7867. }
  7868. if (scope.prevElClipPaths) {
  7869. // Needs restore the state. If last drawn element is in the clipping area.
  7870. ctx.restore();
  7871. }
  7872. ctx.restore();
  7873. }
  7874. if (env$1.wxa) {
  7875. // Flush for weixin application
  7876. each$1(this._layers, function (layer) {
  7877. if (layer && layer.ctx && layer.ctx.draw) {
  7878. layer.ctx.draw();
  7879. }
  7880. });
  7881. }
  7882. return finished;
  7883. },
  7884. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  7885. var ctx = currentLayer.ctx;
  7886. var m = el.transform;
  7887. if (
  7888. (currentLayer.__dirty || forcePaint)
  7889. // Ignore invisible element
  7890. && !el.invisible
  7891. // Ignore transparent element
  7892. && el.style.opacity !== 0
  7893. // Ignore scale 0 element, in some environment like node-canvas
  7894. // Draw a scale 0 element can cause all following draw wrong
  7895. // And setTransform with scale 0 will cause set back transform failed.
  7896. && !(m && !m[0] && !m[3])
  7897. // Ignore culled element
  7898. && !(el.culling && isDisplayableCulled(el, this._width, this._height))
  7899. ) {
  7900. var clipPaths = el.__clipPaths;
  7901. // Optimize when clipping on group with several elements
  7902. if (!scope.prevElClipPaths
  7903. || isClipPathChanged(clipPaths, scope.prevElClipPaths)
  7904. ) {
  7905. // If has previous clipping state, restore from it
  7906. if (scope.prevElClipPaths) {
  7907. currentLayer.ctx.restore();
  7908. scope.prevElClipPaths = null;
  7909. // Reset prevEl since context has been restored
  7910. scope.prevEl = null;
  7911. }
  7912. // New clipping state
  7913. if (clipPaths) {
  7914. ctx.save();
  7915. doClip(clipPaths, ctx);
  7916. scope.prevElClipPaths = clipPaths;
  7917. }
  7918. }
  7919. el.beforeBrush && el.beforeBrush(ctx);
  7920. el.brush(ctx, scope.prevEl || null);
  7921. scope.prevEl = el;
  7922. el.afterBrush && el.afterBrush(ctx);
  7923. }
  7924. },
  7925. /**
  7926. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  7927. * @param {number} zlevel
  7928. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  7929. * @return {module:zrender/Layer}
  7930. */
  7931. getLayer: function (zlevel, virtual) {
  7932. if (this._singleCanvas && !this._needsManuallyCompositing) {
  7933. zlevel = CANVAS_ZLEVEL;
  7934. }
  7935. var layer = this._layers[zlevel];
  7936. if (!layer) {
  7937. // Create a new layer
  7938. layer = new Layer('zr_' + zlevel, this, this.dpr);
  7939. layer.zlevel = zlevel;
  7940. layer.__builtin__ = true;
  7941. if (this._layerConfig[zlevel]) {
  7942. merge(layer, this._layerConfig[zlevel], true);
  7943. }
  7944. if (virtual) {
  7945. layer.virtual = virtual;
  7946. }
  7947. this.insertLayer(zlevel, layer);
  7948. // Context is created after dom inserted to document
  7949. // Or excanvas will get 0px clientWidth and clientHeight
  7950. layer.initContext();
  7951. }
  7952. return layer;
  7953. },
  7954. insertLayer: function (zlevel, layer) {
  7955. var layersMap = this._layers;
  7956. var zlevelList = this._zlevelList;
  7957. var len = zlevelList.length;
  7958. var prevLayer = null;
  7959. var i = -1;
  7960. var domRoot = this._domRoot;
  7961. if (layersMap[zlevel]) {
  7962. zrLog('ZLevel ' + zlevel + ' has been used already');
  7963. return;
  7964. }
  7965. // Check if is a valid layer
  7966. if (!isLayerValid(layer)) {
  7967. zrLog('Layer of zlevel ' + zlevel + ' is not valid');
  7968. return;
  7969. }
  7970. if (len > 0 && zlevel > zlevelList[0]) {
  7971. for (i = 0; i < len - 1; i++) {
  7972. if (
  7973. zlevelList[i] < zlevel
  7974. && zlevelList[i + 1] > zlevel
  7975. ) {
  7976. break;
  7977. }
  7978. }
  7979. prevLayer = layersMap[zlevelList[i]];
  7980. }
  7981. zlevelList.splice(i + 1, 0, zlevel);
  7982. layersMap[zlevel] = layer;
  7983. // Vitual layer will not directly show on the screen.
  7984. // (It can be a WebGL layer and assigned to a ZImage element)
  7985. // But it still under management of zrender.
  7986. if (!layer.virtual) {
  7987. if (prevLayer) {
  7988. var prevDom = prevLayer.dom;
  7989. if (prevDom.nextSibling) {
  7990. domRoot.insertBefore(
  7991. layer.dom,
  7992. prevDom.nextSibling
  7993. );
  7994. }
  7995. else {
  7996. domRoot.appendChild(layer.dom);
  7997. }
  7998. }
  7999. else {
  8000. if (domRoot.firstChild) {
  8001. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8002. }
  8003. else {
  8004. domRoot.appendChild(layer.dom);
  8005. }
  8006. }
  8007. }
  8008. },
  8009. // Iterate each layer
  8010. eachLayer: function (cb, context) {
  8011. var zlevelList = this._zlevelList;
  8012. var z;
  8013. var i;
  8014. for (i = 0; i < zlevelList.length; i++) {
  8015. z = zlevelList[i];
  8016. cb.call(context, this._layers[z], z);
  8017. }
  8018. },
  8019. // Iterate each buildin layer
  8020. eachBuiltinLayer: function (cb, context) {
  8021. var zlevelList = this._zlevelList;
  8022. var layer;
  8023. var z;
  8024. var i;
  8025. for (i = 0; i < zlevelList.length; i++) {
  8026. z = zlevelList[i];
  8027. layer = this._layers[z];
  8028. if (layer.__builtin__) {
  8029. cb.call(context, layer, z);
  8030. }
  8031. }
  8032. },
  8033. // Iterate each other layer except buildin layer
  8034. eachOtherLayer: function (cb, context) {
  8035. var zlevelList = this._zlevelList;
  8036. var layer;
  8037. var z;
  8038. var i;
  8039. for (i = 0; i < zlevelList.length; i++) {
  8040. z = zlevelList[i];
  8041. layer = this._layers[z];
  8042. if (!layer.__builtin__) {
  8043. cb.call(context, layer, z);
  8044. }
  8045. }
  8046. },
  8047. /**
  8048. * 获取所有已创建的层
  8049. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8050. */
  8051. getLayers: function () {
  8052. return this._layers;
  8053. },
  8054. _updateLayerStatus: function (list) {
  8055. this.eachBuiltinLayer(function (layer, z) {
  8056. layer.__dirty = layer.__used = false;
  8057. });
  8058. function updatePrevLayer(idx) {
  8059. if (prevLayer) {
  8060. if (prevLayer.__endIndex !== idx) {
  8061. prevLayer.__dirty = true;
  8062. }
  8063. prevLayer.__endIndex = idx;
  8064. }
  8065. }
  8066. if (this._singleCanvas) {
  8067. for (var i = 1; i < list.length; i++) {
  8068. var el = list[i];
  8069. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8070. this._needsManuallyCompositing = true;
  8071. break;
  8072. }
  8073. }
  8074. }
  8075. var prevLayer = null;
  8076. var incrementalLayerCount = 0;
  8077. for (var i = 0; i < list.length; i++) {
  8078. var el = list[i];
  8079. var zlevel = el.zlevel;
  8080. var layer;
  8081. // PENDING If change one incremental element style ?
  8082. // TODO Where there are non-incremental elements between incremental elements.
  8083. if (el.incremental) {
  8084. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8085. layer.incremental = true;
  8086. incrementalLayerCount = 1;
  8087. }
  8088. else {
  8089. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8090. }
  8091. if (!layer.__builtin__) {
  8092. zrLog('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8093. }
  8094. if (layer !== prevLayer) {
  8095. layer.__used = true;
  8096. if (layer.__startIndex !== i) {
  8097. layer.__dirty = true;
  8098. }
  8099. layer.__startIndex = i;
  8100. if (!layer.incremental) {
  8101. layer.__drawIndex = i;
  8102. }
  8103. else {
  8104. // Mark layer draw index needs to update.
  8105. layer.__drawIndex = -1;
  8106. }
  8107. updatePrevLayer(i);
  8108. prevLayer = layer;
  8109. }
  8110. if (el.__dirty) {
  8111. layer.__dirty = true;
  8112. if (layer.incremental && layer.__drawIndex < 0) {
  8113. // Start draw from the first dirty element.
  8114. layer.__drawIndex = i;
  8115. }
  8116. }
  8117. }
  8118. updatePrevLayer(i);
  8119. this.eachBuiltinLayer(function (layer, z) {
  8120. // Used in last frame but not in this frame. Needs clear
  8121. if (!layer.__used && layer.getElementCount() > 0) {
  8122. layer.__dirty = true;
  8123. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8124. }
  8125. // For incremental layer. In case start index changed and no elements are dirty.
  8126. if (layer.__dirty && layer.__drawIndex < 0) {
  8127. layer.__drawIndex = layer.__startIndex;
  8128. }
  8129. });
  8130. },
  8131. /**
  8132. * 清除hover层外所有内容
  8133. */
  8134. clear: function () {
  8135. this.eachBuiltinLayer(this._clearLayer);
  8136. return this;
  8137. },
  8138. _clearLayer: function (layer) {
  8139. layer.clear();
  8140. },
  8141. setBackgroundColor: function (backgroundColor) {
  8142. this._backgroundColor = backgroundColor;
  8143. },
  8144. /**
  8145. * 修改指定zlevel的绘制参数
  8146. *
  8147. * @param {string} zlevel
  8148. * @param {Object} config 配置对象
  8149. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8150. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8151. * @param {number} [config.lastFrameAlpha=0.7]
  8152. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8153. */
  8154. configLayer: function (zlevel, config) {
  8155. if (config) {
  8156. var layerConfig = this._layerConfig;
  8157. if (!layerConfig[zlevel]) {
  8158. layerConfig[zlevel] = config;
  8159. }
  8160. else {
  8161. merge(layerConfig[zlevel], config, true);
  8162. }
  8163. for (var i = 0; i < this._zlevelList.length; i++) {
  8164. var _zlevel = this._zlevelList[i];
  8165. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8166. var layer = this._layers[_zlevel];
  8167. merge(layer, layerConfig[zlevel], true);
  8168. }
  8169. }
  8170. }
  8171. },
  8172. /**
  8173. * 删除指定层
  8174. * @param {number} zlevel 层所在的zlevel
  8175. */
  8176. delLayer: function (zlevel) {
  8177. var layers = this._layers;
  8178. var zlevelList = this._zlevelList;
  8179. var layer = layers[zlevel];
  8180. if (!layer) {
  8181. return;
  8182. }
  8183. layer.dom.parentNode.removeChild(layer.dom);
  8184. delete layers[zlevel];
  8185. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8186. },
  8187. /**
  8188. * 区域大小变化后重绘
  8189. */
  8190. resize: function (width, height) {
  8191. if (!this._domRoot.style) { // Maybe in node or worker
  8192. if (width == null || height == null) {
  8193. return;
  8194. }
  8195. this._width = width;
  8196. this._height = height;
  8197. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8198. }
  8199. else {
  8200. var domRoot = this._domRoot;
  8201. // FIXME Why ?
  8202. domRoot.style.display = 'none';
  8203. // Save input w/h
  8204. var opts = this._opts;
  8205. width != null && (opts.width = width);
  8206. height != null && (opts.height = height);
  8207. width = this._getSize(0);
  8208. height = this._getSize(1);
  8209. domRoot.style.display = '';
  8210. // 优化没有实际改变的resize
  8211. if (this._width != width || height != this._height) {
  8212. domRoot.style.width = width + 'px';
  8213. domRoot.style.height = height + 'px';
  8214. for (var id in this._layers) {
  8215. if (this._layers.hasOwnProperty(id)) {
  8216. this._layers[id].resize(width, height);
  8217. }
  8218. }
  8219. each$1(this._progressiveLayers, function (layer) {
  8220. layer.resize(width, height);
  8221. });
  8222. this.refresh(true);
  8223. }
  8224. this._width = width;
  8225. this._height = height;
  8226. }
  8227. return this;
  8228. },
  8229. /**
  8230. * 清除单独的一个层
  8231. * @param {number} zlevel
  8232. */
  8233. clearLayer: function (zlevel) {
  8234. var layer = this._layers[zlevel];
  8235. if (layer) {
  8236. layer.clear();
  8237. }
  8238. },
  8239. /**
  8240. * 释放
  8241. */
  8242. dispose: function () {
  8243. this.root.innerHTML = '';
  8244. this.root =
  8245. this.storage =
  8246. this._domRoot =
  8247. this._layers = null;
  8248. },
  8249. /**
  8250. * Get canvas which has all thing rendered
  8251. * @param {Object} opts
  8252. * @param {string} [opts.backgroundColor]
  8253. * @param {number} [opts.pixelRatio]
  8254. */
  8255. getRenderedCanvas: function (opts) {
  8256. opts = opts || {};
  8257. if (this._singleCanvas && !this._compositeManually) {
  8258. return this._layers[CANVAS_ZLEVEL].dom;
  8259. }
  8260. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8261. imageLayer.initContext();
  8262. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8263. if (opts.pixelRatio <= this.dpr) {
  8264. this.refresh();
  8265. var width = imageLayer.dom.width;
  8266. var height = imageLayer.dom.height;
  8267. var ctx = imageLayer.ctx;
  8268. this.eachLayer(function (layer) {
  8269. if (layer.__builtin__) {
  8270. ctx.drawImage(layer.dom, 0, 0, width, height);
  8271. }
  8272. else if (layer.renderToCanvas) {
  8273. imageLayer.ctx.save();
  8274. layer.renderToCanvas(imageLayer.ctx);
  8275. imageLayer.ctx.restore();
  8276. }
  8277. });
  8278. }
  8279. else {
  8280. // PENDING, echarts-gl and incremental rendering.
  8281. var scope = {};
  8282. var displayList = this.storage.getDisplayList(true);
  8283. for (var i = 0; i < displayList.length; i++) {
  8284. var el = displayList[i];
  8285. this._doPaintEl(el, imageLayer, true, scope);
  8286. }
  8287. }
  8288. return imageLayer.dom;
  8289. },
  8290. /**
  8291. * 获取绘图区域宽度
  8292. */
  8293. getWidth: function () {
  8294. return this._width;
  8295. },
  8296. /**
  8297. * 获取绘图区域高度
  8298. */
  8299. getHeight: function () {
  8300. return this._height;
  8301. },
  8302. _getSize: function (whIdx) {
  8303. var opts = this._opts;
  8304. var wh = ['width', 'height'][whIdx];
  8305. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8306. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8307. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8308. if (opts[wh] != null && opts[wh] !== 'auto') {
  8309. return parseFloat(opts[wh]);
  8310. }
  8311. var root = this.root;
  8312. // IE8 does not support getComputedStyle, but it use VML.
  8313. var stl = document.defaultView.getComputedStyle(root);
  8314. return (
  8315. (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh]))
  8316. - (parseInt10(stl[plt]) || 0)
  8317. - (parseInt10(stl[prb]) || 0)
  8318. ) | 0;
  8319. },
  8320. pathToImage: function (path, dpr) {
  8321. dpr = dpr || this.dpr;
  8322. var canvas = document.createElement('canvas');
  8323. var ctx = canvas.getContext('2d');
  8324. var rect = path.getBoundingRect();
  8325. var style = path.style;
  8326. var shadowBlurSize = style.shadowBlur * dpr;
  8327. var shadowOffsetX = style.shadowOffsetX * dpr;
  8328. var shadowOffsetY = style.shadowOffsetY * dpr;
  8329. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8330. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8331. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8332. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8333. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8334. var width = rect.width + leftMargin + rightMargin;
  8335. var height = rect.height + topMargin + bottomMargin;
  8336. canvas.width = width * dpr;
  8337. canvas.height = height * dpr;
  8338. ctx.scale(dpr, dpr);
  8339. ctx.clearRect(0, 0, width, height);
  8340. ctx.dpr = dpr;
  8341. var pathTransform = {
  8342. position: path.position,
  8343. rotation: path.rotation,
  8344. scale: path.scale
  8345. };
  8346. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8347. path.rotation = 0;
  8348. path.scale = [1, 1];
  8349. path.updateTransform();
  8350. if (path) {
  8351. path.brush(ctx);
  8352. }
  8353. var ImageShape = ZImage;
  8354. var imgShape = new ImageShape({
  8355. style: {
  8356. x: 0,
  8357. y: 0,
  8358. image: canvas
  8359. }
  8360. });
  8361. if (pathTransform.position != null) {
  8362. imgShape.position = path.position = pathTransform.position;
  8363. }
  8364. if (pathTransform.rotation != null) {
  8365. imgShape.rotation = path.rotation = pathTransform.rotation;
  8366. }
  8367. if (pathTransform.scale != null) {
  8368. imgShape.scale = path.scale = pathTransform.scale;
  8369. }
  8370. return imgShape;
  8371. }
  8372. };
  8373. /**
  8374. * 事件辅助类
  8375. * @module zrender/core/event
  8376. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  8377. */
  8378. var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener;
  8379. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  8380. function getBoundingClientRect(el) {
  8381. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect
  8382. return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0};
  8383. }
  8384. // `calculate` is optional, default false
  8385. function clientToLocal(el, e, out, calculate) {
  8386. out = out || {};
  8387. // According to the W3C Working Draft, offsetX and offsetY should be relative
  8388. // to the padding edge of the target element. The only browser using this convention
  8389. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  8390. // not support the properties.
  8391. // (see http://www.jacklmoore.com/notes/mouse-position/)
  8392. // In zr painter.dom, padding edge equals to border edge.
  8393. // FIXME
  8394. // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and
  8395. // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y
  8396. // is too complex. So css-transfrom dont support in this case temporarily.
  8397. if (calculate || !env$1.canvasSupported) {
  8398. defaultGetZrXY(el, e, out);
  8399. }
  8400. // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  8401. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  8402. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  8403. // zoom-factor, overflow / opacity layers, transforms ...)
  8404. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  8405. // <https://bugs.jquery.com/ticket/8523#comment:14>
  8406. // BTW3, In ff, offsetX/offsetY is always 0.
  8407. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  8408. out.zrX = e.layerX;
  8409. out.zrY = e.layerY;
  8410. }
  8411. // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  8412. else if (e.offsetX != null) {
  8413. out.zrX = e.offsetX;
  8414. out.zrY = e.offsetY;
  8415. }
  8416. // For some other device, e.g., IOS safari.
  8417. else {
  8418. defaultGetZrXY(el, e, out);
  8419. }
  8420. return out;
  8421. }
  8422. function defaultGetZrXY(el, e, out) {
  8423. // This well-known method below does not support css transform.
  8424. var box = getBoundingClientRect(el);
  8425. out.zrX = e.clientX - box.left;
  8426. out.zrY = e.clientY - box.top;
  8427. }
  8428. /**
  8429. * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标.
  8430. * `calculate` is optional, default false.
  8431. */
  8432. function normalizeEvent(el, e, calculate) {
  8433. e = e || window.event;
  8434. if (e.zrX != null) {
  8435. return e;
  8436. }
  8437. var eventType = e.type;
  8438. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  8439. if (!isTouch) {
  8440. clientToLocal(el, e, e, calculate);
  8441. e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  8442. }
  8443. else {
  8444. var touch = eventType != 'touchend'
  8445. ? e.targetTouches[0]
  8446. : e.changedTouches[0];
  8447. touch && clientToLocal(el, touch, e, calculate);
  8448. }
  8449. // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  8450. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  8451. // If e.which has been defined, if may be readonly,
  8452. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  8453. var button = e.button;
  8454. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  8455. e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0)));
  8456. }
  8457. return e;
  8458. }
  8459. /**
  8460. * @param {HTMLElement} el
  8461. * @param {string} name
  8462. * @param {Function} handler
  8463. */
  8464. function addEventListener(el, name, handler) {
  8465. if (isDomLevel2) {
  8466. // Reproduct the console warning:
  8467. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  8468. // Consider marking event handler as 'passive' to make the page more responsive.
  8469. // Just set console log level: verbose in chrome dev tool.
  8470. // then the warning log will be printed when addEventListener called.
  8471. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  8472. // We have not yet found a neat way to using passive. Because in zrender the dom event
  8473. // listener delegate all of the upper events of element. Some of those events need
  8474. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  8475. // Before passive can be adopted, these issues should be considered:
  8476. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  8477. // passive or not.
  8478. // (2) How to tread that some zrender event listener is passive, and some is not. If
  8479. // we use other way but not preventDefault of mousewheel and touchmove, browser
  8480. // compatibility should be handled.
  8481. // var opts = (env.passiveSupported && name === 'mousewheel')
  8482. // ? {passive: true}
  8483. // // By default, the third param of el.addEventListener is `capture: false`.
  8484. // : void 0;
  8485. // el.addEventListener(name, handler /* , opts */);
  8486. el.addEventListener(name, handler);
  8487. }
  8488. else {
  8489. el.attachEvent('on' + name, handler);
  8490. }
  8491. }
  8492. function removeEventListener(el, name, handler) {
  8493. if (isDomLevel2) {
  8494. el.removeEventListener(name, handler);
  8495. }
  8496. else {
  8497. el.detachEvent('on' + name, handler);
  8498. }
  8499. }
  8500. /**
  8501. * preventDefault and stopPropagation.
  8502. * Notice: do not do that in zrender. Upper application
  8503. * do that if necessary.
  8504. *
  8505. * @memberOf module:zrender/core/event
  8506. * @method
  8507. * @param {Event} e : event对象
  8508. */
  8509. var stop = isDomLevel2
  8510. ? function (e) {
  8511. e.preventDefault();
  8512. e.stopPropagation();
  8513. e.cancelBubble = true;
  8514. }
  8515. : function (e) {
  8516. e.returnValue = false;
  8517. e.cancelBubble = true;
  8518. };
  8519. function notLeftMouse(e) {
  8520. // If e.which is undefined, considered as left mouse event.
  8521. return e.which > 1;
  8522. }
  8523. /**
  8524. * 动画主类, 调度和管理所有动画控制器
  8525. *
  8526. * @module zrender/animation/Animation
  8527. * @author pissang(https://github.com/pissang)
  8528. */
  8529. // TODO Additive animation
  8530. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8531. // https://developer.apple.com/videos/wwdc2014/#236
  8532. /**
  8533. * @typedef {Object} IZRenderStage
  8534. * @property {Function} update
  8535. */
  8536. /**
  8537. * @alias module:zrender/animation/Animation
  8538. * @constructor
  8539. * @param {Object} [options]
  8540. * @param {Function} [options.onframe]
  8541. * @param {IZRenderStage} [options.stage]
  8542. * @example
  8543. * var animation = new Animation();
  8544. * var obj = {
  8545. * x: 100,
  8546. * y: 100
  8547. * };
  8548. * animation.animate(node.position)
  8549. * .when(1000, {
  8550. * x: 500,
  8551. * y: 500
  8552. * })
  8553. * .when(2000, {
  8554. * x: 100,
  8555. * y: 100
  8556. * })
  8557. * .start('spline');
  8558. */
  8559. var Animation = function (options) {
  8560. options = options || {};
  8561. this.stage = options.stage || {};
  8562. this.onframe = options.onframe || function() {};
  8563. // private properties
  8564. this._clips = [];
  8565. this._running = false;
  8566. this._time;
  8567. this._pausedTime;
  8568. this._pauseStart;
  8569. this._paused = false;
  8570. Eventful.call(this);
  8571. };
  8572. Animation.prototype = {
  8573. constructor: Animation,
  8574. /**
  8575. * 添加 clip
  8576. * @param {module:zrender/animation/Clip} clip
  8577. */
  8578. addClip: function (clip) {
  8579. this._clips.push(clip);
  8580. },
  8581. /**
  8582. * 添加 animator
  8583. * @param {module:zrender/animation/Animator} animator
  8584. */
  8585. addAnimator: function (animator) {
  8586. animator.animation = this;
  8587. var clips = animator.getClips();
  8588. for (var i = 0; i < clips.length; i++) {
  8589. this.addClip(clips[i]);
  8590. }
  8591. },
  8592. /**
  8593. * 删除动画片段
  8594. * @param {module:zrender/animation/Clip} clip
  8595. */
  8596. removeClip: function(clip) {
  8597. var idx = indexOf(this._clips, clip);
  8598. if (idx >= 0) {
  8599. this._clips.splice(idx, 1);
  8600. }
  8601. },
  8602. /**
  8603. * 删除动画片段
  8604. * @param {module:zrender/animation/Animator} animator
  8605. */
  8606. removeAnimator: function (animator) {
  8607. var clips = animator.getClips();
  8608. for (var i = 0; i < clips.length; i++) {
  8609. this.removeClip(clips[i]);
  8610. }
  8611. animator.animation = null;
  8612. },
  8613. _update: function() {
  8614. var time = new Date().getTime() - this._pausedTime;
  8615. var delta = time - this._time;
  8616. var clips = this._clips;
  8617. var len = clips.length;
  8618. var deferredEvents = [];
  8619. var deferredClips = [];
  8620. for (var i = 0; i < len; i++) {
  8621. var clip = clips[i];
  8622. var e = clip.step(time, delta);
  8623. // Throw out the events need to be called after
  8624. // stage.update, like destroy
  8625. if (e) {
  8626. deferredEvents.push(e);
  8627. deferredClips.push(clip);
  8628. }
  8629. }
  8630. // Remove the finished clip
  8631. for (var i = 0; i < len;) {
  8632. if (clips[i]._needsRemove) {
  8633. clips[i] = clips[len - 1];
  8634. clips.pop();
  8635. len--;
  8636. }
  8637. else {
  8638. i++;
  8639. }
  8640. }
  8641. len = deferredEvents.length;
  8642. for (var i = 0; i < len; i++) {
  8643. deferredClips[i].fire(deferredEvents[i]);
  8644. }
  8645. this._time = time;
  8646. this.onframe(delta);
  8647. // 'frame' should be triggered before stage, because upper application
  8648. // depends on the sequence (e.g., echarts-stream and finish
  8649. // event judge)
  8650. this.trigger('frame', delta);
  8651. if (this.stage.update) {
  8652. this.stage.update();
  8653. }
  8654. },
  8655. _startLoop: function () {
  8656. var self = this;
  8657. this._running = true;
  8658. function step() {
  8659. if (self._running) {
  8660. requestAnimationFrame(step);
  8661. !self._paused && self._update();
  8662. }
  8663. }
  8664. requestAnimationFrame(step);
  8665. },
  8666. /**
  8667. * Start animation.
  8668. */
  8669. start: function () {
  8670. this._time = new Date().getTime();
  8671. this._pausedTime = 0;
  8672. this._startLoop();
  8673. },
  8674. /**
  8675. * Stop animation.
  8676. */
  8677. stop: function () {
  8678. this._running = false;
  8679. },
  8680. /**
  8681. * Pause animation.
  8682. */
  8683. pause: function () {
  8684. if (!this._paused) {
  8685. this._pauseStart = new Date().getTime();
  8686. this._paused = true;
  8687. }
  8688. },
  8689. /**
  8690. * Resume animation.
  8691. */
  8692. resume: function () {
  8693. if (this._paused) {
  8694. this._pausedTime += (new Date().getTime()) - this._pauseStart;
  8695. this._paused = false;
  8696. }
  8697. },
  8698. /**
  8699. * Clear animation.
  8700. */
  8701. clear: function () {
  8702. this._clips = [];
  8703. },
  8704. /**
  8705. * Whether animation finished.
  8706. */
  8707. isFinished: function () {
  8708. return !this._clips.length;
  8709. },
  8710. /**
  8711. * Creat animator for a target, whose props can be animated.
  8712. *
  8713. * @param {Object} target
  8714. * @param {Object} options
  8715. * @param {boolean} [options.loop=false] Whether loop animation.
  8716. * @param {Function} [options.getter=null] Get value from target.
  8717. * @param {Function} [options.setter=null] Set value to target.
  8718. * @return {module:zrender/animation/Animation~Animator}
  8719. */
  8720. // TODO Gap
  8721. animate: function (target, options) {
  8722. options = options || {};
  8723. var animator = new Animator(
  8724. target,
  8725. options.loop,
  8726. options.getter,
  8727. options.setter
  8728. );
  8729. this.addAnimator(animator);
  8730. return animator;
  8731. }
  8732. };
  8733. mixin(Animation, Eventful);
  8734. /**
  8735. * Only implements needed gestures for mobile.
  8736. */
  8737. var GestureMgr = function () {
  8738. /**
  8739. * @private
  8740. * @type {Array.<Object>}
  8741. */
  8742. this._track = [];
  8743. };
  8744. GestureMgr.prototype = {
  8745. constructor: GestureMgr,
  8746. recognize: function (event, target, root) {
  8747. this._doTrack(event, target, root);
  8748. return this._recognize(event);
  8749. },
  8750. clear: function () {
  8751. this._track.length = 0;
  8752. return this;
  8753. },
  8754. _doTrack: function (event, target, root) {
  8755. var touches = event.touches;
  8756. if (!touches) {
  8757. return;
  8758. }
  8759. var trackItem = {
  8760. points: [],
  8761. touches: [],
  8762. target: target,
  8763. event: event
  8764. };
  8765. for (var i = 0, len = touches.length; i < len; i++) {
  8766. var touch = touches[i];
  8767. var pos = clientToLocal(root, touch, {});
  8768. trackItem.points.push([pos.zrX, pos.zrY]);
  8769. trackItem.touches.push(touch);
  8770. }
  8771. this._track.push(trackItem);
  8772. },
  8773. _recognize: function (event) {
  8774. for (var eventName in recognizers) {
  8775. if (recognizers.hasOwnProperty(eventName)) {
  8776. var gestureInfo = recognizers[eventName](this._track, event);
  8777. if (gestureInfo) {
  8778. return gestureInfo;
  8779. }
  8780. }
  8781. }
  8782. }
  8783. };
  8784. function dist$1(pointPair) {
  8785. var dx = pointPair[1][0] - pointPair[0][0];
  8786. var dy = pointPair[1][1] - pointPair[0][1];
  8787. return Math.sqrt(dx * dx + dy * dy);
  8788. }
  8789. function center(pointPair) {
  8790. return [
  8791. (pointPair[0][0] + pointPair[1][0]) / 2,
  8792. (pointPair[0][1] + pointPair[1][1]) / 2
  8793. ];
  8794. }
  8795. var recognizers = {
  8796. pinch: function (track, event) {
  8797. var trackLen = track.length;
  8798. if (!trackLen) {
  8799. return;
  8800. }
  8801. var pinchEnd = (track[trackLen - 1] || {}).points;
  8802. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  8803. if (pinchPre
  8804. && pinchPre.length > 1
  8805. && pinchEnd
  8806. && pinchEnd.length > 1
  8807. ) {
  8808. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  8809. !isFinite(pinchScale) && (pinchScale = 1);
  8810. event.pinchScale = pinchScale;
  8811. var pinchCenter = center(pinchEnd);
  8812. event.pinchX = pinchCenter[0];
  8813. event.pinchY = pinchCenter[1];
  8814. return {
  8815. type: 'pinch',
  8816. target: track[0].target,
  8817. event: event
  8818. };
  8819. }
  8820. }
  8821. // Only pinch currently.
  8822. };
  8823. var TOUCH_CLICK_DELAY = 300;
  8824. var mouseHandlerNames = [
  8825. 'click', 'dblclick', 'mousewheel', 'mouseout',
  8826. 'mouseup', 'mousedown', 'mousemove', 'contextmenu'
  8827. ];
  8828. var touchHandlerNames = [
  8829. 'touchstart', 'touchend', 'touchmove'
  8830. ];
  8831. var pointerEventNames = {
  8832. pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1
  8833. };
  8834. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8835. var nm = name.replace('mouse', 'pointer');
  8836. return pointerEventNames[nm] ? nm : name;
  8837. });
  8838. function eventNameFix(name) {
  8839. return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name;
  8840. }
  8841. function processGesture(proxy, event, stage) {
  8842. var gestureMgr = proxy._gestureMgr;
  8843. stage === 'start' && gestureMgr.clear();
  8844. var gestureInfo = gestureMgr.recognize(
  8845. event,
  8846. proxy.handler.findHover(event.zrX, event.zrY, null).target,
  8847. proxy.dom
  8848. );
  8849. stage === 'end' && gestureMgr.clear();
  8850. // Do not do any preventDefault here. Upper application do that if necessary.
  8851. if (gestureInfo) {
  8852. var type = gestureInfo.type;
  8853. event.gestureEvent = type;
  8854. proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event);
  8855. }
  8856. }
  8857. // function onMSGestureChange(proxy, event) {
  8858. // if (event.translationX || event.translationY) {
  8859. // // mousemove is carried by MSGesture to reduce the sensitivity.
  8860. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  8861. // }
  8862. // if (event.scale !== 1) {
  8863. // event.pinchX = event.offsetX;
  8864. // event.pinchY = event.offsetY;
  8865. // event.pinchScale = event.scale;
  8866. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  8867. // }
  8868. // }
  8869. /**
  8870. * Prevent mouse event from being dispatched after Touch Events action
  8871. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  8872. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  8873. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  8874. * Result: Blocking Mouse Events for 700ms.
  8875. */
  8876. function setTouchTimer(instance) {
  8877. instance._touching = true;
  8878. clearTimeout(instance._touchTimer);
  8879. instance._touchTimer = setTimeout(function () {
  8880. instance._touching = false;
  8881. }, 700);
  8882. }
  8883. var domHandlers = {
  8884. /**
  8885. * Mouse move handler
  8886. * @inner
  8887. * @param {Event} event
  8888. */
  8889. mousemove: function (event) {
  8890. event = normalizeEvent(this.dom, event);
  8891. this.trigger('mousemove', event);
  8892. },
  8893. /**
  8894. * Mouse out handler
  8895. * @inner
  8896. * @param {Event} event
  8897. */
  8898. mouseout: function (event) {
  8899. event = normalizeEvent(this.dom, event);
  8900. var element = event.toElement || event.relatedTarget;
  8901. if (element != this.dom) {
  8902. while (element && element.nodeType != 9) {
  8903. // 忽略包含在root中的dom引起的mouseOut
  8904. if (element === this.dom) {
  8905. return;
  8906. }
  8907. element = element.parentNode;
  8908. }
  8909. }
  8910. this.trigger('mouseout', event);
  8911. },
  8912. /**
  8913. * Touch开始响应函数
  8914. * @inner
  8915. * @param {Event} event
  8916. */
  8917. touchstart: function (event) {
  8918. // Default mouse behaviour should not be disabled here.
  8919. // For example, page may needs to be slided.
  8920. event = normalizeEvent(this.dom, event);
  8921. // Mark touch, which is useful in distinguish touch and
  8922. // mouse event in upper applicatoin.
  8923. event.zrByTouch = true;
  8924. this._lastTouchMoment = new Date();
  8925. processGesture(this, event, 'start');
  8926. // In touch device, trigger `mousemove`(`mouseover`) should
  8927. // be triggered, and must before `mousedown` triggered.
  8928. domHandlers.mousemove.call(this, event);
  8929. domHandlers.mousedown.call(this, event);
  8930. setTouchTimer(this);
  8931. },
  8932. /**
  8933. * Touch移动响应函数
  8934. * @inner
  8935. * @param {Event} event
  8936. */
  8937. touchmove: function (event) {
  8938. event = normalizeEvent(this.dom, event);
  8939. // Mark touch, which is useful in distinguish touch and
  8940. // mouse event in upper applicatoin.
  8941. event.zrByTouch = true;
  8942. processGesture(this, event, 'change');
  8943. // Mouse move should always be triggered no matter whether
  8944. // there is gestrue event, because mouse move and pinch may
  8945. // be used at the same time.
  8946. domHandlers.mousemove.call(this, event);
  8947. setTouchTimer(this);
  8948. },
  8949. /**
  8950. * Touch结束响应函数
  8951. * @inner
  8952. * @param {Event} event
  8953. */
  8954. touchend: function (event) {
  8955. event = normalizeEvent(this.dom, event);
  8956. // Mark touch, which is useful in distinguish touch and
  8957. // mouse event in upper applicatoin.
  8958. event.zrByTouch = true;
  8959. processGesture(this, event, 'end');
  8960. domHandlers.mouseup.call(this, event);
  8961. // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  8962. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  8963. // we can conveniently implement "hover style" in both PC and touch device just
  8964. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  8965. // to remove "hover style" on an element, without any additional code for
  8966. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  8967. // style" will remain for user view)
  8968. // click event should always be triggered no matter whether
  8969. // there is gestrue event. System click can not be prevented.
  8970. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  8971. domHandlers.click.call(this, event);
  8972. }
  8973. setTouchTimer(this);
  8974. },
  8975. pointerdown: function (event) {
  8976. domHandlers.mousedown.call(this, event);
  8977. // if (useMSGuesture(this, event)) {
  8978. // this._msGesture.addPointer(event.pointerId);
  8979. // }
  8980. },
  8981. pointermove: function (event) {
  8982. // FIXME
  8983. // pointermove is so sensitive that it always triggered when
  8984. // tap(click) on touch screen, which affect some judgement in
  8985. // upper application. So, we dont support mousemove on MS touch
  8986. // device yet.
  8987. if (!isPointerFromTouch(event)) {
  8988. domHandlers.mousemove.call(this, event);
  8989. }
  8990. },
  8991. pointerup: function (event) {
  8992. domHandlers.mouseup.call(this, event);
  8993. },
  8994. pointerout: function (event) {
  8995. // pointerout will be triggered when tap on touch screen
  8996. // (IE11+/Edge on MS Surface) after click event triggered,
  8997. // which is inconsistent with the mousout behavior we defined
  8998. // in touchend. So we unify them.
  8999. // (check domHandlers.touchend for detailed explanation)
  9000. if (!isPointerFromTouch(event)) {
  9001. domHandlers.mouseout.call(this, event);
  9002. }
  9003. }
  9004. };
  9005. function isPointerFromTouch(event) {
  9006. var pointerType = event.pointerType;
  9007. return pointerType === 'pen' || pointerType === 'touch';
  9008. }
  9009. // function useMSGuesture(handlerProxy, event) {
  9010. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9011. // }
  9012. // Common handlers
  9013. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9014. domHandlers[name] = function (event) {
  9015. event = normalizeEvent(this.dom, event);
  9016. this.trigger(name, event);
  9017. };
  9018. });
  9019. /**
  9020. * 为控制类实例初始化dom 事件处理函数
  9021. *
  9022. * @inner
  9023. * @param {module:zrender/Handler} instance 控制类实例
  9024. */
  9025. function initDomHandler(instance) {
  9026. each$1(touchHandlerNames, function (name) {
  9027. instance._handlers[name] = bind(domHandlers[name], instance);
  9028. });
  9029. each$1(pointerHandlerNames, function (name) {
  9030. instance._handlers[name] = bind(domHandlers[name], instance);
  9031. });
  9032. each$1(mouseHandlerNames, function (name) {
  9033. instance._handlers[name] = makeMouseHandler(domHandlers[name], instance);
  9034. });
  9035. function makeMouseHandler(fn, instance) {
  9036. return function () {
  9037. if (instance._touching) {
  9038. return;
  9039. }
  9040. return fn.apply(instance, arguments);
  9041. };
  9042. }
  9043. }
  9044. function HandlerDomProxy(dom) {
  9045. Eventful.call(this);
  9046. this.dom = dom;
  9047. /**
  9048. * @private
  9049. * @type {boolean}
  9050. */
  9051. this._touching = false;
  9052. /**
  9053. * @private
  9054. * @type {number}
  9055. */
  9056. this._touchTimer;
  9057. /**
  9058. * @private
  9059. * @type {module:zrender/core/GestureMgr}
  9060. */
  9061. this._gestureMgr = new GestureMgr();
  9062. this._handlers = {};
  9063. initDomHandler(this);
  9064. if (env$1.pointerEventsSupported) { // Only IE11+/Edge
  9065. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9066. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9067. // at the same time.
  9068. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9069. // screen, which do not occurs in pointer event.
  9070. // So we use pointer event to both detect touch gesture and mouse behavior.
  9071. mountHandlers(pointerHandlerNames, this);
  9072. // FIXME
  9073. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9074. // which does not prevent defuault behavior occasionally (which may cause view port
  9075. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9076. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9077. // touch screen. And we only support click behavior on MS touch screen now.
  9078. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9079. // We dont support touch on IE on win7.
  9080. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9081. // if (typeof MSGesture === 'function') {
  9082. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9083. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9084. // }
  9085. }
  9086. else {
  9087. if (env$1.touchEventsSupported) {
  9088. mountHandlers(touchHandlerNames, this);
  9089. // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9090. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9091. }
  9092. // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9093. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9094. // mouse event can not be handle in those devices.
  9095. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9096. // mouseevent after touch event triggered, see `setTouchTimer`.
  9097. mountHandlers(mouseHandlerNames, this);
  9098. }
  9099. function mountHandlers(handlerNames, instance) {
  9100. each$1(handlerNames, function (name) {
  9101. addEventListener(dom, eventNameFix(name), instance._handlers[name]);
  9102. }, instance);
  9103. }
  9104. }
  9105. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9106. handlerDomProxyProto.dispose = function () {
  9107. var handlerNames = mouseHandlerNames.concat(touchHandlerNames);
  9108. for (var i = 0; i < handlerNames.length; i++) {
  9109. var name = handlerNames[i];
  9110. removeEventListener(this.dom, eventNameFix(name), this._handlers[name]);
  9111. }
  9112. };
  9113. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9114. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9115. };
  9116. mixin(HandlerDomProxy, Eventful);
  9117. /*!
  9118. * ZRender, a high performance 2d drawing library.
  9119. *
  9120. * Copyright (c) 2013, Baidu Inc.
  9121. * All rights reserved.
  9122. *
  9123. * LICENSE
  9124. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9125. */
  9126. var useVML = !env$1.canvasSupported;
  9127. var painterCtors = {
  9128. canvas: Painter
  9129. };
  9130. var instances$1 = {}; // ZRender实例map索引
  9131. /**
  9132. * @type {string}
  9133. */
  9134. var version$1 = '4.0.4';
  9135. /**
  9136. * Initializing a zrender instance
  9137. * @param {HTMLElement} dom
  9138. * @param {Object} opts
  9139. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9140. * @param {number} [opts.devicePixelRatio]
  9141. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9142. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9143. * @return {module:zrender/ZRender}
  9144. */
  9145. function init$1(dom, opts) {
  9146. var zr = new ZRender(guid(), dom, opts);
  9147. instances$1[zr.id] = zr;
  9148. return zr;
  9149. }
  9150. /**
  9151. * Dispose zrender instance
  9152. * @param {module:zrender/ZRender} zr
  9153. */
  9154. function dispose$1(zr) {
  9155. if (zr) {
  9156. zr.dispose();
  9157. }
  9158. else {
  9159. for (var key in instances$1) {
  9160. if (instances$1.hasOwnProperty(key)) {
  9161. instances$1[key].dispose();
  9162. }
  9163. }
  9164. instances$1 = {};
  9165. }
  9166. return this;
  9167. }
  9168. /**
  9169. * Get zrender instance by id
  9170. * @param {string} id zrender instance id
  9171. * @return {module:zrender/ZRender}
  9172. */
  9173. function getInstance(id) {
  9174. return instances$1[id];
  9175. }
  9176. function registerPainter(name, Ctor) {
  9177. painterCtors[name] = Ctor;
  9178. }
  9179. function delInstance(id) {
  9180. delete instances$1[id];
  9181. }
  9182. /**
  9183. * @module zrender/ZRender
  9184. */
  9185. /**
  9186. * @constructor
  9187. * @alias module:zrender/ZRender
  9188. * @param {string} id
  9189. * @param {HTMLElement} dom
  9190. * @param {Object} opts
  9191. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9192. * @param {number} [opts.devicePixelRatio]
  9193. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9194. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9195. */
  9196. var ZRender = function (id, dom, opts) {
  9197. opts = opts || {};
  9198. /**
  9199. * @type {HTMLDomElement}
  9200. */
  9201. this.dom = dom;
  9202. /**
  9203. * @type {string}
  9204. */
  9205. this.id = id;
  9206. var self = this;
  9207. var storage = new Storage();
  9208. var rendererType = opts.renderer;
  9209. // TODO WebGL
  9210. if (useVML) {
  9211. if (!painterCtors.vml) {
  9212. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9213. }
  9214. rendererType = 'vml';
  9215. }
  9216. else if (!rendererType || !painterCtors[rendererType]) {
  9217. rendererType = 'canvas';
  9218. }
  9219. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9220. this.storage = storage;
  9221. this.painter = painter;
  9222. var handerProxy = (!env$1.node && !env$1.worker) ? new HandlerDomProxy(painter.getViewportRoot()) : null;
  9223. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9224. /**
  9225. * @type {module:zrender/animation/Animation}
  9226. */
  9227. this.animation = new Animation({
  9228. stage: {
  9229. update: bind(this.flush, this)
  9230. }
  9231. });
  9232. this.animation.start();
  9233. /**
  9234. * @type {boolean}
  9235. * @private
  9236. */
  9237. this._needsRefresh;
  9238. // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9239. // FIXME 有点ugly
  9240. var oldDelFromStorage = storage.delFromStorage;
  9241. var oldAddToStorage = storage.addToStorage;
  9242. storage.delFromStorage = function (el) {
  9243. oldDelFromStorage.call(storage, el);
  9244. el && el.removeSelfFromZr(self);
  9245. };
  9246. storage.addToStorage = function (el) {
  9247. oldAddToStorage.call(storage, el);
  9248. el.addSelfToZr(self);
  9249. };
  9250. };
  9251. ZRender.prototype = {
  9252. constructor: ZRender,
  9253. /**
  9254. * 获取实例唯一标识
  9255. * @return {string}
  9256. */
  9257. getId: function () {
  9258. return this.id;
  9259. },
  9260. /**
  9261. * 添加元素
  9262. * @param {module:zrender/Element} el
  9263. */
  9264. add: function (el) {
  9265. this.storage.addRoot(el);
  9266. this._needsRefresh = true;
  9267. },
  9268. /**
  9269. * 删除元素
  9270. * @param {module:zrender/Element} el
  9271. */
  9272. remove: function (el) {
  9273. this.storage.delRoot(el);
  9274. this._needsRefresh = true;
  9275. },
  9276. /**
  9277. * Change configuration of layer
  9278. * @param {string} zLevel
  9279. * @param {Object} config
  9280. * @param {string} [config.clearColor=0] Clear color
  9281. * @param {string} [config.motionBlur=false] If enable motion blur
  9282. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9283. */
  9284. configLayer: function (zLevel, config) {
  9285. if (this.painter.configLayer) {
  9286. this.painter.configLayer(zLevel, config);
  9287. }
  9288. this._needsRefresh = true;
  9289. },
  9290. /**
  9291. * Set background color
  9292. * @param {string} backgroundColor
  9293. */
  9294. setBackgroundColor: function (backgroundColor) {
  9295. if (this.painter.setBackgroundColor) {
  9296. this.painter.setBackgroundColor(backgroundColor);
  9297. }
  9298. this._needsRefresh = true;
  9299. },
  9300. /**
  9301. * Repaint the canvas immediately
  9302. */
  9303. refreshImmediately: function () {
  9304. // var start = new Date();
  9305. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9306. // Or it will cause zrender refreshes again and again.
  9307. this._needsRefresh = false;
  9308. this.painter.refresh();
  9309. /**
  9310. * Avoid trigger zr.refresh in Element#beforeUpdate hook
  9311. */
  9312. this._needsRefresh = false;
  9313. // var end = new Date();
  9314. // var log = document.getElementById('log');
  9315. // if (log) {
  9316. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9317. // }
  9318. },
  9319. /**
  9320. * Mark and repaint the canvas in the next frame of browser
  9321. */
  9322. refresh: function() {
  9323. this._needsRefresh = true;
  9324. },
  9325. /**
  9326. * Perform all refresh
  9327. */
  9328. flush: function () {
  9329. var triggerRendered;
  9330. if (this._needsRefresh) {
  9331. triggerRendered = true;
  9332. this.refreshImmediately();
  9333. }
  9334. if (this._needsRefreshHover) {
  9335. triggerRendered = true;
  9336. this.refreshHoverImmediately();
  9337. }
  9338. triggerRendered && this.trigger('rendered');
  9339. },
  9340. /**
  9341. * Add element to hover layer
  9342. * @param {module:zrender/Element} el
  9343. * @param {Object} style
  9344. */
  9345. addHover: function (el, style) {
  9346. if (this.painter.addHover) {
  9347. this.painter.addHover(el, style);
  9348. this.refreshHover();
  9349. }
  9350. },
  9351. /**
  9352. * Add element from hover layer
  9353. * @param {module:zrender/Element} el
  9354. */
  9355. removeHover: function (el) {
  9356. if (this.painter.removeHover) {
  9357. this.painter.removeHover(el);
  9358. this.refreshHover();
  9359. }
  9360. },
  9361. /**
  9362. * Clear all hover elements in hover layer
  9363. * @param {module:zrender/Element} el
  9364. */
  9365. clearHover: function () {
  9366. if (this.painter.clearHover) {
  9367. this.painter.clearHover();
  9368. this.refreshHover();
  9369. }
  9370. },
  9371. /**
  9372. * Refresh hover in next frame
  9373. */
  9374. refreshHover: function () {
  9375. this._needsRefreshHover = true;
  9376. },
  9377. /**
  9378. * Refresh hover immediately
  9379. */
  9380. refreshHoverImmediately: function () {
  9381. this._needsRefreshHover = false;
  9382. this.painter.refreshHover && this.painter.refreshHover();
  9383. },
  9384. /**
  9385. * Resize the canvas.
  9386. * Should be invoked when container size is changed
  9387. * @param {Object} [opts]
  9388. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9389. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9390. */
  9391. resize: function(opts) {
  9392. opts = opts || {};
  9393. this.painter.resize(opts.width, opts.height);
  9394. this.handler.resize();
  9395. },
  9396. /**
  9397. * Stop and clear all animation immediately
  9398. */
  9399. clearAnimation: function () {
  9400. this.animation.clear();
  9401. },
  9402. /**
  9403. * Get container width
  9404. */
  9405. getWidth: function() {
  9406. return this.painter.getWidth();
  9407. },
  9408. /**
  9409. * Get container height
  9410. */
  9411. getHeight: function() {
  9412. return this.painter.getHeight();
  9413. },
  9414. /**
  9415. * Export the canvas as Base64 URL
  9416. * @param {string} type
  9417. * @param {string} [backgroundColor='#fff']
  9418. * @return {string} Base64 URL
  9419. */
  9420. // toDataURL: function(type, backgroundColor) {
  9421. // return this.painter.getRenderedCanvas({
  9422. // backgroundColor: backgroundColor
  9423. // }).toDataURL(type);
  9424. // },
  9425. /**
  9426. * Converting a path to image.
  9427. * It has much better performance of drawing image rather than drawing a vector path.
  9428. * @param {module:zrender/graphic/Path} e
  9429. * @param {number} width
  9430. * @param {number} height
  9431. */
  9432. pathToImage: function(e, dpr) {
  9433. return this.painter.pathToImage(e, dpr);
  9434. },
  9435. /**
  9436. * Set default cursor
  9437. * @param {string} [cursorStyle='default'] 例如 crosshair
  9438. */
  9439. setCursorStyle: function (cursorStyle) {
  9440. this.handler.setCursorStyle(cursorStyle);
  9441. },
  9442. /**
  9443. * Find hovered element
  9444. * @param {number} x
  9445. * @param {number} y
  9446. * @return {Object} {target, topTarget}
  9447. */
  9448. findHover: function (x, y) {
  9449. return this.handler.findHover(x, y);
  9450. },
  9451. /**
  9452. * Bind event
  9453. *
  9454. * @param {string} eventName Event name
  9455. * @param {Function} eventHandler Handler function
  9456. * @param {Object} [context] Context object
  9457. */
  9458. on: function(eventName, eventHandler, context) {
  9459. this.handler.on(eventName, eventHandler, context);
  9460. },
  9461. /**
  9462. * Unbind event
  9463. * @param {string} eventName Event name
  9464. * @param {Function} [eventHandler] Handler function
  9465. */
  9466. off: function(eventName, eventHandler) {
  9467. this.handler.off(eventName, eventHandler);
  9468. },
  9469. /**
  9470. * Trigger event manually
  9471. *
  9472. * @param {string} eventName Event name
  9473. * @param {event=} event Event object
  9474. */
  9475. trigger: function (eventName, event) {
  9476. this.handler.trigger(eventName, event);
  9477. },
  9478. /**
  9479. * Clear all objects and the canvas.
  9480. */
  9481. clear: function () {
  9482. this.storage.delRoot();
  9483. this.painter.clear();
  9484. },
  9485. /**
  9486. * Dispose self.
  9487. */
  9488. dispose: function () {
  9489. this.animation.stop();
  9490. this.clear();
  9491. this.storage.dispose();
  9492. this.painter.dispose();
  9493. this.handler.dispose();
  9494. this.animation =
  9495. this.storage =
  9496. this.painter =
  9497. this.handler = null;
  9498. delInstance(this.id);
  9499. }
  9500. };
  9501. var zrender = (Object.freeze || Object)({
  9502. version: version$1,
  9503. init: init$1,
  9504. dispose: dispose$1,
  9505. getInstance: getInstance,
  9506. registerPainter: registerPainter
  9507. });
  9508. /*
  9509. * Licensed to the Apache Software Foundation (ASF) under one
  9510. * or more contributor license agreements. See the NOTICE file
  9511. * distributed with this work for additional information
  9512. * regarding copyright ownership. The ASF licenses this file
  9513. * to you under the Apache License, Version 2.0 (the
  9514. * "License"); you may not use this file except in compliance
  9515. * with the License. You may obtain a copy of the License at
  9516. *
  9517. * http://www.apache.org/licenses/LICENSE-2.0
  9518. *
  9519. * Unless required by applicable law or agreed to in writing,
  9520. * software distributed under the License is distributed on an
  9521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9522. * KIND, either express or implied. See the License for the
  9523. * specific language governing permissions and limitations
  9524. * under the License.
  9525. */
  9526. var each$2 = each$1;
  9527. var isObject$2 = isObject$1;
  9528. var isArray$1 = isArray;
  9529. /**
  9530. * Make the name displayable. But we should
  9531. * make sure it is not duplicated with user
  9532. * specified name, so use '\0';
  9533. */
  9534. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9535. /**
  9536. * If value is not array, then translate it to array.
  9537. * @param {*} value
  9538. * @return {Array} [value] or value
  9539. */
  9540. function normalizeToArray(value) {
  9541. return value instanceof Array
  9542. ? value
  9543. : value == null
  9544. ? []
  9545. : [value];
  9546. }
  9547. /**
  9548. * Sync default option between normal and emphasis like `position` and `show`
  9549. * In case some one will write code like
  9550. * label: {
  9551. * show: false,
  9552. * position: 'outside',
  9553. * fontSize: 18
  9554. * },
  9555. * emphasis: {
  9556. * label: { show: true }
  9557. * }
  9558. * @param {Object} opt
  9559. * @param {string} key
  9560. * @param {Array.<string>} subOpts
  9561. */
  9562. function defaultEmphasis(opt, key, subOpts) {
  9563. // Caution: performance sensitive.
  9564. if (opt) {
  9565. opt[key] = opt[key] || {};
  9566. opt.emphasis = opt.emphasis || {};
  9567. opt.emphasis[key] = opt.emphasis[key] || {};
  9568. // Default emphasis option from normal
  9569. for (var i = 0, len = subOpts.length; i < len; i++) {
  9570. var subOptName = subOpts[i];
  9571. if (!opt.emphasis[key].hasOwnProperty(subOptName)
  9572. && opt[key].hasOwnProperty(subOptName)
  9573. ) {
  9574. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9575. }
  9576. }
  9577. }
  9578. }
  9579. var TEXT_STYLE_OPTIONS = [
  9580. 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9581. 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth',
  9582. 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline',
  9583. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY',
  9584. 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY',
  9585. 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding'
  9586. ];
  9587. // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9588. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9589. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9590. // // FIXME: deprecated, check and remove it.
  9591. // 'textStyle'
  9592. // ]);
  9593. /**
  9594. * The method do not ensure performance.
  9595. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9596. * This helper method retieves value from data.
  9597. * @param {string|number|Date|Array|Object} dataItem
  9598. * @return {number|string|Date|Array.<number|string|Date>}
  9599. */
  9600. function getDataItemValue(dataItem) {
  9601. return (isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date))
  9602. ? dataItem.value : dataItem;
  9603. }
  9604. /**
  9605. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9606. * This helper method determine if dataItem has extra option besides value
  9607. * @param {string|number|Date|Array|Object} dataItem
  9608. */
  9609. function isDataItemOption(dataItem) {
  9610. return isObject$2(dataItem)
  9611. && !(dataItem instanceof Array);
  9612. // // markLine data can be array
  9613. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9614. }
  9615. /**
  9616. * Mapping to exists for merge.
  9617. *
  9618. * @public
  9619. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9620. * @param {Object|Array.<Object>} newCptOptions
  9621. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9622. * index of which is the same as exists.
  9623. */
  9624. function mappingToExists(exists, newCptOptions) {
  9625. // Mapping by the order by original option (but not order of
  9626. // new option) in merge mode. Because we should ensure
  9627. // some specified index (like xAxisIndex) is consistent with
  9628. // original option, which is easy to understand, espatially in
  9629. // media query. And in most case, merge option is used to
  9630. // update partial option but not be expected to change order.
  9631. newCptOptions = (newCptOptions || []).slice();
  9632. var result = map(exists || [], function (obj, index) {
  9633. return {exist: obj};
  9634. });
  9635. // Mapping by id or name if specified.
  9636. each$2(newCptOptions, function (cptOption, index) {
  9637. if (!isObject$2(cptOption)) {
  9638. return;
  9639. }
  9640. // id has highest priority.
  9641. for (var i = 0; i < result.length; i++) {
  9642. if (!result[i].option // Consider name: two map to one.
  9643. && cptOption.id != null
  9644. && result[i].exist.id === cptOption.id + ''
  9645. ) {
  9646. result[i].option = cptOption;
  9647. newCptOptions[index] = null;
  9648. return;
  9649. }
  9650. }
  9651. for (var i = 0; i < result.length; i++) {
  9652. var exist = result[i].exist;
  9653. if (!result[i].option // Consider name: two map to one.
  9654. // Can not match when both ids exist but different.
  9655. && (exist.id == null || cptOption.id == null)
  9656. && cptOption.name != null
  9657. && !isIdInner(cptOption)
  9658. && !isIdInner(exist)
  9659. && exist.name === cptOption.name + ''
  9660. ) {
  9661. result[i].option = cptOption;
  9662. newCptOptions[index] = null;
  9663. return;
  9664. }
  9665. }
  9666. });
  9667. // Otherwise mapping by index.
  9668. each$2(newCptOptions, function (cptOption, index) {
  9669. if (!isObject$2(cptOption)) {
  9670. return;
  9671. }
  9672. var i = 0;
  9673. for (; i < result.length; i++) {
  9674. var exist = result[i].exist;
  9675. if (!result[i].option
  9676. // Existing model that already has id should be able to
  9677. // mapped to (because after mapping performed model may
  9678. // be assigned with a id, whish should not affect next
  9679. // mapping), except those has inner id.
  9680. && !isIdInner(exist)
  9681. // Caution:
  9682. // Do not overwrite id. But name can be overwritten,
  9683. // because axis use name as 'show label text'.
  9684. // 'exist' always has id and name and we dont
  9685. // need to check it.
  9686. && cptOption.id == null
  9687. ) {
  9688. result[i].option = cptOption;
  9689. break;
  9690. }
  9691. }
  9692. if (i >= result.length) {
  9693. result.push({option: cptOption});
  9694. }
  9695. });
  9696. return result;
  9697. }
  9698. /**
  9699. * Make id and name for mapping result (result of mappingToExists)
  9700. * into `keyInfo` field.
  9701. *
  9702. * @public
  9703. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9704. * which order is the same as exists.
  9705. * @return {Array.<Object>} The input.
  9706. */
  9707. function makeIdAndName(mapResult) {
  9708. // We use this id to hash component models and view instances
  9709. // in echarts. id can be specified by user, or auto generated.
  9710. // The id generation rule ensures new view instance are able
  9711. // to mapped to old instance when setOption are called in
  9712. // no-merge mode. So we generate model id by name and plus
  9713. // type in view id.
  9714. // name can be duplicated among components, which is convenient
  9715. // to specify multi components (like series) by one name.
  9716. // Ensure that each id is distinct.
  9717. var idMap = createHashMap();
  9718. each$2(mapResult, function (item, index) {
  9719. var existCpt = item.exist;
  9720. existCpt && idMap.set(existCpt.id, item);
  9721. });
  9722. each$2(mapResult, function (item, index) {
  9723. var opt = item.option;
  9724. assert$1(
  9725. !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item,
  9726. 'id duplicates: ' + (opt && opt.id)
  9727. );
  9728. opt && opt.id != null && idMap.set(opt.id, item);
  9729. !item.keyInfo && (item.keyInfo = {});
  9730. });
  9731. // Make name and id.
  9732. each$2(mapResult, function (item, index) {
  9733. var existCpt = item.exist;
  9734. var opt = item.option;
  9735. var keyInfo = item.keyInfo;
  9736. if (!isObject$2(opt)) {
  9737. return;
  9738. }
  9739. // name can be overwitten. Consider case: axis.name = '20km'.
  9740. // But id generated by name will not be changed, which affect
  9741. // only in that case: setOption with 'not merge mode' and view
  9742. // instance will be recreated, which can be accepted.
  9743. keyInfo.name = opt.name != null
  9744. ? opt.name + ''
  9745. : existCpt
  9746. ? existCpt.name
  9747. // Avoid diffferent series has the same name,
  9748. // because name may be used like in color pallet.
  9749. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9750. if (existCpt) {
  9751. keyInfo.id = existCpt.id;
  9752. }
  9753. else if (opt.id != null) {
  9754. keyInfo.id = opt.id + '';
  9755. }
  9756. else {
  9757. // Consider this situatoin:
  9758. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9759. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9760. // Series with the same name between optionA and optionB
  9761. // should be mapped.
  9762. var idNum = 0;
  9763. do {
  9764. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9765. }
  9766. while (idMap.get(keyInfo.id));
  9767. }
  9768. idMap.set(keyInfo.id, item);
  9769. });
  9770. }
  9771. function isNameSpecified(componentModel) {
  9772. var name = componentModel.name;
  9773. // Is specified when `indexOf` get -1 or > 0.
  9774. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  9775. }
  9776. /**
  9777. * @public
  9778. * @param {Object} cptOption
  9779. * @return {boolean}
  9780. */
  9781. function isIdInner(cptOption) {
  9782. return isObject$2(cptOption)
  9783. && cptOption.id
  9784. && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  9785. }
  9786. /**
  9787. * A helper for removing duplicate items between batchA and batchB,
  9788. * and in themselves, and categorize by series.
  9789. *
  9790. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9791. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  9792. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  9793. */
  9794. function compressBatches(batchA, batchB) {
  9795. var mapA = {};
  9796. var mapB = {};
  9797. makeMap(batchA || [], mapA);
  9798. makeMap(batchB || [], mapB, mapA);
  9799. return [mapToArray(mapA), mapToArray(mapB)];
  9800. function makeMap(sourceBatch, map$$1, otherMap) {
  9801. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  9802. var seriesId = sourceBatch[i].seriesId;
  9803. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  9804. var otherDataIndices = otherMap && otherMap[seriesId];
  9805. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  9806. var dataIndex = dataIndices[j];
  9807. if (otherDataIndices && otherDataIndices[dataIndex]) {
  9808. otherDataIndices[dataIndex] = null;
  9809. }
  9810. else {
  9811. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  9812. }
  9813. }
  9814. }
  9815. }
  9816. function mapToArray(map$$1, isData) {
  9817. var result = [];
  9818. for (var i in map$$1) {
  9819. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  9820. if (isData) {
  9821. result.push(+i);
  9822. }
  9823. else {
  9824. var dataIndices = mapToArray(map$$1[i], true);
  9825. dataIndices.length && result.push({seriesId: i, dataIndex: dataIndices});
  9826. }
  9827. }
  9828. }
  9829. return result;
  9830. }
  9831. }
  9832. /**
  9833. * @param {module:echarts/data/List} data
  9834. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  9835. * each of which can be Array or primary type.
  9836. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  9837. */
  9838. function queryDataIndex(data, payload) {
  9839. if (payload.dataIndexInside != null) {
  9840. return payload.dataIndexInside;
  9841. }
  9842. else if (payload.dataIndex != null) {
  9843. return isArray(payload.dataIndex)
  9844. ? map(payload.dataIndex, function (value) {
  9845. return data.indexOfRawIndex(value);
  9846. })
  9847. : data.indexOfRawIndex(payload.dataIndex);
  9848. }
  9849. else if (payload.name != null) {
  9850. return isArray(payload.name)
  9851. ? map(payload.name, function (value) {
  9852. return data.indexOfName(value);
  9853. })
  9854. : data.indexOfName(payload.name);
  9855. }
  9856. }
  9857. /**
  9858. * Enable property storage to any host object.
  9859. * Notice: Serialization is not supported.
  9860. *
  9861. * For example:
  9862. * var inner = zrUitl.makeInner();
  9863. *
  9864. * function some1(hostObj) {
  9865. * inner(hostObj).someProperty = 1212;
  9866. * ...
  9867. * }
  9868. * function some2() {
  9869. * var fields = inner(this);
  9870. * fields.someProperty1 = 1212;
  9871. * fields.someProperty2 = 'xx';
  9872. * ...
  9873. * }
  9874. *
  9875. * @return {Function}
  9876. */
  9877. function makeInner() {
  9878. // Consider different scope by es module import.
  9879. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  9880. return function (hostObj) {
  9881. return hostObj[key] || (hostObj[key] = {});
  9882. };
  9883. }
  9884. var innerUniqueIndex = 0;
  9885. /**
  9886. * @param {module:echarts/model/Global} ecModel
  9887. * @param {string|Object} finder
  9888. * If string, e.g., 'geo', means {geoIndex: 0}.
  9889. * If Object, could contain some of these properties below:
  9890. * {
  9891. * seriesIndex, seriesId, seriesName,
  9892. * geoIndex, geoId, geoName,
  9893. * bmapIndex, bmapId, bmapName,
  9894. * xAxisIndex, xAxisId, xAxisName,
  9895. * yAxisIndex, yAxisId, yAxisName,
  9896. * gridIndex, gridId, gridName,
  9897. * ... (can be extended)
  9898. * }
  9899. * Each properties can be number|string|Array.<number>|Array.<string>
  9900. * For example, a finder could be
  9901. * {
  9902. * seriesIndex: 3,
  9903. * geoId: ['aa', 'cc'],
  9904. * gridName: ['xx', 'rr']
  9905. * }
  9906. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  9907. * If nothing or null/undefined specified, return nothing.
  9908. * @param {Object} [opt]
  9909. * @param {string} [opt.defaultMainType]
  9910. * @param {Array.<string>} [opt.includeMainTypes]
  9911. * @return {Object} result like:
  9912. * {
  9913. * seriesModels: [seriesModel1, seriesModel2],
  9914. * seriesModel: seriesModel1, // The first model
  9915. * geoModels: [geoModel1, geoModel2],
  9916. * geoModel: geoModel1, // The first model
  9917. * ...
  9918. * }
  9919. */
  9920. function parseFinder(ecModel, finder, opt) {
  9921. if (isString(finder)) {
  9922. var obj = {};
  9923. obj[finder + 'Index'] = 0;
  9924. finder = obj;
  9925. }
  9926. var defaultMainType = opt && opt.defaultMainType;
  9927. if (defaultMainType
  9928. && !has(finder, defaultMainType + 'Index')
  9929. && !has(finder, defaultMainType + 'Id')
  9930. && !has(finder, defaultMainType + 'Name')
  9931. ) {
  9932. finder[defaultMainType + 'Index'] = 0;
  9933. }
  9934. var result = {};
  9935. each$2(finder, function (value, key) {
  9936. var value = finder[key];
  9937. // Exclude 'dataIndex' and other illgal keys.
  9938. if (key === 'dataIndex' || key === 'dataIndexInside') {
  9939. result[key] = value;
  9940. return;
  9941. }
  9942. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  9943. var mainType = parsedKey[1];
  9944. var queryType = (parsedKey[2] || '').toLowerCase();
  9945. if (!mainType
  9946. || !queryType
  9947. || value == null
  9948. || (queryType === 'index' && value === 'none')
  9949. || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0)
  9950. ) {
  9951. return;
  9952. }
  9953. var queryParam = {mainType: mainType};
  9954. if (queryType !== 'index' || value !== 'all') {
  9955. queryParam[queryType] = value;
  9956. }
  9957. var models = ecModel.queryComponents(queryParam);
  9958. result[mainType + 'Models'] = models;
  9959. result[mainType + 'Model'] = models[0];
  9960. });
  9961. return result;
  9962. }
  9963. function has(obj, prop) {
  9964. return obj && obj.hasOwnProperty(prop);
  9965. }
  9966. function setAttribute(dom, key, value) {
  9967. dom.setAttribute
  9968. ? dom.setAttribute(key, value)
  9969. : (dom[key] = value);
  9970. }
  9971. function getAttribute(dom, key) {
  9972. return dom.getAttribute
  9973. ? dom.getAttribute(key)
  9974. : dom[key];
  9975. }
  9976. /*
  9977. * Licensed to the Apache Software Foundation (ASF) under one
  9978. * or more contributor license agreements. See the NOTICE file
  9979. * distributed with this work for additional information
  9980. * regarding copyright ownership. The ASF licenses this file
  9981. * to you under the Apache License, Version 2.0 (the
  9982. * "License"); you may not use this file except in compliance
  9983. * with the License. You may obtain a copy of the License at
  9984. *
  9985. * http://www.apache.org/licenses/LICENSE-2.0
  9986. *
  9987. * Unless required by applicable law or agreed to in writing,
  9988. * software distributed under the License is distributed on an
  9989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9990. * KIND, either express or implied. See the License for the
  9991. * specific language governing permissions and limitations
  9992. * under the License.
  9993. */
  9994. var TYPE_DELIMITER = '.';
  9995. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  9996. /**
  9997. * Notice, parseClassType('') should returns {main: '', sub: ''}
  9998. * @public
  9999. */
  10000. function parseClassType$1(componentType) {
  10001. var ret = {main: '', sub: ''};
  10002. if (componentType) {
  10003. componentType = componentType.split(TYPE_DELIMITER);
  10004. ret.main = componentType[0] || '';
  10005. ret.sub = componentType[1] || '';
  10006. }
  10007. return ret;
  10008. }
  10009. /**
  10010. * @public
  10011. */
  10012. function checkClassType(componentType) {
  10013. assert$1(
  10014. /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType),
  10015. 'componentType "' + componentType + '" illegal'
  10016. );
  10017. }
  10018. /**
  10019. * @public
  10020. */
  10021. function enableClassExtend(RootClass, mandatoryMethods) {
  10022. RootClass.$constructor = RootClass;
  10023. RootClass.extend = function (proto) {
  10024. if (__DEV__) {
  10025. each$1(mandatoryMethods, function (method) {
  10026. if (!proto[method]) {
  10027. console.warn(
  10028. 'Method `' + method + '` should be implemented'
  10029. + (proto.type ? ' in ' + proto.type : '') + '.'
  10030. );
  10031. }
  10032. });
  10033. }
  10034. var superClass = this;
  10035. var ExtendedClass = function () {
  10036. if (!proto.$constructor) {
  10037. superClass.apply(this, arguments);
  10038. }
  10039. else {
  10040. proto.$constructor.apply(this, arguments);
  10041. }
  10042. };
  10043. extend(ExtendedClass.prototype, proto);
  10044. ExtendedClass.extend = this.extend;
  10045. ExtendedClass.superCall = superCall;
  10046. ExtendedClass.superApply = superApply;
  10047. inherits(ExtendedClass, this);
  10048. ExtendedClass.superClass = superClass;
  10049. return ExtendedClass;
  10050. };
  10051. }
  10052. var classBase = 0;
  10053. /**
  10054. * Can not use instanceof, consider different scope by
  10055. * cross domain or es module import in ec extensions.
  10056. * Mount a method "isInstance()" to Clz.
  10057. */
  10058. function enableClassCheck(Clz) {
  10059. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10060. Clz.prototype[classAttr] = true;
  10061. if (__DEV__) {
  10062. assert$1(!Clz.isInstance, 'The method "is" can not be defined.');
  10063. }
  10064. Clz.isInstance = function (obj) {
  10065. return !!(obj && obj[classAttr]);
  10066. };
  10067. }
  10068. // superCall should have class info, which can not be fetch from 'this'.
  10069. // Consider this case:
  10070. // class A has method f,
  10071. // class B inherits class A, overrides method f, f call superApply('f'),
  10072. // class C inherits class B, do not overrides method f,
  10073. // then when method of class C is called, dead loop occured.
  10074. function superCall(context, methodName) {
  10075. var args = slice(arguments, 2);
  10076. return this.superClass.prototype[methodName].apply(context, args);
  10077. }
  10078. function superApply(context, methodName, args) {
  10079. return this.superClass.prototype[methodName].apply(context, args);
  10080. }
  10081. /**
  10082. * @param {Object} entity
  10083. * @param {Object} options
  10084. * @param {boolean} [options.registerWhenExtend]
  10085. * @public
  10086. */
  10087. function enableClassManagement(entity, options) {
  10088. options = options || {};
  10089. /**
  10090. * Component model classes
  10091. * key: componentType,
  10092. * value:
  10093. * componentClass, when componentType is 'xxx'
  10094. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10095. * @type {Object}
  10096. */
  10097. var storage = {};
  10098. entity.registerClass = function (Clazz, componentType) {
  10099. if (componentType) {
  10100. checkClassType(componentType);
  10101. componentType = parseClassType$1(componentType);
  10102. if (!componentType.sub) {
  10103. if (__DEV__) {
  10104. if (storage[componentType.main]) {
  10105. console.warn(componentType.main + ' exists.');
  10106. }
  10107. }
  10108. storage[componentType.main] = Clazz;
  10109. }
  10110. else if (componentType.sub !== IS_CONTAINER) {
  10111. var container = makeContainer(componentType);
  10112. container[componentType.sub] = Clazz;
  10113. }
  10114. }
  10115. return Clazz;
  10116. };
  10117. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10118. var Clazz = storage[componentMainType];
  10119. if (Clazz && Clazz[IS_CONTAINER]) {
  10120. Clazz = subType ? Clazz[subType] : null;
  10121. }
  10122. if (throwWhenNotFound && !Clazz) {
  10123. throw new Error(
  10124. !subType
  10125. ? componentMainType + '.' + 'type should be specified.'
  10126. : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.'
  10127. );
  10128. }
  10129. return Clazz;
  10130. };
  10131. entity.getClassesByMainType = function (componentType) {
  10132. componentType = parseClassType$1(componentType);
  10133. var result = [];
  10134. var obj = storage[componentType.main];
  10135. if (obj && obj[IS_CONTAINER]) {
  10136. each$1(obj, function (o, type) {
  10137. type !== IS_CONTAINER && result.push(o);
  10138. });
  10139. }
  10140. else {
  10141. result.push(obj);
  10142. }
  10143. return result;
  10144. };
  10145. entity.hasClass = function (componentType) {
  10146. // Just consider componentType.main.
  10147. componentType = parseClassType$1(componentType);
  10148. return !!storage[componentType.main];
  10149. };
  10150. /**
  10151. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10152. */
  10153. entity.getAllClassMainTypes = function () {
  10154. var types = [];
  10155. each$1(storage, function (obj, type) {
  10156. types.push(type);
  10157. });
  10158. return types;
  10159. };
  10160. /**
  10161. * If a main type is container and has sub types
  10162. * @param {string} mainType
  10163. * @return {boolean}
  10164. */
  10165. entity.hasSubTypes = function (componentType) {
  10166. componentType = parseClassType$1(componentType);
  10167. var obj = storage[componentType.main];
  10168. return obj && obj[IS_CONTAINER];
  10169. };
  10170. entity.parseClassType = parseClassType$1;
  10171. function makeContainer(componentType) {
  10172. var container = storage[componentType.main];
  10173. if (!container || !container[IS_CONTAINER]) {
  10174. container = storage[componentType.main] = {};
  10175. container[IS_CONTAINER] = true;
  10176. }
  10177. return container;
  10178. }
  10179. if (options.registerWhenExtend) {
  10180. var originalExtend = entity.extend;
  10181. if (originalExtend) {
  10182. entity.extend = function (proto) {
  10183. var ExtendedClass = originalExtend.call(this, proto);
  10184. return entity.registerClass(ExtendedClass, proto.type);
  10185. };
  10186. }
  10187. }
  10188. return entity;
  10189. }
  10190. /**
  10191. * @param {string|Array.<string>} properties
  10192. */
  10193. /*
  10194. * Licensed to the Apache Software Foundation (ASF) under one
  10195. * or more contributor license agreements. See the NOTICE file
  10196. * distributed with this work for additional information
  10197. * regarding copyright ownership. The ASF licenses this file
  10198. * to you under the Apache License, Version 2.0 (the
  10199. * "License"); you may not use this file except in compliance
  10200. * with the License. You may obtain a copy of the License at
  10201. *
  10202. * http://www.apache.org/licenses/LICENSE-2.0
  10203. *
  10204. * Unless required by applicable law or agreed to in writing,
  10205. * software distributed under the License is distributed on an
  10206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10207. * KIND, either express or implied. See the License for the
  10208. * specific language governing permissions and limitations
  10209. * under the License.
  10210. */
  10211. // TODO Parse shadow style
  10212. // TODO Only shallow path support
  10213. var makeStyleMapper = function (properties) {
  10214. // Normalize
  10215. for (var i = 0; i < properties.length; i++) {
  10216. if (!properties[i][1]) {
  10217. properties[i][1] = properties[i][0];
  10218. }
  10219. }
  10220. return function (model, excludes, includes) {
  10221. var style = {};
  10222. for (var i = 0; i < properties.length; i++) {
  10223. var propName = properties[i][1];
  10224. if ((excludes && indexOf(excludes, propName) >= 0)
  10225. || (includes && indexOf(includes, propName) < 0)
  10226. ) {
  10227. continue;
  10228. }
  10229. var val = model.getShallow(propName);
  10230. if (val != null) {
  10231. style[properties[i][0]] = val;
  10232. }
  10233. }
  10234. return style;
  10235. };
  10236. };
  10237. /*
  10238. * Licensed to the Apache Software Foundation (ASF) under one
  10239. * or more contributor license agreements. See the NOTICE file
  10240. * distributed with this work for additional information
  10241. * regarding copyright ownership. The ASF licenses this file
  10242. * to you under the Apache License, Version 2.0 (the
  10243. * "License"); you may not use this file except in compliance
  10244. * with the License. You may obtain a copy of the License at
  10245. *
  10246. * http://www.apache.org/licenses/LICENSE-2.0
  10247. *
  10248. * Unless required by applicable law or agreed to in writing,
  10249. * software distributed under the License is distributed on an
  10250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10251. * KIND, either express or implied. See the License for the
  10252. * specific language governing permissions and limitations
  10253. * under the License.
  10254. */
  10255. var getLineStyle = makeStyleMapper(
  10256. [
  10257. ['lineWidth', 'width'],
  10258. ['stroke', 'color'],
  10259. ['opacity'],
  10260. ['shadowBlur'],
  10261. ['shadowOffsetX'],
  10262. ['shadowOffsetY'],
  10263. ['shadowColor']
  10264. ]
  10265. );
  10266. var lineStyleMixin = {
  10267. getLineStyle: function (excludes) {
  10268. var style = getLineStyle(this, excludes);
  10269. var lineDash = this.getLineDash(style.lineWidth);
  10270. lineDash && (style.lineDash = lineDash);
  10271. return style;
  10272. },
  10273. getLineDash: function (lineWidth) {
  10274. if (lineWidth == null) {
  10275. lineWidth = 1;
  10276. }
  10277. var lineType = this.get('type');
  10278. var dotSize = Math.max(lineWidth, 2);
  10279. var dashSize = lineWidth * 4;
  10280. return (lineType === 'solid' || lineType == null) ? null
  10281. : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]);
  10282. }
  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 getAreaStyle = makeStyleMapper(
  10303. [
  10304. ['fill', 'color'],
  10305. ['shadowBlur'],
  10306. ['shadowOffsetX'],
  10307. ['shadowOffsetY'],
  10308. ['opacity'],
  10309. ['shadowColor']
  10310. ]
  10311. );
  10312. var areaStyleMixin = {
  10313. getAreaStyle: function (excludes, includes) {
  10314. return getAreaStyle(this, excludes, includes);
  10315. }
  10316. };
  10317. /**
  10318. * 曲线辅助模块
  10319. * @module zrender/core/curve
  10320. * @author pissang(https://www.github.com/pissang)
  10321. */
  10322. var mathPow = Math.pow;
  10323. var mathSqrt$2 = Math.sqrt;
  10324. var EPSILON$1 = 1e-8;
  10325. var EPSILON_NUMERIC = 1e-4;
  10326. var THREE_SQRT = mathSqrt$2(3);
  10327. var ONE_THIRD = 1 / 3;
  10328. // 临时变量
  10329. var _v0 = create();
  10330. var _v1 = create();
  10331. var _v2 = create();
  10332. function isAroundZero(val) {
  10333. return val > -EPSILON$1 && val < EPSILON$1;
  10334. }
  10335. function isNotAroundZero$1(val) {
  10336. return val > EPSILON$1 || val < -EPSILON$1;
  10337. }
  10338. /**
  10339. * 计算三次贝塞尔值
  10340. * @memberOf module:zrender/core/curve
  10341. * @param {number} p0
  10342. * @param {number} p1
  10343. * @param {number} p2
  10344. * @param {number} p3
  10345. * @param {number} t
  10346. * @return {number}
  10347. */
  10348. function cubicAt(p0, p1, p2, p3, t) {
  10349. var onet = 1 - t;
  10350. return onet * onet * (onet * p0 + 3 * t * p1)
  10351. + t * t * (t * p3 + 3 * onet * p2);
  10352. }
  10353. /**
  10354. * 计算三次贝塞尔导数值
  10355. * @memberOf module:zrender/core/curve
  10356. * @param {number} p0
  10357. * @param {number} p1
  10358. * @param {number} p2
  10359. * @param {number} p3
  10360. * @param {number} t
  10361. * @return {number}
  10362. */
  10363. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10364. var onet = 1 - t;
  10365. return 3 * (
  10366. ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet
  10367. + (p3 - p2) * t * t
  10368. );
  10369. }
  10370. /**
  10371. * 计算三次贝塞尔方程根,使用盛金公式
  10372. * @memberOf module:zrender/core/curve
  10373. * @param {number} p0
  10374. * @param {number} p1
  10375. * @param {number} p2
  10376. * @param {number} p3
  10377. * @param {number} val
  10378. * @param {Array.<number>} roots
  10379. * @return {number} 有效根数目
  10380. */
  10381. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10382. // Evaluate roots of cubic functions
  10383. var a = p3 + 3 * (p1 - p2) - p0;
  10384. var b = 3 * (p2 - p1 * 2 + p0);
  10385. var c = 3 * (p1 - p0);
  10386. var d = p0 - val;
  10387. var A = b * b - 3 * a * c;
  10388. var B = b * c - 9 * a * d;
  10389. var C = c * c - 3 * b * d;
  10390. var n = 0;
  10391. if (isAroundZero(A) && isAroundZero(B)) {
  10392. if (isAroundZero(b)) {
  10393. roots[0] = 0;
  10394. }
  10395. else {
  10396. var t1 = -c / b; //t1, t2, t3, b is not zero
  10397. if (t1 >= 0 && t1 <= 1) {
  10398. roots[n++] = t1;
  10399. }
  10400. }
  10401. }
  10402. else {
  10403. var disc = B * B - 4 * A * C;
  10404. if (isAroundZero(disc)) {
  10405. var K = B / A;
  10406. var t1 = -b / a + K; // t1, a is not zero
  10407. var t2 = -K / 2; // t2, t3
  10408. if (t1 >= 0 && t1 <= 1) {
  10409. roots[n++] = t1;
  10410. }
  10411. if (t2 >= 0 && t2 <= 1) {
  10412. roots[n++] = t2;
  10413. }
  10414. }
  10415. else if (disc > 0) {
  10416. var discSqrt = mathSqrt$2(disc);
  10417. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10418. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10419. if (Y1 < 0) {
  10420. Y1 = -mathPow(-Y1, ONE_THIRD);
  10421. }
  10422. else {
  10423. Y1 = mathPow(Y1, ONE_THIRD);
  10424. }
  10425. if (Y2 < 0) {
  10426. Y2 = -mathPow(-Y2, ONE_THIRD);
  10427. }
  10428. else {
  10429. Y2 = mathPow(Y2, ONE_THIRD);
  10430. }
  10431. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10432. if (t1 >= 0 && t1 <= 1) {
  10433. roots[n++] = t1;
  10434. }
  10435. }
  10436. else {
  10437. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10438. var theta = Math.acos(T) / 3;
  10439. var ASqrt = mathSqrt$2(A);
  10440. var tmp = Math.cos(theta);
  10441. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10442. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10443. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10444. if (t1 >= 0 && t1 <= 1) {
  10445. roots[n++] = t1;
  10446. }
  10447. if (t2 >= 0 && t2 <= 1) {
  10448. roots[n++] = t2;
  10449. }
  10450. if (t3 >= 0 && t3 <= 1) {
  10451. roots[n++] = t3;
  10452. }
  10453. }
  10454. }
  10455. return n;
  10456. }
  10457. /**
  10458. * 计算三次贝塞尔方程极限值的位置
  10459. * @memberOf module:zrender/core/curve
  10460. * @param {number} p0
  10461. * @param {number} p1
  10462. * @param {number} p2
  10463. * @param {number} p3
  10464. * @param {Array.<number>} extrema
  10465. * @return {number} 有效数目
  10466. */
  10467. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10468. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10469. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10470. var c = 3 * p1 - 3 * p0;
  10471. var n = 0;
  10472. if (isAroundZero(a)) {
  10473. if (isNotAroundZero$1(b)) {
  10474. var t1 = -c / b;
  10475. if (t1 >= 0 && t1 <=1) {
  10476. extrema[n++] = t1;
  10477. }
  10478. }
  10479. }
  10480. else {
  10481. var disc = b * b - 4 * a * c;
  10482. if (isAroundZero(disc)) {
  10483. extrema[0] = -b / (2 * a);
  10484. }
  10485. else if (disc > 0) {
  10486. var discSqrt = mathSqrt$2(disc);
  10487. var t1 = (-b + discSqrt) / (2 * a);
  10488. var t2 = (-b - discSqrt) / (2 * a);
  10489. if (t1 >= 0 && t1 <= 1) {
  10490. extrema[n++] = t1;
  10491. }
  10492. if (t2 >= 0 && t2 <= 1) {
  10493. extrema[n++] = t2;
  10494. }
  10495. }
  10496. }
  10497. return n;
  10498. }
  10499. /**
  10500. * 细分三次贝塞尔曲线
  10501. * @memberOf module:zrender/core/curve
  10502. * @param {number} p0
  10503. * @param {number} p1
  10504. * @param {number} p2
  10505. * @param {number} p3
  10506. * @param {number} t
  10507. * @param {Array.<number>} out
  10508. */
  10509. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10510. var p01 = (p1 - p0) * t + p0;
  10511. var p12 = (p2 - p1) * t + p1;
  10512. var p23 = (p3 - p2) * t + p2;
  10513. var p012 = (p12 - p01) * t + p01;
  10514. var p123 = (p23 - p12) * t + p12;
  10515. var p0123 = (p123 - p012) * t + p012;
  10516. // Seg0
  10517. out[0] = p0;
  10518. out[1] = p01;
  10519. out[2] = p012;
  10520. out[3] = p0123;
  10521. // Seg1
  10522. out[4] = p0123;
  10523. out[5] = p123;
  10524. out[6] = p23;
  10525. out[7] = p3;
  10526. }
  10527. /**
  10528. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10529. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10530. * @param {number} x0
  10531. * @param {number} y0
  10532. * @param {number} x1
  10533. * @param {number} y1
  10534. * @param {number} x2
  10535. * @param {number} y2
  10536. * @param {number} x3
  10537. * @param {number} y3
  10538. * @param {number} x
  10539. * @param {number} y
  10540. * @param {Array.<number>} [out] 投射点
  10541. * @return {number}
  10542. */
  10543. function cubicProjectPoint(
  10544. x0, y0, x1, y1, x2, y2, x3, y3,
  10545. x, y, out
  10546. ) {
  10547. // http://pomax.github.io/bezierinfo/#projections
  10548. var t;
  10549. var interval = 0.005;
  10550. var d = Infinity;
  10551. var prev;
  10552. var next;
  10553. var d1;
  10554. var d2;
  10555. _v0[0] = x;
  10556. _v0[1] = y;
  10557. // 先粗略估计一下可能的最小距离的 t 值
  10558. // PENDING
  10559. for (var _t = 0; _t < 1; _t += 0.05) {
  10560. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10561. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10562. d1 = distSquare(_v0, _v1);
  10563. if (d1 < d) {
  10564. t = _t;
  10565. d = d1;
  10566. }
  10567. }
  10568. d = Infinity;
  10569. // At most 32 iteration
  10570. for (var i = 0; i < 32; i++) {
  10571. if (interval < EPSILON_NUMERIC) {
  10572. break;
  10573. }
  10574. prev = t - interval;
  10575. next = t + interval;
  10576. // t - interval
  10577. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10578. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10579. d1 = distSquare(_v1, _v0);
  10580. if (prev >= 0 && d1 < d) {
  10581. t = prev;
  10582. d = d1;
  10583. }
  10584. else {
  10585. // t + interval
  10586. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10587. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10588. d2 = distSquare(_v2, _v0);
  10589. if (next <= 1 && d2 < d) {
  10590. t = next;
  10591. d = d2;
  10592. }
  10593. else {
  10594. interval *= 0.5;
  10595. }
  10596. }
  10597. }
  10598. // t
  10599. if (out) {
  10600. out[0] = cubicAt(x0, x1, x2, x3, t);
  10601. out[1] = cubicAt(y0, y1, y2, y3, t);
  10602. }
  10603. // console.log(interval, i);
  10604. return mathSqrt$2(d);
  10605. }
  10606. /**
  10607. * 计算二次方贝塞尔值
  10608. * @param {number} p0
  10609. * @param {number} p1
  10610. * @param {number} p2
  10611. * @param {number} t
  10612. * @return {number}
  10613. */
  10614. function quadraticAt(p0, p1, p2, t) {
  10615. var onet = 1 - t;
  10616. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10617. }
  10618. /**
  10619. * 计算二次方贝塞尔导数值
  10620. * @param {number} p0
  10621. * @param {number} p1
  10622. * @param {number} p2
  10623. * @param {number} t
  10624. * @return {number}
  10625. */
  10626. function quadraticDerivativeAt(p0, p1, p2, t) {
  10627. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10628. }
  10629. /**
  10630. * 计算二次方贝塞尔方程根
  10631. * @param {number} p0
  10632. * @param {number} p1
  10633. * @param {number} p2
  10634. * @param {number} t
  10635. * @param {Array.<number>} roots
  10636. * @return {number} 有效根数目
  10637. */
  10638. function quadraticRootAt(p0, p1, p2, val, roots) {
  10639. var a = p0 - 2 * p1 + p2;
  10640. var b = 2 * (p1 - p0);
  10641. var c = p0 - val;
  10642. var n = 0;
  10643. if (isAroundZero(a)) {
  10644. if (isNotAroundZero$1(b)) {
  10645. var t1 = -c / b;
  10646. if (t1 >= 0 && t1 <= 1) {
  10647. roots[n++] = t1;
  10648. }
  10649. }
  10650. }
  10651. else {
  10652. var disc = b * b - 4 * a * c;
  10653. if (isAroundZero(disc)) {
  10654. var t1 = -b / (2 * a);
  10655. if (t1 >= 0 && t1 <= 1) {
  10656. roots[n++] = t1;
  10657. }
  10658. }
  10659. else if (disc > 0) {
  10660. var discSqrt = mathSqrt$2(disc);
  10661. var t1 = (-b + discSqrt) / (2 * a);
  10662. var t2 = (-b - discSqrt) / (2 * a);
  10663. if (t1 >= 0 && t1 <= 1) {
  10664. roots[n++] = t1;
  10665. }
  10666. if (t2 >= 0 && t2 <= 1) {
  10667. roots[n++] = t2;
  10668. }
  10669. }
  10670. }
  10671. return n;
  10672. }
  10673. /**
  10674. * 计算二次贝塞尔方程极限值
  10675. * @memberOf module:zrender/core/curve
  10676. * @param {number} p0
  10677. * @param {number} p1
  10678. * @param {number} p2
  10679. * @return {number}
  10680. */
  10681. function quadraticExtremum(p0, p1, p2) {
  10682. var divider = p0 + p2 - 2 * p1;
  10683. if (divider === 0) {
  10684. // p1 is center of p0 and p2
  10685. return 0.5;
  10686. }
  10687. else {
  10688. return (p0 - p1) / divider;
  10689. }
  10690. }
  10691. /**
  10692. * 细分二次贝塞尔曲线
  10693. * @memberOf module:zrender/core/curve
  10694. * @param {number} p0
  10695. * @param {number} p1
  10696. * @param {number} p2
  10697. * @param {number} t
  10698. * @param {Array.<number>} out
  10699. */
  10700. function quadraticSubdivide(p0, p1, p2, t, out) {
  10701. var p01 = (p1 - p0) * t + p0;
  10702. var p12 = (p2 - p1) * t + p1;
  10703. var p012 = (p12 - p01) * t + p01;
  10704. // Seg0
  10705. out[0] = p0;
  10706. out[1] = p01;
  10707. out[2] = p012;
  10708. // Seg1
  10709. out[3] = p012;
  10710. out[4] = p12;
  10711. out[5] = p2;
  10712. }
  10713. /**
  10714. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10715. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10716. * @param {number} x0
  10717. * @param {number} y0
  10718. * @param {number} x1
  10719. * @param {number} y1
  10720. * @param {number} x2
  10721. * @param {number} y2
  10722. * @param {number} x
  10723. * @param {number} y
  10724. * @param {Array.<number>} out 投射点
  10725. * @return {number}
  10726. */
  10727. function quadraticProjectPoint(
  10728. x0, y0, x1, y1, x2, y2,
  10729. x, y, out
  10730. ) {
  10731. // http://pomax.github.io/bezierinfo/#projections
  10732. var t;
  10733. var interval = 0.005;
  10734. var d = Infinity;
  10735. _v0[0] = x;
  10736. _v0[1] = y;
  10737. // 先粗略估计一下可能的最小距离的 t 值
  10738. // PENDING
  10739. for (var _t = 0; _t < 1; _t += 0.05) {
  10740. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10741. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10742. var d1 = distSquare(_v0, _v1);
  10743. if (d1 < d) {
  10744. t = _t;
  10745. d = d1;
  10746. }
  10747. }
  10748. d = Infinity;
  10749. // At most 32 iteration
  10750. for (var i = 0; i < 32; i++) {
  10751. if (interval < EPSILON_NUMERIC) {
  10752. break;
  10753. }
  10754. var prev = t - interval;
  10755. var next = t + interval;
  10756. // t - interval
  10757. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10758. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10759. var d1 = distSquare(_v1, _v0);
  10760. if (prev >= 0 && d1 < d) {
  10761. t = prev;
  10762. d = d1;
  10763. }
  10764. else {
  10765. // t + interval
  10766. _v2[0] = quadraticAt(x0, x1, x2, next);
  10767. _v2[1] = quadraticAt(y0, y1, y2, next);
  10768. var d2 = distSquare(_v2, _v0);
  10769. if (next <= 1 && d2 < d) {
  10770. t = next;
  10771. d = d2;
  10772. }
  10773. else {
  10774. interval *= 0.5;
  10775. }
  10776. }
  10777. }
  10778. // t
  10779. if (out) {
  10780. out[0] = quadraticAt(x0, x1, x2, t);
  10781. out[1] = quadraticAt(y0, y1, y2, t);
  10782. }
  10783. // console.log(interval, i);
  10784. return mathSqrt$2(d);
  10785. }
  10786. /**
  10787. * @author Yi Shen(https://github.com/pissang)
  10788. */
  10789. var mathMin$3 = Math.min;
  10790. var mathMax$3 = Math.max;
  10791. var mathSin$2 = Math.sin;
  10792. var mathCos$2 = Math.cos;
  10793. var PI2 = Math.PI * 2;
  10794. var start = create();
  10795. var end = create();
  10796. var extremity = create();
  10797. /**
  10798. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10799. * @module zrender/core/bbox
  10800. * @param {Array<Object>} points 顶点数组
  10801. * @param {number} min
  10802. * @param {number} max
  10803. */
  10804. function fromPoints(points, min$$1, max$$1) {
  10805. if (points.length === 0) {
  10806. return;
  10807. }
  10808. var p = points[0];
  10809. var left = p[0];
  10810. var right = p[0];
  10811. var top = p[1];
  10812. var bottom = p[1];
  10813. var i;
  10814. for (i = 1; i < points.length; i++) {
  10815. p = points[i];
  10816. left = mathMin$3(left, p[0]);
  10817. right = mathMax$3(right, p[0]);
  10818. top = mathMin$3(top, p[1]);
  10819. bottom = mathMax$3(bottom, p[1]);
  10820. }
  10821. min$$1[0] = left;
  10822. min$$1[1] = top;
  10823. max$$1[0] = right;
  10824. max$$1[1] = bottom;
  10825. }
  10826. /**
  10827. * @memberOf module:zrender/core/bbox
  10828. * @param {number} x0
  10829. * @param {number} y0
  10830. * @param {number} x1
  10831. * @param {number} y1
  10832. * @param {Array.<number>} min
  10833. * @param {Array.<number>} max
  10834. */
  10835. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10836. min$$1[0] = mathMin$3(x0, x1);
  10837. min$$1[1] = mathMin$3(y0, y1);
  10838. max$$1[0] = mathMax$3(x0, x1);
  10839. max$$1[1] = mathMax$3(y0, y1);
  10840. }
  10841. var xDim = [];
  10842. var yDim = [];
  10843. /**
  10844. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  10845. * @memberOf module:zrender/core/bbox
  10846. * @param {number} x0
  10847. * @param {number} y0
  10848. * @param {number} x1
  10849. * @param {number} y1
  10850. * @param {number} x2
  10851. * @param {number} y2
  10852. * @param {number} x3
  10853. * @param {number} y3
  10854. * @param {Array.<number>} min
  10855. * @param {Array.<number>} max
  10856. */
  10857. function fromCubic(
  10858. x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1
  10859. ) {
  10860. var cubicExtrema$$1 = cubicExtrema;
  10861. var cubicAt$$1 = cubicAt;
  10862. var i;
  10863. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  10864. min$$1[0] = Infinity;
  10865. min$$1[1] = Infinity;
  10866. max$$1[0] = -Infinity;
  10867. max$$1[1] = -Infinity;
  10868. for (i = 0; i < n; i++) {
  10869. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  10870. min$$1[0] = mathMin$3(x, min$$1[0]);
  10871. max$$1[0] = mathMax$3(x, max$$1[0]);
  10872. }
  10873. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  10874. for (i = 0; i < n; i++) {
  10875. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  10876. min$$1[1] = mathMin$3(y, min$$1[1]);
  10877. max$$1[1] = mathMax$3(y, max$$1[1]);
  10878. }
  10879. min$$1[0] = mathMin$3(x0, min$$1[0]);
  10880. max$$1[0] = mathMax$3(x0, max$$1[0]);
  10881. min$$1[0] = mathMin$3(x3, min$$1[0]);
  10882. max$$1[0] = mathMax$3(x3, max$$1[0]);
  10883. min$$1[1] = mathMin$3(y0, min$$1[1]);
  10884. max$$1[1] = mathMax$3(y0, max$$1[1]);
  10885. min$$1[1] = mathMin$3(y3, min$$1[1]);
  10886. max$$1[1] = mathMax$3(y3, max$$1[1]);
  10887. }
  10888. /**
  10889. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  10890. * @memberOf module:zrender/core/bbox
  10891. * @param {number} x0
  10892. * @param {number} y0
  10893. * @param {number} x1
  10894. * @param {number} y1
  10895. * @param {number} x2
  10896. * @param {number} y2
  10897. * @param {Array.<number>} min
  10898. * @param {Array.<number>} max
  10899. */
  10900. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  10901. var quadraticExtremum$$1 = quadraticExtremum;
  10902. var quadraticAt$$1 = quadraticAt;
  10903. // Find extremities, where derivative in x dim or y dim is zero
  10904. var tx =
  10905. mathMax$3(
  10906. mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0
  10907. );
  10908. var ty =
  10909. mathMax$3(
  10910. mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0
  10911. );
  10912. var x = quadraticAt$$1(x0, x1, x2, tx);
  10913. var y = quadraticAt$$1(y0, y1, y2, ty);
  10914. min$$1[0] = mathMin$3(x0, x2, x);
  10915. min$$1[1] = mathMin$3(y0, y2, y);
  10916. max$$1[0] = mathMax$3(x0, x2, x);
  10917. max$$1[1] = mathMax$3(y0, y2, y);
  10918. }
  10919. /**
  10920. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  10921. * @method
  10922. * @memberOf module:zrender/core/bbox
  10923. * @param {number} x
  10924. * @param {number} y
  10925. * @param {number} rx
  10926. * @param {number} ry
  10927. * @param {number} startAngle
  10928. * @param {number} endAngle
  10929. * @param {number} anticlockwise
  10930. * @param {Array.<number>} min
  10931. * @param {Array.<number>} max
  10932. */
  10933. function fromArc(
  10934. x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1
  10935. ) {
  10936. var vec2Min = min;
  10937. var vec2Max = max;
  10938. var diff = Math.abs(startAngle - endAngle);
  10939. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  10940. // Is a circle
  10941. min$$1[0] = x - rx;
  10942. min$$1[1] = y - ry;
  10943. max$$1[0] = x + rx;
  10944. max$$1[1] = y + ry;
  10945. return;
  10946. }
  10947. start[0] = mathCos$2(startAngle) * rx + x;
  10948. start[1] = mathSin$2(startAngle) * ry + y;
  10949. end[0] = mathCos$2(endAngle) * rx + x;
  10950. end[1] = mathSin$2(endAngle) * ry + y;
  10951. vec2Min(min$$1, start, end);
  10952. vec2Max(max$$1, start, end);
  10953. // Thresh to [0, Math.PI * 2]
  10954. startAngle = startAngle % (PI2);
  10955. if (startAngle < 0) {
  10956. startAngle = startAngle + PI2;
  10957. }
  10958. endAngle = endAngle % (PI2);
  10959. if (endAngle < 0) {
  10960. endAngle = endAngle + PI2;
  10961. }
  10962. if (startAngle > endAngle && !anticlockwise) {
  10963. endAngle += PI2;
  10964. }
  10965. else if (startAngle < endAngle && anticlockwise) {
  10966. startAngle += PI2;
  10967. }
  10968. if (anticlockwise) {
  10969. var tmp = endAngle;
  10970. endAngle = startAngle;
  10971. startAngle = tmp;
  10972. }
  10973. // var number = 0;
  10974. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  10975. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  10976. if (angle > startAngle) {
  10977. extremity[0] = mathCos$2(angle) * rx + x;
  10978. extremity[1] = mathSin$2(angle) * ry + y;
  10979. vec2Min(min$$1, extremity, min$$1);
  10980. vec2Max(max$$1, extremity, max$$1);
  10981. }
  10982. }
  10983. }
  10984. /**
  10985. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  10986. * 可以用于 isInsidePath 判断以及获取boundingRect
  10987. *
  10988. * @module zrender/core/PathProxy
  10989. * @author Yi Shen (http://www.github.com/pissang)
  10990. */
  10991. // TODO getTotalLength, getPointAtLength
  10992. var CMD = {
  10993. M: 1,
  10994. L: 2,
  10995. C: 3,
  10996. Q: 4,
  10997. A: 5,
  10998. Z: 6,
  10999. // Rect
  11000. R: 7
  11001. };
  11002. // var CMD_MEM_SIZE = {
  11003. // M: 3,
  11004. // L: 3,
  11005. // C: 7,
  11006. // Q: 5,
  11007. // A: 9,
  11008. // R: 5,
  11009. // Z: 1
  11010. // };
  11011. var min$1 = [];
  11012. var max$1 = [];
  11013. var min2 = [];
  11014. var max2 = [];
  11015. var mathMin$2 = Math.min;
  11016. var mathMax$2 = Math.max;
  11017. var mathCos$1 = Math.cos;
  11018. var mathSin$1 = Math.sin;
  11019. var mathSqrt$1 = Math.sqrt;
  11020. var mathAbs = Math.abs;
  11021. var hasTypedArray = typeof Float32Array != 'undefined';
  11022. /**
  11023. * @alias module:zrender/core/PathProxy
  11024. * @constructor
  11025. */
  11026. var PathProxy = function (notSaveData) {
  11027. this._saveData = !(notSaveData || false);
  11028. if (this._saveData) {
  11029. /**
  11030. * Path data. Stored as flat array
  11031. * @type {Array.<Object>}
  11032. */
  11033. this.data = [];
  11034. }
  11035. this._ctx = null;
  11036. };
  11037. /**
  11038. * 快速计算Path包围盒(并不是最小包围盒)
  11039. * @return {Object}
  11040. */
  11041. PathProxy.prototype = {
  11042. constructor: PathProxy,
  11043. _xi: 0,
  11044. _yi: 0,
  11045. _x0: 0,
  11046. _y0: 0,
  11047. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11048. _ux: 0,
  11049. _uy: 0,
  11050. _len: 0,
  11051. _lineDash: null,
  11052. _dashOffset: 0,
  11053. _dashIdx: 0,
  11054. _dashSum: 0,
  11055. /**
  11056. * @readOnly
  11057. */
  11058. setScale: function (sx, sy) {
  11059. this._ux = mathAbs(1 / devicePixelRatio / sx) || 0;
  11060. this._uy = mathAbs(1 / devicePixelRatio / sy) || 0;
  11061. },
  11062. getContext: function () {
  11063. return this._ctx;
  11064. },
  11065. /**
  11066. * @param {CanvasRenderingContext2D} ctx
  11067. * @return {module:zrender/core/PathProxy}
  11068. */
  11069. beginPath: function (ctx) {
  11070. this._ctx = ctx;
  11071. ctx && ctx.beginPath();
  11072. ctx && (this.dpr = ctx.dpr);
  11073. // Reset
  11074. if (this._saveData) {
  11075. this._len = 0;
  11076. }
  11077. if (this._lineDash) {
  11078. this._lineDash = null;
  11079. this._dashOffset = 0;
  11080. }
  11081. return this;
  11082. },
  11083. /**
  11084. * @param {number} x
  11085. * @param {number} y
  11086. * @return {module:zrender/core/PathProxy}
  11087. */
  11088. moveTo: function (x, y) {
  11089. this.addData(CMD.M, x, y);
  11090. this._ctx && this._ctx.moveTo(x, y);
  11091. // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11092. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11093. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11094. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11095. this._x0 = x;
  11096. this._y0 = y;
  11097. this._xi = x;
  11098. this._yi = y;
  11099. return this;
  11100. },
  11101. /**
  11102. * @param {number} x
  11103. * @param {number} y
  11104. * @return {module:zrender/core/PathProxy}
  11105. */
  11106. lineTo: function (x, y) {
  11107. var exceedUnit = mathAbs(x - this._xi) > this._ux
  11108. || mathAbs(y - this._yi) > this._uy
  11109. // Force draw the first segment
  11110. || this._len < 5;
  11111. this.addData(CMD.L, x, y);
  11112. if (this._ctx && exceedUnit) {
  11113. this._needsDash() ? this._dashedLineTo(x, y)
  11114. : this._ctx.lineTo(x, y);
  11115. }
  11116. if (exceedUnit) {
  11117. this._xi = x;
  11118. this._yi = y;
  11119. }
  11120. return this;
  11121. },
  11122. /**
  11123. * @param {number} x1
  11124. * @param {number} y1
  11125. * @param {number} x2
  11126. * @param {number} y2
  11127. * @param {number} x3
  11128. * @param {number} y3
  11129. * @return {module:zrender/core/PathProxy}
  11130. */
  11131. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11132. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11133. if (this._ctx) {
  11134. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3)
  11135. : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11136. }
  11137. this._xi = x3;
  11138. this._yi = y3;
  11139. return this;
  11140. },
  11141. /**
  11142. * @param {number} x1
  11143. * @param {number} y1
  11144. * @param {number} x2
  11145. * @param {number} y2
  11146. * @return {module:zrender/core/PathProxy}
  11147. */
  11148. quadraticCurveTo: function (x1, y1, x2, y2) {
  11149. this.addData(CMD.Q, x1, y1, x2, y2);
  11150. if (this._ctx) {
  11151. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2)
  11152. : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11153. }
  11154. this._xi = x2;
  11155. this._yi = y2;
  11156. return this;
  11157. },
  11158. /**
  11159. * @param {number} cx
  11160. * @param {number} cy
  11161. * @param {number} r
  11162. * @param {number} startAngle
  11163. * @param {number} endAngle
  11164. * @param {boolean} anticlockwise
  11165. * @return {module:zrender/core/PathProxy}
  11166. */
  11167. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11168. this.addData(
  11169. CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1
  11170. );
  11171. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11172. this._xi = mathCos$1(endAngle) * r + cx;
  11173. this._yi = mathSin$1(endAngle) * r + cx;
  11174. return this;
  11175. },
  11176. // TODO
  11177. arcTo: function (x1, y1, x2, y2, radius) {
  11178. if (this._ctx) {
  11179. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11180. }
  11181. return this;
  11182. },
  11183. // TODO
  11184. rect: function (x, y, w, h) {
  11185. this._ctx && this._ctx.rect(x, y, w, h);
  11186. this.addData(CMD.R, x, y, w, h);
  11187. return this;
  11188. },
  11189. /**
  11190. * @return {module:zrender/core/PathProxy}
  11191. */
  11192. closePath: function () {
  11193. this.addData(CMD.Z);
  11194. var ctx = this._ctx;
  11195. var x0 = this._x0;
  11196. var y0 = this._y0;
  11197. if (ctx) {
  11198. this._needsDash() && this._dashedLineTo(x0, y0);
  11199. ctx.closePath();
  11200. }
  11201. this._xi = x0;
  11202. this._yi = y0;
  11203. return this;
  11204. },
  11205. /**
  11206. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11207. * stroke 同样
  11208. * @param {CanvasRenderingContext2D} ctx
  11209. * @return {module:zrender/core/PathProxy}
  11210. */
  11211. fill: function (ctx) {
  11212. ctx && ctx.fill();
  11213. this.toStatic();
  11214. },
  11215. /**
  11216. * @param {CanvasRenderingContext2D} ctx
  11217. * @return {module:zrender/core/PathProxy}
  11218. */
  11219. stroke: function (ctx) {
  11220. ctx && ctx.stroke();
  11221. this.toStatic();
  11222. },
  11223. /**
  11224. * 必须在其它绘制命令前调用
  11225. * Must be invoked before all other path drawing methods
  11226. * @return {module:zrender/core/PathProxy}
  11227. */
  11228. setLineDash: function (lineDash) {
  11229. if (lineDash instanceof Array) {
  11230. this._lineDash = lineDash;
  11231. this._dashIdx = 0;
  11232. var lineDashSum = 0;
  11233. for (var i = 0; i < lineDash.length; i++) {
  11234. lineDashSum += lineDash[i];
  11235. }
  11236. this._dashSum = lineDashSum;
  11237. }
  11238. return this;
  11239. },
  11240. /**
  11241. * 必须在其它绘制命令前调用
  11242. * Must be invoked before all other path drawing methods
  11243. * @return {module:zrender/core/PathProxy}
  11244. */
  11245. setLineDashOffset: function (offset) {
  11246. this._dashOffset = offset;
  11247. return this;
  11248. },
  11249. /**
  11250. *
  11251. * @return {boolean}
  11252. */
  11253. len: function () {
  11254. return this._len;
  11255. },
  11256. /**
  11257. * 直接设置 Path 数据
  11258. */
  11259. setData: function (data) {
  11260. var len$$1 = data.length;
  11261. if (! (this.data && this.data.length == len$$1) && hasTypedArray) {
  11262. this.data = new Float32Array(len$$1);
  11263. }
  11264. for (var i = 0; i < len$$1; i++) {
  11265. this.data[i] = data[i];
  11266. }
  11267. this._len = len$$1;
  11268. },
  11269. /**
  11270. * 添加子路径
  11271. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11272. */
  11273. appendPath: function (path) {
  11274. if (!(path instanceof Array)) {
  11275. path = [path];
  11276. }
  11277. var len$$1 = path.length;
  11278. var appendSize = 0;
  11279. var offset = this._len;
  11280. for (var i = 0; i < len$$1; i++) {
  11281. appendSize += path[i].len();
  11282. }
  11283. if (hasTypedArray && (this.data instanceof Float32Array)) {
  11284. this.data = new Float32Array(offset + appendSize);
  11285. }
  11286. for (var i = 0; i < len$$1; i++) {
  11287. var appendPathData = path[i].data;
  11288. for (var k = 0; k < appendPathData.length; k++) {
  11289. this.data[offset++] = appendPathData[k];
  11290. }
  11291. }
  11292. this._len = offset;
  11293. },
  11294. /**
  11295. * 填充 Path 数据。
  11296. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11297. */
  11298. addData: function (cmd) {
  11299. if (!this._saveData) {
  11300. return;
  11301. }
  11302. var data = this.data;
  11303. if (this._len + arguments.length > data.length) {
  11304. // 因为之前的数组已经转换成静态的 Float32Array
  11305. // 所以不够用时需要扩展一个新的动态数组
  11306. this._expandData();
  11307. data = this.data;
  11308. }
  11309. for (var i = 0; i < arguments.length; i++) {
  11310. data[this._len++] = arguments[i];
  11311. }
  11312. this._prevCmd = cmd;
  11313. },
  11314. _expandData: function () {
  11315. // Only if data is Float32Array
  11316. if (!(this.data instanceof Array)) {
  11317. var newData = [];
  11318. for (var i = 0; i < this._len; i++) {
  11319. newData[i] = this.data[i];
  11320. }
  11321. this.data = newData;
  11322. }
  11323. },
  11324. /**
  11325. * If needs js implemented dashed line
  11326. * @return {boolean}
  11327. * @private
  11328. */
  11329. _needsDash: function () {
  11330. return this._lineDash;
  11331. },
  11332. _dashedLineTo: function (x1, y1) {
  11333. var dashSum = this._dashSum;
  11334. var offset = this._dashOffset;
  11335. var lineDash = this._lineDash;
  11336. var ctx = this._ctx;
  11337. var x0 = this._xi;
  11338. var y0 = this._yi;
  11339. var dx = x1 - x0;
  11340. var dy = y1 - y0;
  11341. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11342. var x = x0;
  11343. var y = y0;
  11344. var dash;
  11345. var nDash = lineDash.length;
  11346. var idx;
  11347. dx /= dist$$1;
  11348. dy /= dist$$1;
  11349. if (offset < 0) {
  11350. // Convert to positive offset
  11351. offset = dashSum + offset;
  11352. }
  11353. offset %= dashSum;
  11354. x -= offset * dx;
  11355. y -= offset * dy;
  11356. while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1)
  11357. || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) {
  11358. idx = this._dashIdx;
  11359. dash = lineDash[idx];
  11360. x += dx * dash;
  11361. y += dy * dash;
  11362. this._dashIdx = (idx + 1) % nDash;
  11363. // Skip positive offset
  11364. if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) {
  11365. continue;
  11366. }
  11367. ctx[idx % 2 ? 'moveTo' : 'lineTo'](
  11368. dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1),
  11369. dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1)
  11370. );
  11371. }
  11372. // Offset for next lineTo
  11373. dx = x - x1;
  11374. dy = y - y1;
  11375. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11376. },
  11377. // Not accurate dashed line to
  11378. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11379. var dashSum = this._dashSum;
  11380. var offset = this._dashOffset;
  11381. var lineDash = this._lineDash;
  11382. var ctx = this._ctx;
  11383. var x0 = this._xi;
  11384. var y0 = this._yi;
  11385. var t;
  11386. var dx;
  11387. var dy;
  11388. var cubicAt$$1 = cubicAt;
  11389. var bezierLen = 0;
  11390. var idx = this._dashIdx;
  11391. var nDash = lineDash.length;
  11392. var x;
  11393. var y;
  11394. var tmpLen = 0;
  11395. if (offset < 0) {
  11396. // Convert to positive offset
  11397. offset = dashSum + offset;
  11398. }
  11399. offset %= dashSum;
  11400. // Bezier approx length
  11401. for (t = 0; t < 1; t += 0.1) {
  11402. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1)
  11403. - cubicAt$$1(x0, x1, x2, x3, t);
  11404. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1)
  11405. - cubicAt$$1(y0, y1, y2, y3, t);
  11406. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11407. }
  11408. // Find idx after add offset
  11409. for (; idx < nDash; idx++) {
  11410. tmpLen += lineDash[idx];
  11411. if (tmpLen > offset) {
  11412. break;
  11413. }
  11414. }
  11415. t = (tmpLen - offset) / bezierLen;
  11416. while (t <= 1) {
  11417. x = cubicAt$$1(x0, x1, x2, x3, t);
  11418. y = cubicAt$$1(y0, y1, y2, y3, t);
  11419. // Use line to approximate dashed bezier
  11420. // Bad result if dash is long
  11421. idx % 2 ? ctx.moveTo(x, y)
  11422. : ctx.lineTo(x, y);
  11423. t += lineDash[idx] / bezierLen;
  11424. idx = (idx + 1) % nDash;
  11425. }
  11426. // Finish the last segment and calculate the new offset
  11427. (idx % 2 !== 0) && ctx.lineTo(x3, y3);
  11428. dx = x3 - x;
  11429. dy = y3 - y;
  11430. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11431. },
  11432. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11433. // Convert quadratic to cubic using degree elevation
  11434. var x3 = x2;
  11435. var y3 = y2;
  11436. x2 = (x2 + 2 * x1) / 3;
  11437. y2 = (y2 + 2 * y1) / 3;
  11438. x1 = (this._xi + 2 * x1) / 3;
  11439. y1 = (this._yi + 2 * y1) / 3;
  11440. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11441. },
  11442. /**
  11443. * 转成静态的 Float32Array 减少堆内存占用
  11444. * Convert dynamic array to static Float32Array
  11445. */
  11446. toStatic: function () {
  11447. var data = this.data;
  11448. if (data instanceof Array) {
  11449. data.length = this._len;
  11450. if (hasTypedArray) {
  11451. this.data = new Float32Array(data);
  11452. }
  11453. }
  11454. },
  11455. /**
  11456. * @return {module:zrender/core/BoundingRect}
  11457. */
  11458. getBoundingRect: function () {
  11459. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11460. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11461. var data = this.data;
  11462. var xi = 0;
  11463. var yi = 0;
  11464. var x0 = 0;
  11465. var y0 = 0;
  11466. for (var i = 0; i < data.length;) {
  11467. var cmd = data[i++];
  11468. if (i == 1) {
  11469. // 如果第一个命令是 L, C, Q
  11470. // 则 previous point 同绘制命令的第一个 point
  11471. //
  11472. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11473. xi = data[i];
  11474. yi = data[i + 1];
  11475. x0 = xi;
  11476. y0 = yi;
  11477. }
  11478. switch (cmd) {
  11479. case CMD.M:
  11480. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11481. // 在 closePath 的时候使用
  11482. x0 = data[i++];
  11483. y0 = data[i++];
  11484. xi = x0;
  11485. yi = y0;
  11486. min2[0] = x0;
  11487. min2[1] = y0;
  11488. max2[0] = x0;
  11489. max2[1] = y0;
  11490. break;
  11491. case CMD.L:
  11492. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11493. xi = data[i++];
  11494. yi = data[i++];
  11495. break;
  11496. case CMD.C:
  11497. fromCubic(
  11498. xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  11499. min2, max2
  11500. );
  11501. xi = data[i++];
  11502. yi = data[i++];
  11503. break;
  11504. case CMD.Q:
  11505. fromQuadratic(
  11506. xi, yi, data[i++], data[i++], data[i], data[i + 1],
  11507. min2, max2
  11508. );
  11509. xi = data[i++];
  11510. yi = data[i++];
  11511. break;
  11512. case CMD.A:
  11513. // TODO Arc 判断的开销比较大
  11514. var cx = data[i++];
  11515. var cy = data[i++];
  11516. var rx = data[i++];
  11517. var ry = data[i++];
  11518. var startAngle = data[i++];
  11519. var endAngle = data[i++] + startAngle;
  11520. // TODO Arc 旋转
  11521. var psi = data[i++];
  11522. var anticlockwise = 1 - data[i++];
  11523. if (i == 1) {
  11524. // 直接使用 arc 命令
  11525. // 第一个命令起点还未定义
  11526. x0 = mathCos$1(startAngle) * rx + cx;
  11527. y0 = mathSin$1(startAngle) * ry + cy;
  11528. }
  11529. fromArc(
  11530. cx, cy, rx, ry, startAngle, endAngle,
  11531. anticlockwise, min2, max2
  11532. );
  11533. xi = mathCos$1(endAngle) * rx + cx;
  11534. yi = mathSin$1(endAngle) * ry + cy;
  11535. break;
  11536. case CMD.R:
  11537. x0 = xi = data[i++];
  11538. y0 = yi = data[i++];
  11539. var width = data[i++];
  11540. var height = data[i++];
  11541. // Use fromLine
  11542. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11543. break;
  11544. case CMD.Z:
  11545. xi = x0;
  11546. yi = y0;
  11547. break;
  11548. }
  11549. // Union
  11550. min(min$1, min$1, min2);
  11551. max(max$1, max$1, max2);
  11552. }
  11553. // No data
  11554. if (i === 0) {
  11555. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11556. }
  11557. return new BoundingRect(
  11558. min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]
  11559. );
  11560. },
  11561. /**
  11562. * Rebuild path from current data
  11563. * Rebuild path will not consider javascript implemented line dash.
  11564. * @param {CanvasRenderingContext2D} ctx
  11565. */
  11566. rebuildPath: function (ctx) {
  11567. var d = this.data;
  11568. var x0, y0;
  11569. var xi, yi;
  11570. var x, y;
  11571. var ux = this._ux;
  11572. var uy = this._uy;
  11573. var len$$1 = this._len;
  11574. for (var i = 0; i < len$$1;) {
  11575. var cmd = d[i++];
  11576. if (i == 1) {
  11577. // 如果第一个命令是 L, C, Q
  11578. // 则 previous point 同绘制命令的第一个 point
  11579. //
  11580. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11581. xi = d[i];
  11582. yi = d[i + 1];
  11583. x0 = xi;
  11584. y0 = yi;
  11585. }
  11586. switch (cmd) {
  11587. case CMD.M:
  11588. x0 = xi = d[i++];
  11589. y0 = yi = d[i++];
  11590. ctx.moveTo(xi, yi);
  11591. break;
  11592. case CMD.L:
  11593. x = d[i++];
  11594. y = d[i++];
  11595. // Not draw too small seg between
  11596. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11597. ctx.lineTo(x, y);
  11598. xi = x;
  11599. yi = y;
  11600. }
  11601. break;
  11602. case CMD.C:
  11603. ctx.bezierCurveTo(
  11604. d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]
  11605. );
  11606. xi = d[i - 2];
  11607. yi = d[i - 1];
  11608. break;
  11609. case CMD.Q:
  11610. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11611. xi = d[i - 2];
  11612. yi = d[i - 1];
  11613. break;
  11614. case CMD.A:
  11615. var cx = d[i++];
  11616. var cy = d[i++];
  11617. var rx = d[i++];
  11618. var ry = d[i++];
  11619. var theta = d[i++];
  11620. var dTheta = d[i++];
  11621. var psi = d[i++];
  11622. var fs = d[i++];
  11623. var r = (rx > ry) ? rx : ry;
  11624. var scaleX = (rx > ry) ? 1 : rx / ry;
  11625. var scaleY = (rx > ry) ? ry / rx : 1;
  11626. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11627. var endAngle = theta + dTheta;
  11628. if (isEllipse) {
  11629. ctx.translate(cx, cy);
  11630. ctx.rotate(psi);
  11631. ctx.scale(scaleX, scaleY);
  11632. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11633. ctx.scale(1 / scaleX, 1 / scaleY);
  11634. ctx.rotate(-psi);
  11635. ctx.translate(-cx, -cy);
  11636. }
  11637. else {
  11638. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11639. }
  11640. if (i == 1) {
  11641. // 直接使用 arc 命令
  11642. // 第一个命令起点还未定义
  11643. x0 = mathCos$1(theta) * rx + cx;
  11644. y0 = mathSin$1(theta) * ry + cy;
  11645. }
  11646. xi = mathCos$1(endAngle) * rx + cx;
  11647. yi = mathSin$1(endAngle) * ry + cy;
  11648. break;
  11649. case CMD.R:
  11650. x0 = xi = d[i];
  11651. y0 = yi = d[i + 1];
  11652. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11653. break;
  11654. case CMD.Z:
  11655. ctx.closePath();
  11656. xi = x0;
  11657. yi = y0;
  11658. }
  11659. }
  11660. }
  11661. };
  11662. PathProxy.CMD = CMD;
  11663. /**
  11664. * 线段包含判断
  11665. * @param {number} x0
  11666. * @param {number} y0
  11667. * @param {number} x1
  11668. * @param {number} y1
  11669. * @param {number} lineWidth
  11670. * @param {number} x
  11671. * @param {number} y
  11672. * @return {boolean}
  11673. */
  11674. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11675. if (lineWidth === 0) {
  11676. return false;
  11677. }
  11678. var _l = lineWidth;
  11679. var _a = 0;
  11680. var _b = x0;
  11681. // Quick reject
  11682. if (
  11683. (y > y0 + _l && y > y1 + _l)
  11684. || (y < y0 - _l && y < y1 - _l)
  11685. || (x > x0 + _l && x > x1 + _l)
  11686. || (x < x0 - _l && x < x1 - _l)
  11687. ) {
  11688. return false;
  11689. }
  11690. if (x0 !== x1) {
  11691. _a = (y0 - y1) / (x0 - x1);
  11692. _b = (x0 * y1 - x1 * y0) / (x0 - x1) ;
  11693. }
  11694. else {
  11695. return Math.abs(x - x0) <= _l / 2;
  11696. }
  11697. var tmp = _a * x - y + _b;
  11698. var _s = tmp * tmp / (_a * _a + 1);
  11699. return _s <= _l / 2 * _l / 2;
  11700. }
  11701. /**
  11702. * 三次贝塞尔曲线描边包含判断
  11703. * @param {number} x0
  11704. * @param {number} y0
  11705. * @param {number} x1
  11706. * @param {number} y1
  11707. * @param {number} x2
  11708. * @param {number} y2
  11709. * @param {number} x3
  11710. * @param {number} y3
  11711. * @param {number} lineWidth
  11712. * @param {number} x
  11713. * @param {number} y
  11714. * @return {boolean}
  11715. */
  11716. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11717. if (lineWidth === 0) {
  11718. return false;
  11719. }
  11720. var _l = lineWidth;
  11721. // Quick reject
  11722. if (
  11723. (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l)
  11724. || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l)
  11725. || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l)
  11726. || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l)
  11727. ) {
  11728. return false;
  11729. }
  11730. var d = cubicProjectPoint(
  11731. x0, y0, x1, y1, x2, y2, x3, y3,
  11732. x, y, null
  11733. );
  11734. return d <= _l / 2;
  11735. }
  11736. /**
  11737. * 二次贝塞尔曲线描边包含判断
  11738. * @param {number} x0
  11739. * @param {number} y0
  11740. * @param {number} x1
  11741. * @param {number} y1
  11742. * @param {number} x2
  11743. * @param {number} y2
  11744. * @param {number} lineWidth
  11745. * @param {number} x
  11746. * @param {number} y
  11747. * @return {boolean}
  11748. */
  11749. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11750. if (lineWidth === 0) {
  11751. return false;
  11752. }
  11753. var _l = lineWidth;
  11754. // Quick reject
  11755. if (
  11756. (y > y0 + _l && y > y1 + _l && y > y2 + _l)
  11757. || (y < y0 - _l && y < y1 - _l && y < y2 - _l)
  11758. || (x > x0 + _l && x > x1 + _l && x > x2 + _l)
  11759. || (x < x0 - _l && x < x1 - _l && x < x2 - _l)
  11760. ) {
  11761. return false;
  11762. }
  11763. var d = quadraticProjectPoint(
  11764. x0, y0, x1, y1, x2, y2,
  11765. x, y, null
  11766. );
  11767. return d <= _l / 2;
  11768. }
  11769. var PI2$3 = Math.PI * 2;
  11770. function normalizeRadian(angle) {
  11771. angle %= PI2$3;
  11772. if (angle < 0) {
  11773. angle += PI2$3;
  11774. }
  11775. return angle;
  11776. }
  11777. var PI2$2 = Math.PI * 2;
  11778. /**
  11779. * 圆弧描边包含判断
  11780. * @param {number} cx
  11781. * @param {number} cy
  11782. * @param {number} r
  11783. * @param {number} startAngle
  11784. * @param {number} endAngle
  11785. * @param {boolean} anticlockwise
  11786. * @param {number} lineWidth
  11787. * @param {number} x
  11788. * @param {number} y
  11789. * @return {Boolean}
  11790. */
  11791. function containStroke$4(
  11792. cx, cy, r, startAngle, endAngle, anticlockwise,
  11793. lineWidth, x, y
  11794. ) {
  11795. if (lineWidth === 0) {
  11796. return false;
  11797. }
  11798. var _l = lineWidth;
  11799. x -= cx;
  11800. y -= cy;
  11801. var d = Math.sqrt(x * x + y * y);
  11802. if ((d - _l > r) || (d + _l < r)) {
  11803. return false;
  11804. }
  11805. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11806. // Is a circle
  11807. return true;
  11808. }
  11809. if (anticlockwise) {
  11810. var tmp = startAngle;
  11811. startAngle = normalizeRadian(endAngle);
  11812. endAngle = normalizeRadian(tmp);
  11813. } else {
  11814. startAngle = normalizeRadian(startAngle);
  11815. endAngle = normalizeRadian(endAngle);
  11816. }
  11817. if (startAngle > endAngle) {
  11818. endAngle += PI2$2;
  11819. }
  11820. var angle = Math.atan2(y, x);
  11821. if (angle < 0) {
  11822. angle += PI2$2;
  11823. }
  11824. return (angle >= startAngle && angle <= endAngle)
  11825. || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle);
  11826. }
  11827. function windingLine(x0, y0, x1, y1, x, y) {
  11828. if ((y > y0 && y > y1) || (y < y0 && y < y1)) {
  11829. return 0;
  11830. }
  11831. // Ignore horizontal line
  11832. if (y1 === y0) {
  11833. return 0;
  11834. }
  11835. var dir = y1 < y0 ? 1 : -1;
  11836. var t = (y - y0) / (y1 - y0);
  11837. // Avoid winding error when intersection point is the connect point of two line of polygon
  11838. if (t === 1 || t === 0) {
  11839. dir = y1 < y0 ? 0.5 : -0.5;
  11840. }
  11841. var x_ = t * (x1 - x0) + x0;
  11842. // If (x, y) on the line, considered as "contain".
  11843. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11844. }
  11845. var CMD$1 = PathProxy.CMD;
  11846. var PI2$1 = Math.PI * 2;
  11847. var EPSILON$2 = 1e-4;
  11848. function isAroundEqual(a, b) {
  11849. return Math.abs(a - b) < EPSILON$2;
  11850. }
  11851. // 临时数组
  11852. var roots = [-1, -1, -1];
  11853. var extrema = [-1, -1];
  11854. function swapExtrema() {
  11855. var tmp = extrema[0];
  11856. extrema[0] = extrema[1];
  11857. extrema[1] = tmp;
  11858. }
  11859. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11860. // Quick reject
  11861. if (
  11862. (y > y0 && y > y1 && y > y2 && y > y3)
  11863. || (y < y0 && y < y1 && y < y2 && y < y3)
  11864. ) {
  11865. return 0;
  11866. }
  11867. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11868. if (nRoots === 0) {
  11869. return 0;
  11870. }
  11871. else {
  11872. var w = 0;
  11873. var nExtrema = -1;
  11874. var y0_, y1_;
  11875. for (var i = 0; i < nRoots; i++) {
  11876. var t = roots[i];
  11877. // Avoid winding error when intersection point is the connect point of two line of polygon
  11878. var unit = (t === 0 || t === 1) ? 0.5 : 1;
  11879. var x_ = cubicAt(x0, x1, x2, x3, t);
  11880. if (x_ < x) { // Quick reject
  11881. continue;
  11882. }
  11883. if (nExtrema < 0) {
  11884. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11885. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11886. swapExtrema();
  11887. }
  11888. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11889. if (nExtrema > 1) {
  11890. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11891. }
  11892. }
  11893. if (nExtrema == 2) {
  11894. // 分成三段单调函数
  11895. if (t < extrema[0]) {
  11896. w += y0_ < y0 ? unit : -unit;
  11897. }
  11898. else if (t < extrema[1]) {
  11899. w += y1_ < y0_ ? unit : -unit;
  11900. }
  11901. else {
  11902. w += y3 < y1_ ? unit : -unit;
  11903. }
  11904. }
  11905. else {
  11906. // 分成两段单调函数
  11907. if (t < extrema[0]) {
  11908. w += y0_ < y0 ? unit : -unit;
  11909. }
  11910. else {
  11911. w += y3 < y0_ ? unit : -unit;
  11912. }
  11913. }
  11914. }
  11915. return w;
  11916. }
  11917. }
  11918. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11919. // Quick reject
  11920. if (
  11921. (y > y0 && y > y1 && y > y2)
  11922. || (y < y0 && y < y1 && y < y2)
  11923. ) {
  11924. return 0;
  11925. }
  11926. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11927. if (nRoots === 0) {
  11928. return 0;
  11929. }
  11930. else {
  11931. var t = quadraticExtremum(y0, y1, y2);
  11932. if (t >= 0 && t <= 1) {
  11933. var w = 0;
  11934. var y_ = quadraticAt(y0, y1, y2, t);
  11935. for (var i = 0; i < nRoots; i++) {
  11936. // Remove one endpoint.
  11937. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1;
  11938. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  11939. if (x_ < x) { // Quick reject
  11940. continue;
  11941. }
  11942. if (roots[i] < t) {
  11943. w += y_ < y0 ? unit : -unit;
  11944. }
  11945. else {
  11946. w += y2 < y_ ? unit : -unit;
  11947. }
  11948. }
  11949. return w;
  11950. }
  11951. else {
  11952. // Remove one endpoint.
  11953. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1;
  11954. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  11955. if (x_ < x) { // Quick reject
  11956. return 0;
  11957. }
  11958. return y2 < y0 ? unit : -unit;
  11959. }
  11960. }
  11961. }
  11962. // TODO
  11963. // Arc 旋转
  11964. function windingArc(
  11965. cx, cy, r, startAngle, endAngle, anticlockwise, x, y
  11966. ) {
  11967. y -= cy;
  11968. if (y > r || y < -r) {
  11969. return 0;
  11970. }
  11971. var tmp = Math.sqrt(r * r - y * y);
  11972. roots[0] = -tmp;
  11973. roots[1] = tmp;
  11974. var diff = Math.abs(startAngle - endAngle);
  11975. if (diff < 1e-4) {
  11976. return 0;
  11977. }
  11978. if (diff % PI2$1 < 1e-4) {
  11979. // Is a circle
  11980. startAngle = 0;
  11981. endAngle = PI2$1;
  11982. var dir = anticlockwise ? 1 : -1;
  11983. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  11984. return dir;
  11985. } else {
  11986. return 0;
  11987. }
  11988. }
  11989. if (anticlockwise) {
  11990. var tmp = startAngle;
  11991. startAngle = normalizeRadian(endAngle);
  11992. endAngle = normalizeRadian(tmp);
  11993. }
  11994. else {
  11995. startAngle = normalizeRadian(startAngle);
  11996. endAngle = normalizeRadian(endAngle);
  11997. }
  11998. if (startAngle > endAngle) {
  11999. endAngle += PI2$1;
  12000. }
  12001. var w = 0;
  12002. for (var i = 0; i < 2; i++) {
  12003. var x_ = roots[i];
  12004. if (x_ + cx > x) {
  12005. var angle = Math.atan2(y, x_);
  12006. var dir = anticlockwise ? 1 : -1;
  12007. if (angle < 0) {
  12008. angle = PI2$1 + angle;
  12009. }
  12010. if (
  12011. (angle >= startAngle && angle <= endAngle)
  12012. || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle)
  12013. ) {
  12014. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12015. dir = -dir;
  12016. }
  12017. w += dir;
  12018. }
  12019. }
  12020. }
  12021. return w;
  12022. }
  12023. function containPath(data, lineWidth, isStroke, x, y) {
  12024. var w = 0;
  12025. var xi = 0;
  12026. var yi = 0;
  12027. var x0 = 0;
  12028. var y0 = 0;
  12029. for (var i = 0; i < data.length;) {
  12030. var cmd = data[i++];
  12031. // Begin a new subpath
  12032. if (cmd === CMD$1.M && i > 1) {
  12033. // Close previous subpath
  12034. if (!isStroke) {
  12035. w += windingLine(xi, yi, x0, y0, x, y);
  12036. }
  12037. // 如果被任何一个 subpath 包含
  12038. // if (w !== 0) {
  12039. // return true;
  12040. // }
  12041. }
  12042. if (i == 1) {
  12043. // 如果第一个命令是 L, C, Q
  12044. // 则 previous point 同绘制命令的第一个 point
  12045. //
  12046. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12047. xi = data[i];
  12048. yi = data[i + 1];
  12049. x0 = xi;
  12050. y0 = yi;
  12051. }
  12052. switch (cmd) {
  12053. case CMD$1.M:
  12054. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12055. // 在 closePath 的时候使用
  12056. x0 = data[i++];
  12057. y0 = data[i++];
  12058. xi = x0;
  12059. yi = y0;
  12060. break;
  12061. case CMD$1.L:
  12062. if (isStroke) {
  12063. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12064. return true;
  12065. }
  12066. }
  12067. else {
  12068. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12069. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12070. }
  12071. xi = data[i++];
  12072. yi = data[i++];
  12073. break;
  12074. case CMD$1.C:
  12075. if (isStroke) {
  12076. if (containStroke$2(xi, yi,
  12077. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12078. lineWidth, x, y
  12079. )) {
  12080. return true;
  12081. }
  12082. }
  12083. else {
  12084. w += windingCubic(
  12085. xi, yi,
  12086. data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1],
  12087. x, y
  12088. ) || 0;
  12089. }
  12090. xi = data[i++];
  12091. yi = data[i++];
  12092. break;
  12093. case CMD$1.Q:
  12094. if (isStroke) {
  12095. if (containStroke$3(xi, yi,
  12096. data[i++], data[i++], data[i], data[i + 1],
  12097. lineWidth, x, y
  12098. )) {
  12099. return true;
  12100. }
  12101. }
  12102. else {
  12103. w += windingQuadratic(
  12104. xi, yi,
  12105. data[i++], data[i++], data[i], data[i + 1],
  12106. x, y
  12107. ) || 0;
  12108. }
  12109. xi = data[i++];
  12110. yi = data[i++];
  12111. break;
  12112. case CMD$1.A:
  12113. // TODO Arc 判断的开销比较大
  12114. var cx = data[i++];
  12115. var cy = data[i++];
  12116. var rx = data[i++];
  12117. var ry = data[i++];
  12118. var theta = data[i++];
  12119. var dTheta = data[i++];
  12120. // TODO Arc 旋转
  12121. var psi = data[i++];
  12122. var anticlockwise = 1 - data[i++];
  12123. var x1 = Math.cos(theta) * rx + cx;
  12124. var y1 = Math.sin(theta) * ry + cy;
  12125. // 不是直接使用 arc 命令
  12126. if (i > 1) {
  12127. w += windingLine(xi, yi, x1, y1, x, y);
  12128. }
  12129. else {
  12130. // 第一个命令起点还未定义
  12131. x0 = x1;
  12132. y0 = y1;
  12133. }
  12134. // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12135. var _x = (x - cx) * ry / rx + cx;
  12136. if (isStroke) {
  12137. if (containStroke$4(
  12138. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12139. lineWidth, _x, y
  12140. )) {
  12141. return true;
  12142. }
  12143. }
  12144. else {
  12145. w += windingArc(
  12146. cx, cy, ry, theta, theta + dTheta, anticlockwise,
  12147. _x, y
  12148. );
  12149. }
  12150. xi = Math.cos(theta + dTheta) * rx + cx;
  12151. yi = Math.sin(theta + dTheta) * ry + cy;
  12152. break;
  12153. case CMD$1.R:
  12154. x0 = xi = data[i++];
  12155. y0 = yi = data[i++];
  12156. var width = data[i++];
  12157. var height = data[i++];
  12158. var x1 = x0 + width;
  12159. var y1 = y0 + height;
  12160. if (isStroke) {
  12161. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y)
  12162. || containStroke$1(x1, y0, x1, y1, lineWidth, x, y)
  12163. || containStroke$1(x1, y1, x0, y1, lineWidth, x, y)
  12164. || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)
  12165. ) {
  12166. return true;
  12167. }
  12168. }
  12169. else {
  12170. // FIXME Clockwise ?
  12171. w += windingLine(x1, y0, x1, y1, x, y);
  12172. w += windingLine(x0, y1, x0, y0, x, y);
  12173. }
  12174. break;
  12175. case CMD$1.Z:
  12176. if (isStroke) {
  12177. if (containStroke$1(
  12178. xi, yi, x0, y0, lineWidth, x, y
  12179. )) {
  12180. return true;
  12181. }
  12182. }
  12183. else {
  12184. // Close a subpath
  12185. w += windingLine(xi, yi, x0, y0, x, y);
  12186. // 如果被任何一个 subpath 包含
  12187. // FIXME subpaths may overlap
  12188. // if (w !== 0) {
  12189. // return true;
  12190. // }
  12191. }
  12192. xi = x0;
  12193. yi = y0;
  12194. break;
  12195. }
  12196. }
  12197. if (!isStroke && !isAroundEqual(yi, y0)) {
  12198. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12199. }
  12200. return w !== 0;
  12201. }
  12202. function contain(pathData, x, y) {
  12203. return containPath(pathData, 0, false, x, y);
  12204. }
  12205. function containStroke(pathData, lineWidth, x, y) {
  12206. return containPath(pathData, lineWidth, true, x, y);
  12207. }
  12208. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12209. var abs = Math.abs;
  12210. var pathProxyForDraw = new PathProxy(true);
  12211. /**
  12212. * @alias module:zrender/graphic/Path
  12213. * @extends module:zrender/graphic/Displayable
  12214. * @constructor
  12215. * @param {Object} opts
  12216. */
  12217. function Path(opts) {
  12218. Displayable.call(this, opts);
  12219. /**
  12220. * @type {module:zrender/core/PathProxy}
  12221. * @readOnly
  12222. */
  12223. this.path = null;
  12224. }
  12225. Path.prototype = {
  12226. constructor: Path,
  12227. type: 'path',
  12228. __dirtyPath: true,
  12229. strokeContainThreshold: 5,
  12230. brush: function (ctx, prevEl) {
  12231. var style = this.style;
  12232. var path = this.path || pathProxyForDraw;
  12233. var hasStroke = style.hasStroke();
  12234. var hasFill = style.hasFill();
  12235. var fill = style.fill;
  12236. var stroke = style.stroke;
  12237. var hasFillGradient = hasFill && !!(fill.colorStops);
  12238. var hasStrokeGradient = hasStroke && !!(stroke.colorStops);
  12239. var hasFillPattern = hasFill && !!(fill.image);
  12240. var hasStrokePattern = hasStroke && !!(stroke.image);
  12241. style.bind(ctx, this, prevEl);
  12242. this.setTransform(ctx);
  12243. if (this.__dirty) {
  12244. var rect;
  12245. // Update gradient because bounding rect may changed
  12246. if (hasFillGradient) {
  12247. rect = rect || this.getBoundingRect();
  12248. this._fillGradient = style.getGradient(ctx, fill, rect);
  12249. }
  12250. if (hasStrokeGradient) {
  12251. rect = rect || this.getBoundingRect();
  12252. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12253. }
  12254. }
  12255. // Use the gradient or pattern
  12256. if (hasFillGradient) {
  12257. // PENDING If may have affect the state
  12258. ctx.fillStyle = this._fillGradient;
  12259. }
  12260. else if (hasFillPattern) {
  12261. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12262. }
  12263. if (hasStrokeGradient) {
  12264. ctx.strokeStyle = this._strokeGradient;
  12265. }
  12266. else if (hasStrokePattern) {
  12267. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12268. }
  12269. var lineDash = style.lineDash;
  12270. var lineDashOffset = style.lineDashOffset;
  12271. var ctxLineDash = !!ctx.setLineDash;
  12272. // Update path sx, sy
  12273. var scale = this.getGlobalScale();
  12274. path.setScale(scale[0], scale[1]);
  12275. // Proxy context
  12276. // Rebuild path in following 2 cases
  12277. // 1. Path is dirty
  12278. // 2. Path needs javascript implemented lineDash stroking.
  12279. // In this case, lineDash information will not be saved in PathProxy
  12280. if (this.__dirtyPath
  12281. || (lineDash && !ctxLineDash && hasStroke)
  12282. ) {
  12283. path.beginPath(ctx);
  12284. // Setting line dash before build path
  12285. if (lineDash && !ctxLineDash) {
  12286. path.setLineDash(lineDash);
  12287. path.setLineDashOffset(lineDashOffset);
  12288. }
  12289. this.buildPath(path, this.shape, false);
  12290. // Clear path dirty flag
  12291. if (this.path) {
  12292. this.__dirtyPath = false;
  12293. }
  12294. }
  12295. else {
  12296. // Replay path building
  12297. ctx.beginPath();
  12298. this.path.rebuildPath(ctx);
  12299. }
  12300. hasFill && path.fill(ctx);
  12301. if (lineDash && ctxLineDash) {
  12302. ctx.setLineDash(lineDash);
  12303. ctx.lineDashOffset = lineDashOffset;
  12304. }
  12305. hasStroke && path.stroke(ctx);
  12306. if (lineDash && ctxLineDash) {
  12307. // PENDING
  12308. // Remove lineDash
  12309. ctx.setLineDash([]);
  12310. }
  12311. // Draw rect text
  12312. if (style.text != null) {
  12313. // Only restore transform when needs draw text.
  12314. this.restoreTransform(ctx);
  12315. this.drawRectText(ctx, this.getBoundingRect());
  12316. }
  12317. },
  12318. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12319. // Like in circle
  12320. buildPath: function (ctx, shapeCfg, inBundle) {},
  12321. createPathProxy: function () {
  12322. this.path = new PathProxy();
  12323. },
  12324. getBoundingRect: function () {
  12325. var rect = this._rect;
  12326. var style = this.style;
  12327. var needsUpdateRect = !rect;
  12328. if (needsUpdateRect) {
  12329. var path = this.path;
  12330. if (!path) {
  12331. // Create path on demand.
  12332. path = this.path = new PathProxy();
  12333. }
  12334. if (this.__dirtyPath) {
  12335. path.beginPath();
  12336. this.buildPath(path, this.shape, false);
  12337. }
  12338. rect = path.getBoundingRect();
  12339. }
  12340. this._rect = rect;
  12341. if (style.hasStroke()) {
  12342. // Needs update rect with stroke lineWidth when
  12343. // 1. Element changes scale or lineWidth
  12344. // 2. Shape is changed
  12345. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12346. if (this.__dirty || needsUpdateRect) {
  12347. rectWithStroke.copy(rect);
  12348. // FIXME Must after updateTransform
  12349. var w = style.lineWidth;
  12350. // PENDING, Min line width is needed when line is horizontal or vertical
  12351. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12352. // Only add extra hover lineWidth when there are no fill
  12353. if (!style.hasFill()) {
  12354. w = Math.max(w, this.strokeContainThreshold || 4);
  12355. }
  12356. // Consider line width
  12357. // Line scale can't be 0;
  12358. if (lineScale > 1e-10) {
  12359. rectWithStroke.width += w / lineScale;
  12360. rectWithStroke.height += w / lineScale;
  12361. rectWithStroke.x -= w / lineScale / 2;
  12362. rectWithStroke.y -= w / lineScale / 2;
  12363. }
  12364. }
  12365. // Return rect with stroke
  12366. return rectWithStroke;
  12367. }
  12368. return rect;
  12369. },
  12370. contain: function (x, y) {
  12371. var localPos = this.transformCoordToLocal(x, y);
  12372. var rect = this.getBoundingRect();
  12373. var style = this.style;
  12374. x = localPos[0];
  12375. y = localPos[1];
  12376. if (rect.contain(x, y)) {
  12377. var pathData = this.path.data;
  12378. if (style.hasStroke()) {
  12379. var lineWidth = style.lineWidth;
  12380. var lineScale = style.strokeNoScale ? this.getLineScale() : 1;
  12381. // Line scale can't be 0;
  12382. if (lineScale > 1e-10) {
  12383. // Only add extra hover lineWidth when there are no fill
  12384. if (!style.hasFill()) {
  12385. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12386. }
  12387. if (containStroke(
  12388. pathData, lineWidth / lineScale, x, y
  12389. )) {
  12390. return true;
  12391. }
  12392. }
  12393. }
  12394. if (style.hasFill()) {
  12395. return contain(pathData, x, y);
  12396. }
  12397. }
  12398. return false;
  12399. },
  12400. /**
  12401. * @param {boolean} dirtyPath
  12402. */
  12403. dirty: function (dirtyPath) {
  12404. if (dirtyPath == null) {
  12405. dirtyPath = true;
  12406. }
  12407. // Only mark dirty, not mark clean
  12408. if (dirtyPath) {
  12409. this.__dirtyPath = dirtyPath;
  12410. this._rect = null;
  12411. }
  12412. this.__dirty = true;
  12413. this.__zr && this.__zr.refresh();
  12414. // Used as a clipping path
  12415. if (this.__clipTarget) {
  12416. this.__clipTarget.dirty();
  12417. }
  12418. },
  12419. /**
  12420. * Alias for animate('shape')
  12421. * @param {boolean} loop
  12422. */
  12423. animateShape: function (loop) {
  12424. return this.animate('shape', loop);
  12425. },
  12426. // Overwrite attrKV
  12427. attrKV: function (key, value) {
  12428. // FIXME
  12429. if (key === 'shape') {
  12430. this.setShape(value);
  12431. this.__dirtyPath = true;
  12432. this._rect = null;
  12433. }
  12434. else {
  12435. Displayable.prototype.attrKV.call(this, key, value);
  12436. }
  12437. },
  12438. /**
  12439. * @param {Object|string} key
  12440. * @param {*} value
  12441. */
  12442. setShape: function (key, value) {
  12443. var shape = this.shape;
  12444. // Path from string may not have shape
  12445. if (shape) {
  12446. if (isObject$1(key)) {
  12447. for (var name in key) {
  12448. if (key.hasOwnProperty(name)) {
  12449. shape[name] = key[name];
  12450. }
  12451. }
  12452. }
  12453. else {
  12454. shape[key] = value;
  12455. }
  12456. this.dirty(true);
  12457. }
  12458. return this;
  12459. },
  12460. getLineScale: function () {
  12461. var m = this.transform;
  12462. // Get the line scale.
  12463. // Determinant of `m` means how much the area is enlarged by the
  12464. // transformation. So its square root can be used as a scale factor
  12465. // for width.
  12466. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10
  12467. ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1]))
  12468. : 1;
  12469. }
  12470. };
  12471. /**
  12472. * 扩展一个 Path element, 比如星形,圆等。
  12473. * Extend a path element
  12474. * @param {Object} props
  12475. * @param {string} props.type Path type
  12476. * @param {Function} props.init Initialize
  12477. * @param {Function} props.buildPath Overwrite buildPath method
  12478. * @param {Object} [props.style] Extended default style config
  12479. * @param {Object} [props.shape] Extended default shape config
  12480. */
  12481. Path.extend = function (defaults$$1) {
  12482. var Sub = function (opts) {
  12483. Path.call(this, opts);
  12484. if (defaults$$1.style) {
  12485. // Extend default style
  12486. this.style.extendFrom(defaults$$1.style, false);
  12487. }
  12488. // Extend default shape
  12489. var defaultShape = defaults$$1.shape;
  12490. if (defaultShape) {
  12491. this.shape = this.shape || {};
  12492. var thisShape = this.shape;
  12493. for (var name in defaultShape) {
  12494. if (
  12495. ! thisShape.hasOwnProperty(name)
  12496. && defaultShape.hasOwnProperty(name)
  12497. ) {
  12498. thisShape[name] = defaultShape[name];
  12499. }
  12500. }
  12501. }
  12502. defaults$$1.init && defaults$$1.init.call(this, opts);
  12503. };
  12504. inherits(Sub, Path);
  12505. // FIXME 不能 extend position, rotation 等引用对象
  12506. for (var name in defaults$$1) {
  12507. // Extending prototype values and methods
  12508. if (name !== 'style' && name !== 'shape') {
  12509. Sub.prototype[name] = defaults$$1[name];
  12510. }
  12511. }
  12512. return Sub;
  12513. };
  12514. inherits(Path, Displayable);
  12515. var CMD$2 = PathProxy.CMD;
  12516. var points = [[], [], []];
  12517. var mathSqrt$3 = Math.sqrt;
  12518. var mathAtan2 = Math.atan2;
  12519. var transformPath = function (path, m) {
  12520. var data = path.data;
  12521. var cmd;
  12522. var nPoint;
  12523. var i;
  12524. var j;
  12525. var k;
  12526. var p;
  12527. var M = CMD$2.M;
  12528. var C = CMD$2.C;
  12529. var L = CMD$2.L;
  12530. var R = CMD$2.R;
  12531. var A = CMD$2.A;
  12532. var Q = CMD$2.Q;
  12533. for (i = 0, j = 0; i < data.length;) {
  12534. cmd = data[i++];
  12535. j = i;
  12536. nPoint = 0;
  12537. switch (cmd) {
  12538. case M:
  12539. nPoint = 1;
  12540. break;
  12541. case L:
  12542. nPoint = 1;
  12543. break;
  12544. case C:
  12545. nPoint = 3;
  12546. break;
  12547. case Q:
  12548. nPoint = 2;
  12549. break;
  12550. case A:
  12551. var x = m[4];
  12552. var y = m[5];
  12553. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12554. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12555. var angle = mathAtan2(-m[1] / sy, m[0] / sx);
  12556. // cx
  12557. data[i] *= sx;
  12558. data[i++] += x;
  12559. // cy
  12560. data[i] *= sy;
  12561. data[i++] += y;
  12562. // Scale rx and ry
  12563. // FIXME Assume psi is 0 here
  12564. data[i++] *= sx;
  12565. data[i++] *= sy;
  12566. // Start angle
  12567. data[i++] += angle;
  12568. // end angle
  12569. data[i++] += angle;
  12570. // FIXME psi
  12571. i += 2;
  12572. j = i;
  12573. break;
  12574. case R:
  12575. // x0, y0
  12576. p[0] = data[i++];
  12577. p[1] = data[i++];
  12578. applyTransform(p, p, m);
  12579. data[j++] = p[0];
  12580. data[j++] = p[1];
  12581. // x1, y1
  12582. p[0] += data[i++];
  12583. p[1] += data[i++];
  12584. applyTransform(p, p, m);
  12585. data[j++] = p[0];
  12586. data[j++] = p[1];
  12587. }
  12588. for (k = 0; k < nPoint; k++) {
  12589. var p = points[k];
  12590. p[0] = data[i++];
  12591. p[1] = data[i++];
  12592. applyTransform(p, p, m);
  12593. // Write back
  12594. data[j++] = p[0];
  12595. data[j++] = p[1];
  12596. }
  12597. }
  12598. };
  12599. // command chars
  12600. var cc = [
  12601. 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12602. 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12603. ];
  12604. var mathSqrt = Math.sqrt;
  12605. var mathSin = Math.sin;
  12606. var mathCos = Math.cos;
  12607. var PI = Math.PI;
  12608. var vMag = function(v) {
  12609. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12610. };
  12611. var vRatio = function(u, v) {
  12612. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12613. };
  12614. var vAngle = function(u, v) {
  12615. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1)
  12616. * Math.acos(vRatio(u, v));
  12617. };
  12618. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12619. var psi = psiDeg * (PI / 180.0);
  12620. var xp = mathCos(psi) * (x1 - x2) / 2.0
  12621. + mathSin(psi) * (y1 - y2) / 2.0;
  12622. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0
  12623. + mathCos(psi) * (y1 - y2) / 2.0;
  12624. var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry);
  12625. if (lambda > 1) {
  12626. rx *= mathSqrt(lambda);
  12627. ry *= mathSqrt(lambda);
  12628. }
  12629. var f = (fa === fs ? -1 : 1)
  12630. * mathSqrt((((rx * rx) * (ry * ry))
  12631. - ((rx * rx) * (yp * yp))
  12632. - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp)
  12633. + (ry * ry) * (xp * xp))
  12634. ) || 0;
  12635. var cxp = f * rx * yp / ry;
  12636. var cyp = f * -ry * xp / rx;
  12637. var cx = (x1 + x2) / 2.0
  12638. + mathCos(psi) * cxp
  12639. - mathSin(psi) * cyp;
  12640. var cy = (y1 + y2) / 2.0
  12641. + mathSin(psi) * cxp
  12642. + mathCos(psi) * cyp;
  12643. var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]);
  12644. var u = [ (xp - cxp) / rx, (yp - cyp) / ry ];
  12645. var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ];
  12646. var dTheta = vAngle(u, v);
  12647. if (vRatio(u, v) <= -1) {
  12648. dTheta = PI;
  12649. }
  12650. if (vRatio(u, v) >= 1) {
  12651. dTheta = 0;
  12652. }
  12653. if (fs === 0 && dTheta > 0) {
  12654. dTheta = dTheta - 2 * PI;
  12655. }
  12656. if (fs === 1 && dTheta < 0) {
  12657. dTheta = dTheta + 2 * PI;
  12658. }
  12659. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12660. }
  12661. function createPathProxyFromString(data) {
  12662. if (!data) {
  12663. return [];
  12664. }
  12665. // command string
  12666. var cs = data.replace(/-/g, ' -')
  12667. .replace(/ /g, ' ')
  12668. .replace(/ /g, ',')
  12669. .replace(/,,/g, ',');
  12670. var n;
  12671. // create pipes so that we can split the data
  12672. for (n = 0; n < cc.length; n++) {
  12673. cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12674. }
  12675. // create array
  12676. var arr = cs.split('|');
  12677. // init context point
  12678. var cpx = 0;
  12679. var cpy = 0;
  12680. var path = new PathProxy();
  12681. var CMD = PathProxy.CMD;
  12682. var prevCmd;
  12683. for (n = 1; n < arr.length; n++) {
  12684. var str = arr[n];
  12685. var c = str.charAt(0);
  12686. var off = 0;
  12687. var p = str.slice(1).replace(/e,-/g, 'e-').split(',');
  12688. var cmd;
  12689. if (p.length > 0 && p[0] === '') {
  12690. p.shift();
  12691. }
  12692. for (var i = 0; i < p.length; i++) {
  12693. p[i] = parseFloat(p[i]);
  12694. }
  12695. while (off < p.length && !isNaN(p[off])) {
  12696. if (isNaN(p[0])) {
  12697. break;
  12698. }
  12699. var ctlPtx;
  12700. var ctlPty;
  12701. var rx;
  12702. var ry;
  12703. var psi;
  12704. var fa;
  12705. var fs;
  12706. var x1 = cpx;
  12707. var y1 = cpy;
  12708. // convert l, H, h, V, and v to L
  12709. switch (c) {
  12710. case 'l':
  12711. cpx += p[off++];
  12712. cpy += p[off++];
  12713. cmd = CMD.L;
  12714. path.addData(cmd, cpx, cpy);
  12715. break;
  12716. case 'L':
  12717. cpx = p[off++];
  12718. cpy = p[off++];
  12719. cmd = CMD.L;
  12720. path.addData(cmd, cpx, cpy);
  12721. break;
  12722. case 'm':
  12723. cpx += p[off++];
  12724. cpy += p[off++];
  12725. cmd = CMD.M;
  12726. path.addData(cmd, cpx, cpy);
  12727. c = 'l';
  12728. break;
  12729. case 'M':
  12730. cpx = p[off++];
  12731. cpy = p[off++];
  12732. cmd = CMD.M;
  12733. path.addData(cmd, cpx, cpy);
  12734. c = 'L';
  12735. break;
  12736. case 'h':
  12737. cpx += p[off++];
  12738. cmd = CMD.L;
  12739. path.addData(cmd, cpx, cpy);
  12740. break;
  12741. case 'H':
  12742. cpx = p[off++];
  12743. cmd = CMD.L;
  12744. path.addData(cmd, cpx, cpy);
  12745. break;
  12746. case 'v':
  12747. cpy += p[off++];
  12748. cmd = CMD.L;
  12749. path.addData(cmd, cpx, cpy);
  12750. break;
  12751. case 'V':
  12752. cpy = p[off++];
  12753. cmd = CMD.L;
  12754. path.addData(cmd, cpx, cpy);
  12755. break;
  12756. case 'C':
  12757. cmd = CMD.C;
  12758. path.addData(
  12759. cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]
  12760. );
  12761. cpx = p[off - 2];
  12762. cpy = p[off - 1];
  12763. break;
  12764. case 'c':
  12765. cmd = CMD.C;
  12766. path.addData(
  12767. cmd,
  12768. p[off++] + cpx, p[off++] + cpy,
  12769. p[off++] + cpx, p[off++] + cpy,
  12770. p[off++] + cpx, p[off++] + cpy
  12771. );
  12772. cpx += p[off - 2];
  12773. cpy += p[off - 1];
  12774. break;
  12775. case 'S':
  12776. ctlPtx = cpx;
  12777. ctlPty = cpy;
  12778. var len = path.len();
  12779. var pathData = path.data;
  12780. if (prevCmd === CMD.C) {
  12781. ctlPtx += cpx - pathData[len - 4];
  12782. ctlPty += cpy - pathData[len - 3];
  12783. }
  12784. cmd = CMD.C;
  12785. x1 = p[off++];
  12786. y1 = p[off++];
  12787. cpx = p[off++];
  12788. cpy = p[off++];
  12789. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12790. break;
  12791. case 's':
  12792. ctlPtx = cpx;
  12793. ctlPty = cpy;
  12794. var len = path.len();
  12795. var pathData = path.data;
  12796. if (prevCmd === CMD.C) {
  12797. ctlPtx += cpx - pathData[len - 4];
  12798. ctlPty += cpy - pathData[len - 3];
  12799. }
  12800. cmd = CMD.C;
  12801. x1 = cpx + p[off++];
  12802. y1 = cpy + p[off++];
  12803. cpx += p[off++];
  12804. cpy += p[off++];
  12805. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12806. break;
  12807. case 'Q':
  12808. x1 = p[off++];
  12809. y1 = p[off++];
  12810. cpx = p[off++];
  12811. cpy = p[off++];
  12812. cmd = CMD.Q;
  12813. path.addData(cmd, x1, y1, cpx, cpy);
  12814. break;
  12815. case 'q':
  12816. x1 = p[off++] + cpx;
  12817. y1 = p[off++] + cpy;
  12818. cpx += p[off++];
  12819. cpy += p[off++];
  12820. cmd = CMD.Q;
  12821. path.addData(cmd, x1, y1, cpx, cpy);
  12822. break;
  12823. case 'T':
  12824. ctlPtx = cpx;
  12825. ctlPty = cpy;
  12826. var len = path.len();
  12827. var pathData = path.data;
  12828. if (prevCmd === CMD.Q) {
  12829. ctlPtx += cpx - pathData[len - 4];
  12830. ctlPty += cpy - pathData[len - 3];
  12831. }
  12832. cpx = p[off++];
  12833. cpy = p[off++];
  12834. cmd = CMD.Q;
  12835. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12836. break;
  12837. case 't':
  12838. ctlPtx = cpx;
  12839. ctlPty = cpy;
  12840. var len = path.len();
  12841. var pathData = path.data;
  12842. if (prevCmd === CMD.Q) {
  12843. ctlPtx += cpx - pathData[len - 4];
  12844. ctlPty += cpy - pathData[len - 3];
  12845. }
  12846. cpx += p[off++];
  12847. cpy += p[off++];
  12848. cmd = CMD.Q;
  12849. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12850. break;
  12851. case 'A':
  12852. rx = p[off++];
  12853. ry = p[off++];
  12854. psi = p[off++];
  12855. fa = p[off++];
  12856. fs = p[off++];
  12857. x1 = cpx, y1 = cpy;
  12858. cpx = p[off++];
  12859. cpy = p[off++];
  12860. cmd = CMD.A;
  12861. processArc(
  12862. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12863. );
  12864. break;
  12865. case 'a':
  12866. rx = p[off++];
  12867. ry = p[off++];
  12868. psi = p[off++];
  12869. fa = p[off++];
  12870. fs = p[off++];
  12871. x1 = cpx, y1 = cpy;
  12872. cpx += p[off++];
  12873. cpy += p[off++];
  12874. cmd = CMD.A;
  12875. processArc(
  12876. x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path
  12877. );
  12878. break;
  12879. }
  12880. }
  12881. if (c === 'z' || c === 'Z') {
  12882. cmd = CMD.Z;
  12883. path.addData(cmd);
  12884. }
  12885. prevCmd = cmd;
  12886. }
  12887. path.toStatic();
  12888. return path;
  12889. }
  12890. // TODO Optimize double memory cost problem
  12891. function createPathOptions(str, opts) {
  12892. var pathProxy = createPathProxyFromString(str);
  12893. opts = opts || {};
  12894. opts.buildPath = function (path) {
  12895. if (path.setData) {
  12896. path.setData(pathProxy.data);
  12897. // Svg and vml renderer don't have context
  12898. var ctx = path.getContext();
  12899. if (ctx) {
  12900. path.rebuildPath(ctx);
  12901. }
  12902. }
  12903. else {
  12904. var ctx = path;
  12905. pathProxy.rebuildPath(ctx);
  12906. }
  12907. };
  12908. opts.applyTransform = function (m) {
  12909. transformPath(pathProxy, m);
  12910. this.dirty(true);
  12911. };
  12912. return opts;
  12913. }
  12914. /**
  12915. * Create a Path object from path string data
  12916. * http://www.w3.org/TR/SVG/paths.html#PathData
  12917. * @param {Object} opts Other options
  12918. */
  12919. function createFromString(str, opts) {
  12920. return new Path(createPathOptions(str, opts));
  12921. }
  12922. /**
  12923. * Create a Path class from path string data
  12924. * @param {string} str
  12925. * @param {Object} opts Other options
  12926. */
  12927. function extendFromString(str, opts) {
  12928. return Path.extend(createPathOptions(str, opts));
  12929. }
  12930. /**
  12931. * Merge multiple paths
  12932. */
  12933. // TODO Apply transform
  12934. // TODO stroke dash
  12935. // TODO Optimize double memory cost problem
  12936. function mergePath$1(pathEls, opts) {
  12937. var pathList = [];
  12938. var len = pathEls.length;
  12939. for (var i = 0; i < len; i++) {
  12940. var pathEl = pathEls[i];
  12941. if (!pathEl.path) {
  12942. pathEl.createPathProxy();
  12943. }
  12944. if (pathEl.__dirtyPath) {
  12945. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12946. }
  12947. pathList.push(pathEl.path);
  12948. }
  12949. var pathBundle = new Path(opts);
  12950. // Need path proxy.
  12951. pathBundle.createPathProxy();
  12952. pathBundle.buildPath = function (path) {
  12953. path.appendPath(pathList);
  12954. // Svg and vml renderer don't have context
  12955. var ctx = path.getContext();
  12956. if (ctx) {
  12957. path.rebuildPath(ctx);
  12958. }
  12959. };
  12960. return pathBundle;
  12961. }
  12962. /**
  12963. * @alias zrender/graphic/Text
  12964. * @extends module:zrender/graphic/Displayable
  12965. * @constructor
  12966. * @param {Object} opts
  12967. */
  12968. var Text = function (opts) { // jshint ignore:line
  12969. Displayable.call(this, opts);
  12970. };
  12971. Text.prototype = {
  12972. constructor: Text,
  12973. type: 'text',
  12974. brush: function (ctx, prevEl) {
  12975. var style = this.style;
  12976. // Optimize, avoid normalize every time.
  12977. this.__dirty && normalizeTextStyle(style, true);
  12978. // Use props with prefix 'text'.
  12979. style.fill = style.stroke = style.shadowBlur = style.shadowColor =
  12980. style.shadowOffsetX = style.shadowOffsetY = null;
  12981. var text = style.text;
  12982. // Convert to string
  12983. text != null && (text += '');
  12984. // Always bind style
  12985. style.bind(ctx, this, prevEl);
  12986. if (!needDrawText(text, style)) {
  12987. return;
  12988. }
  12989. this.setTransform(ctx);
  12990. renderText(this, ctx, text, style);
  12991. this.restoreTransform(ctx);
  12992. },
  12993. getBoundingRect: function () {
  12994. var style = this.style;
  12995. // Optimize, avoid normalize every time.
  12996. this.__dirty && normalizeTextStyle(style, true);
  12997. if (!this._rect) {
  12998. var text = style.text;
  12999. text != null ? (text += '') : (text = '');
  13000. var rect = getBoundingRect(
  13001. style.text + '',
  13002. style.font,
  13003. style.textAlign,
  13004. style.textVerticalAlign,
  13005. style.textPadding,
  13006. style.rich
  13007. );
  13008. rect.x += style.x || 0;
  13009. rect.y += style.y || 0;
  13010. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  13011. var w = style.textStrokeWidth;
  13012. rect.x -= w / 2;
  13013. rect.y -= w / 2;
  13014. rect.width += w;
  13015. rect.height += w;
  13016. }
  13017. this._rect = rect;
  13018. }
  13019. return this._rect;
  13020. }
  13021. };
  13022. inherits(Text, Displayable);
  13023. /**
  13024. * 圆形
  13025. * @module zrender/shape/Circle
  13026. */
  13027. var Circle = Path.extend({
  13028. type: 'circle',
  13029. shape: {
  13030. cx: 0,
  13031. cy: 0,
  13032. r: 0
  13033. },
  13034. buildPath : function (ctx, shape, inBundle) {
  13035. // Better stroking in ShapeBundle
  13036. // Always do it may have performence issue ( fill may be 2x more cost)
  13037. if (inBundle) {
  13038. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13039. }
  13040. // else {
  13041. // if (ctx.allocate && !ctx.data.length) {
  13042. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13043. // }
  13044. // }
  13045. // Better stroking in ShapeBundle
  13046. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13047. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13048. }
  13049. });
  13050. // Fix weird bug in some version of IE11 (like 11.0.9600.178**),
  13051. // where exception "unexpected call to method or property access"
  13052. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13053. // whose area size is zero is drawn and ctx.clip() is called and
  13054. // shadowBlur is set. See #4572, #3112, #5777.
  13055. // (e.g.,
  13056. // ctx.moveTo(10, 10);
  13057. // ctx.lineTo(20, 10);
  13058. // ctx.closePath();
  13059. // ctx.clip();
  13060. // ctx.shadowBlur = 10;
  13061. // ...
  13062. // ctx.fill();
  13063. // )
  13064. var shadowTemp = [
  13065. ['shadowBlur', 0],
  13066. ['shadowColor', '#000'],
  13067. ['shadowOffsetX', 0],
  13068. ['shadowOffsetY', 0]
  13069. ];
  13070. var fixClipWithShadow = function (orignalBrush) {
  13071. // version string can be: '11.0'
  13072. return (env$1.browser.ie && env$1.browser.version >= 11)
  13073. ? function () {
  13074. var clipPaths = this.__clipPaths;
  13075. var style = this.style;
  13076. var modified;
  13077. if (clipPaths) {
  13078. for (var i = 0; i < clipPaths.length; i++) {
  13079. var clipPath = clipPaths[i];
  13080. var shape = clipPath && clipPath.shape;
  13081. var type = clipPath && clipPath.type;
  13082. if (shape && (
  13083. (type === 'sector' && shape.startAngle === shape.endAngle)
  13084. || (type === 'rect' && (!shape.width || !shape.height))
  13085. )) {
  13086. for (var j = 0; j < shadowTemp.length; j++) {
  13087. // It is save to put shadowTemp static, because shadowTemp
  13088. // will be all modified each item brush called.
  13089. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13090. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13091. }
  13092. modified = true;
  13093. break;
  13094. }
  13095. }
  13096. }
  13097. orignalBrush.apply(this, arguments);
  13098. if (modified) {
  13099. for (var j = 0; j < shadowTemp.length; j++) {
  13100. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13101. }
  13102. }
  13103. }
  13104. : orignalBrush;
  13105. };
  13106. /**
  13107. * 扇形
  13108. * @module zrender/graphic/shape/Sector
  13109. */
  13110. var Sector = Path.extend({
  13111. type: 'sector',
  13112. shape: {
  13113. cx: 0,
  13114. cy: 0,
  13115. r0: 0,
  13116. r: 0,
  13117. startAngle: 0,
  13118. endAngle: Math.PI * 2,
  13119. clockwise: true
  13120. },
  13121. brush: fixClipWithShadow(Path.prototype.brush),
  13122. buildPath: function (ctx, shape) {
  13123. var x = shape.cx;
  13124. var y = shape.cy;
  13125. var r0 = Math.max(shape.r0 || 0, 0);
  13126. var r = Math.max(shape.r, 0);
  13127. var startAngle = shape.startAngle;
  13128. var endAngle = shape.endAngle;
  13129. var clockwise = shape.clockwise;
  13130. var unitX = Math.cos(startAngle);
  13131. var unitY = Math.sin(startAngle);
  13132. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13133. ctx.lineTo(unitX * r + x, unitY * r + y);
  13134. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13135. ctx.lineTo(
  13136. Math.cos(endAngle) * r0 + x,
  13137. Math.sin(endAngle) * r0 + y
  13138. );
  13139. if (r0 !== 0) {
  13140. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13141. }
  13142. ctx.closePath();
  13143. }
  13144. });
  13145. /**
  13146. * 圆环
  13147. * @module zrender/graphic/shape/Ring
  13148. */
  13149. var Ring = Path.extend({
  13150. type: 'ring',
  13151. shape: {
  13152. cx: 0,
  13153. cy: 0,
  13154. r: 0,
  13155. r0: 0
  13156. },
  13157. buildPath: function (ctx, shape) {
  13158. var x = shape.cx;
  13159. var y = shape.cy;
  13160. var PI2 = Math.PI * 2;
  13161. ctx.moveTo(x + shape.r, y);
  13162. ctx.arc(x, y, shape.r, 0, PI2, false);
  13163. ctx.moveTo(x + shape.r0, y);
  13164. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13165. }
  13166. });
  13167. /**
  13168. * Catmull-Rom spline 插值折线
  13169. * @module zrender/shape/util/smoothSpline
  13170. * @author pissang (https://www.github.com/pissang)
  13171. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13172. * errorrik (errorrik@gmail.com)
  13173. */
  13174. /**
  13175. * @inner
  13176. */
  13177. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13178. var v0 = (p2 - p0) * 0.5;
  13179. var v1 = (p3 - p1) * 0.5;
  13180. return (2 * (p1 - p2) + v0 + v1) * t3
  13181. + (-3 * (p1 - p2) - 2 * v0 - v1) * t2
  13182. + v0 * t + p1;
  13183. }
  13184. /**
  13185. * @alias module:zrender/shape/util/smoothSpline
  13186. * @param {Array} points 线段顶点数组
  13187. * @param {boolean} isLoop
  13188. * @return {Array}
  13189. */
  13190. var smoothSpline = function (points, isLoop) {
  13191. var len$$1 = points.length;
  13192. var ret = [];
  13193. var distance$$1 = 0;
  13194. for (var i = 1; i < len$$1; i++) {
  13195. distance$$1 += distance(points[i - 1], points[i]);
  13196. }
  13197. var segs = distance$$1 / 2;
  13198. segs = segs < len$$1 ? len$$1 : segs;
  13199. for (var i = 0; i < segs; i++) {
  13200. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13201. var idx = Math.floor(pos);
  13202. var w = pos - idx;
  13203. var p0;
  13204. var p1 = points[idx % len$$1];
  13205. var p2;
  13206. var p3;
  13207. if (!isLoop) {
  13208. p0 = points[idx === 0 ? idx : idx - 1];
  13209. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13210. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13211. }
  13212. else {
  13213. p0 = points[(idx - 1 + len$$1) % len$$1];
  13214. p2 = points[(idx + 1) % len$$1];
  13215. p3 = points[(idx + 2) % len$$1];
  13216. }
  13217. var w2 = w * w;
  13218. var w3 = w * w2;
  13219. ret.push([
  13220. interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3),
  13221. interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)
  13222. ]);
  13223. }
  13224. return ret;
  13225. };
  13226. /**
  13227. * 贝塞尔平滑曲线
  13228. * @module zrender/shape/util/smoothBezier
  13229. * @author pissang (https://www.github.com/pissang)
  13230. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13231. * errorrik (errorrik@gmail.com)
  13232. */
  13233. /**
  13234. * 贝塞尔平滑曲线
  13235. * @alias module:zrender/shape/util/smoothBezier
  13236. * @param {Array} points 线段顶点数组
  13237. * @param {number} smooth 平滑等级, 0-1
  13238. * @param {boolean} isLoop
  13239. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13240. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13241. * 整个折线的包围盒做一个并集用来约束控制点。
  13242. * @param {Array} 计算出来的控制点数组
  13243. */
  13244. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13245. var cps = [];
  13246. var v = [];
  13247. var v1 = [];
  13248. var v2 = [];
  13249. var prevPoint;
  13250. var nextPoint;
  13251. var min$$1, max$$1;
  13252. if (constraint) {
  13253. min$$1 = [Infinity, Infinity];
  13254. max$$1 = [-Infinity, -Infinity];
  13255. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13256. min(min$$1, min$$1, points[i]);
  13257. max(max$$1, max$$1, points[i]);
  13258. }
  13259. // 与指定的包围盒做并集
  13260. min(min$$1, min$$1, constraint[0]);
  13261. max(max$$1, max$$1, constraint[1]);
  13262. }
  13263. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13264. var point = points[i];
  13265. if (isLoop) {
  13266. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13267. nextPoint = points[(i + 1) % len$$1];
  13268. }
  13269. else {
  13270. if (i === 0 || i === len$$1 - 1) {
  13271. cps.push(clone$1(points[i]));
  13272. continue;
  13273. }
  13274. else {
  13275. prevPoint = points[i - 1];
  13276. nextPoint = points[i + 1];
  13277. }
  13278. }
  13279. sub(v, nextPoint, prevPoint);
  13280. // use degree to scale the handle length
  13281. scale(v, v, smooth);
  13282. var d0 = distance(point, prevPoint);
  13283. var d1 = distance(point, nextPoint);
  13284. var sum = d0 + d1;
  13285. if (sum !== 0) {
  13286. d0 /= sum;
  13287. d1 /= sum;
  13288. }
  13289. scale(v1, v, -d0);
  13290. scale(v2, v, d1);
  13291. var cp0 = add([], point, v1);
  13292. var cp1 = add([], point, v2);
  13293. if (constraint) {
  13294. max(cp0, cp0, min$$1);
  13295. min(cp0, cp0, max$$1);
  13296. max(cp1, cp1, min$$1);
  13297. min(cp1, cp1, max$$1);
  13298. }
  13299. cps.push(cp0);
  13300. cps.push(cp1);
  13301. }
  13302. if (isLoop) {
  13303. cps.push(cps.shift());
  13304. }
  13305. return cps;
  13306. };
  13307. function buildPath$1(ctx, shape, closePath) {
  13308. var points = shape.points;
  13309. var smooth = shape.smooth;
  13310. if (points && points.length >= 2) {
  13311. if (smooth && smooth !== 'spline') {
  13312. var controlPoints = smoothBezier(
  13313. points, smooth, closePath, shape.smoothConstraint
  13314. );
  13315. ctx.moveTo(points[0][0], points[0][1]);
  13316. var len = points.length;
  13317. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13318. var cp1 = controlPoints[i * 2];
  13319. var cp2 = controlPoints[i * 2 + 1];
  13320. var p = points[(i + 1) % len];
  13321. ctx.bezierCurveTo(
  13322. cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]
  13323. );
  13324. }
  13325. }
  13326. else {
  13327. if (smooth === 'spline') {
  13328. points = smoothSpline(points, closePath);
  13329. }
  13330. ctx.moveTo(points[0][0], points[0][1]);
  13331. for (var i = 1, l = points.length; i < l; i++) {
  13332. ctx.lineTo(points[i][0], points[i][1]);
  13333. }
  13334. }
  13335. closePath && ctx.closePath();
  13336. }
  13337. }
  13338. /**
  13339. * 多边形
  13340. * @module zrender/shape/Polygon
  13341. */
  13342. var Polygon = Path.extend({
  13343. type: 'polygon',
  13344. shape: {
  13345. points: null,
  13346. smooth: false,
  13347. smoothConstraint: null
  13348. },
  13349. buildPath: function (ctx, shape) {
  13350. buildPath$1(ctx, shape, true);
  13351. }
  13352. });
  13353. /**
  13354. * @module zrender/graphic/shape/Polyline
  13355. */
  13356. var Polyline = Path.extend({
  13357. type: 'polyline',
  13358. shape: {
  13359. points: null,
  13360. smooth: false,
  13361. smoothConstraint: null
  13362. },
  13363. style: {
  13364. stroke: '#000',
  13365. fill: null
  13366. },
  13367. buildPath: function (ctx, shape) {
  13368. buildPath$1(ctx, shape, false);
  13369. }
  13370. });
  13371. /**
  13372. * 矩形
  13373. * @module zrender/graphic/shape/Rect
  13374. */
  13375. var Rect = Path.extend({
  13376. type: 'rect',
  13377. shape: {
  13378. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13379. // r缩写为1 相当于 [1, 1, 1, 1]
  13380. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13381. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13382. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13383. r: 0,
  13384. x: 0,
  13385. y: 0,
  13386. width: 0,
  13387. height: 0
  13388. },
  13389. buildPath: function (ctx, shape) {
  13390. var x = shape.x;
  13391. var y = shape.y;
  13392. var width = shape.width;
  13393. var height = shape.height;
  13394. if (!shape.r) {
  13395. ctx.rect(x, y, width, height);
  13396. }
  13397. else {
  13398. buildPath(ctx, shape);
  13399. }
  13400. ctx.closePath();
  13401. return;
  13402. }
  13403. });
  13404. /**
  13405. * 直线
  13406. * @module zrender/graphic/shape/Line
  13407. */
  13408. var Line = Path.extend({
  13409. type: 'line',
  13410. shape: {
  13411. // Start point
  13412. x1: 0,
  13413. y1: 0,
  13414. // End point
  13415. x2: 0,
  13416. y2: 0,
  13417. percent: 1
  13418. },
  13419. style: {
  13420. stroke: '#000',
  13421. fill: null
  13422. },
  13423. buildPath: function (ctx, shape) {
  13424. var x1 = shape.x1;
  13425. var y1 = shape.y1;
  13426. var x2 = shape.x2;
  13427. var y2 = shape.y2;
  13428. var percent = shape.percent;
  13429. if (percent === 0) {
  13430. return;
  13431. }
  13432. ctx.moveTo(x1, y1);
  13433. if (percent < 1) {
  13434. x2 = x1 * (1 - percent) + x2 * percent;
  13435. y2 = y1 * (1 - percent) + y2 * percent;
  13436. }
  13437. ctx.lineTo(x2, y2);
  13438. },
  13439. /**
  13440. * Get point at percent
  13441. * @param {number} percent
  13442. * @return {Array.<number>}
  13443. */
  13444. pointAt: function (p) {
  13445. var shape = this.shape;
  13446. return [
  13447. shape.x1 * (1 - p) + shape.x2 * p,
  13448. shape.y1 * (1 - p) + shape.y2 * p
  13449. ];
  13450. }
  13451. });
  13452. /**
  13453. * 贝塞尔曲线
  13454. * @module zrender/shape/BezierCurve
  13455. */
  13456. var out = [];
  13457. function someVectorAt(shape, t, isTangent) {
  13458. var cpx2 = shape.cpx2;
  13459. var cpy2 = shape.cpy2;
  13460. if (cpx2 === null || cpy2 === null) {
  13461. return [
  13462. (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t),
  13463. (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)
  13464. ];
  13465. }
  13466. else {
  13467. return [
  13468. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t),
  13469. (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)
  13470. ];
  13471. }
  13472. }
  13473. var BezierCurve = Path.extend({
  13474. type: 'bezier-curve',
  13475. shape: {
  13476. x1: 0,
  13477. y1: 0,
  13478. x2: 0,
  13479. y2: 0,
  13480. cpx1: 0,
  13481. cpy1: 0,
  13482. // cpx2: 0,
  13483. // cpy2: 0
  13484. // Curve show percent, for animating
  13485. percent: 1
  13486. },
  13487. style: {
  13488. stroke: '#000',
  13489. fill: null
  13490. },
  13491. buildPath: function (ctx, shape) {
  13492. var x1 = shape.x1;
  13493. var y1 = shape.y1;
  13494. var x2 = shape.x2;
  13495. var y2 = shape.y2;
  13496. var cpx1 = shape.cpx1;
  13497. var cpy1 = shape.cpy1;
  13498. var cpx2 = shape.cpx2;
  13499. var cpy2 = shape.cpy2;
  13500. var percent = shape.percent;
  13501. if (percent === 0) {
  13502. return;
  13503. }
  13504. ctx.moveTo(x1, y1);
  13505. if (cpx2 == null || cpy2 == null) {
  13506. if (percent < 1) {
  13507. quadraticSubdivide(
  13508. x1, cpx1, x2, percent, out
  13509. );
  13510. cpx1 = out[1];
  13511. x2 = out[2];
  13512. quadraticSubdivide(
  13513. y1, cpy1, y2, percent, out
  13514. );
  13515. cpy1 = out[1];
  13516. y2 = out[2];
  13517. }
  13518. ctx.quadraticCurveTo(
  13519. cpx1, cpy1,
  13520. x2, y2
  13521. );
  13522. }
  13523. else {
  13524. if (percent < 1) {
  13525. cubicSubdivide(
  13526. x1, cpx1, cpx2, x2, percent, out
  13527. );
  13528. cpx1 = out[1];
  13529. cpx2 = out[2];
  13530. x2 = out[3];
  13531. cubicSubdivide(
  13532. y1, cpy1, cpy2, y2, percent, out
  13533. );
  13534. cpy1 = out[1];
  13535. cpy2 = out[2];
  13536. y2 = out[3];
  13537. }
  13538. ctx.bezierCurveTo(
  13539. cpx1, cpy1,
  13540. cpx2, cpy2,
  13541. x2, y2
  13542. );
  13543. }
  13544. },
  13545. /**
  13546. * Get point at percent
  13547. * @param {number} t
  13548. * @return {Array.<number>}
  13549. */
  13550. pointAt: function (t) {
  13551. return someVectorAt(this.shape, t, false);
  13552. },
  13553. /**
  13554. * Get tangent at percent
  13555. * @param {number} t
  13556. * @return {Array.<number>}
  13557. */
  13558. tangentAt: function (t) {
  13559. var p = someVectorAt(this.shape, t, true);
  13560. return normalize(p, p);
  13561. }
  13562. });
  13563. /**
  13564. * 圆弧
  13565. * @module zrender/graphic/shape/Arc
  13566. */
  13567. var Arc = Path.extend({
  13568. type: 'arc',
  13569. shape: {
  13570. cx: 0,
  13571. cy: 0,
  13572. r: 0,
  13573. startAngle: 0,
  13574. endAngle: Math.PI * 2,
  13575. clockwise: true
  13576. },
  13577. style: {
  13578. stroke: '#000',
  13579. fill: null
  13580. },
  13581. buildPath: function (ctx, shape) {
  13582. var x = shape.cx;
  13583. var y = shape.cy;
  13584. var r = Math.max(shape.r, 0);
  13585. var startAngle = shape.startAngle;
  13586. var endAngle = shape.endAngle;
  13587. var clockwise = shape.clockwise;
  13588. var unitX = Math.cos(startAngle);
  13589. var unitY = Math.sin(startAngle);
  13590. ctx.moveTo(unitX * r + x, unitY * r + y);
  13591. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13592. }
  13593. });
  13594. // CompoundPath to improve performance
  13595. var CompoundPath = Path.extend({
  13596. type: 'compound',
  13597. shape: {
  13598. paths: null
  13599. },
  13600. _updatePathDirty: function () {
  13601. var dirtyPath = this.__dirtyPath;
  13602. var paths = this.shape.paths;
  13603. for (var i = 0; i < paths.length; i++) {
  13604. // Mark as dirty if any subpath is dirty
  13605. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13606. }
  13607. this.__dirtyPath = dirtyPath;
  13608. this.__dirty = this.__dirty || dirtyPath;
  13609. },
  13610. beforeBrush: function () {
  13611. this._updatePathDirty();
  13612. var paths = this.shape.paths || [];
  13613. var scale = this.getGlobalScale();
  13614. // Update path scale
  13615. for (var i = 0; i < paths.length; i++) {
  13616. if (!paths[i].path) {
  13617. paths[i].createPathProxy();
  13618. }
  13619. paths[i].path.setScale(scale[0], scale[1]);
  13620. }
  13621. },
  13622. buildPath: function (ctx, shape) {
  13623. var paths = shape.paths || [];
  13624. for (var i = 0; i < paths.length; i++) {
  13625. paths[i].buildPath(ctx, paths[i].shape, true);
  13626. }
  13627. },
  13628. afterBrush: function () {
  13629. var paths = this.shape.paths || [];
  13630. for (var i = 0; i < paths.length; i++) {
  13631. paths[i].__dirtyPath = false;
  13632. }
  13633. },
  13634. getBoundingRect: function () {
  13635. this._updatePathDirty();
  13636. return Path.prototype.getBoundingRect.call(this);
  13637. }
  13638. });
  13639. /**
  13640. * @param {Array.<Object>} colorStops
  13641. */
  13642. var Gradient = function (colorStops) {
  13643. this.colorStops = colorStops || [];
  13644. };
  13645. Gradient.prototype = {
  13646. constructor: Gradient,
  13647. addColorStop: function (offset, color) {
  13648. this.colorStops.push({
  13649. offset: offset,
  13650. color: color
  13651. });
  13652. }
  13653. };
  13654. /**
  13655. * x, y, x2, y2 are all percent from 0 to 1
  13656. * @param {number} [x=0]
  13657. * @param {number} [y=0]
  13658. * @param {number} [x2=1]
  13659. * @param {number} [y2=0]
  13660. * @param {Array.<Object>} colorStops
  13661. * @param {boolean} [globalCoord=false]
  13662. */
  13663. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13664. // Should do nothing more in this constructor. Because gradient can be
  13665. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13666. // this constructor will not be called.
  13667. this.x = x == null ? 0 : x;
  13668. this.y = y == null ? 0 : y;
  13669. this.x2 = x2 == null ? 1 : x2;
  13670. this.y2 = y2 == null ? 0 : y2;
  13671. // Can be cloned
  13672. this.type = 'linear';
  13673. // If use global coord
  13674. this.global = globalCoord || false;
  13675. Gradient.call(this, colorStops);
  13676. };
  13677. LinearGradient.prototype = {
  13678. constructor: LinearGradient
  13679. };
  13680. inherits(LinearGradient, Gradient);
  13681. /**
  13682. * x, y, r are all percent from 0 to 1
  13683. * @param {number} [x=0.5]
  13684. * @param {number} [y=0.5]
  13685. * @param {number} [r=0.5]
  13686. * @param {Array.<Object>} [colorStops]
  13687. * @param {boolean} [globalCoord=false]
  13688. */
  13689. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13690. // Should do nothing more in this constructor. Because gradient can be
  13691. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13692. // this constructor will not be called.
  13693. this.x = x == null ? 0.5 : x;
  13694. this.y = y == null ? 0.5 : y;
  13695. this.r = r == null ? 0.5 : r;
  13696. // Can be cloned
  13697. this.type = 'radial';
  13698. // If use global coord
  13699. this.global = globalCoord || false;
  13700. Gradient.call(this, colorStops);
  13701. };
  13702. RadialGradient.prototype = {
  13703. constructor: RadialGradient
  13704. };
  13705. inherits(RadialGradient, Gradient);
  13706. /**
  13707. * Displayable for incremental rendering. It will be rendered in a separate layer
  13708. * IncrementalDisplay have too main methods. `clearDisplayables` and `addDisplayables`
  13709. * addDisplayables will render the added displayables incremetally.
  13710. *
  13711. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13712. */
  13713. // TODO Style override ?
  13714. function IncrementalDisplayble(opts) {
  13715. Displayable.call(this, opts);
  13716. this._displayables = [];
  13717. this._temporaryDisplayables = [];
  13718. this._cursor = 0;
  13719. this.notClear = true;
  13720. }
  13721. IncrementalDisplayble.prototype.incremental = true;
  13722. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13723. this._displayables = [];
  13724. this._temporaryDisplayables = [];
  13725. this._cursor = 0;
  13726. this.dirty();
  13727. this.notClear = false;
  13728. };
  13729. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13730. if (notPersistent) {
  13731. this._temporaryDisplayables.push(displayable);
  13732. }
  13733. else {
  13734. this._displayables.push(displayable);
  13735. }
  13736. this.dirty();
  13737. };
  13738. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13739. notPersistent = notPersistent || false;
  13740. for (var i = 0; i < displayables.length; i++) {
  13741. this.addDisplayable(displayables[i], notPersistent);
  13742. }
  13743. };
  13744. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13745. for (var i = this._cursor; i < this._displayables.length; i++) {
  13746. cb && cb(this._displayables[i]);
  13747. }
  13748. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13749. cb && cb(this._temporaryDisplayables[i]);
  13750. }
  13751. };
  13752. IncrementalDisplayble.prototype.update = function () {
  13753. this.updateTransform();
  13754. for (var i = this._cursor; i < this._displayables.length; i++) {
  13755. var displayable = this._displayables[i];
  13756. // PENDING
  13757. displayable.parent = this;
  13758. displayable.update();
  13759. displayable.parent = null;
  13760. }
  13761. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13762. var displayable = this._temporaryDisplayables[i];
  13763. // PENDING
  13764. displayable.parent = this;
  13765. displayable.update();
  13766. displayable.parent = null;
  13767. }
  13768. };
  13769. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13770. // Render persistant displayables.
  13771. for (var i = this._cursor; i < this._displayables.length; i++) {
  13772. var displayable = this._displayables[i];
  13773. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13774. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13775. displayable.afterBrush && displayable.afterBrush(ctx);
  13776. }
  13777. this._cursor = i;
  13778. // Render temporary displayables.
  13779. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13780. var displayable = this._temporaryDisplayables[i];
  13781. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13782. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13783. displayable.afterBrush && displayable.afterBrush(ctx);
  13784. }
  13785. this._temporaryDisplayables = [];
  13786. this.notClear = true;
  13787. };
  13788. var m = [];
  13789. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13790. if (!this._rect) {
  13791. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13792. for (var i = 0; i < this._displayables.length; i++) {
  13793. var displayable = this._displayables[i];
  13794. var childRect = displayable.getBoundingRect().clone();
  13795. if (displayable.needLocalTransform()) {
  13796. childRect.applyTransform(displayable.getLocalTransform(m));
  13797. }
  13798. rect.union(childRect);
  13799. }
  13800. this._rect = rect;
  13801. }
  13802. return this._rect;
  13803. };
  13804. IncrementalDisplayble.prototype.contain = function (x, y) {
  13805. var localPos = this.transformCoordToLocal(x, y);
  13806. var rect = this.getBoundingRect();
  13807. if (rect.contain(localPos[0], localPos[1])) {
  13808. for (var i = 0; i < this._displayables.length; i++) {
  13809. var displayable = this._displayables[i];
  13810. if (displayable.contain(x, y)) {
  13811. return true;
  13812. }
  13813. }
  13814. }
  13815. return false;
  13816. };
  13817. inherits(IncrementalDisplayble, Displayable);
  13818. /*
  13819. * Licensed to the Apache Software Foundation (ASF) under one
  13820. * or more contributor license agreements. See the NOTICE file
  13821. * distributed with this work for additional information
  13822. * regarding copyright ownership. The ASF licenses this file
  13823. * to you under the Apache License, Version 2.0 (the
  13824. * "License"); you may not use this file except in compliance
  13825. * with the License. You may obtain a copy of the License at
  13826. *
  13827. * http://www.apache.org/licenses/LICENSE-2.0
  13828. *
  13829. * Unless required by applicable law or agreed to in writing,
  13830. * software distributed under the License is distributed on an
  13831. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13832. * KIND, either express or implied. See the License for the
  13833. * specific language governing permissions and limitations
  13834. * under the License.
  13835. */
  13836. var round = Math.round;
  13837. var mathMax$1 = Math.max;
  13838. var mathMin$1 = Math.min;
  13839. var EMPTY_OBJ = {};
  13840. /**
  13841. * Extend shape with parameters
  13842. */
  13843. function extendShape(opts) {
  13844. return Path.extend(opts);
  13845. }
  13846. /**
  13847. * Extend path
  13848. */
  13849. function extendPath(pathData, opts) {
  13850. return extendFromString(pathData, opts);
  13851. }
  13852. /**
  13853. * Create a path element from path data string
  13854. * @param {string} pathData
  13855. * @param {Object} opts
  13856. * @param {module:zrender/core/BoundingRect} rect
  13857. * @param {string} [layout=cover] 'center' or 'cover'
  13858. */
  13859. function makePath(pathData, opts, rect, layout) {
  13860. var path = createFromString(pathData, opts);
  13861. var boundingRect = path.getBoundingRect();
  13862. if (rect) {
  13863. if (layout === 'center') {
  13864. rect = centerGraphic(rect, boundingRect);
  13865. }
  13866. resizePath(path, rect);
  13867. }
  13868. return path;
  13869. }
  13870. /**
  13871. * Create a image element from image url
  13872. * @param {string} imageUrl image url
  13873. * @param {Object} opts options
  13874. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13875. * @param {string} [layout=cover] 'center' or 'cover'
  13876. */
  13877. function makeImage(imageUrl, rect, layout) {
  13878. var path = new ZImage({
  13879. style: {
  13880. image: imageUrl,
  13881. x: rect.x,
  13882. y: rect.y,
  13883. width: rect.width,
  13884. height: rect.height
  13885. },
  13886. onload: function (img) {
  13887. if (layout === 'center') {
  13888. var boundingRect = {
  13889. width: img.width,
  13890. height: img.height
  13891. };
  13892. path.setStyle(centerGraphic(rect, boundingRect));
  13893. }
  13894. }
  13895. });
  13896. return path;
  13897. }
  13898. /**
  13899. * Get position of centered element in bounding box.
  13900. *
  13901. * @param {Object} rect element local bounding box
  13902. * @param {Object} boundingRect constraint bounding box
  13903. * @return {Object} element position containing x, y, width, and height
  13904. */
  13905. function centerGraphic(rect, boundingRect) {
  13906. // Set rect to center, keep width / height ratio.
  13907. var aspect = boundingRect.width / boundingRect.height;
  13908. var width = rect.height * aspect;
  13909. var height;
  13910. if (width <= rect.width) {
  13911. height = rect.height;
  13912. }
  13913. else {
  13914. width = rect.width;
  13915. height = width / aspect;
  13916. }
  13917. var cx = rect.x + rect.width / 2;
  13918. var cy = rect.y + rect.height / 2;
  13919. return {
  13920. x: cx - width / 2,
  13921. y: cy - height / 2,
  13922. width: width,
  13923. height: height
  13924. };
  13925. }
  13926. var mergePath = mergePath$1;
  13927. /**
  13928. * Resize a path to fit the rect
  13929. * @param {module:zrender/graphic/Path} path
  13930. * @param {Object} rect
  13931. */
  13932. function resizePath(path, rect) {
  13933. if (!path.applyTransform) {
  13934. return;
  13935. }
  13936. var pathRect = path.getBoundingRect();
  13937. var m = pathRect.calculateTransform(rect);
  13938. path.applyTransform(m);
  13939. }
  13940. /**
  13941. * Sub pixel optimize line for canvas
  13942. *
  13943. * @param {Object} param
  13944. * @param {Object} [param.shape]
  13945. * @param {number} [param.shape.x1]
  13946. * @param {number} [param.shape.y1]
  13947. * @param {number} [param.shape.x2]
  13948. * @param {number} [param.shape.y2]
  13949. * @param {Object} [param.style]
  13950. * @param {number} [param.style.lineWidth]
  13951. * @return {Object} Modified param
  13952. */
  13953. function subPixelOptimizeLine(param) {
  13954. var shape = param.shape;
  13955. var lineWidth = param.style.lineWidth;
  13956. if (round(shape.x1 * 2) === round(shape.x2 * 2)) {
  13957. shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true);
  13958. }
  13959. if (round(shape.y1 * 2) === round(shape.y2 * 2)) {
  13960. shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true);
  13961. }
  13962. return param;
  13963. }
  13964. /**
  13965. * Sub pixel optimize rect for canvas
  13966. *
  13967. * @param {Object} param
  13968. * @param {Object} [param.shape]
  13969. * @param {number} [param.shape.x]
  13970. * @param {number} [param.shape.y]
  13971. * @param {number} [param.shape.width]
  13972. * @param {number} [param.shape.height]
  13973. * @param {Object} [param.style]
  13974. * @param {number} [param.style.lineWidth]
  13975. * @return {Object} Modified param
  13976. */
  13977. function subPixelOptimizeRect(param) {
  13978. var shape = param.shape;
  13979. var lineWidth = param.style.lineWidth;
  13980. var originX = shape.x;
  13981. var originY = shape.y;
  13982. var originWidth = shape.width;
  13983. var originHeight = shape.height;
  13984. shape.x = subPixelOptimize(shape.x, lineWidth, true);
  13985. shape.y = subPixelOptimize(shape.y, lineWidth, true);
  13986. shape.width = Math.max(
  13987. subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x,
  13988. originWidth === 0 ? 0 : 1
  13989. );
  13990. shape.height = Math.max(
  13991. subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y,
  13992. originHeight === 0 ? 0 : 1
  13993. );
  13994. return param;
  13995. }
  13996. /**
  13997. * Sub pixel optimize for canvas
  13998. *
  13999. * @param {number} position Coordinate, such as x, y
  14000. * @param {number} lineWidth Should be nonnegative integer.
  14001. * @param {boolean=} positiveOrNegative Default false (negative).
  14002. * @return {number} Optimized position.
  14003. */
  14004. function subPixelOptimize(position, lineWidth, positiveOrNegative) {
  14005. // Assure that (position + lineWidth / 2) is near integer edge,
  14006. // otherwise line will be fuzzy in canvas.
  14007. var doubledPosition = round(position * 2);
  14008. return (doubledPosition + round(lineWidth)) % 2 === 0
  14009. ? doubledPosition / 2
  14010. : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  14011. }
  14012. function hasFillOrStroke(fillOrStroke) {
  14013. return fillOrStroke != null && fillOrStroke != 'none';
  14014. }
  14015. function liftColor(color) {
  14016. return typeof color === 'string' ? lift(color, -0.1) : color;
  14017. }
  14018. /**
  14019. * @private
  14020. */
  14021. function cacheElementStl(el) {
  14022. if (el.__hoverStlDirty) {
  14023. var stroke = el.style.stroke;
  14024. var fill = el.style.fill;
  14025. // Create hoverStyle on mouseover
  14026. var hoverStyle = el.__hoverStl;
  14027. hoverStyle.fill = hoverStyle.fill
  14028. || (hasFillOrStroke(fill) ? liftColor(fill) : null);
  14029. hoverStyle.stroke = hoverStyle.stroke
  14030. || (hasFillOrStroke(stroke) ? liftColor(stroke) : null);
  14031. var normalStyle = {};
  14032. for (var name in hoverStyle) {
  14033. // See comment in `doSingleEnterHover`.
  14034. if (hoverStyle[name] != null) {
  14035. normalStyle[name] = el.style[name];
  14036. }
  14037. }
  14038. el.__normalStl = normalStyle;
  14039. el.__hoverStlDirty = false;
  14040. }
  14041. }
  14042. /**
  14043. * @private
  14044. */
  14045. function doSingleEnterHover(el) {
  14046. if (el.__isHover) {
  14047. return;
  14048. }
  14049. cacheElementStl(el);
  14050. if (el.useHoverLayer) {
  14051. el.__zr && el.__zr.addHover(el, el.__hoverStl);
  14052. }
  14053. else {
  14054. var style = el.style;
  14055. var insideRollbackOpt = style.insideRollbackOpt;
  14056. // Consider case: only `position: 'top'` is set on emphasis, then text
  14057. // color should be returned to `autoColor`, rather than remain '#fff'.
  14058. // So we should rollback then apply again after style merging.
  14059. insideRollbackOpt && rollbackInsideStyle(style);
  14060. // styles can be:
  14061. // {
  14062. // label: {
  14063. // show: false,
  14064. // position: 'outside',
  14065. // fontSize: 18
  14066. // },
  14067. // emphasis: {
  14068. // label: {
  14069. // show: true
  14070. // }
  14071. // }
  14072. // },
  14073. // where properties of `emphasis` may not appear in `normal`. We previously use
  14074. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14075. // But consider rich text and setOption in merge mode, it is impossible to cover
  14076. // all properties in merge. So we use merge mode when setting style here, where
  14077. // only properties that is not `null/undefined` can be set. The disadventage:
  14078. // null/undefined can not be used to remove style any more in `emphasis`.
  14079. style.extendFrom(el.__hoverStl);
  14080. // Do not save `insideRollback`.
  14081. if (insideRollbackOpt) {
  14082. applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt);
  14083. // textFill may be rollbacked to null.
  14084. if (style.textFill == null) {
  14085. style.textFill = insideRollbackOpt.autoColor;
  14086. }
  14087. }
  14088. el.dirty(false);
  14089. el.z2 += 1;
  14090. }
  14091. el.__isHover = true;
  14092. }
  14093. /**
  14094. * @inner
  14095. */
  14096. function doSingleLeaveHover(el) {
  14097. if (!el.__isHover) {
  14098. return;
  14099. }
  14100. var normalStl = el.__normalStl;
  14101. if (el.useHoverLayer) {
  14102. el.__zr && el.__zr.removeHover(el);
  14103. }
  14104. else {
  14105. // Consider null/undefined value, should use
  14106. // `setStyle` but not `extendFrom(stl, true)`.
  14107. normalStl && el.setStyle(normalStl);
  14108. el.z2 -= 1;
  14109. }
  14110. el.__isHover = false;
  14111. }
  14112. /**
  14113. * @inner
  14114. */
  14115. function doEnterHover(el) {
  14116. el.type === 'group'
  14117. ? el.traverse(function (child) {
  14118. if (child.type !== 'group') {
  14119. doSingleEnterHover(child);
  14120. }
  14121. })
  14122. : doSingleEnterHover(el);
  14123. }
  14124. function doLeaveHover(el) {
  14125. el.type === 'group'
  14126. ? el.traverse(function (child) {
  14127. if (child.type !== 'group') {
  14128. doSingleLeaveHover(child);
  14129. }
  14130. })
  14131. : doSingleLeaveHover(el);
  14132. }
  14133. /**
  14134. * @inner
  14135. */
  14136. function setElementHoverStl(el, hoverStl) {
  14137. // If element has sepcified hoverStyle, then use it instead of given hoverStyle
  14138. // Often used when item group has a label element and it's hoverStyle is different
  14139. el.__hoverStl = el.hoverStyle || hoverStl || {};
  14140. el.__hoverStlDirty = true;
  14141. if (el.__isHover) {
  14142. cacheElementStl(el);
  14143. }
  14144. }
  14145. /**
  14146. * @inner
  14147. */
  14148. function onElementMouseOver(e) {
  14149. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14150. return;
  14151. }
  14152. // Only if element is not in emphasis status
  14153. !this.__isEmphasis && doEnterHover(this);
  14154. }
  14155. /**
  14156. * @inner
  14157. */
  14158. function onElementMouseOut(e) {
  14159. if (this.__hoverSilentOnTouch && e.zrByTouch) {
  14160. return;
  14161. }
  14162. // Only if element is not in emphasis status
  14163. !this.__isEmphasis && doLeaveHover(this);
  14164. }
  14165. /**
  14166. * @inner
  14167. */
  14168. function enterEmphasis() {
  14169. this.__isEmphasis = true;
  14170. doEnterHover(this);
  14171. }
  14172. /**
  14173. * @inner
  14174. */
  14175. function leaveEmphasis() {
  14176. this.__isEmphasis = false;
  14177. doLeaveHover(this);
  14178. }
  14179. /**
  14180. * Set hover style of element.
  14181. * This method can be called repeatly without side-effects.
  14182. * @param {module:zrender/Element} el
  14183. * @param {Object} [hoverStyle]
  14184. * @param {Object} [opt]
  14185. * @param {boolean} [opt.hoverSilentOnTouch=false]
  14186. * In touch device, mouseover event will be trigger on touchstart event
  14187. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14188. * conviniently use hoverStyle when tap on touch screen without additional
  14189. * code for compatibility.
  14190. * But if the chart/component has select feature, which usually also use
  14191. * hoverStyle, there might be conflict between 'select-highlight' and
  14192. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14193. * In this case, hoverSilentOnTouch should be used to disable hover-highlight
  14194. * on touch device.
  14195. */
  14196. function setHoverStyle(el, hoverStyle, opt) {
  14197. el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch;
  14198. el.type === 'group'
  14199. ? el.traverse(function (child) {
  14200. if (child.type !== 'group') {
  14201. setElementHoverStl(child, hoverStyle);
  14202. }
  14203. })
  14204. : setElementHoverStl(el, hoverStyle);
  14205. // Duplicated function will be auto-ignored, see Eventful.js.
  14206. el.on('mouseover', onElementMouseOver)
  14207. .on('mouseout', onElementMouseOut);
  14208. // Emphasis, normal can be triggered manually
  14209. el.on('emphasis', enterEmphasis)
  14210. .on('normal', leaveEmphasis);
  14211. }
  14212. /**
  14213. * @param {Object|module:zrender/graphic/Style} normalStyle
  14214. * @param {Object} emphasisStyle
  14215. * @param {module:echarts/model/Model} normalModel
  14216. * @param {module:echarts/model/Model} emphasisModel
  14217. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14218. * @param {string|Function} [opt.defaultText]
  14219. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14220. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14221. * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by
  14222. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14223. * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by
  14224. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)`
  14225. * @param {Object} [normalSpecified]
  14226. * @param {Object} [emphasisSpecified]
  14227. */
  14228. function setLabelStyle(
  14229. normalStyle, emphasisStyle,
  14230. normalModel, emphasisModel,
  14231. opt,
  14232. normalSpecified, emphasisSpecified
  14233. ) {
  14234. opt = opt || EMPTY_OBJ;
  14235. var labelFetcher = opt.labelFetcher;
  14236. var labelDataIndex = opt.labelDataIndex;
  14237. var labelDimIndex = opt.labelDimIndex;
  14238. // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14239. // is not supported util someone requests.
  14240. var showNormal = normalModel.getShallow('show');
  14241. var showEmphasis = emphasisModel.getShallow('show');
  14242. // Consider performance, only fetch label when necessary.
  14243. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14244. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14245. var baseText;
  14246. if (showNormal || showEmphasis) {
  14247. if (labelFetcher) {
  14248. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex);
  14249. }
  14250. if (baseText == null) {
  14251. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14252. }
  14253. }
  14254. var normalStyleText = showNormal ? baseText : null;
  14255. var emphasisStyleText = showEmphasis
  14256. ? retrieve2(
  14257. labelFetcher
  14258. ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex)
  14259. : null,
  14260. baseText
  14261. )
  14262. : null;
  14263. // Optimize: If style.text is null, text will not be drawn.
  14264. if (normalStyleText != null || emphasisStyleText != null) {
  14265. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14266. // values have to be set on `normalStyle`.
  14267. // If we set default values on `emphasisStyle`, consider case:
  14268. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14269. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14270. // Then the 'red' will not work on emphasis.
  14271. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14272. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14273. }
  14274. normalStyle.text = normalStyleText;
  14275. emphasisStyle.text = emphasisStyleText;
  14276. }
  14277. /**
  14278. * Set basic textStyle properties.
  14279. * @param {Object|module:zrender/graphic/Style} textStyle
  14280. * @param {module:echarts/model/Model} model
  14281. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14282. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14283. * @param {boolean} [isEmphasis]
  14284. */
  14285. function setTextStyle(
  14286. textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis
  14287. ) {
  14288. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14289. specifiedTextStyle && extend(textStyle, specifiedTextStyle);
  14290. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14291. return textStyle;
  14292. }
  14293. /**
  14294. * Set text option in the style.
  14295. * @deprecated
  14296. * @param {Object} textStyle
  14297. * @param {module:echarts/model/Model} labelModel
  14298. * @param {string|boolean} defaultColor Default text color.
  14299. * If set as false, it will be processed as a emphasis style.
  14300. */
  14301. function setText(textStyle, labelModel, defaultColor) {
  14302. var opt = {isRectText: true};
  14303. var isEmphasis;
  14304. if (defaultColor === false) {
  14305. isEmphasis = true;
  14306. }
  14307. else {
  14308. // Support setting color as 'auto' to get visual color.
  14309. opt.autoColor = defaultColor;
  14310. }
  14311. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis);
  14312. textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14313. }
  14314. /**
  14315. * {
  14316. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14317. * isRectText: boolean,
  14318. * autoColor: string, specify a color when color is 'auto',
  14319. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14320. * If autoColor specified, it is used as default textFill.
  14321. * useInsideStyle:
  14322. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14323. * if `textFill` is not specified.
  14324. * `false`: Do not use inside style.
  14325. * `null/undefined`: use inside style if `isRectText` is true and
  14326. * `textFill` is not specified and textPosition contains `'inside'`.
  14327. * forceRich: boolean
  14328. * }
  14329. */
  14330. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14331. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14332. opt = opt || EMPTY_OBJ;
  14333. if (opt.isRectText) {
  14334. var textPosition = textStyleModel.getShallow('position')
  14335. || (isEmphasis ? null : 'inside');
  14336. // 'outside' is not a valid zr textPostion value, but used
  14337. // in bar series, and magric type should be considered.
  14338. textPosition === 'outside' && (textPosition = 'top');
  14339. textStyle.textPosition = textPosition;
  14340. textStyle.textOffset = textStyleModel.getShallow('offset');
  14341. var labelRotate = textStyleModel.getShallow('rotate');
  14342. labelRotate != null && (labelRotate *= Math.PI / 180);
  14343. textStyle.textRotation = labelRotate;
  14344. textStyle.textDistance = retrieve2(
  14345. textStyleModel.getShallow('distance'), isEmphasis ? null : 5
  14346. );
  14347. }
  14348. var ecModel = textStyleModel.ecModel;
  14349. var globalTextStyle = ecModel && ecModel.option.textStyle;
  14350. // Consider case:
  14351. // {
  14352. // data: [{
  14353. // value: 12,
  14354. // label: {
  14355. // rich: {
  14356. // // no 'a' here but using parent 'a'.
  14357. // }
  14358. // }
  14359. // }],
  14360. // rich: {
  14361. // a: { ... }
  14362. // }
  14363. // }
  14364. var richItemNames = getRichItemNames(textStyleModel);
  14365. var richResult;
  14366. if (richItemNames) {
  14367. richResult = {};
  14368. for (var name in richItemNames) {
  14369. if (richItemNames.hasOwnProperty(name)) {
  14370. // Cascade is supported in rich.
  14371. var richTextStyle = textStyleModel.getModel(['rich', name]);
  14372. // In rich, never `disableBox`.
  14373. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14374. }
  14375. }
  14376. }
  14377. textStyle.rich = richResult;
  14378. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14379. if (opt.forceRich && !opt.textStyle) {
  14380. opt.textStyle = {};
  14381. }
  14382. return textStyle;
  14383. }
  14384. // Consider case:
  14385. // {
  14386. // data: [{
  14387. // value: 12,
  14388. // label: {
  14389. // rich: {
  14390. // // no 'a' here but using parent 'a'.
  14391. // }
  14392. // }
  14393. // }],
  14394. // rich: {
  14395. // a: { ... }
  14396. // }
  14397. // }
  14398. function getRichItemNames(textStyleModel) {
  14399. // Use object to remove duplicated names.
  14400. var richItemNameMap;
  14401. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14402. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14403. if (rich) {
  14404. richItemNameMap = richItemNameMap || {};
  14405. for (var name in rich) {
  14406. if (rich.hasOwnProperty(name)) {
  14407. richItemNameMap[name] = 1;
  14408. }
  14409. }
  14410. }
  14411. textStyleModel = textStyleModel.parentModel;
  14412. }
  14413. return richItemNameMap;
  14414. }
  14415. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14416. // In merge mode, default value should not be given.
  14417. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14418. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt)
  14419. || globalTextStyle.color;
  14420. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt)
  14421. || globalTextStyle.textBorderColor;
  14422. textStyle.textStrokeWidth = retrieve2(
  14423. textStyleModel.getShallow('textBorderWidth'),
  14424. globalTextStyle.textBorderWidth
  14425. );
  14426. if (!isEmphasis) {
  14427. if (isBlock) {
  14428. // Always set `insideRollback`, for clearing previous.
  14429. var originalTextPosition = textStyle.textPosition;
  14430. textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt);
  14431. // Save original textPosition, because style.textPosition will be repalced by
  14432. // real location (like [10, 30]) in zrender.
  14433. textStyle.insideOriginalTextPosition = originalTextPosition;
  14434. textStyle.insideRollbackOpt = opt;
  14435. }
  14436. // Set default finally.
  14437. if (textStyle.textFill == null) {
  14438. textStyle.textFill = opt.autoColor;
  14439. }
  14440. }
  14441. // Do not use `getFont` here, because merge should be supported, where
  14442. // part of these properties may be changed in emphasis style, and the
  14443. // others should remain their original value got from normal style.
  14444. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14445. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14446. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14447. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14448. textStyle.textAlign = textStyleModel.getShallow('align');
  14449. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign')
  14450. || textStyleModel.getShallow('baseline');
  14451. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14452. textStyle.textWidth = textStyleModel.getShallow('width');
  14453. textStyle.textHeight = textStyleModel.getShallow('height');
  14454. textStyle.textTag = textStyleModel.getShallow('tag');
  14455. if (!isBlock || !opt.disableBox) {
  14456. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14457. textStyle.textPadding = textStyleModel.getShallow('padding');
  14458. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14459. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14460. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14461. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14462. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14463. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14464. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14465. }
  14466. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor')
  14467. || globalTextStyle.textShadowColor;
  14468. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur')
  14469. || globalTextStyle.textShadowBlur;
  14470. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX')
  14471. || globalTextStyle.textShadowOffsetX;
  14472. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY')
  14473. || globalTextStyle.textShadowOffsetY;
  14474. }
  14475. function getAutoColor(color, opt) {
  14476. return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null;
  14477. }
  14478. function applyInsideStyle(textStyle, textPosition, opt) {
  14479. var useInsideStyle = opt.useInsideStyle;
  14480. var insideRollback;
  14481. if (textStyle.textFill == null
  14482. && useInsideStyle !== false
  14483. && (useInsideStyle === true
  14484. || (opt.isRectText
  14485. && textPosition
  14486. // textPosition can be [10, 30]
  14487. && typeof textPosition === 'string'
  14488. && textPosition.indexOf('inside') >= 0
  14489. )
  14490. )
  14491. ) {
  14492. insideRollback = {
  14493. textFill: null,
  14494. textStroke: textStyle.textStroke,
  14495. textStrokeWidth: textStyle.textStrokeWidth
  14496. };
  14497. textStyle.textFill = '#fff';
  14498. // Consider text with #fff overflow its container.
  14499. if (textStyle.textStroke == null) {
  14500. textStyle.textStroke = opt.autoColor;
  14501. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14502. }
  14503. }
  14504. return insideRollback;
  14505. }
  14506. function rollbackInsideStyle(style) {
  14507. var insideRollback = style.insideRollback;
  14508. if (insideRollback) {
  14509. style.textFill = insideRollback.textFill;
  14510. style.textStroke = insideRollback.textStroke;
  14511. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14512. }
  14513. }
  14514. function getFont(opt, ecModel) {
  14515. // ecModel or default text style model.
  14516. var gTextStyleModel = ecModel || ecModel.getModel('textStyle');
  14517. return trim([
  14518. // FIXME in node-canvas fontWeight is before fontStyle
  14519. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '',
  14520. opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '',
  14521. (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px',
  14522. opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'
  14523. ].join(' '));
  14524. }
  14525. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14526. if (typeof dataIndex === 'function') {
  14527. cb = dataIndex;
  14528. dataIndex = null;
  14529. }
  14530. // Do not check 'animation' property directly here. Consider this case:
  14531. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14532. // but its parent model (`seriesModel`) does.
  14533. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14534. if (animationEnabled) {
  14535. var postfix = isUpdate ? 'Update' : '';
  14536. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14537. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14538. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14539. if (typeof animationDelay === 'function') {
  14540. animationDelay = animationDelay(
  14541. dataIndex,
  14542. animatableModel.getAnimationDelayParams
  14543. ? animatableModel.getAnimationDelayParams(el, dataIndex)
  14544. : null
  14545. );
  14546. }
  14547. if (typeof duration === 'function') {
  14548. duration = duration(dataIndex);
  14549. }
  14550. duration > 0
  14551. ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb)
  14552. : (el.stopAnimation(), el.attr(props), cb && cb());
  14553. }
  14554. else {
  14555. el.stopAnimation();
  14556. el.attr(props);
  14557. cb && cb();
  14558. }
  14559. }
  14560. /**
  14561. * Update graphic element properties with or without animation according to the
  14562. * configuration in series.
  14563. *
  14564. * Caution: this method will stop previous animation.
  14565. * So if do not use this method to one element twice before
  14566. * animation starts, unless you know what you are doing.
  14567. *
  14568. * @param {module:zrender/Element} el
  14569. * @param {Object} props
  14570. * @param {module:echarts/model/Model} [animatableModel]
  14571. * @param {number} [dataIndex]
  14572. * @param {Function} [cb]
  14573. * @example
  14574. * graphic.updateProps(el, {
  14575. * position: [100, 100]
  14576. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14577. * // Or
  14578. * graphic.updateProps(el, {
  14579. * position: [100, 100]
  14580. * }, seriesModel, function () { console.log('Animation done!'); });
  14581. */
  14582. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14583. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14584. }
  14585. /**
  14586. * Init graphic element properties with or without animation according to the
  14587. * configuration in series.
  14588. *
  14589. * Caution: this method will stop previous animation.
  14590. * So if do not use this method to one element twice before
  14591. * animation starts, unless you know what you are doing.
  14592. *
  14593. * @param {module:zrender/Element} el
  14594. * @param {Object} props
  14595. * @param {module:echarts/model/Model} [animatableModel]
  14596. * @param {number} [dataIndex]
  14597. * @param {Function} cb
  14598. */
  14599. function initProps(el, props, animatableModel, dataIndex, cb) {
  14600. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14601. }
  14602. /**
  14603. * Get transform matrix of target (param target),
  14604. * in coordinate of its ancestor (param ancestor)
  14605. *
  14606. * @param {module:zrender/mixin/Transformable} target
  14607. * @param {module:zrender/mixin/Transformable} [ancestor]
  14608. */
  14609. function getTransform(target, ancestor) {
  14610. var mat = identity([]);
  14611. while (target && target !== ancestor) {
  14612. mul$1(mat, target.getLocalTransform(), mat);
  14613. target = target.parent;
  14614. }
  14615. return mat;
  14616. }
  14617. /**
  14618. * Apply transform to an vertex.
  14619. * @param {Array.<number>} target [x, y]
  14620. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14621. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14622. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14623. * @param {boolean=} invert Whether use invert matrix.
  14624. * @return {Array.<number>} [x, y]
  14625. */
  14626. function applyTransform$1(target, transform, invert$$1) {
  14627. if (transform && !isArrayLike(transform)) {
  14628. transform = Transformable.getLocalTransform(transform);
  14629. }
  14630. if (invert$$1) {
  14631. transform = invert([], transform);
  14632. }
  14633. return applyTransform([], target, transform);
  14634. }
  14635. /**
  14636. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14637. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14638. * @param {boolean=} invert Whether use invert matrix.
  14639. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14640. */
  14641. function transformDirection(direction, transform, invert$$1) {
  14642. // Pick a base, ensure that transform result will not be (0, 0).
  14643. var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0)
  14644. ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14645. var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0)
  14646. ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14647. var vertex = [
  14648. direction === 'left' ? -hBase : direction === 'right' ? hBase : 0,
  14649. direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0
  14650. ];
  14651. vertex = applyTransform$1(vertex, transform, invert$$1);
  14652. return Math.abs(vertex[0]) > Math.abs(vertex[1])
  14653. ? (vertex[0] > 0 ? 'right' : 'left')
  14654. : (vertex[1] > 0 ? 'bottom' : 'top');
  14655. }
  14656. /**
  14657. * Apply group transition animation from g1 to g2.
  14658. * If no animatableModel, no animation.
  14659. */
  14660. function groupTransition(g1, g2, animatableModel, cb) {
  14661. if (!g1 || !g2) {
  14662. return;
  14663. }
  14664. function getElMap(g) {
  14665. var elMap = {};
  14666. g.traverse(function (el) {
  14667. if (!el.isGroup && el.anid) {
  14668. elMap[el.anid] = el;
  14669. }
  14670. });
  14671. return elMap;
  14672. }
  14673. function getAnimatableProps(el) {
  14674. var obj = {
  14675. position: clone$1(el.position),
  14676. rotation: el.rotation
  14677. };
  14678. if (el.shape) {
  14679. obj.shape = extend({}, el.shape);
  14680. }
  14681. return obj;
  14682. }
  14683. var elMap1 = getElMap(g1);
  14684. g2.traverse(function (el) {
  14685. if (!el.isGroup && el.anid) {
  14686. var oldEl = elMap1[el.anid];
  14687. if (oldEl) {
  14688. var newProp = getAnimatableProps(el);
  14689. el.attr(getAnimatableProps(oldEl));
  14690. updateProps(el, newProp, animatableModel, el.dataIndex);
  14691. }
  14692. // else {
  14693. // if (el.previousProps) {
  14694. // graphic.updateProps
  14695. // }
  14696. // }
  14697. }
  14698. });
  14699. }
  14700. /**
  14701. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14702. * @param {Object} rect {x, y, width, height}
  14703. * @return {Array.<Array.<number>>} A new clipped points.
  14704. */
  14705. function clipPointsByRect(points, rect) {
  14706. return map(points, function (point) {
  14707. var x = point[0];
  14708. x = mathMax$1(x, rect.x);
  14709. x = mathMin$1(x, rect.x + rect.width);
  14710. var y = point[1];
  14711. y = mathMax$1(y, rect.y);
  14712. y = mathMin$1(y, rect.y + rect.height);
  14713. return [x, y];
  14714. });
  14715. }
  14716. /**
  14717. * @param {Object} targetRect {x, y, width, height}
  14718. * @param {Object} rect {x, y, width, height}
  14719. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14720. */
  14721. function clipRectByRect(targetRect, rect) {
  14722. var x = mathMax$1(targetRect.x, rect.x);
  14723. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14724. var y = mathMax$1(targetRect.y, rect.y);
  14725. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height);
  14726. if (x2 >= x && y2 >= y) {
  14727. return {
  14728. x: x,
  14729. y: y,
  14730. width: x2 - x,
  14731. height: y2 - y
  14732. };
  14733. }
  14734. }
  14735. /**
  14736. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14737. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14738. * @param {Object} [rect] {x, y, width, height}
  14739. * @return {module:zrender/Element} Icon path or image element.
  14740. */
  14741. function createIcon(iconStr, opt, rect) {
  14742. opt = extend({rectHover: true}, opt);
  14743. var style = opt.style = {strokeNoScale: true};
  14744. rect = rect || {x: -1, y: -1, width: 2, height: 2};
  14745. if (iconStr) {
  14746. return iconStr.indexOf('image://') === 0
  14747. ? (
  14748. style.image = iconStr.slice(8),
  14749. defaults(style, rect),
  14750. new ZImage(opt)
  14751. )
  14752. : (
  14753. makePath(
  14754. iconStr.replace('path://', ''),
  14755. opt,
  14756. rect,
  14757. 'center'
  14758. )
  14759. );
  14760. }
  14761. }
  14762. var graphic = (Object.freeze || Object)({
  14763. extendShape: extendShape,
  14764. extendPath: extendPath,
  14765. makePath: makePath,
  14766. makeImage: makeImage,
  14767. mergePath: mergePath,
  14768. resizePath: resizePath,
  14769. subPixelOptimizeLine: subPixelOptimizeLine,
  14770. subPixelOptimizeRect: subPixelOptimizeRect,
  14771. subPixelOptimize: subPixelOptimize,
  14772. setHoverStyle: setHoverStyle,
  14773. setLabelStyle: setLabelStyle,
  14774. setTextStyle: setTextStyle,
  14775. setText: setText,
  14776. getFont: getFont,
  14777. updateProps: updateProps,
  14778. initProps: initProps,
  14779. getTransform: getTransform,
  14780. applyTransform: applyTransform$1,
  14781. transformDirection: transformDirection,
  14782. groupTransition: groupTransition,
  14783. clipPointsByRect: clipPointsByRect,
  14784. clipRectByRect: clipRectByRect,
  14785. createIcon: createIcon,
  14786. Group: Group,
  14787. Image: ZImage,
  14788. Text: Text,
  14789. Circle: Circle,
  14790. Sector: Sector,
  14791. Ring: Ring,
  14792. Polygon: Polygon,
  14793. Polyline: Polyline,
  14794. Rect: Rect,
  14795. Line: Line,
  14796. BezierCurve: BezierCurve,
  14797. Arc: Arc,
  14798. IncrementalDisplayable: IncrementalDisplayble,
  14799. CompoundPath: CompoundPath,
  14800. LinearGradient: LinearGradient,
  14801. RadialGradient: RadialGradient,
  14802. BoundingRect: BoundingRect
  14803. });
  14804. /*
  14805. * Licensed to the Apache Software Foundation (ASF) under one
  14806. * or more contributor license agreements. See the NOTICE file
  14807. * distributed with this work for additional information
  14808. * regarding copyright ownership. The ASF licenses this file
  14809. * to you under the Apache License, Version 2.0 (the
  14810. * "License"); you may not use this file except in compliance
  14811. * with the License. You may obtain a copy of the License at
  14812. *
  14813. * http://www.apache.org/licenses/LICENSE-2.0
  14814. *
  14815. * Unless required by applicable law or agreed to in writing,
  14816. * software distributed under the License is distributed on an
  14817. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14818. * KIND, either express or implied. See the License for the
  14819. * specific language governing permissions and limitations
  14820. * under the License.
  14821. */
  14822. var PATH_COLOR = ['textStyle', 'color'];
  14823. var textStyleMixin = {
  14824. /**
  14825. * Get color property or get color from option.textStyle.color
  14826. * @param {boolean} [isEmphasis]
  14827. * @return {string}
  14828. */
  14829. getTextColor: function (isEmphasis) {
  14830. var ecModel = this.ecModel;
  14831. return this.getShallow('color')
  14832. || (
  14833. (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null
  14834. );
  14835. },
  14836. /**
  14837. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  14838. * @return {string}
  14839. */
  14840. getFont: function () {
  14841. return getFont({
  14842. fontStyle: this.getShallow('fontStyle'),
  14843. fontWeight: this.getShallow('fontWeight'),
  14844. fontSize: this.getShallow('fontSize'),
  14845. fontFamily: this.getShallow('fontFamily')
  14846. }, this.ecModel);
  14847. },
  14848. getTextRect: function (text) {
  14849. return getBoundingRect(
  14850. text,
  14851. this.getFont(),
  14852. this.getShallow('align'),
  14853. this.getShallow('verticalAlign') || this.getShallow('baseline'),
  14854. this.getShallow('padding'),
  14855. this.getShallow('rich'),
  14856. this.getShallow('truncateText')
  14857. );
  14858. }
  14859. };
  14860. /*
  14861. * Licensed to the Apache Software Foundation (ASF) under one
  14862. * or more contributor license agreements. See the NOTICE file
  14863. * distributed with this work for additional information
  14864. * regarding copyright ownership. The ASF licenses this file
  14865. * to you under the Apache License, Version 2.0 (the
  14866. * "License"); you may not use this file except in compliance
  14867. * with the License. You may obtain a copy of the License at
  14868. *
  14869. * http://www.apache.org/licenses/LICENSE-2.0
  14870. *
  14871. * Unless required by applicable law or agreed to in writing,
  14872. * software distributed under the License is distributed on an
  14873. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14874. * KIND, either express or implied. See the License for the
  14875. * specific language governing permissions and limitations
  14876. * under the License.
  14877. */
  14878. var getItemStyle = makeStyleMapper(
  14879. [
  14880. ['fill', 'color'],
  14881. ['stroke', 'borderColor'],
  14882. ['lineWidth', 'borderWidth'],
  14883. ['opacity'],
  14884. ['shadowBlur'],
  14885. ['shadowOffsetX'],
  14886. ['shadowOffsetY'],
  14887. ['shadowColor'],
  14888. ['textPosition'],
  14889. ['textAlign']
  14890. ]
  14891. );
  14892. var itemStyleMixin = {
  14893. getItemStyle: function (excludes, includes) {
  14894. var style = getItemStyle(this, excludes, includes);
  14895. var lineDash = this.getBorderLineDash();
  14896. lineDash && (style.lineDash = lineDash);
  14897. return style;
  14898. },
  14899. getBorderLineDash: function () {
  14900. var lineType = this.get('borderType');
  14901. return (lineType === 'solid' || lineType == null) ? null
  14902. : (lineType === 'dashed' ? [5, 5] : [1, 1]);
  14903. }
  14904. };
  14905. /*
  14906. * Licensed to the Apache Software Foundation (ASF) under one
  14907. * or more contributor license agreements. See the NOTICE file
  14908. * distributed with this work for additional information
  14909. * regarding copyright ownership. The ASF licenses this file
  14910. * to you under the Apache License, Version 2.0 (the
  14911. * "License"); you may not use this file except in compliance
  14912. * with the License. You may obtain a copy of the License at
  14913. *
  14914. * http://www.apache.org/licenses/LICENSE-2.0
  14915. *
  14916. * Unless required by applicable law or agreed to in writing,
  14917. * software distributed under the License is distributed on an
  14918. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  14919. * KIND, either express or implied. See the License for the
  14920. * specific language governing permissions and limitations
  14921. * under the License.
  14922. */
  14923. /**
  14924. * @module echarts/model/Model
  14925. */
  14926. var mixin$1 = mixin;
  14927. var inner = makeInner();
  14928. /**
  14929. * @alias module:echarts/model/Model
  14930. * @constructor
  14931. * @param {Object} option
  14932. * @param {module:echarts/model/Model} [parentModel]
  14933. * @param {module:echarts/model/Global} [ecModel]
  14934. */
  14935. function Model(option, parentModel, ecModel) {
  14936. /**
  14937. * @type {module:echarts/model/Model}
  14938. * @readOnly
  14939. */
  14940. this.parentModel = parentModel;
  14941. /**
  14942. * @type {module:echarts/model/Global}
  14943. * @readOnly
  14944. */
  14945. this.ecModel = ecModel;
  14946. /**
  14947. * @type {Object}
  14948. * @protected
  14949. */
  14950. this.option = option;
  14951. // Simple optimization
  14952. // if (this.init) {
  14953. // if (arguments.length <= 4) {
  14954. // this.init(option, parentModel, ecModel, extraOpt);
  14955. // }
  14956. // else {
  14957. // this.init.apply(this, arguments);
  14958. // }
  14959. // }
  14960. }
  14961. Model.prototype = {
  14962. constructor: Model,
  14963. /**
  14964. * Model 的初始化函数
  14965. * @param {Object} option
  14966. */
  14967. init: null,
  14968. /**
  14969. * 从新的 Option merge
  14970. */
  14971. mergeOption: function (option) {
  14972. merge(this.option, option, true);
  14973. },
  14974. /**
  14975. * @param {string|Array.<string>} path
  14976. * @param {boolean} [ignoreParent=false]
  14977. * @return {*}
  14978. */
  14979. get: function (path, ignoreParent) {
  14980. if (path == null) {
  14981. return this.option;
  14982. }
  14983. return doGet(
  14984. this.option,
  14985. this.parsePath(path),
  14986. !ignoreParent && getParent(this, path)
  14987. );
  14988. },
  14989. /**
  14990. * @param {string} key
  14991. * @param {boolean} [ignoreParent=false]
  14992. * @return {*}
  14993. */
  14994. getShallow: function (key, ignoreParent) {
  14995. var option = this.option;
  14996. var val = option == null ? option : option[key];
  14997. var parentModel = !ignoreParent && getParent(this, key);
  14998. if (val == null && parentModel) {
  14999. val = parentModel.getShallow(key);
  15000. }
  15001. return val;
  15002. },
  15003. /**
  15004. * @param {string|Array.<string>} [path]
  15005. * @param {module:echarts/model/Model} [parentModel]
  15006. * @return {module:echarts/model/Model}
  15007. */
  15008. getModel: function (path, parentModel) {
  15009. var obj = path == null
  15010. ? this.option
  15011. : doGet(this.option, path = this.parsePath(path));
  15012. var thisParentModel;
  15013. parentModel = parentModel || (
  15014. (thisParentModel = getParent(this, path))
  15015. && thisParentModel.getModel(path)
  15016. );
  15017. return new Model(obj, parentModel, this.ecModel);
  15018. },
  15019. /**
  15020. * If model has option
  15021. */
  15022. isEmpty: function () {
  15023. return this.option == null;
  15024. },
  15025. restoreData: function () {},
  15026. // Pending
  15027. clone: function () {
  15028. var Ctor = this.constructor;
  15029. return new Ctor(clone(this.option));
  15030. },
  15031. setReadOnly: function (properties) {
  15032. // clazzUtil.setReadOnly(this, properties);
  15033. },
  15034. // If path is null/undefined, return null/undefined.
  15035. parsePath: function(path) {
  15036. if (typeof path === 'string') {
  15037. path = path.split('.');
  15038. }
  15039. return path;
  15040. },
  15041. /**
  15042. * @param {Function} getParentMethod
  15043. * param {Array.<string>|string} path
  15044. * return {module:echarts/model/Model}
  15045. */
  15046. customizeGetParent: function (getParentMethod) {
  15047. inner(this).getParent = getParentMethod;
  15048. },
  15049. isAnimationEnabled: function () {
  15050. if (!env$1.node) {
  15051. if (this.option.animation != null) {
  15052. return !!this.option.animation;
  15053. }
  15054. else if (this.parentModel) {
  15055. return this.parentModel.isAnimationEnabled();
  15056. }
  15057. }
  15058. }
  15059. };
  15060. function doGet(obj, pathArr, parentModel) {
  15061. for (var i = 0; i < pathArr.length; i++) {
  15062. // Ignore empty
  15063. if (!pathArr[i]) {
  15064. continue;
  15065. }
  15066. // obj could be number/string/... (like 0)
  15067. obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null;
  15068. if (obj == null) {
  15069. break;
  15070. }
  15071. }
  15072. if (obj == null && parentModel) {
  15073. obj = parentModel.get(pathArr);
  15074. }
  15075. return obj;
  15076. }
  15077. // `path` can be null/undefined
  15078. function getParent(model, path) {
  15079. var getParentMethod = inner(model).getParent;
  15080. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15081. }
  15082. // Enable Model.extend.
  15083. enableClassExtend(Model);
  15084. enableClassCheck(Model);
  15085. mixin$1(Model, lineStyleMixin);
  15086. mixin$1(Model, areaStyleMixin);
  15087. mixin$1(Model, textStyleMixin);
  15088. mixin$1(Model, itemStyleMixin);
  15089. /*
  15090. * Licensed to the Apache Software Foundation (ASF) under one
  15091. * or more contributor license agreements. See the NOTICE file
  15092. * distributed with this work for additional information
  15093. * regarding copyright ownership. The ASF licenses this file
  15094. * to you under the Apache License, Version 2.0 (the
  15095. * "License"); you may not use this file except in compliance
  15096. * with the License. You may obtain a copy of the License at
  15097. *
  15098. * http://www.apache.org/licenses/LICENSE-2.0
  15099. *
  15100. * Unless required by applicable law or agreed to in writing,
  15101. * software distributed under the License is distributed on an
  15102. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15103. * KIND, either express or implied. See the License for the
  15104. * specific language governing permissions and limitations
  15105. * under the License.
  15106. */
  15107. var base = 0;
  15108. /**
  15109. * @public
  15110. * @param {string} type
  15111. * @return {string}
  15112. */
  15113. function getUID(type) {
  15114. // Considering the case of crossing js context,
  15115. // use Math.random to make id as unique as possible.
  15116. return [(type || ''), base++, Math.random().toFixed(5)].join('_');
  15117. }
  15118. /**
  15119. * @inner
  15120. */
  15121. function enableSubTypeDefaulter(entity) {
  15122. var subTypeDefaulters = {};
  15123. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15124. componentType = parseClassType$1(componentType);
  15125. subTypeDefaulters[componentType.main] = defaulter;
  15126. };
  15127. entity.determineSubType = function (componentType, option) {
  15128. var type = option.type;
  15129. if (!type) {
  15130. var componentTypeMain = parseClassType$1(componentType).main;
  15131. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15132. type = subTypeDefaulters[componentTypeMain](option);
  15133. }
  15134. }
  15135. return type;
  15136. };
  15137. return entity;
  15138. }
  15139. /**
  15140. * Topological travel on Activity Network (Activity On Vertices).
  15141. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15142. *
  15143. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15144. *
  15145. * If there is circle dependencey, Error will be thrown.
  15146. *
  15147. */
  15148. function enableTopologicalTravel(entity, dependencyGetter) {
  15149. /**
  15150. * @public
  15151. * @param {Array.<string>} targetNameList Target Component type list.
  15152. * Can be ['aa', 'bb', 'aa.xx']
  15153. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15154. * @param {Function} callback Params: componentType, dependencies.
  15155. * @param {Object} context Scope of callback.
  15156. */
  15157. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15158. if (!targetNameList.length) {
  15159. return;
  15160. }
  15161. var result = makeDepndencyGraph(fullNameList);
  15162. var graph = result.graph;
  15163. var stack = result.noEntryList;
  15164. var targetNameSet = {};
  15165. each$1(targetNameList, function (name) {
  15166. targetNameSet[name] = true;
  15167. });
  15168. while (stack.length) {
  15169. var currComponentType = stack.pop();
  15170. var currVertex = graph[currComponentType];
  15171. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15172. if (isInTargetNameSet) {
  15173. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15174. delete targetNameSet[currComponentType];
  15175. }
  15176. each$1(
  15177. currVertex.successor,
  15178. isInTargetNameSet ? removeEdgeAndAdd : removeEdge
  15179. );
  15180. }
  15181. each$1(targetNameSet, function () {
  15182. throw new Error('Circle dependency may exists');
  15183. });
  15184. function removeEdge(succComponentType) {
  15185. graph[succComponentType].entryCount--;
  15186. if (graph[succComponentType].entryCount === 0) {
  15187. stack.push(succComponentType);
  15188. }
  15189. }
  15190. // Consider this case: legend depends on series, and we call
  15191. // chart.setOption({series: [...]}), where only series is in option.
  15192. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15193. // not be called, but only sereis.mergeOption is called. Thus legend
  15194. // have no chance to update its local record about series (like which
  15195. // name of series is available in legend).
  15196. function removeEdgeAndAdd(succComponentType) {
  15197. targetNameSet[succComponentType] = true;
  15198. removeEdge(succComponentType);
  15199. }
  15200. };
  15201. /**
  15202. * DepndencyGraph: {Object}
  15203. * key: conponentType,
  15204. * value: {
  15205. * successor: [conponentTypes...],
  15206. * originalDeps: [conponentTypes...],
  15207. * entryCount: {number}
  15208. * }
  15209. */
  15210. function makeDepndencyGraph(fullNameList) {
  15211. var graph = {};
  15212. var noEntryList = [];
  15213. each$1(fullNameList, function (name) {
  15214. var thisItem = createDependencyGraphItem(graph, name);
  15215. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15216. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15217. thisItem.entryCount = availableDeps.length;
  15218. if (thisItem.entryCount === 0) {
  15219. noEntryList.push(name);
  15220. }
  15221. each$1(availableDeps, function (dependentName) {
  15222. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15223. thisItem.predecessor.push(dependentName);
  15224. }
  15225. var thatItem = createDependencyGraphItem(graph, dependentName);
  15226. if (indexOf(thatItem.successor, dependentName) < 0) {
  15227. thatItem.successor.push(name);
  15228. }
  15229. });
  15230. });
  15231. return {graph: graph, noEntryList: noEntryList};
  15232. }
  15233. function createDependencyGraphItem(graph, name) {
  15234. if (!graph[name]) {
  15235. graph[name] = {predecessor: [], successor: []};
  15236. }
  15237. return graph[name];
  15238. }
  15239. function getAvailableDependencies(originalDeps, fullNameList) {
  15240. var availableDeps = [];
  15241. each$1(originalDeps, function (dep) {
  15242. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15243. });
  15244. return availableDeps;
  15245. }
  15246. }
  15247. /*
  15248. * Licensed to the Apache Software Foundation (ASF) under one
  15249. * or more contributor license agreements. See the NOTICE file
  15250. * distributed with this work for additional information
  15251. * regarding copyright ownership. The ASF licenses this file
  15252. * to you under the Apache License, Version 2.0 (the
  15253. * "License"); you may not use this file except in compliance
  15254. * with the License. You may obtain a copy of the License at
  15255. *
  15256. * http://www.apache.org/licenses/LICENSE-2.0
  15257. *
  15258. * Unless required by applicable law or agreed to in writing,
  15259. * software distributed under the License is distributed on an
  15260. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15261. * KIND, either express or implied. See the License for the
  15262. * specific language governing permissions and limitations
  15263. * under the License.
  15264. */
  15265. var RADIAN_EPSILON = 1e-4;
  15266. function _trim(str) {
  15267. return str.replace(/^\s+/, '').replace(/\s+$/, '');
  15268. }
  15269. /**
  15270. * Linear mapping a value from domain to range
  15271. * @memberOf module:echarts/util/number
  15272. * @param {(number|Array.<number>)} val
  15273. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15274. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15275. * @param {boolean} clamp
  15276. * @return {(number|Array.<number>}
  15277. */
  15278. function linearMap(val, domain, range, clamp) {
  15279. var subDomain = domain[1] - domain[0];
  15280. var subRange = range[1] - range[0];
  15281. if (subDomain === 0) {
  15282. return subRange === 0
  15283. ? range[0]
  15284. : (range[0] + range[1]) / 2;
  15285. }
  15286. // Avoid accuracy problem in edge, such as
  15287. // 146.39 - 62.83 === 83.55999999999999.
  15288. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15289. // It is a little verbose for efficiency considering this method
  15290. // is a hotspot.
  15291. if (clamp) {
  15292. if (subDomain > 0) {
  15293. if (val <= domain[0]) {
  15294. return range[0];
  15295. }
  15296. else if (val >= domain[1]) {
  15297. return range[1];
  15298. }
  15299. }
  15300. else {
  15301. if (val >= domain[0]) {
  15302. return range[0];
  15303. }
  15304. else if (val <= domain[1]) {
  15305. return range[1];
  15306. }
  15307. }
  15308. }
  15309. else {
  15310. if (val === domain[0]) {
  15311. return range[0];
  15312. }
  15313. if (val === domain[1]) {
  15314. return range[1];
  15315. }
  15316. }
  15317. return (val - domain[0]) / subDomain * subRange + range[0];
  15318. }
  15319. /**
  15320. * Convert a percent string to absolute number.
  15321. * Returns NaN if percent is not a valid string or number
  15322. * @memberOf module:echarts/util/number
  15323. * @param {string|number} percent
  15324. * @param {number} all
  15325. * @return {number}
  15326. */
  15327. function parsePercent$1(percent, all) {
  15328. switch (percent) {
  15329. case 'center':
  15330. case 'middle':
  15331. percent = '50%';
  15332. break;
  15333. case 'left':
  15334. case 'top':
  15335. percent = '0%';
  15336. break;
  15337. case 'right':
  15338. case 'bottom':
  15339. percent = '100%';
  15340. break;
  15341. }
  15342. if (typeof percent === 'string') {
  15343. if (_trim(percent).match(/%$/)) {
  15344. return parseFloat(percent) / 100 * all;
  15345. }
  15346. return parseFloat(percent);
  15347. }
  15348. return percent == null ? NaN : +percent;
  15349. }
  15350. /**
  15351. * (1) Fix rounding error of float numbers.
  15352. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15353. *
  15354. * @param {number} x
  15355. * @param {number} [precision]
  15356. * @param {boolean} [returnStr]
  15357. * @return {number|string}
  15358. */
  15359. function round$1(x, precision, returnStr) {
  15360. if (precision == null) {
  15361. precision = 10;
  15362. }
  15363. // Avoid range error
  15364. precision = Math.min(Math.max(0, precision), 20);
  15365. x = (+x).toFixed(precision);
  15366. return returnStr ? x : +x;
  15367. }
  15368. function asc(arr) {
  15369. arr.sort(function (a, b) {
  15370. return a - b;
  15371. });
  15372. return arr;
  15373. }
  15374. /**
  15375. * Get precision
  15376. * @param {number} val
  15377. */
  15378. function getPrecision(val) {
  15379. val = +val;
  15380. if (isNaN(val)) {
  15381. return 0;
  15382. }
  15383. // It is much faster than methods converting number to string as follows
  15384. // var tmp = val.toString();
  15385. // return tmp.length - 1 - tmp.indexOf('.');
  15386. // especially when precision is low
  15387. var e = 1;
  15388. var count = 0;
  15389. while (Math.round(val * e) / e !== val) {
  15390. e *= 10;
  15391. count++;
  15392. }
  15393. return count;
  15394. }
  15395. /**
  15396. * @param {string|number} val
  15397. * @return {number}
  15398. */
  15399. function getPrecisionSafe(val) {
  15400. var str = val.toString();
  15401. // Consider scientific notation: '3.4e-12' '3.4e+12'
  15402. var eIndex = str.indexOf('e');
  15403. if (eIndex > 0) {
  15404. var precision = +str.slice(eIndex + 1);
  15405. return precision < 0 ? -precision : 0;
  15406. }
  15407. else {
  15408. var dotIndex = str.indexOf('.');
  15409. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15410. }
  15411. }
  15412. /**
  15413. * Minimal dicernible data precisioin according to a single pixel.
  15414. *
  15415. * @param {Array.<number>} dataExtent
  15416. * @param {Array.<number>} pixelExtent
  15417. * @return {number} precision
  15418. */
  15419. function getPixelPrecision(dataExtent, pixelExtent) {
  15420. var log = Math.log;
  15421. var LN10 = Math.LN10;
  15422. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15423. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10);
  15424. // toFixed() digits argument must be between 0 and 20.
  15425. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15426. return !isFinite(precision) ? 20 : precision;
  15427. }
  15428. /**
  15429. * Get a data of given precision, assuring the sum of percentages
  15430. * in valueList is 1.
  15431. * The largest remainer method is used.
  15432. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15433. *
  15434. * @param {Array.<number>} valueList a list of all data
  15435. * @param {number} idx index of the data to be processed in valueList
  15436. * @param {number} precision integer number showing digits of precision
  15437. * @return {number} percent ranging from 0 to 100
  15438. */
  15439. function getPercentWithPrecision(valueList, idx, precision) {
  15440. if (!valueList[idx]) {
  15441. return 0;
  15442. }
  15443. var sum = reduce(valueList, function (acc, val) {
  15444. return acc + (isNaN(val) ? 0 : val);
  15445. }, 0);
  15446. if (sum === 0) {
  15447. return 0;
  15448. }
  15449. var digits = Math.pow(10, precision);
  15450. var votesPerQuota = map(valueList, function (val) {
  15451. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15452. });
  15453. var targetSeats = digits * 100;
  15454. var seats = map(votesPerQuota, function (votes) {
  15455. // Assign automatic seats.
  15456. return Math.floor(votes);
  15457. });
  15458. var currentSum = reduce(seats, function (acc, val) {
  15459. return acc + val;
  15460. }, 0);
  15461. var remainder = map(votesPerQuota, function (votes, idx) {
  15462. return votes - seats[idx];
  15463. });
  15464. // Has remainding votes.
  15465. while (currentSum < targetSeats) {
  15466. // Find next largest remainder.
  15467. var max = Number.NEGATIVE_INFINITY;
  15468. var maxId = null;
  15469. for (var i = 0, len = remainder.length; i < len; ++i) {
  15470. if (remainder[i] > max) {
  15471. max = remainder[i];
  15472. maxId = i;
  15473. }
  15474. }
  15475. // Add a vote to max remainder.
  15476. ++seats[maxId];
  15477. remainder[maxId] = 0;
  15478. ++currentSum;
  15479. }
  15480. return seats[idx] / digits;
  15481. }
  15482. // Number.MAX_SAFE_INTEGER, ie do not support.
  15483. var MAX_SAFE_INTEGER = 9007199254740991;
  15484. /**
  15485. * To 0 - 2 * PI, considering negative radian.
  15486. * @param {number} radian
  15487. * @return {number}
  15488. */
  15489. function remRadian(radian) {
  15490. var pi2 = Math.PI * 2;
  15491. return (radian % pi2 + pi2) % pi2;
  15492. }
  15493. /**
  15494. * @param {type} radian
  15495. * @return {boolean}
  15496. */
  15497. function isRadianAroundZero(val) {
  15498. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15499. }
  15500. 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
  15501. /**
  15502. * @param {string|Date|number} value These values can be accepted:
  15503. * + An instance of Date, represent a time in its own time zone.
  15504. * + Or string in a subset of ISO 8601, only including:
  15505. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15506. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15507. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15508. * all of which will be treated as local time if time zone is not specified
  15509. * (see <https://momentjs.com/>).
  15510. * + Or other string format, including (all of which will be treated as loacal time):
  15511. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15512. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15513. * + a timestamp, which represent a time in UTC.
  15514. * @return {Date} date
  15515. */
  15516. function parseDate(value) {
  15517. if (value instanceof Date) {
  15518. return value;
  15519. }
  15520. else if (typeof value === 'string') {
  15521. // Different browsers parse date in different way, so we parse it manually.
  15522. // Some other issues:
  15523. // new Date('1970-01-01') is UTC,
  15524. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15525. // See issue #3623
  15526. var match = TIME_REG.exec(value);
  15527. if (!match) {
  15528. // return Invalid Date.
  15529. return new Date(NaN);
  15530. }
  15531. // Use local time when no timezone offset specifed.
  15532. if (!match[8]) {
  15533. // match[n] can only be string or undefined.
  15534. // But take care of '12' + 1 => '121'.
  15535. return new Date(
  15536. +match[1],
  15537. +(match[2] || 1) - 1,
  15538. +match[3] || 1,
  15539. +match[4] || 0,
  15540. +(match[5] || 0),
  15541. +match[6] || 0,
  15542. +match[7] || 0
  15543. );
  15544. }
  15545. // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15546. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15547. // For example, system timezone is set as "Time Zone: America/Toronto",
  15548. // then these code will get different result:
  15549. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15550. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15551. // So we should not use `new Date`, but use `Date.UTC`.
  15552. else {
  15553. var hour = +match[4] || 0;
  15554. if (match[8].toUpperCase() !== 'Z') {
  15555. hour -= match[8].slice(0, 3);
  15556. }
  15557. return new Date(Date.UTC(
  15558. +match[1],
  15559. +(match[2] || 1) - 1,
  15560. +match[3] || 1,
  15561. hour,
  15562. +(match[5] || 0),
  15563. +match[6] || 0,
  15564. +match[7] || 0
  15565. ));
  15566. }
  15567. }
  15568. else if (value == null) {
  15569. return new Date(NaN);
  15570. }
  15571. return new Date(Math.round(value));
  15572. }
  15573. /**
  15574. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15575. *
  15576. * @param {number} val
  15577. * @return {number}
  15578. */
  15579. function quantity(val) {
  15580. return Math.pow(10, quantityExponent(val));
  15581. }
  15582. function quantityExponent(val) {
  15583. return Math.floor(Math.log(val) / Math.LN10);
  15584. }
  15585. /**
  15586. * find a “nice” number approximately equal to x. Round the number if round = true,
  15587. * take ceiling if round = false. The primary observation is that the “nicest”
  15588. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15589. *
  15590. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15591. *
  15592. * @param {number} val Non-negative value.
  15593. * @param {boolean} round
  15594. * @return {number}
  15595. */
  15596. function nice(val, round) {
  15597. var exponent = quantityExponent(val);
  15598. var exp10 = Math.pow(10, exponent);
  15599. var f = val / exp10; // 1 <= f < 10
  15600. var nf;
  15601. if (round) {
  15602. if (f < 1.5) { nf = 1; }
  15603. else if (f < 2.5) { nf = 2; }
  15604. else if (f < 4) { nf = 3; }
  15605. else if (f < 7) { nf = 5; }
  15606. else { nf = 10; }
  15607. }
  15608. else {
  15609. if (f < 1) { nf = 1; }
  15610. else if (f < 2) { nf = 2; }
  15611. else if (f < 3) { nf = 3; }
  15612. else if (f < 5) { nf = 5; }
  15613. else { nf = 10; }
  15614. }
  15615. val = nf * exp10;
  15616. // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15617. // 20 is the uppper bound of toFixed.
  15618. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15619. }
  15620. /**
  15621. * BSD 3-Clause
  15622. *
  15623. * Copyright (c) 2010-2015, Michael Bostock
  15624. * All rights reserved.
  15625. *
  15626. * Redistribution and use in source and binary forms, with or without
  15627. * modification, are permitted provided that the following conditions are met:
  15628. *
  15629. * * Redistributions of source code must retain the above copyright notice, this
  15630. * list of conditions and the following disclaimer.
  15631. *
  15632. * * Redistributions in binary form must reproduce the above copyright notice,
  15633. * this list of conditions and the following disclaimer in the documentation
  15634. * and/or other materials provided with the distribution.
  15635. *
  15636. * * The name Michael Bostock may not be used to endorse or promote products
  15637. * derived from this software without specific prior written permission.
  15638. *
  15639. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  15640. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  15641. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  15642. * DISCLAIMED. IN NO EVENT SHALL MICHAEL BOSTOCK BE LIABLE FOR ANY DIRECT,
  15643. * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,
  15644. * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  15645. * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY
  15646. * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
  15647. * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE,
  15648. * EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  15649. */
  15650. /**
  15651. * @see <https://github.com/mbostock/d3/blob/master/src/arrays/quantile.js>
  15652. * @see <http://en.wikipedia.org/wiki/Quantile>
  15653. * @param {Array.<number>} ascArr
  15654. */
  15655. function quantile(ascArr, p) {
  15656. var H = (ascArr.length - 1) * p + 1;
  15657. var h = Math.floor(H);
  15658. var v = +ascArr[h - 1];
  15659. var e = H - h;
  15660. return e ? v + e * (ascArr[h] - v) : v;
  15661. }
  15662. /**
  15663. * Order intervals asc, and split them when overlap.
  15664. * expect(numberUtil.reformIntervals([
  15665. * {interval: [18, 62], close: [1, 1]},
  15666. * {interval: [-Infinity, -70], close: [0, 0]},
  15667. * {interval: [-70, -26], close: [1, 1]},
  15668. * {interval: [-26, 18], close: [1, 1]},
  15669. * {interval: [62, 150], close: [1, 1]},
  15670. * {interval: [106, 150], close: [1, 1]},
  15671. * {interval: [150, Infinity], close: [0, 0]}
  15672. * ])).toEqual([
  15673. * {interval: [-Infinity, -70], close: [0, 0]},
  15674. * {interval: [-70, -26], close: [1, 1]},
  15675. * {interval: [-26, 18], close: [0, 1]},
  15676. * {interval: [18, 62], close: [0, 1]},
  15677. * {interval: [62, 150], close: [0, 1]},
  15678. * {interval: [150, Infinity], close: [0, 0]}
  15679. * ]);
  15680. * @param {Array.<Object>} list, where `close` mean open or close
  15681. * of the interval, and Infinity can be used.
  15682. * @return {Array.<Object>} The origin list, which has been reformed.
  15683. */
  15684. function reformIntervals(list) {
  15685. list.sort(function (a, b) {
  15686. return littleThan(a, b, 0) ? -1 : 1;
  15687. });
  15688. var curr = -Infinity;
  15689. var currClose = 1;
  15690. for (var i = 0; i < list.length;) {
  15691. var interval = list[i].interval;
  15692. var close = list[i].close;
  15693. for (var lg = 0; lg < 2; lg++) {
  15694. if (interval[lg] <= curr) {
  15695. interval[lg] = curr;
  15696. close[lg] = !lg ? 1 - currClose : 1;
  15697. }
  15698. curr = interval[lg];
  15699. currClose = close[lg];
  15700. }
  15701. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15702. list.splice(i, 1);
  15703. }
  15704. else {
  15705. i++;
  15706. }
  15707. }
  15708. return list;
  15709. function littleThan(a, b, lg) {
  15710. return a.interval[lg] < b.interval[lg]
  15711. || (
  15712. a.interval[lg] === b.interval[lg]
  15713. && (
  15714. (a.close[lg] - b.close[lg] === (!lg ? 1 : -1))
  15715. || (!lg && littleThan(a, b, 1))
  15716. )
  15717. );
  15718. }
  15719. }
  15720. /**
  15721. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15722. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15723. * subtraction forces infinities to NaN
  15724. *
  15725. * @param {*} v
  15726. * @return {boolean}
  15727. */
  15728. function isNumeric(v) {
  15729. return v - parseFloat(v) >= 0;
  15730. }
  15731. var number = (Object.freeze || Object)({
  15732. linearMap: linearMap,
  15733. parsePercent: parsePercent$1,
  15734. round: round$1,
  15735. asc: asc,
  15736. getPrecision: getPrecision,
  15737. getPrecisionSafe: getPrecisionSafe,
  15738. getPixelPrecision: getPixelPrecision,
  15739. getPercentWithPrecision: getPercentWithPrecision,
  15740. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15741. remRadian: remRadian,
  15742. isRadianAroundZero: isRadianAroundZero,
  15743. parseDate: parseDate,
  15744. quantity: quantity,
  15745. nice: nice,
  15746. quantile: quantile,
  15747. reformIntervals: reformIntervals,
  15748. isNumeric: isNumeric
  15749. });
  15750. /*
  15751. * Licensed to the Apache Software Foundation (ASF) under one
  15752. * or more contributor license agreements. See the NOTICE file
  15753. * distributed with this work for additional information
  15754. * regarding copyright ownership. The ASF licenses this file
  15755. * to you under the Apache License, Version 2.0 (the
  15756. * "License"); you may not use this file except in compliance
  15757. * with the License. You may obtain a copy of the License at
  15758. *
  15759. * http://www.apache.org/licenses/LICENSE-2.0
  15760. *
  15761. * Unless required by applicable law or agreed to in writing,
  15762. * software distributed under the License is distributed on an
  15763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15764. * KIND, either express or implied. See the License for the
  15765. * specific language governing permissions and limitations
  15766. * under the License.
  15767. */
  15768. /**
  15769. * 每三位默认加,格式化
  15770. * @param {string|number} x
  15771. * @return {string}
  15772. */
  15773. function addCommas(x) {
  15774. if (isNaN(x)) {
  15775. return '-';
  15776. }
  15777. x = (x + '').split('.');
  15778. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,')
  15779. + (x.length > 1 ? ('.' + x[1]) : '');
  15780. }
  15781. /**
  15782. * @param {string} str
  15783. * @param {boolean} [upperCaseFirst=false]
  15784. * @return {string} str
  15785. */
  15786. function toCamelCase(str, upperCaseFirst) {
  15787. str = (str || '').toLowerCase().replace(/-(.)/g, function(match, group1) {
  15788. return group1.toUpperCase();
  15789. });
  15790. if (upperCaseFirst && str) {
  15791. str = str.charAt(0).toUpperCase() + str.slice(1);
  15792. }
  15793. return str;
  15794. }
  15795. var normalizeCssArray$1 = normalizeCssArray;
  15796. var replaceReg = /([&<>"'])/g;
  15797. var replaceMap = {
  15798. '&': '&amp;',
  15799. '<': '&lt;',
  15800. '>': '&gt;',
  15801. '"': '&quot;',
  15802. '\'': '&#39;'
  15803. };
  15804. function encodeHTML(source) {
  15805. return source == null
  15806. ? ''
  15807. : (source + '').replace(replaceReg, function (str, c) {
  15808. return replaceMap[c];
  15809. });
  15810. }
  15811. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  15812. var wrapVar = function (varName, seriesIdx) {
  15813. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  15814. };
  15815. /**
  15816. * Template formatter
  15817. * @param {string} tpl
  15818. * @param {Array.<Object>|Object} paramsList
  15819. * @param {boolean} [encode=false]
  15820. * @return {string}
  15821. */
  15822. function formatTpl(tpl, paramsList, encode) {
  15823. if (!isArray(paramsList)) {
  15824. paramsList = [paramsList];
  15825. }
  15826. var seriesLen = paramsList.length;
  15827. if (!seriesLen) {
  15828. return '';
  15829. }
  15830. var $vars = paramsList[0].$vars || [];
  15831. for (var i = 0; i < $vars.length; i++) {
  15832. var alias = TPL_VAR_ALIAS[i];
  15833. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  15834. }
  15835. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  15836. for (var k = 0; k < $vars.length; k++) {
  15837. var val = paramsList[seriesIdx][$vars[k]];
  15838. tpl = tpl.replace(
  15839. wrapVar(TPL_VAR_ALIAS[k], seriesIdx),
  15840. encode ? encodeHTML(val) : val
  15841. );
  15842. }
  15843. }
  15844. return tpl;
  15845. }
  15846. /**
  15847. * simple Template formatter
  15848. *
  15849. * @param {string} tpl
  15850. * @param {Object} param
  15851. * @param {boolean} [encode=false]
  15852. * @return {string}
  15853. */
  15854. function formatTplSimple(tpl, param, encode) {
  15855. each$1(param, function (value, key) {
  15856. tpl = tpl.replace(
  15857. '{' + key + '}',
  15858. encode ? encodeHTML(value) : value
  15859. );
  15860. });
  15861. return tpl;
  15862. }
  15863. /**
  15864. * @param {Object|string} [opt] If string, means color.
  15865. * @param {string} [opt.color]
  15866. * @param {string} [opt.extraCssText]
  15867. * @param {string} [opt.type='item'] 'item' or 'subItem'
  15868. * @return {string}
  15869. */
  15870. function getTooltipMarker(opt, extraCssText) {
  15871. opt = isString(opt) ? {color: opt, extraCssText: extraCssText} : (opt || {});
  15872. var color = opt.color;
  15873. var type = opt.type;
  15874. var extraCssText = opt.extraCssText;
  15875. if (!color) {
  15876. return '';
  15877. }
  15878. return type === 'subItem'
  15879. ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;'
  15880. + 'border-radius:4px;width:4px;height:4px;background-color:'
  15881. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>'
  15882. : '<span style="display:inline-block;margin-right:5px;'
  15883. + 'border-radius:10px;width:10px;height:10px;background-color:'
  15884. + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  15885. }
  15886. function pad(str, len) {
  15887. str += '';
  15888. return '0000'.substr(0, len - str.length) + str;
  15889. }
  15890. /**
  15891. * ISO Date format
  15892. * @param {string} tpl
  15893. * @param {number} value
  15894. * @param {boolean} [isUTC=false] Default in local time.
  15895. * see `module:echarts/scale/Time`
  15896. * and `module:echarts/util/number#parseDate`.
  15897. * @inner
  15898. */
  15899. function formatTime(tpl, value, isUTC) {
  15900. if (tpl === 'week'
  15901. || tpl === 'month'
  15902. || tpl === 'quarter'
  15903. || tpl === 'half-year'
  15904. || tpl === 'year'
  15905. ) {
  15906. tpl = 'MM-dd\nyyyy';
  15907. }
  15908. var date = parseDate(value);
  15909. var utc = isUTC ? 'UTC' : '';
  15910. var y = date['get' + utc + 'FullYear']();
  15911. var M = date['get' + utc + 'Month']() + 1;
  15912. var d = date['get' + utc + 'Date']();
  15913. var h = date['get' + utc + 'Hours']();
  15914. var m = date['get' + utc + 'Minutes']();
  15915. var s = date['get' + utc + 'Seconds']();
  15916. var S = date['get' + utc + 'Milliseconds']();
  15917. tpl = tpl.replace('MM', pad(M, 2))
  15918. .replace('M', M)
  15919. .replace('yyyy', y)
  15920. .replace('yy', y % 100)
  15921. .replace('dd', pad(d, 2))
  15922. .replace('d', d)
  15923. .replace('hh', pad(h, 2))
  15924. .replace('h', h)
  15925. .replace('mm', pad(m, 2))
  15926. .replace('m', m)
  15927. .replace('ss', pad(s, 2))
  15928. .replace('s', s)
  15929. .replace('SSS', pad(S, 3));
  15930. return tpl;
  15931. }
  15932. /**
  15933. * Capital first
  15934. * @param {string} str
  15935. * @return {string}
  15936. */
  15937. function capitalFirst(str) {
  15938. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  15939. }
  15940. var truncateText$1 = truncateText;
  15941. var getTextRect = getBoundingRect;
  15942. var format = (Object.freeze || Object)({
  15943. addCommas: addCommas,
  15944. toCamelCase: toCamelCase,
  15945. normalizeCssArray: normalizeCssArray$1,
  15946. encodeHTML: encodeHTML,
  15947. formatTpl: formatTpl,
  15948. formatTplSimple: formatTplSimple,
  15949. getTooltipMarker: getTooltipMarker,
  15950. formatTime: formatTime,
  15951. capitalFirst: capitalFirst,
  15952. truncateText: truncateText$1,
  15953. getTextRect: getTextRect
  15954. });
  15955. /*
  15956. * Licensed to the Apache Software Foundation (ASF) under one
  15957. * or more contributor license agreements. See the NOTICE file
  15958. * distributed with this work for additional information
  15959. * regarding copyright ownership. The ASF licenses this file
  15960. * to you under the Apache License, Version 2.0 (the
  15961. * "License"); you may not use this file except in compliance
  15962. * with the License. You may obtain a copy of the License at
  15963. *
  15964. * http://www.apache.org/licenses/LICENSE-2.0
  15965. *
  15966. * Unless required by applicable law or agreed to in writing,
  15967. * software distributed under the License is distributed on an
  15968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15969. * KIND, either express or implied. See the License for the
  15970. * specific language governing permissions and limitations
  15971. * under the License.
  15972. */
  15973. // Layout helpers for each component positioning
  15974. var each$3 = each$1;
  15975. /**
  15976. * @public
  15977. */
  15978. var LOCATION_PARAMS = [
  15979. 'left', 'right', 'top', 'bottom', 'width', 'height'
  15980. ];
  15981. /**
  15982. * @public
  15983. */
  15984. var HV_NAMES = [
  15985. ['width', 'left', 'right'],
  15986. ['height', 'top', 'bottom']
  15987. ];
  15988. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  15989. var x = 0;
  15990. var y = 0;
  15991. if (maxWidth == null) {
  15992. maxWidth = Infinity;
  15993. }
  15994. if (maxHeight == null) {
  15995. maxHeight = Infinity;
  15996. }
  15997. var currentLineMaxSize = 0;
  15998. group.eachChild(function (child, idx) {
  15999. var position = child.position;
  16000. var rect = child.getBoundingRect();
  16001. var nextChild = group.childAt(idx + 1);
  16002. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16003. var nextX;
  16004. var nextY;
  16005. if (orient === 'horizontal') {
  16006. var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0);
  16007. nextX = x + moveX;
  16008. // Wrap when width exceeds maxWidth or meet a `newline` group
  16009. // FIXME compare before adding gap?
  16010. if (nextX > maxWidth || child.newline) {
  16011. x = 0;
  16012. nextX = moveX;
  16013. y += currentLineMaxSize + gap;
  16014. currentLineMaxSize = rect.height;
  16015. }
  16016. else {
  16017. // FIXME: consider rect.y is not `0`?
  16018. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16019. }
  16020. }
  16021. else {
  16022. var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0);
  16023. nextY = y + moveY;
  16024. // Wrap when width exceeds maxHeight or meet a `newline` group
  16025. if (nextY > maxHeight || child.newline) {
  16026. x += currentLineMaxSize + gap;
  16027. y = 0;
  16028. nextY = moveY;
  16029. currentLineMaxSize = rect.width;
  16030. }
  16031. else {
  16032. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16033. }
  16034. }
  16035. if (child.newline) {
  16036. return;
  16037. }
  16038. position[0] = x;
  16039. position[1] = y;
  16040. orient === 'horizontal'
  16041. ? (x = nextX + gap)
  16042. : (y = nextY + gap);
  16043. });
  16044. }
  16045. /**
  16046. * VBox or HBox layouting
  16047. * @param {string} orient
  16048. * @param {module:zrender/container/Group} group
  16049. * @param {number} gap
  16050. * @param {number} [width=Infinity]
  16051. * @param {number} [height=Infinity]
  16052. */
  16053. var box = boxLayout;
  16054. /**
  16055. * VBox layouting
  16056. * @param {module:zrender/container/Group} group
  16057. * @param {number} gap
  16058. * @param {number} [width=Infinity]
  16059. * @param {number} [height=Infinity]
  16060. */
  16061. var vbox = curry(boxLayout, 'vertical');
  16062. /**
  16063. * HBox layouting
  16064. * @param {module:zrender/container/Group} group
  16065. * @param {number} gap
  16066. * @param {number} [width=Infinity]
  16067. * @param {number} [height=Infinity]
  16068. */
  16069. var hbox = curry(boxLayout, 'horizontal');
  16070. /**
  16071. * If x or x2 is not specified or 'center' 'left' 'right',
  16072. * the width would be as long as possible.
  16073. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16074. * the height would be as long as possible.
  16075. *
  16076. * @param {Object} positionInfo
  16077. * @param {number|string} [positionInfo.x]
  16078. * @param {number|string} [positionInfo.y]
  16079. * @param {number|string} [positionInfo.x2]
  16080. * @param {number|string} [positionInfo.y2]
  16081. * @param {Object} containerRect {width, height}
  16082. * @param {string|number} margin
  16083. * @return {Object} {width, height}
  16084. */
  16085. function getAvailableSize(positionInfo, containerRect, margin) {
  16086. var containerWidth = containerRect.width;
  16087. var containerHeight = containerRect.height;
  16088. var x = parsePercent$1(positionInfo.x, containerWidth);
  16089. var y = parsePercent$1(positionInfo.y, containerHeight);
  16090. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16091. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16092. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16093. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16094. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16095. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16096. margin = normalizeCssArray$1(margin || 0);
  16097. return {
  16098. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16099. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16100. };
  16101. }
  16102. /**
  16103. * Parse position info.
  16104. *
  16105. * @param {Object} positionInfo
  16106. * @param {number|string} [positionInfo.left]
  16107. * @param {number|string} [positionInfo.top]
  16108. * @param {number|string} [positionInfo.right]
  16109. * @param {number|string} [positionInfo.bottom]
  16110. * @param {number|string} [positionInfo.width]
  16111. * @param {number|string} [positionInfo.height]
  16112. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16113. * @param {Object} containerRect
  16114. * @param {string|number} [margin]
  16115. *
  16116. * @return {module:zrender/core/BoundingRect}
  16117. */
  16118. function getLayoutRect(
  16119. positionInfo, containerRect, margin
  16120. ) {
  16121. margin = normalizeCssArray$1(margin || 0);
  16122. var containerWidth = containerRect.width;
  16123. var containerHeight = containerRect.height;
  16124. var left = parsePercent$1(positionInfo.left, containerWidth);
  16125. var top = parsePercent$1(positionInfo.top, containerHeight);
  16126. var right = parsePercent$1(positionInfo.right, containerWidth);
  16127. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16128. var width = parsePercent$1(positionInfo.width, containerWidth);
  16129. var height = parsePercent$1(positionInfo.height, containerHeight);
  16130. var verticalMargin = margin[2] + margin[0];
  16131. var horizontalMargin = margin[1] + margin[3];
  16132. var aspect = positionInfo.aspect;
  16133. // If width is not specified, calculate width from left and right
  16134. if (isNaN(width)) {
  16135. width = containerWidth - right - horizontalMargin - left;
  16136. }
  16137. if (isNaN(height)) {
  16138. height = containerHeight - bottom - verticalMargin - top;
  16139. }
  16140. if (aspect != null) {
  16141. // If width and height are not given
  16142. // 1. Graph should not exceeds the container
  16143. // 2. Aspect must be keeped
  16144. // 3. Graph should take the space as more as possible
  16145. // FIXME
  16146. // Margin is not considered, because there is no case that both
  16147. // using margin and aspect so far.
  16148. if (isNaN(width) && isNaN(height)) {
  16149. if (aspect > containerWidth / containerHeight) {
  16150. width = containerWidth * 0.8;
  16151. }
  16152. else {
  16153. height = containerHeight * 0.8;
  16154. }
  16155. }
  16156. // Calculate width or height with given aspect
  16157. if (isNaN(width)) {
  16158. width = aspect * height;
  16159. }
  16160. if (isNaN(height)) {
  16161. height = width / aspect;
  16162. }
  16163. }
  16164. // If left is not specified, calculate left from right and width
  16165. if (isNaN(left)) {
  16166. left = containerWidth - right - width - horizontalMargin;
  16167. }
  16168. if (isNaN(top)) {
  16169. top = containerHeight - bottom - height - verticalMargin;
  16170. }
  16171. // Align left and top
  16172. switch (positionInfo.left || positionInfo.right) {
  16173. case 'center':
  16174. left = containerWidth / 2 - width / 2 - margin[3];
  16175. break;
  16176. case 'right':
  16177. left = containerWidth - width - horizontalMargin;
  16178. break;
  16179. }
  16180. switch (positionInfo.top || positionInfo.bottom) {
  16181. case 'middle':
  16182. case 'center':
  16183. top = containerHeight / 2 - height / 2 - margin[0];
  16184. break;
  16185. case 'bottom':
  16186. top = containerHeight - height - verticalMargin;
  16187. break;
  16188. }
  16189. // If something is wrong and left, top, width, height are calculated as NaN
  16190. left = left || 0;
  16191. top = top || 0;
  16192. if (isNaN(width)) {
  16193. // Width may be NaN if only one value is given except width
  16194. width = containerWidth - horizontalMargin - left - (right || 0);
  16195. }
  16196. if (isNaN(height)) {
  16197. // Height may be NaN if only one value is given except height
  16198. height = containerHeight - verticalMargin - top - (bottom || 0);
  16199. }
  16200. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16201. rect.margin = margin;
  16202. return rect;
  16203. }
  16204. /**
  16205. * Position a zr element in viewport
  16206. * Group position is specified by either
  16207. * {left, top}, {right, bottom}
  16208. * If all properties exists, right and bottom will be igonred.
  16209. *
  16210. * Logic:
  16211. * 1. Scale (against origin point in parent coord)
  16212. * 2. Rotate (against origin point in parent coord)
  16213. * 3. Traslate (with el.position by this method)
  16214. * So this method only fixes the last step 'Traslate', which does not affect
  16215. * scaling and rotating.
  16216. *
  16217. * If be called repeatly with the same input el, the same result will be gotten.
  16218. *
  16219. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16220. * @param {Object} positionInfo
  16221. * @param {number|string} [positionInfo.left]
  16222. * @param {number|string} [positionInfo.top]
  16223. * @param {number|string} [positionInfo.right]
  16224. * @param {number|string} [positionInfo.bottom]
  16225. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16226. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16227. * @param {Object} containerRect
  16228. * @param {string|number} margin
  16229. * @param {Object} [opt]
  16230. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16231. * @param {Array.<number>} [opt.boundingMode='all']
  16232. * Specify how to calculate boundingRect when locating.
  16233. * 'all': Position the boundingRect that is transformed and uioned
  16234. * both itself and its descendants.
  16235. * This mode simplies confine the elements in the bounding
  16236. * of their container (e.g., using 'right: 0').
  16237. * 'raw': Position the boundingRect that is not transformed and only itself.
  16238. * This mode is useful when you want a element can overflow its
  16239. * container. (Consider a rotated circle needs to be located in a corner.)
  16240. * In this mode positionInfo.width/height can only be number.
  16241. */
  16242. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16243. var h = !opt || !opt.hv || opt.hv[0];
  16244. var v = !opt || !opt.hv || opt.hv[1];
  16245. var boundingMode = opt && opt.boundingMode || 'all';
  16246. if (!h && !v) {
  16247. return;
  16248. }
  16249. var rect;
  16250. if (boundingMode === 'raw') {
  16251. rect = el.type === 'group'
  16252. ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0)
  16253. : el.getBoundingRect();
  16254. }
  16255. else {
  16256. rect = el.getBoundingRect();
  16257. if (el.needLocalTransform()) {
  16258. var transform = el.getLocalTransform();
  16259. // Notice: raw rect may be inner object of el,
  16260. // which should not be modified.
  16261. rect = rect.clone();
  16262. rect.applyTransform(transform);
  16263. }
  16264. }
  16265. // The real width and height can not be specified but calculated by the given el.
  16266. positionInfo = getLayoutRect(
  16267. defaults(
  16268. {width: rect.width, height: rect.height},
  16269. positionInfo
  16270. ),
  16271. containerRect,
  16272. margin
  16273. );
  16274. // Because 'tranlate' is the last step in transform
  16275. // (see zrender/core/Transformable#getLocalTransform),
  16276. // we can just only modify el.position to get final result.
  16277. var elPos = el.position;
  16278. var dx = h ? positionInfo.x - rect.x : 0;
  16279. var dy = v ? positionInfo.y - rect.y : 0;
  16280. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16281. }
  16282. /**
  16283. * @param {Object} option Contains some of the properties in HV_NAMES.
  16284. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16285. */
  16286. function sizeCalculable(option, hvIdx) {
  16287. return option[HV_NAMES[hvIdx][0]] != null
  16288. || (option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null);
  16289. }
  16290. /**
  16291. * Consider Case:
  16292. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16293. * through setOption or media query, using normal zrUtil.merge will cause
  16294. * {right: 0} does not take effect.
  16295. *
  16296. * @example
  16297. * ComponentModel.extend({
  16298. * init: function () {
  16299. * ...
  16300. * var inputPositionParams = layout.getLayoutParams(option);
  16301. * this.mergeOption(inputPositionParams);
  16302. * },
  16303. * mergeOption: function (newOption) {
  16304. * newOption && zrUtil.merge(thisOption, newOption, true);
  16305. * layout.mergeLayoutParam(thisOption, newOption);
  16306. * }
  16307. * });
  16308. *
  16309. * @param {Object} targetOption
  16310. * @param {Object} newOption
  16311. * @param {Object|string} [opt]
  16312. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16313. * that width (or height) should not be calculated by left and right (or top and bottom).
  16314. */
  16315. function mergeLayoutParam(targetOption, newOption, opt) {
  16316. !isObject$1(opt) && (opt = {});
  16317. var ignoreSize = opt.ignoreSize;
  16318. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16319. var hResult = merge$$1(HV_NAMES[0], 0);
  16320. var vResult = merge$$1(HV_NAMES[1], 1);
  16321. copy(HV_NAMES[0], targetOption, hResult);
  16322. copy(HV_NAMES[1], targetOption, vResult);
  16323. function merge$$1(names, hvIdx) {
  16324. var newParams = {};
  16325. var newValueCount = 0;
  16326. var merged = {};
  16327. var mergedValueCount = 0;
  16328. var enoughParamNumber = 2;
  16329. each$3(names, function (name) {
  16330. merged[name] = targetOption[name];
  16331. });
  16332. each$3(names, function (name) {
  16333. // Consider case: newOption.width is null, which is
  16334. // set by user for removing width setting.
  16335. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16336. hasValue(newParams, name) && newValueCount++;
  16337. hasValue(merged, name) && mergedValueCount++;
  16338. });
  16339. if (ignoreSize[hvIdx]) {
  16340. // Only one of left/right is premitted to exist.
  16341. if (hasValue(newOption, names[1])) {
  16342. merged[names[2]] = null;
  16343. }
  16344. else if (hasValue(newOption, names[2])) {
  16345. merged[names[1]] = null;
  16346. }
  16347. return merged;
  16348. }
  16349. // Case: newOption: {width: ..., right: ...},
  16350. // or targetOption: {right: ...} and newOption: {width: ...},
  16351. // There is no conflict when merged only has params count
  16352. // little than enoughParamNumber.
  16353. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16354. return merged;
  16355. }
  16356. // Case: newOption: {width: ..., right: ...},
  16357. // Than we can make sure user only want those two, and ignore
  16358. // all origin params in targetOption.
  16359. else if (newValueCount >= enoughParamNumber) {
  16360. return newParams;
  16361. }
  16362. else {
  16363. // Chose another param from targetOption by priority.
  16364. for (var i = 0; i < names.length; i++) {
  16365. var name = names[i];
  16366. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16367. newParams[name] = targetOption[name];
  16368. break;
  16369. }
  16370. }
  16371. return newParams;
  16372. }
  16373. }
  16374. function hasProp(obj, name) {
  16375. return obj.hasOwnProperty(name);
  16376. }
  16377. function hasValue(obj, name) {
  16378. return obj[name] != null && obj[name] !== 'auto';
  16379. }
  16380. function copy(names, target, source) {
  16381. each$3(names, function (name) {
  16382. target[name] = source[name];
  16383. });
  16384. }
  16385. }
  16386. /**
  16387. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16388. * @param {Object} source
  16389. * @return {Object} Result contains those props.
  16390. */
  16391. function getLayoutParams(source) {
  16392. return copyLayoutParams({}, source);
  16393. }
  16394. /**
  16395. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16396. * @param {Object} source
  16397. * @return {Object} Result contains those props.
  16398. */
  16399. function copyLayoutParams(target, source) {
  16400. source && target && each$3(LOCATION_PARAMS, function (name) {
  16401. source.hasOwnProperty(name) && (target[name] = source[name]);
  16402. });
  16403. return target;
  16404. }
  16405. /*
  16406. * Licensed to the Apache Software Foundation (ASF) under one
  16407. * or more contributor license agreements. See the NOTICE file
  16408. * distributed with this work for additional information
  16409. * regarding copyright ownership. The ASF licenses this file
  16410. * to you under the Apache License, Version 2.0 (the
  16411. * "License"); you may not use this file except in compliance
  16412. * with the License. You may obtain a copy of the License at
  16413. *
  16414. * http://www.apache.org/licenses/LICENSE-2.0
  16415. *
  16416. * Unless required by applicable law or agreed to in writing,
  16417. * software distributed under the License is distributed on an
  16418. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16419. * KIND, either express or implied. See the License for the
  16420. * specific language governing permissions and limitations
  16421. * under the License.
  16422. */
  16423. var boxLayoutMixin = {
  16424. getBoxLayoutParams: function () {
  16425. return {
  16426. left: this.get('left'),
  16427. top: this.get('top'),
  16428. right: this.get('right'),
  16429. bottom: this.get('bottom'),
  16430. width: this.get('width'),
  16431. height: this.get('height')
  16432. };
  16433. }
  16434. };
  16435. /*
  16436. * Licensed to the Apache Software Foundation (ASF) under one
  16437. * or more contributor license agreements. See the NOTICE file
  16438. * distributed with this work for additional information
  16439. * regarding copyright ownership. The ASF licenses this file
  16440. * to you under the Apache License, Version 2.0 (the
  16441. * "License"); you may not use this file except in compliance
  16442. * with the License. You may obtain a copy of the License at
  16443. *
  16444. * http://www.apache.org/licenses/LICENSE-2.0
  16445. *
  16446. * Unless required by applicable law or agreed to in writing,
  16447. * software distributed under the License is distributed on an
  16448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16449. * KIND, either express or implied. See the License for the
  16450. * specific language governing permissions and limitations
  16451. * under the License.
  16452. */
  16453. /**
  16454. * Component model
  16455. *
  16456. * @module echarts/model/Component
  16457. */
  16458. var inner$1 = makeInner();
  16459. /**
  16460. * @alias module:echarts/model/Component
  16461. * @constructor
  16462. * @param {Object} option
  16463. * @param {module:echarts/model/Model} parentModel
  16464. * @param {module:echarts/model/Model} ecModel
  16465. */
  16466. var ComponentModel = Model.extend({
  16467. type: 'component',
  16468. /**
  16469. * @readOnly
  16470. * @type {string}
  16471. */
  16472. id: '',
  16473. /**
  16474. * Because simplified concept is probably better, series.name (or component.name)
  16475. * has been having too many resposibilities:
  16476. * (1) Generating id (which requires name in option should not be modified).
  16477. * (2) As an index to mapping series when merging option or calling API (a name
  16478. * can refer to more then one components, which is convinient is some case).
  16479. * (3) Display.
  16480. * @readOnly
  16481. */
  16482. name: '',
  16483. /**
  16484. * @readOnly
  16485. * @type {string}
  16486. */
  16487. mainType: '',
  16488. /**
  16489. * @readOnly
  16490. * @type {string}
  16491. */
  16492. subType: '',
  16493. /**
  16494. * @readOnly
  16495. * @type {number}
  16496. */
  16497. componentIndex: 0,
  16498. /**
  16499. * @type {Object}
  16500. * @protected
  16501. */
  16502. defaultOption: null,
  16503. /**
  16504. * @type {module:echarts/model/Global}
  16505. * @readOnly
  16506. */
  16507. ecModel: null,
  16508. /**
  16509. * key: componentType
  16510. * value: Component model list, can not be null.
  16511. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16512. * @readOnly
  16513. */
  16514. dependentModels: [],
  16515. /**
  16516. * @type {string}
  16517. * @readOnly
  16518. */
  16519. uid: null,
  16520. /**
  16521. * Support merge layout params.
  16522. * Only support 'box' now (left/right/top/bottom/width/height).
  16523. * @type {string|Object} Object can be {ignoreSize: true}
  16524. * @readOnly
  16525. */
  16526. layoutMode: null,
  16527. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16528. Model.call(this, option, parentModel, ecModel, extraOpt);
  16529. this.uid = getUID('ec_cpt_model');
  16530. },
  16531. init: function (option, parentModel, ecModel, extraOpt) {
  16532. this.mergeDefaultAndTheme(option, ecModel);
  16533. },
  16534. mergeDefaultAndTheme: function (option, ecModel) {
  16535. var layoutMode = this.layoutMode;
  16536. var inputPositionParams = layoutMode
  16537. ? getLayoutParams(option) : {};
  16538. var themeModel = ecModel.getTheme();
  16539. merge(option, themeModel.get(this.mainType));
  16540. merge(option, this.getDefaultOption());
  16541. if (layoutMode) {
  16542. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16543. }
  16544. },
  16545. mergeOption: function (option, extraOpt) {
  16546. merge(this.option, option, true);
  16547. var layoutMode = this.layoutMode;
  16548. if (layoutMode) {
  16549. mergeLayoutParam(this.option, option, layoutMode);
  16550. }
  16551. },
  16552. // Hooker after init or mergeOption
  16553. optionUpdated: function (newCptOption, isInit) {},
  16554. getDefaultOption: function () {
  16555. var fields = inner$1(this);
  16556. if (!fields.defaultOption) {
  16557. var optList = [];
  16558. var Class = this.constructor;
  16559. while (Class) {
  16560. var opt = Class.prototype.defaultOption;
  16561. opt && optList.push(opt);
  16562. Class = Class.superClass;
  16563. }
  16564. var defaultOption = {};
  16565. for (var i = optList.length - 1; i >= 0; i--) {
  16566. defaultOption = merge(defaultOption, optList[i], true);
  16567. }
  16568. fields.defaultOption = defaultOption;
  16569. }
  16570. return fields.defaultOption;
  16571. },
  16572. getReferringComponents: function (mainType) {
  16573. return this.ecModel.queryComponents({
  16574. mainType: mainType,
  16575. index: this.get(mainType + 'Index', true),
  16576. id: this.get(mainType + 'Id', true)
  16577. });
  16578. }
  16579. });
  16580. // Reset ComponentModel.extend, add preConstruct.
  16581. // clazzUtil.enableClassExtend(
  16582. // ComponentModel,
  16583. // function (option, parentModel, ecModel, extraOpt) {
  16584. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16585. // zrUtil.extend(this, extraOpt);
  16586. // this.uid = componentUtil.getUID('componentModel');
  16587. // // this.setReadOnly([
  16588. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16589. // // 'dependentModels', 'componentIndex'
  16590. // // ]);
  16591. // }
  16592. // );
  16593. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16594. enableClassManagement(
  16595. ComponentModel, {registerWhenExtend: true}
  16596. );
  16597. enableSubTypeDefaulter(ComponentModel);
  16598. // Add capability of ComponentModel.topologicalTravel.
  16599. enableTopologicalTravel(ComponentModel, getDependencies);
  16600. function getDependencies(componentType) {
  16601. var deps = [];
  16602. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16603. deps = deps.concat(Clazz.prototype.dependencies || []);
  16604. });
  16605. // Ensure main type.
  16606. deps = map(deps, function (type) {
  16607. return parseClassType$1(type).main;
  16608. });
  16609. // Hack dataset for convenience.
  16610. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16611. deps.unshift('dataset');
  16612. }
  16613. return deps;
  16614. }
  16615. mixin(ComponentModel, boxLayoutMixin);
  16616. /*
  16617. * Licensed to the Apache Software Foundation (ASF) under one
  16618. * or more contributor license agreements. See the NOTICE file
  16619. * distributed with this work for additional information
  16620. * regarding copyright ownership. The ASF licenses this file
  16621. * to you under the Apache License, Version 2.0 (the
  16622. * "License"); you may not use this file except in compliance
  16623. * with the License. You may obtain a copy of the License at
  16624. *
  16625. * http://www.apache.org/licenses/LICENSE-2.0
  16626. *
  16627. * Unless required by applicable law or agreed to in writing,
  16628. * software distributed under the License is distributed on an
  16629. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16630. * KIND, either express or implied. See the License for the
  16631. * specific language governing permissions and limitations
  16632. * under the License.
  16633. */
  16634. var platform = '';
  16635. // Navigator not exists in node
  16636. if (typeof navigator !== 'undefined') {
  16637. platform = navigator.platform || '';
  16638. }
  16639. var globalDefault = {
  16640. // backgroundColor: 'rgba(0,0,0,0)',
  16641. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16642. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16643. // Light colors:
  16644. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16645. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16646. // Dark colors:
  16647. color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'],
  16648. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16649. // If xAxis and yAxis declared, grid is created by default.
  16650. // grid: {},
  16651. textStyle: {
  16652. // color: '#000',
  16653. // decoration: 'none',
  16654. // PENDING
  16655. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16656. // fontFamily: 'Arial, Verdana, sans-serif',
  16657. fontSize: 12,
  16658. fontStyle: 'normal',
  16659. fontWeight: 'normal'
  16660. },
  16661. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16662. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16663. // Default is source-over
  16664. blendMode: null,
  16665. animation: 'auto',
  16666. animationDuration: 1000,
  16667. animationDurationUpdate: 300,
  16668. animationEasing: 'exponentialOut',
  16669. animationEasingUpdate: 'cubicOut',
  16670. animationThreshold: 2000,
  16671. // Configuration for progressive/incremental rendering
  16672. progressiveThreshold: 3000,
  16673. progressive: 400,
  16674. // Threshold of if use single hover layer to optimize.
  16675. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16676. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16677. // which is unexpected.
  16678. // see example <echarts/test/heatmap-large.html>.
  16679. hoverLayerThreshold: 3000,
  16680. // See: module:echarts/scale/Time
  16681. useUTC: false
  16682. };
  16683. /*
  16684. * Licensed to the Apache Software Foundation (ASF) under one
  16685. * or more contributor license agreements. See the NOTICE file
  16686. * distributed with this work for additional information
  16687. * regarding copyright ownership. The ASF licenses this file
  16688. * to you under the Apache License, Version 2.0 (the
  16689. * "License"); you may not use this file except in compliance
  16690. * with the License. You may obtain a copy of the License at
  16691. *
  16692. * http://www.apache.org/licenses/LICENSE-2.0
  16693. *
  16694. * Unless required by applicable law or agreed to in writing,
  16695. * software distributed under the License is distributed on an
  16696. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16697. * KIND, either express or implied. See the License for the
  16698. * specific language governing permissions and limitations
  16699. * under the License.
  16700. */
  16701. var inner$2 = makeInner();
  16702. function getNearestColorPalette(colors, requestColorNum) {
  16703. var paletteNum = colors.length;
  16704. // TODO colors must be in order
  16705. for (var i = 0; i < paletteNum; i++) {
  16706. if (colors[i].length > requestColorNum) {
  16707. return colors[i];
  16708. }
  16709. }
  16710. return colors[paletteNum - 1];
  16711. }
  16712. var colorPaletteMixin = {
  16713. clearColorPalette: function () {
  16714. inner$2(this).colorIdx = 0;
  16715. inner$2(this).colorNameMap = {};
  16716. },
  16717. /**
  16718. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16719. * twise with the same parameters will get different result.
  16720. * @param {Object} [scope=this]
  16721. * @param {Object} [requestColorNum]
  16722. * @return {string} color string.
  16723. */
  16724. getColorFromPalette: function (name, scope, requestColorNum) {
  16725. scope = scope || this;
  16726. var scopeFields = inner$2(scope);
  16727. var colorIdx = scopeFields.colorIdx || 0;
  16728. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {};
  16729. // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16730. if (colorNameMap.hasOwnProperty(name)) {
  16731. return colorNameMap[name];
  16732. }
  16733. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16734. var layeredColorPalette = this.get('colorLayer', true);
  16735. var colorPalette = ((requestColorNum == null || !layeredColorPalette)
  16736. ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum));
  16737. // In case can't find in layered color palette.
  16738. colorPalette = colorPalette || defaultColorPalette;
  16739. if (!colorPalette || !colorPalette.length) {
  16740. return;
  16741. }
  16742. var color = colorPalette[colorIdx];
  16743. if (name) {
  16744. colorNameMap[name] = color;
  16745. }
  16746. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16747. return color;
  16748. }
  16749. };
  16750. /*
  16751. * Licensed to the Apache Software Foundation (ASF) under one
  16752. * or more contributor license agreements. See the NOTICE file
  16753. * distributed with this work for additional information
  16754. * regarding copyright ownership. The ASF licenses this file
  16755. * to you under the Apache License, Version 2.0 (the
  16756. * "License"); you may not use this file except in compliance
  16757. * with the License. You may obtain a copy of the License at
  16758. *
  16759. * http://www.apache.org/licenses/LICENSE-2.0
  16760. *
  16761. * Unless required by applicable law or agreed to in writing,
  16762. * software distributed under the License is distributed on an
  16763. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16764. * KIND, either express or implied. See the License for the
  16765. * specific language governing permissions and limitations
  16766. * under the License.
  16767. */
  16768. /**
  16769. * Helper for model references.
  16770. * There are many manners to refer axis/coordSys.
  16771. */
  16772. // TODO
  16773. // merge relevant logic to this file?
  16774. // check: "modelHelper" of tooltip and "BrushTargetManager".
  16775. /**
  16776. * @return {Object} For example:
  16777. * {
  16778. * coordSysName: 'cartesian2d',
  16779. * coordSysDims: ['x', 'y', ...],
  16780. * axisMap: HashMap({
  16781. * x: xAxisModel,
  16782. * y: yAxisModel
  16783. * }),
  16784. * categoryAxisMap: HashMap({
  16785. * x: xAxisModel,
  16786. * y: undefined
  16787. * }),
  16788. * // It also indicate that whether there is category axis.
  16789. * firstCategoryDimIndex: 1,
  16790. * // To replace user specified encode.
  16791. * }
  16792. */
  16793. function getCoordSysDefineBySeries(seriesModel) {
  16794. var coordSysName = seriesModel.get('coordinateSystem');
  16795. var result = {
  16796. coordSysName: coordSysName,
  16797. coordSysDims: [],
  16798. axisMap: createHashMap(),
  16799. categoryAxisMap: createHashMap()
  16800. };
  16801. var fetch = fetchers[coordSysName];
  16802. if (fetch) {
  16803. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  16804. return result;
  16805. }
  16806. }
  16807. var fetchers = {
  16808. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  16809. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  16810. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  16811. if (__DEV__) {
  16812. if (!xAxisModel) {
  16813. throw new Error('xAxis "' + retrieve(
  16814. seriesModel.get('xAxisIndex'),
  16815. seriesModel.get('xAxisId'),
  16816. 0
  16817. ) + '" not found');
  16818. }
  16819. if (!yAxisModel) {
  16820. throw new Error('yAxis "' + retrieve(
  16821. seriesModel.get('xAxisIndex'),
  16822. seriesModel.get('yAxisId'),
  16823. 0
  16824. ) + '" not found');
  16825. }
  16826. }
  16827. result.coordSysDims = ['x', 'y'];
  16828. axisMap.set('x', xAxisModel);
  16829. axisMap.set('y', yAxisModel);
  16830. if (isCategory(xAxisModel)) {
  16831. categoryAxisMap.set('x', xAxisModel);
  16832. result.firstCategoryDimIndex = 0;
  16833. }
  16834. if (isCategory(yAxisModel)) {
  16835. categoryAxisMap.set('y', yAxisModel);
  16836. result.firstCategoryDimIndex = 1;
  16837. }
  16838. },
  16839. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  16840. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  16841. if (__DEV__) {
  16842. if (!singleAxisModel) {
  16843. throw new Error('singleAxis should be specified.');
  16844. }
  16845. }
  16846. result.coordSysDims = ['single'];
  16847. axisMap.set('single', singleAxisModel);
  16848. if (isCategory(singleAxisModel)) {
  16849. categoryAxisMap.set('single', singleAxisModel);
  16850. result.firstCategoryDimIndex = 0;
  16851. }
  16852. },
  16853. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  16854. var polarModel = seriesModel.getReferringComponents('polar')[0];
  16855. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  16856. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  16857. if (__DEV__) {
  16858. if (!angleAxisModel) {
  16859. throw new Error('angleAxis option not found');
  16860. }
  16861. if (!radiusAxisModel) {
  16862. throw new Error('radiusAxis option not found');
  16863. }
  16864. }
  16865. result.coordSysDims = ['radius', 'angle'];
  16866. axisMap.set('radius', radiusAxisModel);
  16867. axisMap.set('angle', angleAxisModel);
  16868. if (isCategory(radiusAxisModel)) {
  16869. categoryAxisMap.set('radius', radiusAxisModel);
  16870. result.firstCategoryDimIndex = 0;
  16871. }
  16872. if (isCategory(angleAxisModel)) {
  16873. categoryAxisMap.set('angle', angleAxisModel);
  16874. result.firstCategoryDimIndex = 1;
  16875. }
  16876. },
  16877. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  16878. result.coordSysDims = ['lng', 'lat'];
  16879. },
  16880. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  16881. var ecModel = seriesModel.ecModel;
  16882. var parallelModel = ecModel.getComponent(
  16883. 'parallel', seriesModel.get('parallelIndex')
  16884. );
  16885. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  16886. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  16887. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  16888. var axisDim = coordSysDims[index];
  16889. axisMap.set(axisDim, axisModel);
  16890. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  16891. categoryAxisMap.set(axisDim, axisModel);
  16892. result.firstCategoryDimIndex = index;
  16893. }
  16894. });
  16895. }
  16896. };
  16897. function isCategory(axisModel) {
  16898. return axisModel.get('type') === 'category';
  16899. }
  16900. /*
  16901. * Licensed to the Apache Software Foundation (ASF) under one
  16902. * or more contributor license agreements. See the NOTICE file
  16903. * distributed with this work for additional information
  16904. * regarding copyright ownership. The ASF licenses this file
  16905. * to you under the Apache License, Version 2.0 (the
  16906. * "License"); you may not use this file except in compliance
  16907. * with the License. You may obtain a copy of the License at
  16908. *
  16909. * http://www.apache.org/licenses/LICENSE-2.0
  16910. *
  16911. * Unless required by applicable law or agreed to in writing,
  16912. * software distributed under the License is distributed on an
  16913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16914. * KIND, either express or implied. See the License for the
  16915. * specific language governing permissions and limitations
  16916. * under the License.
  16917. */
  16918. // Avoid typo.
  16919. var SOURCE_FORMAT_ORIGINAL = 'original';
  16920. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16921. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16922. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16923. var SOURCE_FORMAT_UNKNOWN = 'unknown';
  16924. // ??? CHANGE A NAME
  16925. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16926. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16927. var SERIES_LAYOUT_BY_ROW = 'row';
  16928. /*
  16929. * Licensed to the Apache Software Foundation (ASF) under one
  16930. * or more contributor license agreements. See the NOTICE file
  16931. * distributed with this work for additional information
  16932. * regarding copyright ownership. The ASF licenses this file
  16933. * to you under the Apache License, Version 2.0 (the
  16934. * "License"); you may not use this file except in compliance
  16935. * with the License. You may obtain a copy of the License at
  16936. *
  16937. * http://www.apache.org/licenses/LICENSE-2.0
  16938. *
  16939. * Unless required by applicable law or agreed to in writing,
  16940. * software distributed under the License is distributed on an
  16941. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16942. * KIND, either express or implied. See the License for the
  16943. * specific language governing permissions and limitations
  16944. * under the License.
  16945. */
  16946. /**
  16947. * [sourceFormat]
  16948. *
  16949. * + "original":
  16950. * This format is only used in series.data, where
  16951. * itemStyle can be specified in data item.
  16952. *
  16953. * + "arrayRows":
  16954. * [
  16955. * ['product', 'score', 'amount'],
  16956. * ['Matcha Latte', 89.3, 95.8],
  16957. * ['Milk Tea', 92.1, 89.4],
  16958. * ['Cheese Cocoa', 94.4, 91.2],
  16959. * ['Walnut Brownie', 85.4, 76.9]
  16960. * ]
  16961. *
  16962. * + "objectRows":
  16963. * [
  16964. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  16965. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  16966. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  16967. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  16968. * ]
  16969. *
  16970. * + "keyedColumns":
  16971. * {
  16972. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  16973. * 'count': [823, 235, 1042, 988],
  16974. * 'score': [95.8, 81.4, 91.2, 76.9]
  16975. * }
  16976. *
  16977. * + "typedArray"
  16978. *
  16979. * + "unknown"
  16980. */
  16981. /**
  16982. * @constructor
  16983. * @param {Object} fields
  16984. * @param {string} fields.sourceFormat
  16985. * @param {Array|Object} fields.fromDataset
  16986. * @param {Array|Object} [fields.data]
  16987. * @param {string} [seriesLayoutBy='column']
  16988. * @param {Array.<Object|string>} [dimensionsDefine]
  16989. * @param {Objet|HashMap} [encodeDefine]
  16990. * @param {number} [startIndex=0]
  16991. * @param {number} [dimensionsDetectCount]
  16992. */
  16993. function Source(fields) {
  16994. /**
  16995. * @type {boolean}
  16996. */
  16997. this.fromDataset = fields.fromDataset;
  16998. /**
  16999. * Not null/undefined.
  17000. * @type {Array|Object}
  17001. */
  17002. this.data = fields.data || (
  17003. fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []
  17004. );
  17005. /**
  17006. * See also "detectSourceFormat".
  17007. * Not null/undefined.
  17008. * @type {string}
  17009. */
  17010. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17011. /**
  17012. * 'row' or 'column'
  17013. * Not null/undefined.
  17014. * @type {string} seriesLayoutBy
  17015. */
  17016. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17017. /**
  17018. * dimensions definition in option.
  17019. * can be null/undefined.
  17020. * @type {Array.<Object|string>}
  17021. */
  17022. this.dimensionsDefine = fields.dimensionsDefine;
  17023. /**
  17024. * encode definition in option.
  17025. * can be null/undefined.
  17026. * @type {Objet|HashMap}
  17027. */
  17028. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17029. /**
  17030. * Not null/undefined, uint.
  17031. * @type {number}
  17032. */
  17033. this.startIndex = fields.startIndex || 0;
  17034. /**
  17035. * Can be null/undefined (when unknown), uint.
  17036. * @type {number}
  17037. */
  17038. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17039. }
  17040. /**
  17041. * Wrap original series data for some compatibility cases.
  17042. */
  17043. Source.seriesDataToSource = function (data) {
  17044. return new Source({
  17045. data: data,
  17046. sourceFormat: isTypedArray(data)
  17047. ? SOURCE_FORMAT_TYPED_ARRAY
  17048. : SOURCE_FORMAT_ORIGINAL,
  17049. fromDataset: false
  17050. });
  17051. };
  17052. enableClassCheck(Source);
  17053. /*
  17054. * Licensed to the Apache Software Foundation (ASF) under one
  17055. * or more contributor license agreements. See the NOTICE file
  17056. * distributed with this work for additional information
  17057. * regarding copyright ownership. The ASF licenses this file
  17058. * to you under the Apache License, Version 2.0 (the
  17059. * "License"); you may not use this file except in compliance
  17060. * with the License. You may obtain a copy of the License at
  17061. *
  17062. * http://www.apache.org/licenses/LICENSE-2.0
  17063. *
  17064. * Unless required by applicable law or agreed to in writing,
  17065. * software distributed under the License is distributed on an
  17066. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17067. * KIND, either express or implied. See the License for the
  17068. * specific language governing permissions and limitations
  17069. * under the License.
  17070. */
  17071. var inner$3 = makeInner();
  17072. /**
  17073. * @see {module:echarts/data/Source}
  17074. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17075. * @return {string} sourceFormat
  17076. */
  17077. function detectSourceFormat(datasetModel) {
  17078. var data = datasetModel.option.source;
  17079. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17080. if (isTypedArray(data)) {
  17081. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17082. }
  17083. else if (isArray(data)) {
  17084. // FIXME Whether tolerate null in top level array?
  17085. for (var i = 0, len = data.length; i < len; i++) {
  17086. var item = data[i];
  17087. if (item == null) {
  17088. continue;
  17089. }
  17090. else if (isArray(item)) {
  17091. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17092. break;
  17093. }
  17094. else if (isObject$1(item)) {
  17095. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17096. break;
  17097. }
  17098. }
  17099. }
  17100. else if (isObject$1(data)) {
  17101. for (var key in data) {
  17102. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17103. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17104. break;
  17105. }
  17106. }
  17107. }
  17108. else if (data != null) {
  17109. throw new Error('Invalid data');
  17110. }
  17111. inner$3(datasetModel).sourceFormat = sourceFormat;
  17112. }
  17113. /**
  17114. * [Scenarios]:
  17115. * (1) Provide source data directly:
  17116. * series: {
  17117. * encode: {...},
  17118. * dimensions: [...]
  17119. * seriesLayoutBy: 'row',
  17120. * data: [[...]]
  17121. * }
  17122. * (2) Refer to datasetModel.
  17123. * series: [{
  17124. * encode: {...}
  17125. * // Ignore datasetIndex means `datasetIndex: 0`
  17126. * // and the dimensions defination in dataset is used
  17127. * }, {
  17128. * encode: {...},
  17129. * seriesLayoutBy: 'column',
  17130. * datasetIndex: 1
  17131. * }]
  17132. *
  17133. * Get data from series itself or datset.
  17134. * @return {module:echarts/data/Source} source
  17135. */
  17136. function getSource(seriesModel) {
  17137. return inner$3(seriesModel).source;
  17138. }
  17139. /**
  17140. * MUST be called before mergeOption of all series.
  17141. * @param {module:echarts/model/Global} ecModel
  17142. */
  17143. function resetSourceDefaulter(ecModel) {
  17144. // `datasetMap` is used to make default encode.
  17145. inner$3(ecModel).datasetMap = createHashMap();
  17146. }
  17147. /**
  17148. * [Caution]:
  17149. * MUST be called after series option merged and
  17150. * before "series.getInitailData()" called.
  17151. *
  17152. * [The rule of making default encode]:
  17153. * Category axis (if exists) alway map to the first dimension.
  17154. * Each other axis occupies a subsequent dimension.
  17155. *
  17156. * [Why make default encode]:
  17157. * Simplify the typing of encode in option, avoiding the case like that:
  17158. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17159. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17160. *
  17161. * @param {module:echarts/model/Series} seriesModel
  17162. */
  17163. function prepareSource(seriesModel) {
  17164. var seriesOption = seriesModel.option;
  17165. var data = seriesOption.data;
  17166. var sourceFormat = isTypedArray(data)
  17167. ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17168. var fromDataset = false;
  17169. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17170. var sourceHeader = seriesOption.sourceHeader;
  17171. var dimensionsDefine = seriesOption.dimensions;
  17172. var datasetModel = getDatasetModel(seriesModel);
  17173. if (datasetModel) {
  17174. var datasetOption = datasetModel.option;
  17175. data = datasetOption.source;
  17176. sourceFormat = inner$3(datasetModel).sourceFormat;
  17177. fromDataset = true;
  17178. // These settings from series has higher priority.
  17179. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17180. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17181. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17182. }
  17183. var completeResult = completeBySourceData(
  17184. data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine
  17185. );
  17186. // Note: dataset option does not have `encode`.
  17187. var encodeDefine = seriesOption.encode;
  17188. if (!encodeDefine && datasetModel) {
  17189. encodeDefine = makeDefaultEncode(
  17190. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17191. );
  17192. }
  17193. inner$3(seriesModel).source = new Source({
  17194. data: data,
  17195. fromDataset: fromDataset,
  17196. seriesLayoutBy: seriesLayoutBy,
  17197. sourceFormat: sourceFormat,
  17198. dimensionsDefine: completeResult.dimensionsDefine,
  17199. startIndex: completeResult.startIndex,
  17200. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17201. encodeDefine: encodeDefine
  17202. });
  17203. }
  17204. // return {startIndex, dimensionsDefine, dimensionsCount}
  17205. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17206. if (!data) {
  17207. return {dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)};
  17208. }
  17209. var dimensionsDetectCount;
  17210. var startIndex;
  17211. var findPotentialName;
  17212. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17213. // Rule: Most of the first line are string: it is header.
  17214. // Caution: consider a line with 5 string and 1 number,
  17215. // it still can not be sure it is a head, because the
  17216. // 5 string may be 5 values of category columns.
  17217. if (sourceHeader === 'auto' || sourceHeader == null) {
  17218. arrayRowsTravelFirst(function (val) {
  17219. // '-' is regarded as null/undefined.
  17220. if (val != null && val !== '-') {
  17221. if (isString(val)) {
  17222. startIndex == null && (startIndex = 1);
  17223. }
  17224. else {
  17225. startIndex = 0;
  17226. }
  17227. }
  17228. // 10 is an experience number, avoid long loop.
  17229. }, seriesLayoutBy, data, 10);
  17230. }
  17231. else {
  17232. startIndex = sourceHeader ? 1 : 0;
  17233. }
  17234. if (!dimensionsDefine && startIndex === 1) {
  17235. dimensionsDefine = [];
  17236. arrayRowsTravelFirst(function (val, index) {
  17237. dimensionsDefine[index] = val != null ? val : '';
  17238. }, seriesLayoutBy, data);
  17239. }
  17240. dimensionsDetectCount = dimensionsDefine
  17241. ? dimensionsDefine.length
  17242. : seriesLayoutBy === SERIES_LAYOUT_BY_ROW
  17243. ? data.length
  17244. : data[0]
  17245. ? data[0].length
  17246. : null;
  17247. }
  17248. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17249. if (!dimensionsDefine) {
  17250. dimensionsDefine = objectRowsCollectDimensions(data);
  17251. findPotentialName = true;
  17252. }
  17253. }
  17254. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17255. if (!dimensionsDefine) {
  17256. dimensionsDefine = [];
  17257. findPotentialName = true;
  17258. each$1(data, function (colArr, key) {
  17259. dimensionsDefine.push(key);
  17260. });
  17261. }
  17262. }
  17263. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17264. var value0 = getDataItemValue(data[0]);
  17265. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17266. }
  17267. else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  17268. if (__DEV__) {
  17269. assert$1(!!dimensionsDefine, 'dimensions must be given if data is TypedArray.');
  17270. }
  17271. }
  17272. var potentialNameDimIndex;
  17273. if (findPotentialName) {
  17274. each$1(dimensionsDefine, function (dim, idx) {
  17275. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17276. potentialNameDimIndex = idx;
  17277. }
  17278. });
  17279. }
  17280. return {
  17281. startIndex: startIndex,
  17282. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17283. dimensionsDetectCount: dimensionsDetectCount,
  17284. potentialNameDimIndex: potentialNameDimIndex
  17285. // TODO: potentialIdDimIdx
  17286. };
  17287. }
  17288. // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17289. // which is reasonable. But dimension name is duplicated.
  17290. // Returns undefined or an array contains only object without null/undefiend or string.
  17291. function normalizeDimensionsDefine(dimensionsDefine) {
  17292. if (!dimensionsDefine) {
  17293. // The meaning of null/undefined is different from empty array.
  17294. return;
  17295. }
  17296. var nameMap = createHashMap();
  17297. return map(dimensionsDefine, function (item, index) {
  17298. item = extend({}, isObject$1(item) ? item : {name: item});
  17299. // User can set null in dimensions.
  17300. // We dont auto specify name, othewise a given name may
  17301. // cause it be refered unexpectedly.
  17302. if (item.name == null) {
  17303. return item;
  17304. }
  17305. // Also consider number form like 2012.
  17306. item.name += '';
  17307. // User may also specify displayName.
  17308. // displayName will always exists except user not
  17309. // specified or dim name is not specified or detected.
  17310. // (A auto generated dim name will not be used as
  17311. // displayName).
  17312. if (item.displayName == null) {
  17313. item.displayName = item.name;
  17314. }
  17315. var exist = nameMap.get(item.name);
  17316. if (!exist) {
  17317. nameMap.set(item.name, {count: 1});
  17318. }
  17319. else {
  17320. item.name += '-' + exist.count++;
  17321. }
  17322. return item;
  17323. });
  17324. }
  17325. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17326. maxLoop == null && (maxLoop = Infinity);
  17327. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17328. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17329. cb(data[i] ? data[i][0] : null, i);
  17330. }
  17331. }
  17332. else {
  17333. var value0 = data[0] || [];
  17334. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17335. cb(value0[i], i);
  17336. }
  17337. }
  17338. }
  17339. function objectRowsCollectDimensions(data) {
  17340. var firstIndex = 0;
  17341. var obj;
  17342. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17343. if (obj) {
  17344. var dimensions = [];
  17345. each$1(obj, function (value, key) {
  17346. dimensions.push(key);
  17347. });
  17348. return dimensions;
  17349. }
  17350. }
  17351. // ??? TODO merge to completedimensions, where also has
  17352. // default encode making logic. And the default rule
  17353. // should depends on series? consider 'map'.
  17354. function makeDefaultEncode(
  17355. seriesModel, datasetModel, data, sourceFormat, seriesLayoutBy, completeResult
  17356. ) {
  17357. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  17358. var encode = {};
  17359. // var encodeTooltip = [];
  17360. // var encodeLabel = [];
  17361. var encodeItemName = [];
  17362. var encodeSeriesName = [];
  17363. var seriesType = seriesModel.subType;
  17364. // ??? TODO refactor: provide by series itself.
  17365. // Consider the case: 'map' series is based on geo coordSys,
  17366. // 'graph', 'heatmap' can be based on cartesian. But can not
  17367. // give default rule simply here.
  17368. var nSeriesMap = createHashMap(['pie', 'map', 'funnel']);
  17369. var cSeriesMap = createHashMap([
  17370. 'line', 'bar', 'pictorialBar', 'scatter', 'effectScatter', 'candlestick', 'boxplot'
  17371. ]);
  17372. // Usually in this case series will use the first data
  17373. // dimension as the "value" dimension, or other default
  17374. // processes respectively.
  17375. if (coordSysDefine && cSeriesMap.get(seriesType) != null) {
  17376. var ecModel = seriesModel.ecModel;
  17377. var datasetMap = inner$3(ecModel).datasetMap;
  17378. var key = datasetModel.uid + '_' + seriesLayoutBy;
  17379. var datasetRecord = datasetMap.get(key)
  17380. || datasetMap.set(key, {categoryWayDim: 1, valueWayDim: 0});
  17381. // TODO
  17382. // Auto detect first time axis and do arrangement.
  17383. each$1(coordSysDefine.coordSysDims, function (coordDim) {
  17384. // In value way.
  17385. if (coordSysDefine.firstCategoryDimIndex == null) {
  17386. var dataDim = datasetRecord.valueWayDim++;
  17387. encode[coordDim] = dataDim;
  17388. // ??? TODO give a better default series name rule?
  17389. // especially when encode x y specified.
  17390. // consider: when mutiple series share one dimension
  17391. // category axis, series name should better use
  17392. // the other dimsion name. On the other hand, use
  17393. // both dimensions name.
  17394. encodeSeriesName.push(dataDim);
  17395. // encodeTooltip.push(dataDim);
  17396. // encodeLabel.push(dataDim);
  17397. }
  17398. // In category way, category axis.
  17399. else if (coordSysDefine.categoryAxisMap.get(coordDim)) {
  17400. encode[coordDim] = 0;
  17401. encodeItemName.push(0);
  17402. }
  17403. // In category way, non-category axis.
  17404. else {
  17405. var dataDim = datasetRecord.categoryWayDim++;
  17406. encode[coordDim] = dataDim;
  17407. // encodeTooltip.push(dataDim);
  17408. // encodeLabel.push(dataDim);
  17409. encodeSeriesName.push(dataDim);
  17410. }
  17411. });
  17412. }
  17413. // Do not make a complex rule! Hard to code maintain and not necessary.
  17414. // ??? TODO refactor: provide by series itself.
  17415. // [{name: ..., value: ...}, ...] like:
  17416. else if (nSeriesMap.get(seriesType) != null) {
  17417. // Find the first not ordinal. (5 is an experience value)
  17418. var firstNotOrdinal;
  17419. for (var i = 0; i < 5 && firstNotOrdinal == null; i++) {
  17420. if (!doGuessOrdinal(
  17421. data, sourceFormat, seriesLayoutBy,
  17422. completeResult.dimensionsDefine, completeResult.startIndex, i
  17423. )) {
  17424. firstNotOrdinal = i;
  17425. }
  17426. }
  17427. if (firstNotOrdinal != null) {
  17428. encode.value = firstNotOrdinal;
  17429. var nameDimIndex = completeResult.potentialNameDimIndex
  17430. || Math.max(firstNotOrdinal - 1, 0);
  17431. // By default, label use itemName in charts.
  17432. // So we dont set encodeLabel here.
  17433. encodeSeriesName.push(nameDimIndex);
  17434. encodeItemName.push(nameDimIndex);
  17435. // encodeTooltip.push(firstNotOrdinal);
  17436. }
  17437. }
  17438. // encodeTooltip.length && (encode.tooltip = encodeTooltip);
  17439. // encodeLabel.length && (encode.label = encodeLabel);
  17440. encodeItemName.length && (encode.itemName = encodeItemName);
  17441. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17442. return encode;
  17443. }
  17444. /**
  17445. * If return null/undefined, indicate that should not use datasetModel.
  17446. */
  17447. function getDatasetModel(seriesModel) {
  17448. var option = seriesModel.option;
  17449. // Caution: consider the scenario:
  17450. // A dataset is declared and a series is not expected to use the dataset,
  17451. // and at the beginning `setOption({series: { noData })` (just prepare other
  17452. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17453. // the user should set an empty array to avoid that dataset is used by default.
  17454. var thisData = option.data;
  17455. if (!thisData) {
  17456. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17457. }
  17458. }
  17459. /**
  17460. * The rule should not be complex, otherwise user might not
  17461. * be able to known where the data is wrong.
  17462. * The code is ugly, but how to make it neat?
  17463. *
  17464. * @param {module:echars/data/Source} source
  17465. * @param {number} dimIndex
  17466. * @return {boolean} Whether ordinal.
  17467. */
  17468. function guessOrdinal(source, dimIndex) {
  17469. return doGuessOrdinal(
  17470. source.data,
  17471. source.sourceFormat,
  17472. source.seriesLayoutBy,
  17473. source.dimensionsDefine,
  17474. source.startIndex,
  17475. dimIndex
  17476. );
  17477. }
  17478. // dimIndex may be overflow source data.
  17479. function doGuessOrdinal(
  17480. data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex
  17481. ) {
  17482. var result;
  17483. // Experience value.
  17484. var maxLoop = 5;
  17485. if (isTypedArray(data)) {
  17486. return false;
  17487. }
  17488. // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17489. // always exists in source.
  17490. var dimName;
  17491. if (dimensionsDefine) {
  17492. dimName = dimensionsDefine[dimIndex];
  17493. dimName = isObject$1(dimName) ? dimName.name : dimName;
  17494. }
  17495. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17496. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17497. var sample = data[dimIndex];
  17498. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17499. if ((result = detectValue(sample[startIndex + i])) != null) {
  17500. return result;
  17501. }
  17502. }
  17503. }
  17504. else {
  17505. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17506. var row = data[startIndex + i];
  17507. if (row && (result = detectValue(row[dimIndex])) != null) {
  17508. return result;
  17509. }
  17510. }
  17511. }
  17512. }
  17513. else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17514. if (!dimName) {
  17515. return;
  17516. }
  17517. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17518. var item = data[i];
  17519. if (item && (result = detectValue(item[dimName])) != null) {
  17520. return result;
  17521. }
  17522. }
  17523. }
  17524. else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17525. if (!dimName) {
  17526. return;
  17527. }
  17528. var sample = data[dimName];
  17529. if (!sample || isTypedArray(sample)) {
  17530. return false;
  17531. }
  17532. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17533. if ((result = detectValue(sample[i])) != null) {
  17534. return result;
  17535. }
  17536. }
  17537. }
  17538. else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17539. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17540. var item = data[i];
  17541. var val = getDataItemValue(item);
  17542. if (!isArray(val)) {
  17543. return false;
  17544. }
  17545. if ((result = detectValue(val[dimIndex])) != null) {
  17546. return result;
  17547. }
  17548. }
  17549. }
  17550. function detectValue(val) {
  17551. // Consider usage convenience, '1', '2' will be treated as "number".
  17552. // `isFinit('')` get `true`.
  17553. if (val != null && isFinite(val) && val !== '') {
  17554. return false;
  17555. }
  17556. else if (isString(val) && val !== '-') {
  17557. return true;
  17558. }
  17559. }
  17560. return false;
  17561. }
  17562. /*
  17563. * Licensed to the Apache Software Foundation (ASF) under one
  17564. * or more contributor license agreements. See the NOTICE file
  17565. * distributed with this work for additional information
  17566. * regarding copyright ownership. The ASF licenses this file
  17567. * to you under the Apache License, Version 2.0 (the
  17568. * "License"); you may not use this file except in compliance
  17569. * with the License. You may obtain a copy of the License at
  17570. *
  17571. * http://www.apache.org/licenses/LICENSE-2.0
  17572. *
  17573. * Unless required by applicable law or agreed to in writing,
  17574. * software distributed under the License is distributed on an
  17575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17576. * KIND, either express or implied. See the License for the
  17577. * specific language governing permissions and limitations
  17578. * under the License.
  17579. */
  17580. /**
  17581. * ECharts global model
  17582. *
  17583. * @module {echarts/model/Global}
  17584. */
  17585. /**
  17586. * Caution: If the mechanism should be changed some day, these cases
  17587. * should be considered:
  17588. *
  17589. * (1) In `merge option` mode, if using the same option to call `setOption`
  17590. * many times, the result should be the same (try our best to ensure that).
  17591. * (2) In `merge option` mode, if a component has no id/name specified, it
  17592. * will be merged by index, and the result sequence of the components is
  17593. * consistent to the original sequence.
  17594. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17595. * `mergeOption` in module:echarts/model/OptionManager.
  17596. */
  17597. var OPTION_INNER_KEY = '\0_ec_inner';
  17598. /**
  17599. * @alias module:echarts/model/Global
  17600. *
  17601. * @param {Object} option
  17602. * @param {module:echarts/model/Model} parentModel
  17603. * @param {Object} theme
  17604. */
  17605. var GlobalModel = Model.extend({
  17606. init: function (option, parentModel, theme, optionManager) {
  17607. theme = theme || {};
  17608. this.option = null; // Mark as not initialized.
  17609. /**
  17610. * @type {module:echarts/model/Model}
  17611. * @private
  17612. */
  17613. this._theme = new Model(theme);
  17614. /**
  17615. * @type {module:echarts/model/OptionManager}
  17616. */
  17617. this._optionManager = optionManager;
  17618. },
  17619. setOption: function (option, optionPreprocessorFuncs) {
  17620. assert$1(
  17621. !(OPTION_INNER_KEY in option),
  17622. 'please use chart.getOption()'
  17623. );
  17624. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17625. this.resetOption(null);
  17626. },
  17627. /**
  17628. * @param {string} type null/undefined: reset all.
  17629. * 'recreate': force recreate all.
  17630. * 'timeline': only reset timeline option
  17631. * 'media': only reset media query option
  17632. * @return {boolean} Whether option changed.
  17633. */
  17634. resetOption: function (type) {
  17635. var optionChanged = false;
  17636. var optionManager = this._optionManager;
  17637. if (!type || type === 'recreate') {
  17638. var baseOption = optionManager.mountOption(type === 'recreate');
  17639. if (!this.option || type === 'recreate') {
  17640. initBase.call(this, baseOption);
  17641. }
  17642. else {
  17643. this.restoreData();
  17644. this.mergeOption(baseOption);
  17645. }
  17646. optionChanged = true;
  17647. }
  17648. if (type === 'timeline' || type === 'media') {
  17649. this.restoreData();
  17650. }
  17651. if (!type || type === 'recreate' || type === 'timeline') {
  17652. var timelineOption = optionManager.getTimelineOption(this);
  17653. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17654. }
  17655. if (!type || type === 'recreate' || type === 'media') {
  17656. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17657. if (mediaOptions.length) {
  17658. each$1(mediaOptions, function (mediaOption) {
  17659. this.mergeOption(mediaOption, optionChanged = true);
  17660. }, this);
  17661. }
  17662. }
  17663. return optionChanged;
  17664. },
  17665. /**
  17666. * @protected
  17667. */
  17668. mergeOption: function (newOption) {
  17669. var option = this.option;
  17670. var componentsMap = this._componentsMap;
  17671. var newCptTypes = [];
  17672. resetSourceDefaulter(this);
  17673. // If no component class, merge directly.
  17674. // For example: color, animaiton options, etc.
  17675. each$1(newOption, function (componentOption, mainType) {
  17676. if (componentOption == null) {
  17677. return;
  17678. }
  17679. if (!ComponentModel.hasClass(mainType)) {
  17680. // globalSettingTask.dirty();
  17681. option[mainType] = option[mainType] == null
  17682. ? clone(componentOption)
  17683. : merge(option[mainType], componentOption, true);
  17684. }
  17685. else if (mainType) {
  17686. newCptTypes.push(mainType);
  17687. }
  17688. });
  17689. ComponentModel.topologicalTravel(
  17690. newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this
  17691. );
  17692. function visitComponent(mainType, dependencies) {
  17693. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17694. var mapResult = mappingToExists(
  17695. componentsMap.get(mainType), newCptOptionList
  17696. );
  17697. makeIdAndName(mapResult);
  17698. // Set mainType and complete subType.
  17699. each$1(mapResult, function (item, index) {
  17700. var opt = item.option;
  17701. if (isObject$1(opt)) {
  17702. item.keyInfo.mainType = mainType;
  17703. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17704. }
  17705. });
  17706. var dependentModels = getComponentsByTypes(
  17707. componentsMap, dependencies
  17708. );
  17709. option[mainType] = [];
  17710. componentsMap.set(mainType, []);
  17711. each$1(mapResult, function (resultItem, index) {
  17712. var componentModel = resultItem.exist;
  17713. var newCptOption = resultItem.option;
  17714. assert$1(
  17715. isObject$1(newCptOption) || componentModel,
  17716. 'Empty component definition'
  17717. );
  17718. // Consider where is no new option and should be merged using {},
  17719. // see removeEdgeAndAdd in topologicalTravel and
  17720. // ComponentModel.getAllClassMainTypes.
  17721. if (!newCptOption) {
  17722. componentModel.mergeOption({}, this);
  17723. componentModel.optionUpdated({}, false);
  17724. }
  17725. else {
  17726. var ComponentModelClass = ComponentModel.getClass(
  17727. mainType, resultItem.keyInfo.subType, true
  17728. );
  17729. if (componentModel && componentModel instanceof ComponentModelClass) {
  17730. componentModel.name = resultItem.keyInfo.name;
  17731. // componentModel.settingTask && componentModel.settingTask.dirty();
  17732. componentModel.mergeOption(newCptOption, this);
  17733. componentModel.optionUpdated(newCptOption, false);
  17734. }
  17735. else {
  17736. // PENDING Global as parent ?
  17737. var extraOpt = extend(
  17738. {
  17739. dependentModels: dependentModels,
  17740. componentIndex: index
  17741. },
  17742. resultItem.keyInfo
  17743. );
  17744. componentModel = new ComponentModelClass(
  17745. newCptOption, this, this, extraOpt
  17746. );
  17747. extend(componentModel, extraOpt);
  17748. componentModel.init(newCptOption, this, this, extraOpt);
  17749. // Call optionUpdated after init.
  17750. // newCptOption has been used as componentModel.option
  17751. // and may be merged with theme and default, so pass null
  17752. // to avoid confusion.
  17753. componentModel.optionUpdated(null, true);
  17754. }
  17755. }
  17756. componentsMap.get(mainType)[index] = componentModel;
  17757. option[mainType][index] = componentModel.option;
  17758. }, this);
  17759. // Backup series for filtering.
  17760. if (mainType === 'series') {
  17761. createSeriesIndices(this, componentsMap.get('series'));
  17762. }
  17763. }
  17764. this._seriesIndicesMap = createHashMap(
  17765. this._seriesIndices = this._seriesIndices || []
  17766. );
  17767. },
  17768. /**
  17769. * Get option for output (cloned option and inner info removed)
  17770. * @public
  17771. * @return {Object}
  17772. */
  17773. getOption: function () {
  17774. var option = clone(this.option);
  17775. each$1(option, function (opts, mainType) {
  17776. if (ComponentModel.hasClass(mainType)) {
  17777. var opts = normalizeToArray(opts);
  17778. for (var i = opts.length - 1; i >= 0; i--) {
  17779. // Remove options with inner id.
  17780. if (isIdInner(opts[i])) {
  17781. opts.splice(i, 1);
  17782. }
  17783. }
  17784. option[mainType] = opts;
  17785. }
  17786. });
  17787. delete option[OPTION_INNER_KEY];
  17788. return option;
  17789. },
  17790. /**
  17791. * @return {module:echarts/model/Model}
  17792. */
  17793. getTheme: function () {
  17794. return this._theme;
  17795. },
  17796. /**
  17797. * @param {string} mainType
  17798. * @param {number} [idx=0]
  17799. * @return {module:echarts/model/Component}
  17800. */
  17801. getComponent: function (mainType, idx) {
  17802. var list = this._componentsMap.get(mainType);
  17803. if (list) {
  17804. return list[idx || 0];
  17805. }
  17806. },
  17807. /**
  17808. * If none of index and id and name used, return all components with mainType.
  17809. * @param {Object} condition
  17810. * @param {string} condition.mainType
  17811. * @param {string} [condition.subType] If ignore, only query by mainType
  17812. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17813. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17814. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17815. * @return {Array.<module:echarts/model/Component>}
  17816. */
  17817. queryComponents: function (condition) {
  17818. var mainType = condition.mainType;
  17819. if (!mainType) {
  17820. return [];
  17821. }
  17822. var index = condition.index;
  17823. var id = condition.id;
  17824. var name = condition.name;
  17825. var cpts = this._componentsMap.get(mainType);
  17826. if (!cpts || !cpts.length) {
  17827. return [];
  17828. }
  17829. var result;
  17830. if (index != null) {
  17831. if (!isArray(index)) {
  17832. index = [index];
  17833. }
  17834. result = filter(map(index, function (idx) {
  17835. return cpts[idx];
  17836. }), function (val) {
  17837. return !!val;
  17838. });
  17839. }
  17840. else if (id != null) {
  17841. var isIdArray = isArray(id);
  17842. result = filter(cpts, function (cpt) {
  17843. return (isIdArray && indexOf(id, cpt.id) >= 0)
  17844. || (!isIdArray && cpt.id === id);
  17845. });
  17846. }
  17847. else if (name != null) {
  17848. var isNameArray = isArray(name);
  17849. result = filter(cpts, function (cpt) {
  17850. return (isNameArray && indexOf(name, cpt.name) >= 0)
  17851. || (!isNameArray && cpt.name === name);
  17852. });
  17853. }
  17854. else {
  17855. // Return all components with mainType
  17856. result = cpts.slice();
  17857. }
  17858. return filterBySubType(result, condition);
  17859. },
  17860. /**
  17861. * The interface is different from queryComponents,
  17862. * which is convenient for inner usage.
  17863. *
  17864. * @usage
  17865. * var result = findComponents(
  17866. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17867. * );
  17868. * var result = findComponents(
  17869. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17870. * );
  17871. * var result = findComponents(
  17872. * {mainType: 'series'},
  17873. * function (model, index) {...}
  17874. * );
  17875. * // result like [component0, componnet1, ...]
  17876. *
  17877. * @param {Object} condition
  17878. * @param {string} condition.mainType Mandatory.
  17879. * @param {string} [condition.subType] Optional.
  17880. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17881. * where xxx is mainType.
  17882. * If query attribute is null/undefined or has no index/id/name,
  17883. * do not filtering by query conditions, which is convenient for
  17884. * no-payload situations or when target of action is global.
  17885. * @param {Function} [condition.filter] parameter: component, return boolean.
  17886. * @return {Array.<module:echarts/model/Component>}
  17887. */
  17888. findComponents: function (condition) {
  17889. var query = condition.query;
  17890. var mainType = condition.mainType;
  17891. var queryCond = getQueryCond(query);
  17892. var result = queryCond
  17893. ? this.queryComponents(queryCond)
  17894. : this._componentsMap.get(mainType);
  17895. return doFilter(filterBySubType(result, condition));
  17896. function getQueryCond(q) {
  17897. var indexAttr = mainType + 'Index';
  17898. var idAttr = mainType + 'Id';
  17899. var nameAttr = mainType + 'Name';
  17900. return q && (
  17901. q[indexAttr] != null
  17902. || q[idAttr] != null
  17903. || q[nameAttr] != null
  17904. )
  17905. ? {
  17906. mainType: mainType,
  17907. // subType will be filtered finally.
  17908. index: q[indexAttr],
  17909. id: q[idAttr],
  17910. name: q[nameAttr]
  17911. }
  17912. : null;
  17913. }
  17914. function doFilter(res) {
  17915. return condition.filter
  17916. ? filter(res, condition.filter)
  17917. : res;
  17918. }
  17919. },
  17920. /**
  17921. * @usage
  17922. * eachComponent('legend', function (legendModel, index) {
  17923. * ...
  17924. * });
  17925. * eachComponent(function (componentType, model, index) {
  17926. * // componentType does not include subType
  17927. * // (componentType is 'xxx' but not 'xxx.aa')
  17928. * });
  17929. * eachComponent(
  17930. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17931. * function (model, index) {...}
  17932. * );
  17933. * eachComponent(
  17934. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17935. * function (model, index) {...}
  17936. * );
  17937. *
  17938. * @param {string|Object=} mainType When mainType is object, the definition
  17939. * is the same as the method 'findComponents'.
  17940. * @param {Function} cb
  17941. * @param {*} context
  17942. */
  17943. eachComponent: function (mainType, cb, context) {
  17944. var componentsMap = this._componentsMap;
  17945. if (typeof mainType === 'function') {
  17946. context = cb;
  17947. cb = mainType;
  17948. componentsMap.each(function (components, componentType) {
  17949. each$1(components, function (component, index) {
  17950. cb.call(context, componentType, component, index);
  17951. });
  17952. });
  17953. }
  17954. else if (isString(mainType)) {
  17955. each$1(componentsMap.get(mainType), cb, context);
  17956. }
  17957. else if (isObject$1(mainType)) {
  17958. var queryResult = this.findComponents(mainType);
  17959. each$1(queryResult, cb, context);
  17960. }
  17961. },
  17962. /**
  17963. * @param {string} name
  17964. * @return {Array.<module:echarts/model/Series>}
  17965. */
  17966. getSeriesByName: function (name) {
  17967. var series = this._componentsMap.get('series');
  17968. return filter(series, function (oneSeries) {
  17969. return oneSeries.name === name;
  17970. });
  17971. },
  17972. /**
  17973. * @param {number} seriesIndex
  17974. * @return {module:echarts/model/Series}
  17975. */
  17976. getSeriesByIndex: function (seriesIndex) {
  17977. return this._componentsMap.get('series')[seriesIndex];
  17978. },
  17979. /**
  17980. * Get series list before filtered by type.
  17981. * FIXME: rename to getRawSeriesByType?
  17982. *
  17983. * @param {string} subType
  17984. * @return {Array.<module:echarts/model/Series>}
  17985. */
  17986. getSeriesByType: function (subType) {
  17987. var series = this._componentsMap.get('series');
  17988. return filter(series, function (oneSeries) {
  17989. return oneSeries.subType === subType;
  17990. });
  17991. },
  17992. /**
  17993. * @return {Array.<module:echarts/model/Series>}
  17994. */
  17995. getSeries: function () {
  17996. return this._componentsMap.get('series').slice();
  17997. },
  17998. /**
  17999. * @return {number}
  18000. */
  18001. getSeriesCount: function () {
  18002. return this._componentsMap.get('series').length;
  18003. },
  18004. /**
  18005. * After filtering, series may be different
  18006. * frome raw series.
  18007. *
  18008. * @param {Function} cb
  18009. * @param {*} context
  18010. */
  18011. eachSeries: function (cb, context) {
  18012. assertSeriesInitialized(this);
  18013. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18014. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18015. cb.call(context, series, rawSeriesIndex);
  18016. }, this);
  18017. },
  18018. /**
  18019. * Iterate raw series before filtered.
  18020. *
  18021. * @param {Function} cb
  18022. * @param {*} context
  18023. */
  18024. eachRawSeries: function (cb, context) {
  18025. each$1(this._componentsMap.get('series'), cb, context);
  18026. },
  18027. /**
  18028. * After filtering, series may be different.
  18029. * frome raw series.
  18030. *
  18031. * @parma {string} subType
  18032. * @param {Function} cb
  18033. * @param {*} context
  18034. */
  18035. eachSeriesByType: function (subType, cb, context) {
  18036. assertSeriesInitialized(this);
  18037. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18038. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18039. if (series.subType === subType) {
  18040. cb.call(context, series, rawSeriesIndex);
  18041. }
  18042. }, this);
  18043. },
  18044. /**
  18045. * Iterate raw series before filtered of given type.
  18046. *
  18047. * @parma {string} subType
  18048. * @param {Function} cb
  18049. * @param {*} context
  18050. */
  18051. eachRawSeriesByType: function (subType, cb, context) {
  18052. return each$1(this.getSeriesByType(subType), cb, context);
  18053. },
  18054. /**
  18055. * @param {module:echarts/model/Series} seriesModel
  18056. */
  18057. isSeriesFiltered: function (seriesModel) {
  18058. assertSeriesInitialized(this);
  18059. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18060. },
  18061. /**
  18062. * @return {Array.<number>}
  18063. */
  18064. getCurrentSeriesIndices: function () {
  18065. return (this._seriesIndices || []).slice();
  18066. },
  18067. /**
  18068. * @param {Function} cb
  18069. * @param {*} context
  18070. */
  18071. filterSeries: function (cb, context) {
  18072. assertSeriesInitialized(this);
  18073. var filteredSeries = filter(
  18074. this._componentsMap.get('series'), cb, context
  18075. );
  18076. createSeriesIndices(this, filteredSeries);
  18077. },
  18078. restoreData: function (payload) {
  18079. var componentsMap = this._componentsMap;
  18080. createSeriesIndices(this, componentsMap.get('series'));
  18081. var componentTypes = [];
  18082. componentsMap.each(function (components, componentType) {
  18083. componentTypes.push(componentType);
  18084. });
  18085. ComponentModel.topologicalTravel(
  18086. componentTypes,
  18087. ComponentModel.getAllClassMainTypes(),
  18088. function (componentType, dependencies) {
  18089. each$1(componentsMap.get(componentType), function (component) {
  18090. (componentType !== 'series' || !isNotTargetSeries(component, payload))
  18091. && component.restoreData();
  18092. });
  18093. }
  18094. );
  18095. }
  18096. });
  18097. function isNotTargetSeries(seriesModel, payload) {
  18098. if (payload) {
  18099. var index = payload.seiresIndex;
  18100. var id = payload.seriesId;
  18101. var name = payload.seriesName;
  18102. return (index != null && seriesModel.componentIndex !== index)
  18103. || (id != null && seriesModel.id !== id)
  18104. || (name != null && seriesModel.name !== name);
  18105. }
  18106. }
  18107. /**
  18108. * @inner
  18109. */
  18110. function mergeTheme(option, theme) {
  18111. // PENDING
  18112. // NOT use `colorLayer` in theme if option has `color`
  18113. var notMergeColorLayer = option.color && !option.colorLayer;
  18114. each$1(theme, function (themeItem, name) {
  18115. if (name === 'colorLayer' && notMergeColorLayer) {
  18116. return;
  18117. }
  18118. // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18119. if (!ComponentModel.hasClass(name)) {
  18120. if (typeof themeItem === 'object') {
  18121. option[name] = !option[name]
  18122. ? clone(themeItem)
  18123. : merge(option[name], themeItem, false);
  18124. }
  18125. else {
  18126. if (option[name] == null) {
  18127. option[name] = themeItem;
  18128. }
  18129. }
  18130. }
  18131. });
  18132. }
  18133. function initBase(baseOption) {
  18134. baseOption = baseOption;
  18135. // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18136. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18137. this.option = {};
  18138. this.option[OPTION_INNER_KEY] = 1;
  18139. /**
  18140. * Init with series: [], in case of calling findSeries method
  18141. * before series initialized.
  18142. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18143. * @private
  18144. */
  18145. this._componentsMap = createHashMap({series: []});
  18146. /**
  18147. * Mapping between filtered series list and raw series list.
  18148. * key: filtered series indices, value: raw series indices.
  18149. * @type {Array.<nubmer>}
  18150. * @private
  18151. */
  18152. this._seriesIndices;
  18153. this._seriesIndicesMap;
  18154. mergeTheme(baseOption, this._theme.option);
  18155. // TODO Needs clone when merging to the unexisted property
  18156. merge(baseOption, globalDefault, false);
  18157. this.mergeOption(baseOption);
  18158. }
  18159. /**
  18160. * @inner
  18161. * @param {Array.<string>|string} types model types
  18162. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18163. */
  18164. function getComponentsByTypes(componentsMap, types) {
  18165. if (!isArray(types)) {
  18166. types = types ? [types] : [];
  18167. }
  18168. var ret = {};
  18169. each$1(types, function (type) {
  18170. ret[type] = (componentsMap.get(type) || []).slice();
  18171. });
  18172. return ret;
  18173. }
  18174. /**
  18175. * @inner
  18176. */
  18177. function determineSubType(mainType, newCptOption, existComponent) {
  18178. var subType = newCptOption.type
  18179. ? newCptOption.type
  18180. : existComponent
  18181. ? existComponent.subType
  18182. // Use determineSubType only when there is no existComponent.
  18183. : ComponentModel.determineSubType(mainType, newCptOption);
  18184. // tooltip, markline, markpoint may always has no subType
  18185. return subType;
  18186. }
  18187. /**
  18188. * @inner
  18189. */
  18190. function createSeriesIndices(ecModel, seriesModels) {
  18191. ecModel._seriesIndicesMap = createHashMap(
  18192. ecModel._seriesIndices = map(seriesModels, function (series) {
  18193. return series.componentIndex;
  18194. }) || []
  18195. );
  18196. }
  18197. /**
  18198. * @inner
  18199. */
  18200. function filterBySubType(components, condition) {
  18201. // Using hasOwnProperty for restrict. Consider
  18202. // subType is undefined in user payload.
  18203. return condition.hasOwnProperty('subType')
  18204. ? filter(components, function (cpt) {
  18205. return cpt.subType === condition.subType;
  18206. })
  18207. : components;
  18208. }
  18209. /**
  18210. * @inner
  18211. */
  18212. function assertSeriesInitialized(ecModel) {
  18213. // Components that use _seriesIndices should depends on series component,
  18214. // which make sure that their initialization is after series.
  18215. if (__DEV__) {
  18216. if (!ecModel._seriesIndices) {
  18217. throw new Error('Option should contains series.');
  18218. }
  18219. }
  18220. }
  18221. mixin(GlobalModel, colorPaletteMixin);
  18222. /*
  18223. * Licensed to the Apache Software Foundation (ASF) under one
  18224. * or more contributor license agreements. See the NOTICE file
  18225. * distributed with this work for additional information
  18226. * regarding copyright ownership. The ASF licenses this file
  18227. * to you under the Apache License, Version 2.0 (the
  18228. * "License"); you may not use this file except in compliance
  18229. * with the License. You may obtain a copy of the License at
  18230. *
  18231. * http://www.apache.org/licenses/LICENSE-2.0
  18232. *
  18233. * Unless required by applicable law or agreed to in writing,
  18234. * software distributed under the License is distributed on an
  18235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18236. * KIND, either express or implied. See the License for the
  18237. * specific language governing permissions and limitations
  18238. * under the License.
  18239. */
  18240. var echartsAPIList = [
  18241. 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed',
  18242. 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption',
  18243. 'getViewOfComponentModel', 'getViewOfSeriesModel'
  18244. ];
  18245. // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18246. function ExtensionAPI(chartInstance) {
  18247. each$1(echartsAPIList, function (name) {
  18248. this[name] = bind(chartInstance[name], chartInstance);
  18249. }, this);
  18250. }
  18251. /*
  18252. * Licensed to the Apache Software Foundation (ASF) under one
  18253. * or more contributor license agreements. See the NOTICE file
  18254. * distributed with this work for additional information
  18255. * regarding copyright ownership. The ASF licenses this file
  18256. * to you under the Apache License, Version 2.0 (the
  18257. * "License"); you may not use this file except in compliance
  18258. * with the License. You may obtain a copy of the License at
  18259. *
  18260. * http://www.apache.org/licenses/LICENSE-2.0
  18261. *
  18262. * Unless required by applicable law or agreed to in writing,
  18263. * software distributed under the License is distributed on an
  18264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18265. * KIND, either express or implied. See the License for the
  18266. * specific language governing permissions and limitations
  18267. * under the License.
  18268. */
  18269. var coordinateSystemCreators = {};
  18270. function CoordinateSystemManager() {
  18271. this._coordinateSystems = [];
  18272. }
  18273. CoordinateSystemManager.prototype = {
  18274. constructor: CoordinateSystemManager,
  18275. create: function (ecModel, api) {
  18276. var coordinateSystems = [];
  18277. each$1(coordinateSystemCreators, function (creater, type) {
  18278. var list = creater.create(ecModel, api);
  18279. coordinateSystems = coordinateSystems.concat(list || []);
  18280. });
  18281. this._coordinateSystems = coordinateSystems;
  18282. },
  18283. update: function (ecModel, api) {
  18284. each$1(this._coordinateSystems, function (coordSys) {
  18285. coordSys.update && coordSys.update(ecModel, api);
  18286. });
  18287. },
  18288. getCoordinateSystems: function () {
  18289. return this._coordinateSystems.slice();
  18290. }
  18291. };
  18292. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18293. coordinateSystemCreators[type] = coordinateSystemCreator;
  18294. };
  18295. CoordinateSystemManager.get = function (type) {
  18296. return coordinateSystemCreators[type];
  18297. };
  18298. /*
  18299. * Licensed to the Apache Software Foundation (ASF) under one
  18300. * or more contributor license agreements. See the NOTICE file
  18301. * distributed with this work for additional information
  18302. * regarding copyright ownership. The ASF licenses this file
  18303. * to you under the Apache License, Version 2.0 (the
  18304. * "License"); you may not use this file except in compliance
  18305. * with the License. You may obtain a copy of the License at
  18306. *
  18307. * http://www.apache.org/licenses/LICENSE-2.0
  18308. *
  18309. * Unless required by applicable law or agreed to in writing,
  18310. * software distributed under the License is distributed on an
  18311. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18312. * KIND, either express or implied. See the License for the
  18313. * specific language governing permissions and limitations
  18314. * under the License.
  18315. */
  18316. /**
  18317. * ECharts option manager
  18318. *
  18319. * @module {echarts/model/OptionManager}
  18320. */
  18321. var each$4 = each$1;
  18322. var clone$3 = clone;
  18323. var map$1 = map;
  18324. var merge$1 = merge;
  18325. var QUERY_REG = /^(min|max)?(.+)$/;
  18326. /**
  18327. * TERM EXPLANATIONS:
  18328. *
  18329. * [option]:
  18330. *
  18331. * An object that contains definitions of components. For example:
  18332. * var option = {
  18333. * title: {...},
  18334. * legend: {...},
  18335. * visualMap: {...},
  18336. * series: [
  18337. * {data: [...]},
  18338. * {data: [...]},
  18339. * ...
  18340. * ]
  18341. * };
  18342. *
  18343. * [rawOption]:
  18344. *
  18345. * An object input to echarts.setOption. 'rawOption' may be an
  18346. * 'option', or may be an object contains multi-options. For example:
  18347. * var option = {
  18348. * baseOption: {
  18349. * title: {...},
  18350. * legend: {...},
  18351. * series: [
  18352. * {data: [...]},
  18353. * {data: [...]},
  18354. * ...
  18355. * ]
  18356. * },
  18357. * timeline: {...},
  18358. * options: [
  18359. * {title: {...}, series: {data: [...]}},
  18360. * {title: {...}, series: {data: [...]}},
  18361. * ...
  18362. * ],
  18363. * media: [
  18364. * {
  18365. * query: {maxWidth: 320},
  18366. * option: {series: {x: 20}, visualMap: {show: false}}
  18367. * },
  18368. * {
  18369. * query: {minWidth: 320, maxWidth: 720},
  18370. * option: {series: {x: 500}, visualMap: {show: true}}
  18371. * },
  18372. * {
  18373. * option: {series: {x: 1200}, visualMap: {show: true}}
  18374. * }
  18375. * ]
  18376. * };
  18377. *
  18378. * @alias module:echarts/model/OptionManager
  18379. * @param {module:echarts/ExtensionAPI} api
  18380. */
  18381. function OptionManager(api) {
  18382. /**
  18383. * @private
  18384. * @type {module:echarts/ExtensionAPI}
  18385. */
  18386. this._api = api;
  18387. /**
  18388. * @private
  18389. * @type {Array.<number>}
  18390. */
  18391. this._timelineOptions = [];
  18392. /**
  18393. * @private
  18394. * @type {Array.<Object>}
  18395. */
  18396. this._mediaList = [];
  18397. /**
  18398. * @private
  18399. * @type {Object}
  18400. */
  18401. this._mediaDefault;
  18402. /**
  18403. * -1, means default.
  18404. * empty means no media.
  18405. * @private
  18406. * @type {Array.<number>}
  18407. */
  18408. this._currentMediaIndices = [];
  18409. /**
  18410. * @private
  18411. * @type {Object}
  18412. */
  18413. this._optionBackup;
  18414. /**
  18415. * @private
  18416. * @type {Object}
  18417. */
  18418. this._newBaseOption;
  18419. }
  18420. // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18421. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18422. // rawOption cloned and backuped when timeline changed, which does no
  18423. // good to performance. What's more, that both timeline and setOption
  18424. // method supply 'notMerge' brings complex and some problems.
  18425. // Consider this case:
  18426. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18427. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18428. OptionManager.prototype = {
  18429. constructor: OptionManager,
  18430. /**
  18431. * @public
  18432. * @param {Object} rawOption Raw option.
  18433. * @param {module:echarts/model/Global} ecModel
  18434. * @param {Array.<Function>} optionPreprocessorFuncs
  18435. * @return {Object} Init option
  18436. */
  18437. setOption: function (rawOption, optionPreprocessorFuncs) {
  18438. if (rawOption) {
  18439. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18440. each$1(normalizeToArray(rawOption.series), function (series) {
  18441. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18442. });
  18443. }
  18444. // Caution: some series modify option data, if do not clone,
  18445. // it should ensure that the repeat modify correctly
  18446. // (create a new object when modify itself).
  18447. rawOption = clone$3(rawOption, true);
  18448. // FIXME
  18449. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18450. var oldOptionBackup = this._optionBackup;
  18451. var newParsedOption = parseRawOption.call(
  18452. this, rawOption, optionPreprocessorFuncs, !oldOptionBackup
  18453. );
  18454. this._newBaseOption = newParsedOption.baseOption;
  18455. // For setOption at second time (using merge mode);
  18456. if (oldOptionBackup) {
  18457. // Only baseOption can be merged.
  18458. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption);
  18459. // For simplicity, timeline options and media options do not support merge,
  18460. // that is, if you `setOption` twice and both has timeline options, the latter
  18461. // timeline opitons will not be merged to the formers, but just substitude them.
  18462. if (newParsedOption.timelineOptions.length) {
  18463. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18464. }
  18465. if (newParsedOption.mediaList.length) {
  18466. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18467. }
  18468. if (newParsedOption.mediaDefault) {
  18469. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18470. }
  18471. }
  18472. else {
  18473. this._optionBackup = newParsedOption;
  18474. }
  18475. },
  18476. /**
  18477. * @param {boolean} isRecreate
  18478. * @return {Object}
  18479. */
  18480. mountOption: function (isRecreate) {
  18481. var optionBackup = this._optionBackup;
  18482. // TODO
  18483. // 如果没有reset功能则不clone。
  18484. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18485. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18486. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18487. this._currentMediaIndices = [];
  18488. return clone$3(isRecreate
  18489. // this._optionBackup.baseOption, which is created at the first `setOption`
  18490. // called, and is merged into every new option by inner method `mergeOption`
  18491. // each time `setOption` called, can be only used in `isRecreate`, because
  18492. // its reliability is under suspicion. In other cases option merge is
  18493. // performed by `model.mergeOption`.
  18494. ? optionBackup.baseOption : this._newBaseOption
  18495. );
  18496. },
  18497. /**
  18498. * @param {module:echarts/model/Global} ecModel
  18499. * @return {Object}
  18500. */
  18501. getTimelineOption: function (ecModel) {
  18502. var option;
  18503. var timelineOptions = this._timelineOptions;
  18504. if (timelineOptions.length) {
  18505. // getTimelineOption can only be called after ecModel inited,
  18506. // so we can get currentIndex from timelineModel.
  18507. var timelineModel = ecModel.getComponent('timeline');
  18508. if (timelineModel) {
  18509. option = clone$3(
  18510. timelineOptions[timelineModel.getCurrentIndex()],
  18511. true
  18512. );
  18513. }
  18514. }
  18515. return option;
  18516. },
  18517. /**
  18518. * @param {module:echarts/model/Global} ecModel
  18519. * @return {Array.<Object>}
  18520. */
  18521. getMediaOption: function (ecModel) {
  18522. var ecWidth = this._api.getWidth();
  18523. var ecHeight = this._api.getHeight();
  18524. var mediaList = this._mediaList;
  18525. var mediaDefault = this._mediaDefault;
  18526. var indices = [];
  18527. var result = [];
  18528. // No media defined.
  18529. if (!mediaList.length && !mediaDefault) {
  18530. return result;
  18531. }
  18532. // Multi media may be applied, the latter defined media has higher priority.
  18533. for (var i = 0, len = mediaList.length; i < len; i++) {
  18534. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18535. indices.push(i);
  18536. }
  18537. }
  18538. // FIXME
  18539. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18540. if (!indices.length && mediaDefault) {
  18541. indices = [-1];
  18542. }
  18543. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18544. result = map$1(indices, function (index) {
  18545. return clone$3(
  18546. index === -1 ? mediaDefault.option : mediaList[index].option
  18547. );
  18548. });
  18549. }
  18550. // Otherwise return nothing.
  18551. this._currentMediaIndices = indices;
  18552. return result;
  18553. }
  18554. };
  18555. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18556. var timelineOptions = [];
  18557. var mediaList = [];
  18558. var mediaDefault;
  18559. var baseOption;
  18560. // Compatible with ec2.
  18561. var timelineOpt = rawOption.timeline;
  18562. if (rawOption.baseOption) {
  18563. baseOption = rawOption.baseOption;
  18564. }
  18565. // For timeline
  18566. if (timelineOpt || rawOption.options) {
  18567. baseOption = baseOption || {};
  18568. timelineOptions = (rawOption.options || []).slice();
  18569. }
  18570. // For media query
  18571. if (rawOption.media) {
  18572. baseOption = baseOption || {};
  18573. var media = rawOption.media;
  18574. each$4(media, function (singleMedia) {
  18575. if (singleMedia && singleMedia.option) {
  18576. if (singleMedia.query) {
  18577. mediaList.push(singleMedia);
  18578. }
  18579. else if (!mediaDefault) {
  18580. // Use the first media default.
  18581. mediaDefault = singleMedia;
  18582. }
  18583. }
  18584. });
  18585. }
  18586. // For normal option
  18587. if (!baseOption) {
  18588. baseOption = rawOption;
  18589. }
  18590. // Set timelineOpt to baseOption in ec3,
  18591. // which is convenient for merge option.
  18592. if (!baseOption.timeline) {
  18593. baseOption.timeline = timelineOpt;
  18594. }
  18595. // Preprocess.
  18596. each$4([baseOption].concat(timelineOptions)
  18597. .concat(map(mediaList, function (media) {
  18598. return media.option;
  18599. })),
  18600. function (option) {
  18601. each$4(optionPreprocessorFuncs, function (preProcess) {
  18602. preProcess(option, isNew);
  18603. });
  18604. }
  18605. );
  18606. return {
  18607. baseOption: baseOption,
  18608. timelineOptions: timelineOptions,
  18609. mediaDefault: mediaDefault,
  18610. mediaList: mediaList
  18611. };
  18612. }
  18613. /**
  18614. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18615. * Support: width, height, aspectRatio
  18616. * Can use max or min as prefix.
  18617. */
  18618. function applyMediaQuery(query, ecWidth, ecHeight) {
  18619. var realMap = {
  18620. width: ecWidth,
  18621. height: ecHeight,
  18622. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18623. };
  18624. var applicatable = true;
  18625. each$1(query, function (value, attr) {
  18626. var matched = attr.match(QUERY_REG);
  18627. if (!matched || !matched[1] || !matched[2]) {
  18628. return;
  18629. }
  18630. var operator = matched[1];
  18631. var realAttr = matched[2].toLowerCase();
  18632. if (!compare(realMap[realAttr], value, operator)) {
  18633. applicatable = false;
  18634. }
  18635. });
  18636. return applicatable;
  18637. }
  18638. function compare(real, expect, operator) {
  18639. if (operator === 'min') {
  18640. return real >= expect;
  18641. }
  18642. else if (operator === 'max') {
  18643. return real <= expect;
  18644. }
  18645. else { // Equals
  18646. return real === expect;
  18647. }
  18648. }
  18649. function indicesEquals(indices1, indices2) {
  18650. // indices is always order by asc and has only finite number.
  18651. return indices1.join(',') === indices2.join(',');
  18652. }
  18653. /**
  18654. * Consider case:
  18655. * `chart.setOption(opt1);`
  18656. * Then user do some interaction like dataZoom, dataView changing.
  18657. * `chart.setOption(opt2);`
  18658. * Then user press 'reset button' in toolbox.
  18659. *
  18660. * After doing that all of the interaction effects should be reset, the
  18661. * chart should be the same as the result of invoke
  18662. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18663. *
  18664. * Although it is not able ensure that
  18665. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18666. * `chart.setOption(merge(opt1, opt2));` exactly,
  18667. * this might be the only simple way to implement that feature.
  18668. *
  18669. * MEMO: We've considered some other approaches:
  18670. * 1. Each model handle its self restoration but not uniform treatment.
  18671. * (Too complex in logic and error-prone)
  18672. * 2. Use a shadow ecModel. (Performace expensive)
  18673. */
  18674. function mergeOption(oldOption, newOption) {
  18675. newOption = newOption || {};
  18676. each$4(newOption, function (newCptOpt, mainType) {
  18677. if (newCptOpt == null) {
  18678. return;
  18679. }
  18680. var oldCptOpt = oldOption[mainType];
  18681. if (!ComponentModel.hasClass(mainType)) {
  18682. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18683. }
  18684. else {
  18685. newCptOpt = normalizeToArray(newCptOpt);
  18686. oldCptOpt = normalizeToArray(oldCptOpt);
  18687. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18688. oldOption[mainType] = map$1(mapResult, function (item) {
  18689. return (item.option && item.exist)
  18690. ? merge$1(item.exist, item.option, true)
  18691. : (item.exist || item.option);
  18692. });
  18693. }
  18694. });
  18695. }
  18696. /*
  18697. * Licensed to the Apache Software Foundation (ASF) under one
  18698. * or more contributor license agreements. See the NOTICE file
  18699. * distributed with this work for additional information
  18700. * regarding copyright ownership. The ASF licenses this file
  18701. * to you under the Apache License, Version 2.0 (the
  18702. * "License"); you may not use this file except in compliance
  18703. * with the License. You may obtain a copy of the License at
  18704. *
  18705. * http://www.apache.org/licenses/LICENSE-2.0
  18706. *
  18707. * Unless required by applicable law or agreed to in writing,
  18708. * software distributed under the License is distributed on an
  18709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18710. * KIND, either express or implied. See the License for the
  18711. * specific language governing permissions and limitations
  18712. * under the License.
  18713. */
  18714. var each$5 = each$1;
  18715. var isObject$3 = isObject$1;
  18716. var POSSIBLE_STYLES = [
  18717. 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle',
  18718. 'chordStyle', 'label', 'labelLine'
  18719. ];
  18720. function compatEC2ItemStyle(opt) {
  18721. var itemStyleOpt = opt && opt.itemStyle;
  18722. if (!itemStyleOpt) {
  18723. return;
  18724. }
  18725. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18726. var styleName = POSSIBLE_STYLES[i];
  18727. var normalItemStyleOpt = itemStyleOpt.normal;
  18728. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18729. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18730. opt[styleName] = opt[styleName] || {};
  18731. if (!opt[styleName].normal) {
  18732. opt[styleName].normal = normalItemStyleOpt[styleName];
  18733. }
  18734. else {
  18735. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18736. }
  18737. normalItemStyleOpt[styleName] = null;
  18738. }
  18739. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18740. opt[styleName] = opt[styleName] || {};
  18741. if (!opt[styleName].emphasis) {
  18742. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18743. }
  18744. else {
  18745. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18746. }
  18747. emphasisItemStyleOpt[styleName] = null;
  18748. }
  18749. }
  18750. }
  18751. function convertNormalEmphasis(opt, optType, useExtend) {
  18752. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18753. var normalOpt = opt[optType].normal;
  18754. var emphasisOpt = opt[optType].emphasis;
  18755. if (normalOpt) {
  18756. // Timeline controlStyle has other properties besides normal and emphasis
  18757. if (useExtend) {
  18758. opt[optType].normal = opt[optType].emphasis = null;
  18759. defaults(opt[optType], normalOpt);
  18760. }
  18761. else {
  18762. opt[optType] = normalOpt;
  18763. }
  18764. }
  18765. if (emphasisOpt) {
  18766. opt.emphasis = opt.emphasis || {};
  18767. opt.emphasis[optType] = emphasisOpt;
  18768. }
  18769. }
  18770. }
  18771. function removeEC3NormalStatus(opt) {
  18772. convertNormalEmphasis(opt, 'itemStyle');
  18773. convertNormalEmphasis(opt, 'lineStyle');
  18774. convertNormalEmphasis(opt, 'areaStyle');
  18775. convertNormalEmphasis(opt, 'label');
  18776. convertNormalEmphasis(opt, 'labelLine');
  18777. // treemap
  18778. convertNormalEmphasis(opt, 'upperLabel');
  18779. // graph
  18780. convertNormalEmphasis(opt, 'edgeLabel');
  18781. }
  18782. function compatTextStyle(opt, propName) {
  18783. // Check whether is not object (string\null\undefined ...)
  18784. var labelOptSingle = isObject$3(opt) && opt[propName];
  18785. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18786. if (textStyle) {
  18787. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18788. var propName = TEXT_STYLE_OPTIONS[i];
  18789. if (textStyle.hasOwnProperty(propName)) {
  18790. labelOptSingle[propName] = textStyle[propName];
  18791. }
  18792. }
  18793. }
  18794. }
  18795. function compatEC3CommonStyles(opt) {
  18796. if (opt) {
  18797. removeEC3NormalStatus(opt);
  18798. compatTextStyle(opt, 'label');
  18799. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18800. }
  18801. }
  18802. function processSeries(seriesOpt) {
  18803. if (!isObject$3(seriesOpt)) {
  18804. return;
  18805. }
  18806. compatEC2ItemStyle(seriesOpt);
  18807. removeEC3NormalStatus(seriesOpt);
  18808. compatTextStyle(seriesOpt, 'label');
  18809. // treemap
  18810. compatTextStyle(seriesOpt, 'upperLabel');
  18811. // graph
  18812. compatTextStyle(seriesOpt, 'edgeLabel');
  18813. if (seriesOpt.emphasis) {
  18814. compatTextStyle(seriesOpt.emphasis, 'label');
  18815. // treemap
  18816. compatTextStyle(seriesOpt.emphasis, 'upperLabel');
  18817. // graph
  18818. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18819. }
  18820. var markPoint = seriesOpt.markPoint;
  18821. if (markPoint) {
  18822. compatEC2ItemStyle(markPoint);
  18823. compatEC3CommonStyles(markPoint);
  18824. }
  18825. var markLine = seriesOpt.markLine;
  18826. if (markLine) {
  18827. compatEC2ItemStyle(markLine);
  18828. compatEC3CommonStyles(markLine);
  18829. }
  18830. var markArea = seriesOpt.markArea;
  18831. if (markArea) {
  18832. compatEC3CommonStyles(markArea);
  18833. }
  18834. var data = seriesOpt.data;
  18835. // Break with ec3: if `setOption` again, there may be no `type` in option,
  18836. // then the backward compat based on option type will not be performed.
  18837. if (seriesOpt.type === 'graph') {
  18838. data = data || seriesOpt.nodes;
  18839. var edgeData = seriesOpt.links || seriesOpt.edges;
  18840. if (edgeData && !isTypedArray(edgeData)) {
  18841. for (var i = 0; i < edgeData.length; i++) {
  18842. compatEC3CommonStyles(edgeData[i]);
  18843. }
  18844. }
  18845. each$1(seriesOpt.categories, function (opt) {
  18846. removeEC3NormalStatus(opt);
  18847. });
  18848. }
  18849. if (data && !isTypedArray(data)) {
  18850. for (var i = 0; i < data.length; i++) {
  18851. compatEC3CommonStyles(data[i]);
  18852. }
  18853. }
  18854. // mark point data
  18855. var markPoint = seriesOpt.markPoint;
  18856. if (markPoint && markPoint.data) {
  18857. var mpData = markPoint.data;
  18858. for (var i = 0; i < mpData.length; i++) {
  18859. compatEC3CommonStyles(mpData[i]);
  18860. }
  18861. }
  18862. // mark line data
  18863. var markLine = seriesOpt.markLine;
  18864. if (markLine && markLine.data) {
  18865. var mlData = markLine.data;
  18866. for (var i = 0; i < mlData.length; i++) {
  18867. if (isArray(mlData[i])) {
  18868. compatEC3CommonStyles(mlData[i][0]);
  18869. compatEC3CommonStyles(mlData[i][1]);
  18870. }
  18871. else {
  18872. compatEC3CommonStyles(mlData[i]);
  18873. }
  18874. }
  18875. }
  18876. // Series
  18877. if (seriesOpt.type === 'gauge') {
  18878. compatTextStyle(seriesOpt, 'axisLabel');
  18879. compatTextStyle(seriesOpt, 'title');
  18880. compatTextStyle(seriesOpt, 'detail');
  18881. }
  18882. else if (seriesOpt.type === 'treemap') {
  18883. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18884. each$1(seriesOpt.levels, function (opt) {
  18885. removeEC3NormalStatus(opt);
  18886. });
  18887. }
  18888. else if (seriesOpt.type === 'tree') {
  18889. removeEC3NormalStatus(seriesOpt.leaves);
  18890. }
  18891. // sunburst starts from ec4, so it does not need to compat levels.
  18892. }
  18893. function toArr(o) {
  18894. return isArray(o) ? o : o ? [o] : [];
  18895. }
  18896. function toObj(o) {
  18897. return (isArray(o) ? o[0] : o) || {};
  18898. }
  18899. var compatStyle = function (option, isTheme) {
  18900. each$5(toArr(option.series), function (seriesOpt) {
  18901. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18902. });
  18903. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18904. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18905. each$5(
  18906. axes,
  18907. function (axisName) {
  18908. each$5(toArr(option[axisName]), function (axisOpt) {
  18909. if (axisOpt) {
  18910. compatTextStyle(axisOpt, 'axisLabel');
  18911. compatTextStyle(axisOpt.axisPointer, 'label');
  18912. }
  18913. });
  18914. }
  18915. );
  18916. each$5(toArr(option.parallel), function (parallelOpt) {
  18917. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18918. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18919. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18920. });
  18921. each$5(toArr(option.calendar), function (calendarOpt) {
  18922. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18923. compatTextStyle(calendarOpt, 'dayLabel');
  18924. compatTextStyle(calendarOpt, 'monthLabel');
  18925. compatTextStyle(calendarOpt, 'yearLabel');
  18926. });
  18927. // radar.name.textStyle
  18928. each$5(toArr(option.radar), function (radarOpt) {
  18929. compatTextStyle(radarOpt, 'name');
  18930. });
  18931. each$5(toArr(option.geo), function (geoOpt) {
  18932. if (isObject$3(geoOpt)) {
  18933. compatEC3CommonStyles(geoOpt);
  18934. each$5(toArr(geoOpt.regions), function (regionObj) {
  18935. compatEC3CommonStyles(regionObj);
  18936. });
  18937. }
  18938. });
  18939. each$5(toArr(option.timeline), function (timelineOpt) {
  18940. compatEC3CommonStyles(timelineOpt);
  18941. convertNormalEmphasis(timelineOpt, 'label');
  18942. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18943. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18944. var data = timelineOpt.data;
  18945. isArray(data) && each$1(data, function (item) {
  18946. if (isObject$1(item)) {
  18947. convertNormalEmphasis(item, 'label');
  18948. convertNormalEmphasis(item, 'itemStyle');
  18949. }
  18950. });
  18951. });
  18952. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18953. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18954. each$5(toolboxOpt.feature, function (featureOpt) {
  18955. convertNormalEmphasis(featureOpt, 'iconStyle');
  18956. });
  18957. });
  18958. compatTextStyle(toObj(option.axisPointer), 'label');
  18959. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18960. };
  18961. /*
  18962. * Licensed to the Apache Software Foundation (ASF) under one
  18963. * or more contributor license agreements. See the NOTICE file
  18964. * distributed with this work for additional information
  18965. * regarding copyright ownership. The ASF licenses this file
  18966. * to you under the Apache License, Version 2.0 (the
  18967. * "License"); you may not use this file except in compliance
  18968. * with the License. You may obtain a copy of the License at
  18969. *
  18970. * http://www.apache.org/licenses/LICENSE-2.0
  18971. *
  18972. * Unless required by applicable law or agreed to in writing,
  18973. * software distributed under the License is distributed on an
  18974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18975. * KIND, either express or implied. See the License for the
  18976. * specific language governing permissions and limitations
  18977. * under the License.
  18978. */
  18979. // Compatitable with 2.0
  18980. function get(opt, path) {
  18981. path = path.split(',');
  18982. var obj = opt;
  18983. for (var i = 0; i < path.length; i++) {
  18984. obj = obj && obj[path[i]];
  18985. if (obj == null) {
  18986. break;
  18987. }
  18988. }
  18989. return obj;
  18990. }
  18991. function set$1(opt, path, val, overwrite) {
  18992. path = path.split(',');
  18993. var obj = opt;
  18994. var key;
  18995. for (var i = 0; i < path.length - 1; i++) {
  18996. key = path[i];
  18997. if (obj[key] == null) {
  18998. obj[key] = {};
  18999. }
  19000. obj = obj[key];
  19001. }
  19002. if (overwrite || obj[path[i]] == null) {
  19003. obj[path[i]] = val;
  19004. }
  19005. }
  19006. function compatLayoutProperties(option) {
  19007. each$1(LAYOUT_PROPERTIES, function (prop) {
  19008. if (prop[0] in option && !(prop[1] in option)) {
  19009. option[prop[1]] = option[prop[0]];
  19010. }
  19011. });
  19012. }
  19013. var LAYOUT_PROPERTIES = [
  19014. ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']
  19015. ];
  19016. var COMPATITABLE_COMPONENTS = [
  19017. 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'
  19018. ];
  19019. var backwardCompat = function (option, isTheme) {
  19020. compatStyle(option, isTheme);
  19021. // Make sure series array for model initialization.
  19022. option.series = normalizeToArray(option.series);
  19023. each$1(option.series, function (seriesOpt) {
  19024. if (!isObject$1(seriesOpt)) {
  19025. return;
  19026. }
  19027. var seriesType = seriesOpt.type;
  19028. if (seriesType === 'pie' || seriesType === 'gauge') {
  19029. if (seriesOpt.clockWise != null) {
  19030. seriesOpt.clockwise = seriesOpt.clockWise;
  19031. }
  19032. }
  19033. if (seriesType === 'gauge') {
  19034. var pointerColor = get(seriesOpt, 'pointer.color');
  19035. pointerColor != null
  19036. && set$1(seriesOpt, 'itemStyle.normal.color', pointerColor);
  19037. }
  19038. compatLayoutProperties(seriesOpt);
  19039. });
  19040. // dataRange has changed to visualMap
  19041. if (option.dataRange) {
  19042. option.visualMap = option.dataRange;
  19043. }
  19044. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  19045. var options = option[componentName];
  19046. if (options) {
  19047. if (!isArray(options)) {
  19048. options = [options];
  19049. }
  19050. each$1(options, function (option) {
  19051. compatLayoutProperties(option);
  19052. });
  19053. }
  19054. });
  19055. };
  19056. /*
  19057. * Licensed to the Apache Software Foundation (ASF) under one
  19058. * or more contributor license agreements. See the NOTICE file
  19059. * distributed with this work for additional information
  19060. * regarding copyright ownership. The ASF licenses this file
  19061. * to you under the Apache License, Version 2.0 (the
  19062. * "License"); you may not use this file except in compliance
  19063. * with the License. You may obtain a copy of the License at
  19064. *
  19065. * http://www.apache.org/licenses/LICENSE-2.0
  19066. *
  19067. * Unless required by applicable law or agreed to in writing,
  19068. * software distributed under the License is distributed on an
  19069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19070. * KIND, either express or implied. See the License for the
  19071. * specific language governing permissions and limitations
  19072. * under the License.
  19073. */
  19074. // (1) [Caution]: the logic is correct based on the premises:
  19075. // data processing stage is blocked in stream.
  19076. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  19077. // (2) Only register once when import repeatly.
  19078. // Should be executed before after series filtered and before stack calculation.
  19079. var dataStack = function (ecModel) {
  19080. var stackInfoMap = createHashMap();
  19081. ecModel.eachSeries(function (seriesModel) {
  19082. var stack = seriesModel.get('stack');
  19083. // Compatibal: when `stack` is set as '', do not stack.
  19084. if (stack) {
  19085. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  19086. var data = seriesModel.getData();
  19087. var stackInfo = {
  19088. // Used for calculate axis extent automatically.
  19089. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19090. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19091. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19092. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19093. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19094. data: data,
  19095. seriesModel: seriesModel
  19096. };
  19097. // If stacked on axis that do not support data stack.
  19098. if (!stackInfo.stackedDimension
  19099. || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)
  19100. ) {
  19101. return;
  19102. }
  19103. stackInfoList.length && data.setCalculationInfo(
  19104. 'stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel
  19105. );
  19106. stackInfoList.push(stackInfo);
  19107. }
  19108. });
  19109. stackInfoMap.each(calculateStack);
  19110. };
  19111. function calculateStack(stackInfoList) {
  19112. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19113. var resultVal = [];
  19114. var resultNaN = [NaN, NaN];
  19115. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19116. var targetData = targetStackInfo.data;
  19117. var isStackedByIndex = targetStackInfo.isStackedByIndex;
  19118. // Should not write on raw data, because stack series model list changes
  19119. // depending on legend selection.
  19120. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19121. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex);
  19122. // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19123. // should also be NaN, to draw a appropriate belt area.
  19124. if (isNaN(sum)) {
  19125. return resultNaN;
  19126. }
  19127. var byValue;
  19128. var stackedDataRawIndex;
  19129. if (isStackedByIndex) {
  19130. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19131. }
  19132. else {
  19133. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19134. }
  19135. // If stackOver is NaN, chart view will render point on value start.
  19136. var stackedOver = NaN;
  19137. for (var j = idxInStack - 1; j >= 0; j--) {
  19138. var stackInfo = stackInfoList[j];
  19139. // Has been optimized by inverted indices on `stackedByDimension`.
  19140. if (!isStackedByIndex) {
  19141. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19142. }
  19143. if (stackedDataRawIndex >= 0) {
  19144. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex);
  19145. // Considering positive stack, negative stack and empty data
  19146. if ((sum >= 0 && val > 0) // Positive stack
  19147. || (sum <= 0 && val < 0) // Negative stack
  19148. ) {
  19149. sum += val;
  19150. stackedOver = val;
  19151. break;
  19152. }
  19153. }
  19154. }
  19155. resultVal[0] = sum;
  19156. resultVal[1] = stackedOver;
  19157. return resultVal;
  19158. });
  19159. targetData.hostModel.setData(newData);
  19160. // Update for consequent calculation
  19161. targetStackInfo.data = newData;
  19162. });
  19163. }
  19164. /*
  19165. * Licensed to the Apache Software Foundation (ASF) under one
  19166. * or more contributor license agreements. See the NOTICE file
  19167. * distributed with this work for additional information
  19168. * regarding copyright ownership. The ASF licenses this file
  19169. * to you under the Apache License, Version 2.0 (the
  19170. * "License"); you may not use this file except in compliance
  19171. * with the License. You may obtain a copy of the License at
  19172. *
  19173. * http://www.apache.org/licenses/LICENSE-2.0
  19174. *
  19175. * Unless required by applicable law or agreed to in writing,
  19176. * software distributed under the License is distributed on an
  19177. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19178. * KIND, either express or implied. See the License for the
  19179. * specific language governing permissions and limitations
  19180. * under the License.
  19181. */
  19182. // TODO
  19183. // ??? refactor? check the outer usage of data provider.
  19184. // merge with defaultDimValueGetter?
  19185. /**
  19186. * If normal array used, mutable chunk size is supported.
  19187. * If typed array used, chunk size must be fixed.
  19188. */
  19189. function DefaultDataProvider(source, dimSize) {
  19190. if (!Source.isInstance(source)) {
  19191. source = Source.seriesDataToSource(source);
  19192. }
  19193. this._source = source;
  19194. var data = this._data = source.data;
  19195. var sourceFormat = source.sourceFormat;
  19196. // Typed array. TODO IE10+?
  19197. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19198. if (__DEV__) {
  19199. if (dimSize == null) {
  19200. throw new Error('Typed array data must specify dimension size');
  19201. }
  19202. }
  19203. this._offset = 0;
  19204. this._dimSize = dimSize;
  19205. this._data = data;
  19206. }
  19207. var methods = providerMethods[
  19208. sourceFormat === SOURCE_FORMAT_ARRAY_ROWS
  19209. ? sourceFormat + '_' + source.seriesLayoutBy
  19210. : sourceFormat
  19211. ];
  19212. if (__DEV__) {
  19213. assert$1(methods, 'Invalide sourceFormat: ' + sourceFormat);
  19214. }
  19215. extend(this, methods);
  19216. }
  19217. var providerProto = DefaultDataProvider.prototype;
  19218. // If data is pure without style configuration
  19219. providerProto.pure = false;
  19220. // If data is persistent and will not be released after use.
  19221. providerProto.persistent = true;
  19222. // ???! FIXME legacy data provider do not has method getSource
  19223. providerProto.getSource = function () {
  19224. return this._source;
  19225. };
  19226. var providerMethods = {
  19227. 'arrayRows_column': {
  19228. pure: true,
  19229. count: function () {
  19230. return Math.max(0, this._data.length - this._source.startIndex);
  19231. },
  19232. getItem: function (idx) {
  19233. return this._data[idx + this._source.startIndex];
  19234. },
  19235. appendData: appendDataSimply
  19236. },
  19237. 'arrayRows_row': {
  19238. pure: true,
  19239. count: function () {
  19240. var row = this._data[0];
  19241. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19242. },
  19243. getItem: function (idx) {
  19244. idx += this._source.startIndex;
  19245. var item = [];
  19246. var data = this._data;
  19247. for (var i = 0; i < data.length; i++) {
  19248. var row = data[i];
  19249. item.push(row ? row[idx] : null);
  19250. }
  19251. return item;
  19252. },
  19253. appendData: function () {
  19254. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19255. }
  19256. },
  19257. 'objectRows': {
  19258. pure: true,
  19259. count: countSimply,
  19260. getItem: getItemSimply,
  19261. appendData: appendDataSimply
  19262. },
  19263. 'keyedColumns': {
  19264. pure: true,
  19265. count: function () {
  19266. var dimName = this._source.dimensionsDefine[0].name;
  19267. var col = this._data[dimName];
  19268. return col ? col.length : 0;
  19269. },
  19270. getItem: function (idx) {
  19271. var item = [];
  19272. var dims = this._source.dimensionsDefine;
  19273. for (var i = 0; i < dims.length; i++) {
  19274. var col = this._data[dims[i].name];
  19275. item.push(col ? col[idx] : null);
  19276. }
  19277. return item;
  19278. },
  19279. appendData: function (newData) {
  19280. var data = this._data;
  19281. each$1(newData, function (newCol, key) {
  19282. var oldCol = data[key] || (data[key] = []);
  19283. for (var i = 0; i < (newCol || []).length; i++) {
  19284. oldCol.push(newCol[i]);
  19285. }
  19286. });
  19287. }
  19288. },
  19289. 'original': {
  19290. count: countSimply,
  19291. getItem: getItemSimply,
  19292. appendData: appendDataSimply
  19293. },
  19294. 'typedArray': {
  19295. persistent: false,
  19296. pure: true,
  19297. count: function () {
  19298. return this._data ? (this._data.length / this._dimSize) : 0;
  19299. },
  19300. getItem: function (idx, out) {
  19301. idx = idx - this._offset;
  19302. out = out || [];
  19303. var offset = this._dimSize * idx;
  19304. for (var i = 0; i < this._dimSize; i++) {
  19305. out[i] = this._data[offset + i];
  19306. }
  19307. return out;
  19308. },
  19309. appendData: function (newData) {
  19310. if (__DEV__) {
  19311. assert$1(
  19312. isTypedArray(newData),
  19313. 'Added data must be TypedArray if data in initialization is TypedArray'
  19314. );
  19315. }
  19316. this._data = newData;
  19317. },
  19318. // Clean self if data is already used.
  19319. clean: function () {
  19320. // PENDING
  19321. this._offset += this.count();
  19322. this._data = null;
  19323. }
  19324. }
  19325. };
  19326. function countSimply() {
  19327. return this._data.length;
  19328. }
  19329. function getItemSimply(idx) {
  19330. return this._data[idx];
  19331. }
  19332. function appendDataSimply(newData) {
  19333. for (var i = 0; i < newData.length; i++) {
  19334. this._data.push(newData[i]);
  19335. }
  19336. }
  19337. var rawValueGetters = {
  19338. arrayRows: getRawValueSimply,
  19339. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19340. return dimIndex != null ? dataItem[dimName] : dataItem;
  19341. },
  19342. keyedColumns: getRawValueSimply,
  19343. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19344. // FIXME
  19345. // In some case (markpoint in geo (geo-map.html)), dataItem
  19346. // is {coord: [...]}
  19347. var value = getDataItemValue(dataItem);
  19348. return (dimIndex == null || !(value instanceof Array))
  19349. ? value
  19350. : value[dimIndex];
  19351. },
  19352. typedArray: getRawValueSimply
  19353. };
  19354. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19355. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19356. }
  19357. var defaultDimValueGetters = {
  19358. arrayRows: getDimValueSimply,
  19359. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19360. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19361. },
  19362. keyedColumns: getDimValueSimply,
  19363. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19364. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19365. // If dataItem is an plain object with no value field, the var `value`
  19366. // will be assigned with the object, but it will be tread correctly
  19367. // in the `convertDataValue`.
  19368. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value);
  19369. // If any dataItem is like { value: 10 }
  19370. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19371. this.hasItemOption = true;
  19372. }
  19373. return converDataValue(
  19374. (value instanceof Array)
  19375. ? value[dimIndex]
  19376. // If value is a single number or something else not array.
  19377. : value,
  19378. this._dimensionInfos[dimName]
  19379. );
  19380. },
  19381. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19382. return dataItem[dimIndex];
  19383. }
  19384. };
  19385. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19386. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19387. }
  19388. /**
  19389. * This helper method convert value in data.
  19390. * @param {string|number|Date} value
  19391. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19392. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19393. */
  19394. function converDataValue(value, dimInfo) {
  19395. // Performance sensitive.
  19396. var dimType = dimInfo && dimInfo.type;
  19397. if (dimType === 'ordinal') {
  19398. // If given value is a category string
  19399. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19400. return ordinalMeta
  19401. ? ordinalMeta.parseAndCollect(value)
  19402. : value;
  19403. }
  19404. if (dimType === 'time'
  19405. // spead up when using timestamp
  19406. && typeof value !== 'number'
  19407. && value != null
  19408. && value !== '-'
  19409. ) {
  19410. value = +parseDate(value);
  19411. }
  19412. // dimType defaults 'number'.
  19413. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19414. // parse to NaN.
  19415. return (value == null || value === '')
  19416. ? NaN
  19417. // If string (like '-'), using '+' parse to NaN
  19418. // If object, also parse to NaN
  19419. : +value;
  19420. }
  19421. // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19422. // Consider persistent.
  19423. // Caution: why use raw value to display on label or tooltip?
  19424. // A reason is to avoid format. For example time value we do not know
  19425. // how to format is expected. More over, if stack is used, calculated
  19426. // value may be 0.91000000001, which have brings trouble to display.
  19427. // TODO: consider how to treat null/undefined/NaN when display?
  19428. /**
  19429. * @param {module:echarts/data/List} data
  19430. * @param {number} dataIndex
  19431. * @param {string|number} [dim] dimName or dimIndex
  19432. * @return {Array.<number>|string|number} can be null/undefined.
  19433. */
  19434. function retrieveRawValue(data, dataIndex, dim) {
  19435. if (!data) {
  19436. return;
  19437. }
  19438. // Consider data may be not persistent.
  19439. var dataItem = data.getRawDataItem(dataIndex);
  19440. if (dataItem == null) {
  19441. return;
  19442. }
  19443. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19444. var dimName;
  19445. var dimIndex;
  19446. var dimInfo = data.getDimensionInfo(dim);
  19447. if (dimInfo) {
  19448. dimName = dimInfo.name;
  19449. dimIndex = dimInfo.index;
  19450. }
  19451. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19452. }
  19453. /**
  19454. * Compatible with some cases (in pie, map) like:
  19455. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19456. * where only sourceFormat is 'original' and 'objectRows' supported.
  19457. *
  19458. * ??? TODO
  19459. * Supported detail options in data item when using 'arrayRows'.
  19460. *
  19461. * @param {module:echarts/data/List} data
  19462. * @param {number} dataIndex
  19463. * @param {string} attr like 'selected'
  19464. */
  19465. function retrieveRawAttr(data, dataIndex, attr) {
  19466. if (!data) {
  19467. return;
  19468. }
  19469. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19470. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL
  19471. && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS
  19472. ) {
  19473. return;
  19474. }
  19475. var dataItem = data.getRawDataItem(dataIndex);
  19476. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19477. dataItem = null;
  19478. }
  19479. if (dataItem) {
  19480. return dataItem[attr];
  19481. }
  19482. }
  19483. /*
  19484. * Licensed to the Apache Software Foundation (ASF) under one
  19485. * or more contributor license agreements. See the NOTICE file
  19486. * distributed with this work for additional information
  19487. * regarding copyright ownership. The ASF licenses this file
  19488. * to you under the Apache License, Version 2.0 (the
  19489. * "License"); you may not use this file except in compliance
  19490. * with the License. You may obtain a copy of the License at
  19491. *
  19492. * http://www.apache.org/licenses/LICENSE-2.0
  19493. *
  19494. * Unless required by applicable law or agreed to in writing,
  19495. * software distributed under the License is distributed on an
  19496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19497. * KIND, either express or implied. See the License for the
  19498. * specific language governing permissions and limitations
  19499. * under the License.
  19500. */
  19501. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g;
  19502. // PENDING A little ugly
  19503. var dataFormatMixin = {
  19504. /**
  19505. * Get params for formatter
  19506. * @param {number} dataIndex
  19507. * @param {string} [dataType]
  19508. * @return {Object}
  19509. */
  19510. getDataParams: function (dataIndex, dataType) {
  19511. var data = this.getData(dataType);
  19512. var rawValue = this.getRawValue(dataIndex, dataType);
  19513. var rawDataIndex = data.getRawIndex(dataIndex);
  19514. var name = data.getName(dataIndex);
  19515. var itemOpt = data.getRawDataItem(dataIndex);
  19516. var color = data.getItemVisual(dataIndex, 'color');
  19517. return {
  19518. componentType: this.mainType,
  19519. componentSubType: this.subType,
  19520. seriesType: this.mainType === 'series' ? this.subType : null,
  19521. seriesIndex: this.seriesIndex,
  19522. seriesId: this.id,
  19523. seriesName: this.name,
  19524. name: name,
  19525. dataIndex: rawDataIndex,
  19526. data: itemOpt,
  19527. dataType: dataType,
  19528. value: rawValue,
  19529. color: color,
  19530. marker: getTooltipMarker(color),
  19531. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19532. $vars: ['seriesName', 'name', 'value']
  19533. };
  19534. },
  19535. /**
  19536. * Format label
  19537. * @param {number} dataIndex
  19538. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19539. * @param {string} [dataType]
  19540. * @param {number} [dimIndex]
  19541. * @param {string} [labelProp='label']
  19542. * @return {string} If not formatter, return null/undefined
  19543. */
  19544. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19545. status = status || 'normal';
  19546. var data = this.getData(dataType);
  19547. var itemModel = data.getItemModel(dataIndex);
  19548. var params = this.getDataParams(dataIndex, dataType);
  19549. if (dimIndex != null && (params.value instanceof Array)) {
  19550. params.value = params.value[dimIndex];
  19551. }
  19552. var formatter = itemModel.get(
  19553. status === 'normal'
  19554. ? [labelProp || 'label', 'formatter']
  19555. : [status, labelProp || 'label', 'formatter']
  19556. );
  19557. if (typeof formatter === 'function') {
  19558. params.status = status;
  19559. return formatter(params);
  19560. }
  19561. else if (typeof formatter === 'string') {
  19562. var str = formatTpl(formatter, params);
  19563. // Support 'aaa{@[3]}bbb{@product}ccc'.
  19564. // Do not support '}' in dim name util have to.
  19565. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19566. var len = dim.length;
  19567. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19568. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19569. }
  19570. return retrieveRawValue(data, dataIndex, dim);
  19571. });
  19572. }
  19573. },
  19574. /**
  19575. * Get raw value in option
  19576. * @param {number} idx
  19577. * @param {string} [dataType]
  19578. * @return {Array|number|string}
  19579. */
  19580. getRawValue: function (idx, dataType) {
  19581. return retrieveRawValue(this.getData(dataType), idx);
  19582. },
  19583. /**
  19584. * Should be implemented.
  19585. * @param {number} dataIndex
  19586. * @param {boolean} [multipleSeries=false]
  19587. * @param {number} [dataType]
  19588. * @return {string} tooltip string
  19589. */
  19590. formatTooltip: function () {
  19591. // Empty function
  19592. }
  19593. };
  19594. /*
  19595. * Licensed to the Apache Software Foundation (ASF) under one
  19596. * or more contributor license agreements. See the NOTICE file
  19597. * distributed with this work for additional information
  19598. * regarding copyright ownership. The ASF licenses this file
  19599. * to you under the Apache License, Version 2.0 (the
  19600. * "License"); you may not use this file except in compliance
  19601. * with the License. You may obtain a copy of the License at
  19602. *
  19603. * http://www.apache.org/licenses/LICENSE-2.0
  19604. *
  19605. * Unless required by applicable law or agreed to in writing,
  19606. * software distributed under the License is distributed on an
  19607. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19608. * KIND, either express or implied. See the License for the
  19609. * specific language governing permissions and limitations
  19610. * under the License.
  19611. */
  19612. /**
  19613. * @param {Object} define
  19614. * @return See the return of `createTask`.
  19615. */
  19616. function createTask(define) {
  19617. return new Task(define);
  19618. }
  19619. /**
  19620. * @constructor
  19621. * @param {Object} define
  19622. * @param {Function} define.reset Custom reset
  19623. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  19624. * @param {Function} [define.count] count is used to determin data task.
  19625. * @param {Function} [define.onDirty] count is used to determin data task.
  19626. */
  19627. function Task(define) {
  19628. define = define || {};
  19629. this._reset = define.reset;
  19630. this._plan = define.plan;
  19631. this._count = define.count;
  19632. this._onDirty = define.onDirty;
  19633. this._dirty = true;
  19634. // Context must be specified implicitly, to
  19635. // avoid miss update context when model changed.
  19636. this.context;
  19637. }
  19638. var taskProto = Task.prototype;
  19639. /**
  19640. * @param {Object} performArgs
  19641. * @param {number} [performArgs.step] Specified step.
  19642. * @param {number} [performArgs.skip] Skip customer perform call.
  19643. * @param {number} [performArgs.modBy] Sampling window size.
  19644. * @param {number} [performArgs.modDataCount] Sampling count.
  19645. */
  19646. taskProto.perform = function (performArgs) {
  19647. var upTask = this._upstream;
  19648. var skip = performArgs && performArgs.skip;
  19649. // TODO some refactor.
  19650. // Pull data. Must pull data each time, because context.data
  19651. // may be updated by Series.setData.
  19652. if (this._dirty && upTask) {
  19653. var context = this.context;
  19654. context.data = context.outputData = upTask.context.outputData;
  19655. }
  19656. if (this.__pipeline) {
  19657. this.__pipeline.currentTask = this;
  19658. }
  19659. var planResult;
  19660. if (this._plan && !skip) {
  19661. planResult = this._plan(this.context);
  19662. }
  19663. // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19664. // elements uniformed distributed when progress, especially when moving or zooming.
  19665. var lastModBy = normalizeModBy(this._modBy);
  19666. var lastModDataCount = this._modDataCount || 0;
  19667. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19668. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19669. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19670. planResult = 'reset';
  19671. }
  19672. function normalizeModBy(val) {
  19673. !(val >= 1) && (val = 1); // jshint ignore:line
  19674. return val;
  19675. }
  19676. var forceFirstProgress;
  19677. if (this._dirty || planResult === 'reset') {
  19678. this._dirty = false;
  19679. forceFirstProgress = reset(this, skip);
  19680. }
  19681. this._modBy = modBy;
  19682. this._modDataCount = modDataCount;
  19683. var step = performArgs && performArgs.step;
  19684. if (upTask) {
  19685. if (__DEV__) {
  19686. assert$1(upTask._outputDueEnd != null);
  19687. }
  19688. this._dueEnd = upTask._outputDueEnd;
  19689. }
  19690. // DataTask or overallTask
  19691. else {
  19692. if (__DEV__) {
  19693. assert$1(!this._progress || this._count);
  19694. }
  19695. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19696. }
  19697. // Note: Stubs, that its host overall task let it has progress, has progress.
  19698. // If no progress, pass index from upstream to downstream each time plan called.
  19699. if (this._progress) {
  19700. var start = this._dueIndex;
  19701. var end = Math.min(
  19702. step != null ? this._dueIndex + step : Infinity,
  19703. this._dueEnd
  19704. );
  19705. if (!skip && (forceFirstProgress || start < end)) {
  19706. var progress = this._progress;
  19707. if (isArray(progress)) {
  19708. for (var i = 0; i < progress.length; i++) {
  19709. doProgress(this, progress[i], start, end, modBy, modDataCount);
  19710. }
  19711. }
  19712. else {
  19713. doProgress(this, progress, start, end, modBy, modDataCount);
  19714. }
  19715. }
  19716. this._dueIndex = end;
  19717. // If no `outputDueEnd`, assume that output data and
  19718. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19719. var outputDueEnd = this._settedOutputEnd != null
  19720. ? this._settedOutputEnd : end;
  19721. if (__DEV__) {
  19722. // ??? Can not rollback.
  19723. assert$1(outputDueEnd >= this._outputDueEnd);
  19724. }
  19725. this._outputDueEnd = outputDueEnd;
  19726. }
  19727. else {
  19728. // (1) Some overall task has no progress.
  19729. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19730. // This should always be performed so it can be passed to downstream.
  19731. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null
  19732. ? this._settedOutputEnd : this._dueEnd;
  19733. }
  19734. return this.unfinished();
  19735. };
  19736. var iterator = (function () {
  19737. var end;
  19738. var current;
  19739. var modBy;
  19740. var modDataCount;
  19741. var winCount;
  19742. var it = {
  19743. reset: function (s, e, sStep, sCount) {
  19744. current = s;
  19745. end = e;
  19746. modBy = sStep;
  19747. modDataCount = sCount;
  19748. winCount = Math.ceil(modDataCount / modBy);
  19749. it.next = (modBy > 1 && modDataCount > 0) ? modNext : sequentialNext;
  19750. }
  19751. };
  19752. return it;
  19753. function sequentialNext() {
  19754. return current < end ? current++ : null;
  19755. }
  19756. function modNext() {
  19757. var dataIndex = (current % winCount) * modBy + Math.ceil(current / winCount);
  19758. var result = current >= end
  19759. ? null
  19760. : dataIndex < modDataCount
  19761. ? dataIndex
  19762. // If modDataCount is smaller than data.count() (consider `appendData` case),
  19763. // Use normal linear rendering mode.
  19764. : current;
  19765. current++;
  19766. return result;
  19767. }
  19768. })();
  19769. taskProto.dirty = function () {
  19770. this._dirty = true;
  19771. this._onDirty && this._onDirty(this.context);
  19772. };
  19773. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  19774. iterator.reset(start, end, modBy, modDataCount);
  19775. taskIns._callingProgress = progress;
  19776. taskIns._callingProgress({
  19777. start: start, end: end, count: end - start, next: iterator.next
  19778. }, taskIns.context);
  19779. }
  19780. function reset(taskIns, skip) {
  19781. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19782. taskIns._settedOutputEnd = null;
  19783. var progress;
  19784. var forceFirstProgress;
  19785. if (!skip && taskIns._reset) {
  19786. progress = taskIns._reset(taskIns.context);
  19787. if (progress && progress.progress) {
  19788. forceFirstProgress = progress.forceFirstProgress;
  19789. progress = progress.progress;
  19790. }
  19791. // To simplify no progress checking, array must has item.
  19792. if (isArray(progress) && !progress.length) {
  19793. progress = null;
  19794. }
  19795. }
  19796. taskIns._progress = progress;
  19797. taskIns._modBy = taskIns._modDataCount = null;
  19798. var downstream = taskIns._downstream;
  19799. downstream && downstream.dirty();
  19800. return forceFirstProgress;
  19801. }
  19802. /**
  19803. * @return {boolean}
  19804. */
  19805. taskProto.unfinished = function () {
  19806. return this._progress && this._dueIndex < this._dueEnd;
  19807. };
  19808. /**
  19809. * @param {Object} downTask The downstream task.
  19810. * @return {Object} The downstream task.
  19811. */
  19812. taskProto.pipe = function (downTask) {
  19813. if (__DEV__) {
  19814. assert$1(downTask && !downTask._disposed && downTask !== this);
  19815. }
  19816. // If already downstream, do not dirty downTask.
  19817. if (this._downstream !== downTask || this._dirty) {
  19818. this._downstream = downTask;
  19819. downTask._upstream = this;
  19820. downTask.dirty();
  19821. }
  19822. };
  19823. taskProto.dispose = function () {
  19824. if (this._disposed) {
  19825. return;
  19826. }
  19827. this._upstream && (this._upstream._downstream = null);
  19828. this._downstream && (this._downstream._upstream = null);
  19829. this._dirty = false;
  19830. this._disposed = true;
  19831. };
  19832. taskProto.getUpstream = function () {
  19833. return this._upstream;
  19834. };
  19835. taskProto.getDownstream = function () {
  19836. return this._downstream;
  19837. };
  19838. taskProto.setOutputEnd = function (end) {
  19839. // This only happend in dataTask, dataZoom, map, currently.
  19840. // where dataZoom do not set end each time, but only set
  19841. // when reset. So we should record the setted end, in case
  19842. // that the stub of dataZoom perform again and earse the
  19843. // setted end by upstream.
  19844. this._outputDueEnd = this._settedOutputEnd = end;
  19845. };
  19846. ///////////////////////////////////////////////////////////
  19847. // For stream debug (Should be commented out after used!)
  19848. // Usage: printTask(this, 'begin');
  19849. // Usage: printTask(this, null, {someExtraProp});
  19850. // function printTask(task, prefix, extra) {
  19851. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19852. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19853. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19854. // var props = [];
  19855. // if (task.__pipeline) {
  19856. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19857. // props.push({text: 'idx', value: val});
  19858. // } else {
  19859. // var stubCount = 0;
  19860. // task.agentStubMap.each(() => stubCount++);
  19861. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19862. // }
  19863. // props.push({text: 'uid', value: task.uidDebug});
  19864. // if (task.__pipeline) {
  19865. // props.push({text: 'pid', value: task.__pipeline.id});
  19866. // task.agent && props.push(
  19867. // {text: 'stubFor', value: task.agent.uidDebug}
  19868. // );
  19869. // }
  19870. // props.push(
  19871. // {text: 'dirty', value: task._dirty},
  19872. // {text: 'dueIndex', value: task._dueIndex},
  19873. // {text: 'dueEnd', value: task._dueEnd},
  19874. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19875. // );
  19876. // if (extra) {
  19877. // Object.keys(extra).forEach(key => {
  19878. // props.push({text: key, value: extra[key]});
  19879. // });
  19880. // }
  19881. // var args = ['color: blue'];
  19882. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19883. // args.push('color: black', 'color: red'),
  19884. // `${item.text}: %c${item.value}`
  19885. // )).join('%c, ');
  19886. // console.log.apply(console, [msg].concat(args));
  19887. // // console.log(this);
  19888. // }
  19889. /*
  19890. * Licensed to the Apache Software Foundation (ASF) under one
  19891. * or more contributor license agreements. See the NOTICE file
  19892. * distributed with this work for additional information
  19893. * regarding copyright ownership. The ASF licenses this file
  19894. * to you under the Apache License, Version 2.0 (the
  19895. * "License"); you may not use this file except in compliance
  19896. * with the License. You may obtain a copy of the License at
  19897. *
  19898. * http://www.apache.org/licenses/LICENSE-2.0
  19899. *
  19900. * Unless required by applicable law or agreed to in writing,
  19901. * software distributed under the License is distributed on an
  19902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19903. * KIND, either express or implied. See the License for the
  19904. * specific language governing permissions and limitations
  19905. * under the License.
  19906. */
  19907. var inner$4 = makeInner();
  19908. var SeriesModel = ComponentModel.extend({
  19909. type: 'series.__base__',
  19910. /**
  19911. * @readOnly
  19912. */
  19913. seriesIndex: 0,
  19914. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19915. coordinateSystem: null,
  19916. /**
  19917. * @type {Object}
  19918. * @protected
  19919. */
  19920. defaultOption: null,
  19921. /**
  19922. * Data provided for legend
  19923. * @type {Function}
  19924. */
  19925. // PENDING
  19926. legendDataProvider: null,
  19927. /**
  19928. * Access path of color for visual
  19929. */
  19930. visualColorAccessPath: 'itemStyle.color',
  19931. /**
  19932. * Support merge layout params.
  19933. * Only support 'box' now (left/right/top/bottom/width/height).
  19934. * @type {string|Object} Object can be {ignoreSize: true}
  19935. * @readOnly
  19936. */
  19937. layoutMode: null,
  19938. init: function (option, parentModel, ecModel, extraOpt) {
  19939. /**
  19940. * @type {number}
  19941. * @readOnly
  19942. */
  19943. this.seriesIndex = this.componentIndex;
  19944. this.dataTask = createTask({
  19945. count: dataTaskCount,
  19946. reset: dataTaskReset
  19947. });
  19948. this.dataTask.context = {model: this};
  19949. this.mergeDefaultAndTheme(option, ecModel);
  19950. prepareSource(this);
  19951. var data = this.getInitialData(option, ecModel);
  19952. wrapData(data, this);
  19953. this.dataTask.context.data = data;
  19954. if (__DEV__) {
  19955. assert$1(data, 'getInitialData returned invalid data.');
  19956. }
  19957. /**
  19958. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19959. * @private
  19960. */
  19961. inner$4(this).dataBeforeProcessed = data;
  19962. // If we reverse the order (make data firstly, and then make
  19963. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19964. // cause data.graph.data !== data when using
  19965. // module:echarts/data/Graph or module:echarts/data/Tree.
  19966. // See module:echarts/data/helper/linkList
  19967. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19968. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19969. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19970. // Call `seriesModel.getRawData()` instead.
  19971. // this.restoreData();
  19972. autoSeriesName(this);
  19973. },
  19974. /**
  19975. * Util for merge default and theme to option
  19976. * @param {Object} option
  19977. * @param {module:echarts/model/Global} ecModel
  19978. */
  19979. mergeDefaultAndTheme: function (option, ecModel) {
  19980. var layoutMode = this.layoutMode;
  19981. var inputPositionParams = layoutMode
  19982. ? getLayoutParams(option) : {};
  19983. // Backward compat: using subType on theme.
  19984. // But if name duplicate between series subType
  19985. // (for example: parallel) add component mainType,
  19986. // add suffix 'Series'.
  19987. var themeSubType = this.subType;
  19988. if (ComponentModel.hasClass(themeSubType)) {
  19989. themeSubType += 'Series';
  19990. }
  19991. merge(
  19992. option,
  19993. ecModel.getTheme().get(this.subType)
  19994. );
  19995. merge(option, this.getDefaultOption());
  19996. // Default label emphasis `show`
  19997. defaultEmphasis(option, 'label', ['show']);
  19998. this.fillDataTextStyle(option.data);
  19999. if (layoutMode) {
  20000. mergeLayoutParam(option, inputPositionParams, layoutMode);
  20001. }
  20002. },
  20003. mergeOption: function (newSeriesOption, ecModel) {
  20004. // this.settingTask.dirty();
  20005. newSeriesOption = merge(this.option, newSeriesOption, true);
  20006. this.fillDataTextStyle(newSeriesOption.data);
  20007. var layoutMode = this.layoutMode;
  20008. if (layoutMode) {
  20009. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  20010. }
  20011. prepareSource(this);
  20012. var data = this.getInitialData(newSeriesOption, ecModel);
  20013. wrapData(data, this);
  20014. this.dataTask.dirty();
  20015. this.dataTask.context.data = data;
  20016. inner$4(this).dataBeforeProcessed = data;
  20017. autoSeriesName(this);
  20018. },
  20019. fillDataTextStyle: function (data) {
  20020. // Default data label emphasis `show`
  20021. // FIXME Tree structure data ?
  20022. // FIXME Performance ?
  20023. if (data && !isTypedArray(data)) {
  20024. var props = ['show'];
  20025. for (var i = 0; i < data.length; i++) {
  20026. if (data[i] && data[i].label) {
  20027. defaultEmphasis(data[i], 'label', props);
  20028. }
  20029. }
  20030. }
  20031. },
  20032. /**
  20033. * Init a data structure from data related option in series
  20034. * Must be overwritten
  20035. */
  20036. getInitialData: function () {},
  20037. /**
  20038. * Append data to list
  20039. * @param {Object} params
  20040. * @param {Array|TypedArray} params.data
  20041. */
  20042. appendData: function (params) {
  20043. // FIXME ???
  20044. // (1) If data from dataset, forbidden append.
  20045. // (2) support append data of dataset.
  20046. var data = this.getRawData();
  20047. data.appendData(params.data);
  20048. },
  20049. /**
  20050. * Consider some method like `filter`, `map` need make new data,
  20051. * We should make sure that `seriesModel.getData()` get correct
  20052. * data in the stream procedure. So we fetch data from upstream
  20053. * each time `task.perform` called.
  20054. * @param {string} [dataType]
  20055. * @return {module:echarts/data/List}
  20056. */
  20057. getData: function (dataType) {
  20058. var task = getCurrentTask(this);
  20059. if (task) {
  20060. var data = task.context.data;
  20061. return dataType == null ? data : data.getLinkedData(dataType);
  20062. }
  20063. else {
  20064. // When series is not alive (that may happen when click toolbox
  20065. // restore or setOption with not merge mode), series data may
  20066. // be still need to judge animation or something when graphic
  20067. // elements want to know whether fade out.
  20068. return inner$4(this).data;
  20069. }
  20070. },
  20071. /**
  20072. * @param {module:echarts/data/List} data
  20073. */
  20074. setData: function (data) {
  20075. var task = getCurrentTask(this);
  20076. if (task) {
  20077. var context = task.context;
  20078. // Consider case: filter, data sample.
  20079. if (context.data !== data && task.modifyOutputEnd) {
  20080. task.setOutputEnd(data.count());
  20081. }
  20082. context.outputData = data;
  20083. // Caution: setData should update context.data,
  20084. // Because getData may be called multiply in a
  20085. // single stage and expect to get the data just
  20086. // set. (For example, AxisProxy, x y both call
  20087. // getData and setDate sequentially).
  20088. // So the context.data should be fetched from
  20089. // upstream each time when a stage starts to be
  20090. // performed.
  20091. if (task !== this.dataTask) {
  20092. context.data = data;
  20093. }
  20094. }
  20095. inner$4(this).data = data;
  20096. },
  20097. /**
  20098. * @see {module:echarts/data/helper/sourceHelper#getSource}
  20099. * @return {module:echarts/data/Source} source
  20100. */
  20101. getSource: function () {
  20102. return getSource(this);
  20103. },
  20104. /**
  20105. * Get data before processed
  20106. * @return {module:echarts/data/List}
  20107. */
  20108. getRawData: function () {
  20109. return inner$4(this).dataBeforeProcessed;
  20110. },
  20111. /**
  20112. * Get base axis if has coordinate system and has axis.
  20113. * By default use coordSys.getBaseAxis();
  20114. * Can be overrided for some chart.
  20115. * @return {type} description
  20116. */
  20117. getBaseAxis: function () {
  20118. var coordSys = this.coordinateSystem;
  20119. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  20120. },
  20121. // FIXME
  20122. /**
  20123. * Default tooltip formatter
  20124. *
  20125. * @param {number} dataIndex
  20126. * @param {boolean} [multipleSeries=false]
  20127. * @param {number} [dataType]
  20128. */
  20129. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  20130. function formatArrayValue(value) {
  20131. // ??? TODO refactor these logic.
  20132. // check: category-no-encode-has-axis-data in dataset.html
  20133. var vertially = reduce(value, function (vertially, val, idx) {
  20134. var dimItem = data.getDimensionInfo(idx);
  20135. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  20136. }, 0);
  20137. var result = [];
  20138. tooltipDims.length
  20139. ? each$1(tooltipDims, function (dim) {
  20140. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  20141. })
  20142. // By default, all dims is used on tooltip.
  20143. : each$1(value, setEachItem);
  20144. function setEachItem(val, dim) {
  20145. var dimInfo = data.getDimensionInfo(dim);
  20146. // If `dimInfo.tooltip` is not set, show tooltip.
  20147. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  20148. return;
  20149. }
  20150. var dimType = dimInfo.type;
  20151. var dimHead = getTooltipMarker({color: color, type: 'subItem'});
  20152. var valStr = (vertially
  20153. ? dimHead + encodeHTML(dimInfo.displayName || '-') + ': '
  20154. : ''
  20155. )
  20156. // FIXME should not format time for raw data?
  20157. + encodeHTML(dimType === 'ordinal'
  20158. ? val + ''
  20159. : dimType === 'time'
  20160. ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val))
  20161. : addCommas(val)
  20162. );
  20163. valStr && result.push(valStr);
  20164. }
  20165. return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', ');
  20166. }
  20167. function formatSingleValue(val) {
  20168. return encodeHTML(addCommas(val));
  20169. }
  20170. var data = this.getData();
  20171. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20172. var tooltipDimLen = tooltipDims.length;
  20173. var value = this.getRawValue(dataIndex);
  20174. var isValueArr = isArray(value);
  20175. var color = data.getItemVisual(dataIndex, 'color');
  20176. if (isObject$1(color) && color.colorStops) {
  20177. color = (color.colorStops[0] || {}).color;
  20178. }
  20179. color = color || 'transparent';
  20180. // Complicated rule for pretty tooltip.
  20181. var formattedValue = (tooltipDimLen > 1 || (isValueArr && !tooltipDimLen))
  20182. ? formatArrayValue(value)
  20183. : tooltipDimLen
  20184. ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0]))
  20185. : formatSingleValue(isValueArr ? value[0] : value);
  20186. var colorEl = getTooltipMarker(color);
  20187. var name = data.getName(dataIndex);
  20188. var seriesName = this.name;
  20189. if (!isNameSpecified(this)) {
  20190. seriesName = '';
  20191. }
  20192. seriesName = seriesName
  20193. ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ')
  20194. : '';
  20195. return !multipleSeries
  20196. ? seriesName + colorEl
  20197. + (name
  20198. ? encodeHTML(name) + ': ' + formattedValue
  20199. : formattedValue
  20200. )
  20201. : colorEl + seriesName + formattedValue;
  20202. },
  20203. /**
  20204. * @return {boolean}
  20205. */
  20206. isAnimationEnabled: function () {
  20207. if (env$1.node) {
  20208. return false;
  20209. }
  20210. var animationEnabled = this.getShallow('animation');
  20211. if (animationEnabled) {
  20212. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20213. animationEnabled = false;
  20214. }
  20215. }
  20216. return animationEnabled;
  20217. },
  20218. restoreData: function () {
  20219. this.dataTask.dirty();
  20220. },
  20221. getColorFromPalette: function (name, scope, requestColorNum) {
  20222. var ecModel = this.ecModel;
  20223. // PENDING
  20224. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20225. if (!color) {
  20226. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20227. }
  20228. return color;
  20229. },
  20230. /**
  20231. * Use `data.mapDimension(coordDim, true)` instead.
  20232. * @deprecated
  20233. */
  20234. coordDimToDataDim: function (coordDim) {
  20235. return this.getRawData().mapDimension(coordDim, true);
  20236. },
  20237. /**
  20238. * Get progressive rendering count each step
  20239. * @return {number}
  20240. */
  20241. getProgressive: function () {
  20242. return this.get('progressive');
  20243. },
  20244. /**
  20245. * Get progressive rendering count each step
  20246. * @return {number}
  20247. */
  20248. getProgressiveThreshold: function () {
  20249. return this.get('progressiveThreshold');
  20250. },
  20251. /**
  20252. * Get data indices for show tooltip content. See tooltip.
  20253. * @abstract
  20254. * @param {Array.<string>|string} dim
  20255. * @param {Array.<number>} value
  20256. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20257. * @return {Object} {dataIndices, nestestValue}.
  20258. */
  20259. getAxisTooltipData: null,
  20260. /**
  20261. * See tooltip.
  20262. * @abstract
  20263. * @param {number} dataIndex
  20264. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20265. */
  20266. getTooltipPosition: null,
  20267. /**
  20268. * @see {module:echarts/stream/Scheduler}
  20269. */
  20270. pipeTask: null,
  20271. /**
  20272. * Convinient for override in extended class.
  20273. * @protected
  20274. * @type {Function}
  20275. */
  20276. preventIncremental: null,
  20277. /**
  20278. * @public
  20279. * @readOnly
  20280. * @type {Object}
  20281. */
  20282. pipelineContext: null
  20283. });
  20284. mixin(SeriesModel, dataFormatMixin);
  20285. mixin(SeriesModel, colorPaletteMixin);
  20286. /**
  20287. * MUST be called after `prepareSource` called
  20288. * Here we need to make auto series, especially for auto legend. But we
  20289. * do not modify series.name in option to avoid side effects.
  20290. */
  20291. function autoSeriesName(seriesModel) {
  20292. // User specified name has higher priority, otherwise it may cause
  20293. // series can not be queried unexpectedly.
  20294. var name = seriesModel.name;
  20295. if (!isNameSpecified(seriesModel)) {
  20296. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20297. }
  20298. }
  20299. function getSeriesAutoName(seriesModel) {
  20300. var data = seriesModel.getRawData();
  20301. var dataDims = data.mapDimension('seriesName', true);
  20302. var nameArr = [];
  20303. each$1(dataDims, function (dataDim) {
  20304. var dimInfo = data.getDimensionInfo(dataDim);
  20305. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20306. });
  20307. return nameArr.join(' ');
  20308. }
  20309. function dataTaskCount(context) {
  20310. return context.model.getRawData().count();
  20311. }
  20312. function dataTaskReset(context) {
  20313. var seriesModel = context.model;
  20314. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20315. return dataTaskProgress;
  20316. }
  20317. function dataTaskProgress(param, context) {
  20318. // Avoid repead cloneShallow when data just created in reset.
  20319. if (param.end > context.outputData.count()) {
  20320. context.model.getRawData().cloneShallow(context.outputData);
  20321. }
  20322. }
  20323. // TODO refactor
  20324. function wrapData(data, seriesModel) {
  20325. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20326. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20327. });
  20328. }
  20329. function onDataSelfChange(seriesModel) {
  20330. var task = getCurrentTask(seriesModel);
  20331. if (task) {
  20332. // Consider case: filter, selectRange
  20333. task.setOutputEnd(this.count());
  20334. }
  20335. }
  20336. function getCurrentTask(seriesModel) {
  20337. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20338. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20339. if (pipeline) {
  20340. // When pipline finished, the currrentTask keep the last
  20341. // task (renderTask).
  20342. var task = pipeline.currentTask;
  20343. if (task) {
  20344. var agentStubMap = task.agentStubMap;
  20345. if (agentStubMap) {
  20346. task = agentStubMap.get(seriesModel.uid);
  20347. }
  20348. }
  20349. return task;
  20350. }
  20351. }
  20352. /*
  20353. * Licensed to the Apache Software Foundation (ASF) under one
  20354. * or more contributor license agreements. See the NOTICE file
  20355. * distributed with this work for additional information
  20356. * regarding copyright ownership. The ASF licenses this file
  20357. * to you under the Apache License, Version 2.0 (the
  20358. * "License"); you may not use this file except in compliance
  20359. * with the License. You may obtain a copy of the License at
  20360. *
  20361. * http://www.apache.org/licenses/LICENSE-2.0
  20362. *
  20363. * Unless required by applicable law or agreed to in writing,
  20364. * software distributed under the License is distributed on an
  20365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20366. * KIND, either express or implied. See the License for the
  20367. * specific language governing permissions and limitations
  20368. * under the License.
  20369. */
  20370. var Component = function () {
  20371. /**
  20372. * @type {module:zrender/container/Group}
  20373. * @readOnly
  20374. */
  20375. this.group = new Group();
  20376. /**
  20377. * @type {string}
  20378. * @readOnly
  20379. */
  20380. this.uid = getUID('viewComponent');
  20381. };
  20382. Component.prototype = {
  20383. constructor: Component,
  20384. init: function (ecModel, api) {},
  20385. render: function (componentModel, ecModel, api, payload) {},
  20386. dispose: function () {}
  20387. };
  20388. var componentProto = Component.prototype;
  20389. componentProto.updateView
  20390. = componentProto.updateLayout
  20391. = componentProto.updateVisual
  20392. = function (seriesModel, ecModel, api, payload) {
  20393. // Do nothing;
  20394. };
  20395. // Enable Component.extend.
  20396. enableClassExtend(Component);
  20397. // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20398. enableClassManagement(Component, {registerWhenExtend: true});
  20399. /*
  20400. * Licensed to the Apache Software Foundation (ASF) under one
  20401. * or more contributor license agreements. See the NOTICE file
  20402. * distributed with this work for additional information
  20403. * regarding copyright ownership. The ASF licenses this file
  20404. * to you under the Apache License, Version 2.0 (the
  20405. * "License"); you may not use this file except in compliance
  20406. * with the License. You may obtain a copy of the License at
  20407. *
  20408. * http://www.apache.org/licenses/LICENSE-2.0
  20409. *
  20410. * Unless required by applicable law or agreed to in writing,
  20411. * software distributed under the License is distributed on an
  20412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20413. * KIND, either express or implied. See the License for the
  20414. * specific language governing permissions and limitations
  20415. * under the License.
  20416. */
  20417. /**
  20418. * @return {string} If large mode changed, return string 'reset';
  20419. */
  20420. var createRenderPlanner = function () {
  20421. var inner = makeInner();
  20422. return function (seriesModel) {
  20423. var fields = inner(seriesModel);
  20424. var pipelineContext = seriesModel.pipelineContext;
  20425. var originalLarge = fields.large;
  20426. var originalProgressive = fields.progressiveRender;
  20427. var large = fields.large = pipelineContext.large;
  20428. var progressive = fields.progressiveRender = pipelineContext.progressiveRender;
  20429. return !!((originalLarge ^ large) || (originalProgressive ^ progressive)) && 'reset';
  20430. };
  20431. };
  20432. /*
  20433. * Licensed to the Apache Software Foundation (ASF) under one
  20434. * or more contributor license agreements. See the NOTICE file
  20435. * distributed with this work for additional information
  20436. * regarding copyright ownership. The ASF licenses this file
  20437. * to you under the Apache License, Version 2.0 (the
  20438. * "License"); you may not use this file except in compliance
  20439. * with the License. You may obtain a copy of the License at
  20440. *
  20441. * http://www.apache.org/licenses/LICENSE-2.0
  20442. *
  20443. * Unless required by applicable law or agreed to in writing,
  20444. * software distributed under the License is distributed on an
  20445. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20446. * KIND, either express or implied. See the License for the
  20447. * specific language governing permissions and limitations
  20448. * under the License.
  20449. */
  20450. var inner$5 = makeInner();
  20451. var renderPlanner = createRenderPlanner();
  20452. function Chart() {
  20453. /**
  20454. * @type {module:zrender/container/Group}
  20455. * @readOnly
  20456. */
  20457. this.group = new Group();
  20458. /**
  20459. * @type {string}
  20460. * @readOnly
  20461. */
  20462. this.uid = getUID('viewChart');
  20463. this.renderTask = createTask({
  20464. plan: renderTaskPlan,
  20465. reset: renderTaskReset
  20466. });
  20467. this.renderTask.context = {view: this};
  20468. }
  20469. Chart.prototype = {
  20470. type: 'chart',
  20471. /**
  20472. * Init the chart.
  20473. * @param {module:echarts/model/Global} ecModel
  20474. * @param {module:echarts/ExtensionAPI} api
  20475. */
  20476. init: function (ecModel, api) {},
  20477. /**
  20478. * Render the chart.
  20479. * @param {module:echarts/model/Series} seriesModel
  20480. * @param {module:echarts/model/Global} ecModel
  20481. * @param {module:echarts/ExtensionAPI} api
  20482. * @param {Object} payload
  20483. */
  20484. render: function (seriesModel, ecModel, api, payload) {},
  20485. /**
  20486. * Highlight series or specified data item.
  20487. * @param {module:echarts/model/Series} seriesModel
  20488. * @param {module:echarts/model/Global} ecModel
  20489. * @param {module:echarts/ExtensionAPI} api
  20490. * @param {Object} payload
  20491. */
  20492. highlight: function (seriesModel, ecModel, api, payload) {
  20493. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20494. },
  20495. /**
  20496. * Downplay series or specified data item.
  20497. * @param {module:echarts/model/Series} seriesModel
  20498. * @param {module:echarts/model/Global} ecModel
  20499. * @param {module:echarts/ExtensionAPI} api
  20500. * @param {Object} payload
  20501. */
  20502. downplay: function (seriesModel, ecModel, api, payload) {
  20503. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20504. },
  20505. /**
  20506. * Remove self.
  20507. * @param {module:echarts/model/Global} ecModel
  20508. * @param {module:echarts/ExtensionAPI} api
  20509. */
  20510. remove: function (ecModel, api) {
  20511. this.group.removeAll();
  20512. },
  20513. /**
  20514. * Dispose self.
  20515. * @param {module:echarts/model/Global} ecModel
  20516. * @param {module:echarts/ExtensionAPI} api
  20517. */
  20518. dispose: function () {},
  20519. /**
  20520. * Rendering preparation in progressive mode.
  20521. * @param {module:echarts/model/Series} seriesModel
  20522. * @param {module:echarts/model/Global} ecModel
  20523. * @param {module:echarts/ExtensionAPI} api
  20524. * @param {Object} payload
  20525. */
  20526. incrementalPrepareRender: null,
  20527. /**
  20528. * Render in progressive mode.
  20529. * @param {module:echarts/model/Series} seriesModel
  20530. * @param {module:echarts/model/Global} ecModel
  20531. * @param {module:echarts/ExtensionAPI} api
  20532. * @param {Object} payload
  20533. */
  20534. incrementalRender: null,
  20535. /**
  20536. * Update transform directly.
  20537. * @param {module:echarts/model/Series} seriesModel
  20538. * @param {module:echarts/model/Global} ecModel
  20539. * @param {module:echarts/ExtensionAPI} api
  20540. * @param {Object} payload
  20541. * @return {Object} {update: true}
  20542. */
  20543. updateTransform: null
  20544. /**
  20545. * The view contains the given point.
  20546. * @interface
  20547. * @param {Array.<number>} point
  20548. * @return {boolean}
  20549. */
  20550. // containPoint: function () {}
  20551. };
  20552. var chartProto = Chart.prototype;
  20553. chartProto.updateView
  20554. = chartProto.updateLayout
  20555. = chartProto.updateVisual
  20556. = function (seriesModel, ecModel, api, payload) {
  20557. this.render(seriesModel, ecModel, api, payload);
  20558. };
  20559. /**
  20560. * Set state of single element
  20561. * @param {module:zrender/Element} el
  20562. * @param {string} state
  20563. */
  20564. function elSetState(el, state) {
  20565. if (el) {
  20566. el.trigger(state);
  20567. if (el.type === 'group') {
  20568. for (var i = 0; i < el.childCount(); i++) {
  20569. elSetState(el.childAt(i), state);
  20570. }
  20571. }
  20572. }
  20573. }
  20574. /**
  20575. * @param {module:echarts/data/List} data
  20576. * @param {Object} payload
  20577. * @param {string} state 'normal'|'emphasis'
  20578. */
  20579. function toggleHighlight(data, payload, state) {
  20580. var dataIndex = queryDataIndex(data, payload);
  20581. if (dataIndex != null) {
  20582. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  20583. elSetState(data.getItemGraphicEl(dataIdx), state);
  20584. });
  20585. }
  20586. else {
  20587. data.eachItemGraphicEl(function (el) {
  20588. elSetState(el, state);
  20589. });
  20590. }
  20591. }
  20592. // Enable Chart.extend.
  20593. enableClassExtend(Chart, ['dispose']);
  20594. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20595. enableClassManagement(Chart, {registerWhenExtend: true});
  20596. Chart.markUpdateMethod = function (payload, methodName) {
  20597. inner$5(payload).updateMethod = methodName;
  20598. };
  20599. function renderTaskPlan(context) {
  20600. return renderPlanner(context.model);
  20601. }
  20602. function renderTaskReset(context) {
  20603. var seriesModel = context.model;
  20604. var ecModel = context.ecModel;
  20605. var api = context.api;
  20606. var payload = context.payload;
  20607. // ???! remove updateView updateVisual
  20608. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20609. var view = context.view;
  20610. var updateMethod = payload && inner$5(payload).updateMethod;
  20611. var methodName = progressiveRender
  20612. ? 'incrementalPrepareRender'
  20613. : (updateMethod && view[updateMethod])
  20614. ? updateMethod
  20615. // `appendData` is also supported when data amount
  20616. // is less than progressive threshold.
  20617. : 'render';
  20618. if (methodName !== 'render') {
  20619. view[methodName](seriesModel, ecModel, api, payload);
  20620. }
  20621. return progressMethodMap[methodName];
  20622. }
  20623. var progressMethodMap = {
  20624. incrementalPrepareRender: {
  20625. progress: function (params, context) {
  20626. context.view.incrementalRender(
  20627. params, context.model, context.ecModel, context.api, context.payload
  20628. );
  20629. }
  20630. },
  20631. render: {
  20632. // Put view.render in `progress` to support appendData. But in this case
  20633. // view.render should not be called in reset, otherwise it will be called
  20634. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20635. // in any cases.
  20636. forceFirstProgress: true,
  20637. progress: function (params, context) {
  20638. context.view.render(
  20639. context.model, context.ecModel, context.api, context.payload
  20640. );
  20641. }
  20642. }
  20643. };
  20644. /*
  20645. * Licensed to the Apache Software Foundation (ASF) under one
  20646. * or more contributor license agreements. See the NOTICE file
  20647. * distributed with this work for additional information
  20648. * regarding copyright ownership. The ASF licenses this file
  20649. * to you under the Apache License, Version 2.0 (the
  20650. * "License"); you may not use this file except in compliance
  20651. * with the License. You may obtain a copy of the License at
  20652. *
  20653. * http://www.apache.org/licenses/LICENSE-2.0
  20654. *
  20655. * Unless required by applicable law or agreed to in writing,
  20656. * software distributed under the License is distributed on an
  20657. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20658. * KIND, either express or implied. See the License for the
  20659. * specific language governing permissions and limitations
  20660. * under the License.
  20661. */
  20662. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  20663. var RATE = '\0__throttleRate';
  20664. var THROTTLE_TYPE = '\0__throttleType';
  20665. /**
  20666. * @public
  20667. * @param {(Function)} fn
  20668. * @param {number} [delay=0] Unit: ms.
  20669. * @param {boolean} [debounce=false]
  20670. * true: If call interval less than `delay`, only the last call works.
  20671. * false: If call interval less than `delay, call works on fixed rate.
  20672. * @return {(Function)} throttled fn.
  20673. */
  20674. function throttle(fn, delay, debounce) {
  20675. var currCall;
  20676. var lastCall = 0;
  20677. var lastExec = 0;
  20678. var timer = null;
  20679. var diff;
  20680. var scope;
  20681. var args;
  20682. var debounceNextCall;
  20683. delay = delay || 0;
  20684. function exec() {
  20685. lastExec = (new Date()).getTime();
  20686. timer = null;
  20687. fn.apply(scope, args || []);
  20688. }
  20689. var cb = function () {
  20690. currCall = (new Date()).getTime();
  20691. scope = this;
  20692. args = arguments;
  20693. var thisDelay = debounceNextCall || delay;
  20694. var thisDebounce = debounceNextCall || debounce;
  20695. debounceNextCall = null;
  20696. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20697. clearTimeout(timer);
  20698. // Here we should make sure that: the `exec` SHOULD NOT be called later
  20699. // than a new call of `cb`, that is, preserving the command order. Consider
  20700. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20701. // happens, either the `exec` is called dierectly, or the call is delayed.
  20702. // But the delayed call should never be later than next call of `cb`. Under
  20703. // this assurance, we can simply update view state each time `dispatchAction`
  20704. // triggered by user roaming, but not need to add extra code to avoid the
  20705. // state being "rolled-back".
  20706. if (thisDebounce) {
  20707. timer = setTimeout(exec, thisDelay);
  20708. }
  20709. else {
  20710. if (diff >= 0) {
  20711. exec();
  20712. }
  20713. else {
  20714. timer = setTimeout(exec, -diff);
  20715. }
  20716. }
  20717. lastCall = currCall;
  20718. };
  20719. /**
  20720. * Clear throttle.
  20721. * @public
  20722. */
  20723. cb.clear = function () {
  20724. if (timer) {
  20725. clearTimeout(timer);
  20726. timer = null;
  20727. }
  20728. };
  20729. /**
  20730. * Enable debounce once.
  20731. */
  20732. cb.debounceNextCall = function (debounceDelay) {
  20733. debounceNextCall = debounceDelay;
  20734. };
  20735. return cb;
  20736. }
  20737. /**
  20738. * Create throttle method or update throttle rate.
  20739. *
  20740. * @example
  20741. * ComponentView.prototype.render = function () {
  20742. * ...
  20743. * throttle.createOrUpdate(
  20744. * this,
  20745. * '_dispatchAction',
  20746. * this.model.get('throttle'),
  20747. * 'fixRate'
  20748. * );
  20749. * };
  20750. * ComponentView.prototype.remove = function () {
  20751. * throttle.clear(this, '_dispatchAction');
  20752. * };
  20753. * ComponentView.prototype.dispose = function () {
  20754. * throttle.clear(this, '_dispatchAction');
  20755. * };
  20756. *
  20757. * @public
  20758. * @param {Object} obj
  20759. * @param {string} fnAttr
  20760. * @param {number} [rate]
  20761. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  20762. * @return {Function} throttled function.
  20763. */
  20764. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  20765. var fn = obj[fnAttr];
  20766. if (!fn) {
  20767. return;
  20768. }
  20769. var originFn = fn[ORIGIN_METHOD] || fn;
  20770. var lastThrottleType = fn[THROTTLE_TYPE];
  20771. var lastRate = fn[RATE];
  20772. if (lastRate !== rate || lastThrottleType !== throttleType) {
  20773. if (rate == null || !throttleType) {
  20774. return (obj[fnAttr] = originFn);
  20775. }
  20776. fn = obj[fnAttr] = throttle(
  20777. originFn, rate, throttleType === 'debounce'
  20778. );
  20779. fn[ORIGIN_METHOD] = originFn;
  20780. fn[THROTTLE_TYPE] = throttleType;
  20781. fn[RATE] = rate;
  20782. }
  20783. return fn;
  20784. }
  20785. /**
  20786. * Clear throttle. Example see throttle.createOrUpdate.
  20787. *
  20788. * @public
  20789. * @param {Object} obj
  20790. * @param {string} fnAttr
  20791. */
  20792. function clear(obj, fnAttr) {
  20793. var fn = obj[fnAttr];
  20794. if (fn && fn[ORIGIN_METHOD]) {
  20795. obj[fnAttr] = fn[ORIGIN_METHOD];
  20796. }
  20797. }
  20798. /*
  20799. * Licensed to the Apache Software Foundation (ASF) under one
  20800. * or more contributor license agreements. See the NOTICE file
  20801. * distributed with this work for additional information
  20802. * regarding copyright ownership. The ASF licenses this file
  20803. * to you under the Apache License, Version 2.0 (the
  20804. * "License"); you may not use this file except in compliance
  20805. * with the License. You may obtain a copy of the License at
  20806. *
  20807. * http://www.apache.org/licenses/LICENSE-2.0
  20808. *
  20809. * Unless required by applicable law or agreed to in writing,
  20810. * software distributed under the License is distributed on an
  20811. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20812. * KIND, either express or implied. See the License for the
  20813. * specific language governing permissions and limitations
  20814. * under the License.
  20815. */
  20816. var seriesColor = {
  20817. createOnAllSeries: true,
  20818. performRawSeries: true,
  20819. reset: function (seriesModel, ecModel) {
  20820. var data = seriesModel.getData();
  20821. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.');
  20822. var color = seriesModel.get(colorAccessPath) // Set in itemStyle
  20823. || seriesModel.getColorFromPalette(
  20824. // TODO series count changed.
  20825. seriesModel.name, null, ecModel.getSeriesCount()
  20826. ); // Default color
  20827. // FIXME Set color function or use the platte color
  20828. data.setVisual('color', color);
  20829. // Only visible series has each data be visual encoded
  20830. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20831. if (typeof color === 'function' && !(color instanceof Gradient)) {
  20832. data.each(function (idx) {
  20833. data.setItemVisual(
  20834. idx, 'color', color(seriesModel.getDataParams(idx))
  20835. );
  20836. });
  20837. }
  20838. // itemStyle in each data item
  20839. var dataEach = function (data, idx) {
  20840. var itemModel = data.getItemModel(idx);
  20841. var color = itemModel.get(colorAccessPath, true);
  20842. if (color != null) {
  20843. data.setItemVisual(idx, 'color', color);
  20844. }
  20845. };
  20846. return { dataEach: data.hasItemOption ? dataEach : null };
  20847. }
  20848. }
  20849. };
  20850. /*
  20851. * Licensed to the Apache Software Foundation (ASF) under one
  20852. * or more contributor license agreements. See the NOTICE file
  20853. * distributed with this work for additional information
  20854. * regarding copyright ownership. The ASF licenses this file
  20855. * to you under the Apache License, Version 2.0 (the
  20856. * "License"); you may not use this file except in compliance
  20857. * with the License. You may obtain a copy of the License at
  20858. *
  20859. * http://www.apache.org/licenses/LICENSE-2.0
  20860. *
  20861. * Unless required by applicable law or agreed to in writing,
  20862. * software distributed under the License is distributed on an
  20863. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20864. * KIND, either express or implied. See the License for the
  20865. * specific language governing permissions and limitations
  20866. * under the License.
  20867. */
  20868. var lang = {
  20869. toolbox: {
  20870. brush: {
  20871. title: {
  20872. rect: '矩形选择',
  20873. polygon: '圈选',
  20874. lineX: '横向选择',
  20875. lineY: '纵向选择',
  20876. keep: '保持选择',
  20877. clear: '清除选择'
  20878. }
  20879. },
  20880. dataView: {
  20881. title: '数据视图',
  20882. lang: ['数据视图', '关闭', '刷新']
  20883. },
  20884. dataZoom: {
  20885. title: {
  20886. zoom: '区域缩放',
  20887. back: '区域缩放还原'
  20888. }
  20889. },
  20890. magicType: {
  20891. title: {
  20892. line: '切换为折线图',
  20893. bar: '切换为柱状图',
  20894. stack: '切换为堆叠',
  20895. tiled: '切换为平铺'
  20896. }
  20897. },
  20898. restore: {
  20899. title: '还原'
  20900. },
  20901. saveAsImage: {
  20902. title: '保存为图片',
  20903. lang: ['右键另存为图片']
  20904. }
  20905. },
  20906. series: {
  20907. typeNames: {
  20908. pie: '饼图',
  20909. bar: '柱状图',
  20910. line: '折线图',
  20911. scatter: '散点图',
  20912. effectScatter: '涟漪散点图',
  20913. radar: '雷达图',
  20914. tree: '树图',
  20915. treemap: '矩形树图',
  20916. boxplot: '箱型图',
  20917. candlestick: 'K线图',
  20918. k: 'K线图',
  20919. heatmap: '热力图',
  20920. map: '地图',
  20921. parallel: '平行坐标图',
  20922. lines: '线图',
  20923. graph: '关系图',
  20924. sankey: '桑基图',
  20925. funnel: '漏斗图',
  20926. gauge: '仪表盘图',
  20927. pictorialBar: '象形柱图',
  20928. themeRiver: '主题河流图',
  20929. sunburst: '旭日图'
  20930. }
  20931. },
  20932. aria: {
  20933. general: {
  20934. withTitle: '这是一个关于“{title}”的图表。',
  20935. withoutTitle: '这是一个图表,'
  20936. },
  20937. series: {
  20938. single: {
  20939. prefix: '',
  20940. withName: '图表类型是{seriesType},表示{seriesName}。',
  20941. withoutName: '图表类型是{seriesType}。'
  20942. },
  20943. multiple: {
  20944. prefix: '它由{seriesCount}个图表系列组成。',
  20945. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20946. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20947. separator: {
  20948. middle: ';',
  20949. end: '。'
  20950. }
  20951. }
  20952. },
  20953. data: {
  20954. allData: '其数据是——',
  20955. partialData: '其中,前{displayCnt}项是——',
  20956. withName: '{name}的数据是{value}',
  20957. withoutName: '{value}',
  20958. separator: {
  20959. middle: ',',
  20960. end: ''
  20961. }
  20962. }
  20963. }
  20964. };
  20965. /*
  20966. * Licensed to the Apache Software Foundation (ASF) under one
  20967. * or more contributor license agreements. See the NOTICE file
  20968. * distributed with this work for additional information
  20969. * regarding copyright ownership. The ASF licenses this file
  20970. * to you under the Apache License, Version 2.0 (the
  20971. * "License"); you may not use this file except in compliance
  20972. * with the License. You may obtain a copy of the License at
  20973. *
  20974. * http://www.apache.org/licenses/LICENSE-2.0
  20975. *
  20976. * Unless required by applicable law or agreed to in writing,
  20977. * software distributed under the License is distributed on an
  20978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20979. * KIND, either express or implied. See the License for the
  20980. * specific language governing permissions and limitations
  20981. * under the License.
  20982. */
  20983. var aria = function (dom, ecModel) {
  20984. var ariaModel = ecModel.getModel('aria');
  20985. if (!ariaModel.get('show')) {
  20986. return;
  20987. }
  20988. else if (ariaModel.get('description')) {
  20989. dom.setAttribute('aria-label', ariaModel.get('description'));
  20990. return;
  20991. }
  20992. var seriesCnt = 0;
  20993. ecModel.eachSeries(function (seriesModel, idx) {
  20994. ++seriesCnt;
  20995. }, this);
  20996. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20997. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20998. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20999. var ariaLabel;
  21000. if (seriesCnt < 1) {
  21001. // No series, no aria label
  21002. return;
  21003. }
  21004. else {
  21005. var title = getTitle();
  21006. if (title) {
  21007. ariaLabel = replace(getConfig('general.withTitle'), {
  21008. title: title
  21009. });
  21010. }
  21011. else {
  21012. ariaLabel = getConfig('general.withoutTitle');
  21013. }
  21014. var seriesLabels = [];
  21015. var prefix = seriesCnt > 1
  21016. ? 'series.multiple.prefix'
  21017. : 'series.single.prefix';
  21018. ariaLabel += replace(getConfig(prefix), { seriesCount: seriesCnt });
  21019. ecModel.eachSeries(function (seriesModel, idx) {
  21020. if (idx < displaySeriesCnt) {
  21021. var seriesLabel;
  21022. var seriesName = seriesModel.get('name');
  21023. var seriesTpl = 'series.'
  21024. + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  21025. seriesLabel = getConfig(seriesName
  21026. ? seriesTpl + 'withName'
  21027. : seriesTpl + 'withoutName');
  21028. seriesLabel = replace(seriesLabel, {
  21029. seriesId: seriesModel.seriesIndex,
  21030. seriesName: seriesModel.get('name'),
  21031. seriesType: getSeriesTypeName(seriesModel.subType)
  21032. });
  21033. var data = seriesModel.getData();
  21034. window.data = data;
  21035. if (data.count() > maxDataCnt) {
  21036. // Show part of data
  21037. seriesLabel += replace(getConfig('data.partialData'), {
  21038. displayCnt: maxDataCnt
  21039. });
  21040. }
  21041. else {
  21042. seriesLabel += getConfig('data.allData');
  21043. }
  21044. var dataLabels = [];
  21045. for (var i = 0; i < data.count(); i++) {
  21046. if (i < maxDataCnt) {
  21047. var name = data.getName(i);
  21048. var value = retrieveRawValue(data, i);
  21049. dataLabels.push(
  21050. replace(
  21051. name
  21052. ? getConfig('data.withName')
  21053. : getConfig('data.withoutName'),
  21054. {
  21055. name: name,
  21056. value: value
  21057. }
  21058. )
  21059. );
  21060. }
  21061. }
  21062. seriesLabel += dataLabels
  21063. .join(getConfig('data.separator.middle'))
  21064. + getConfig('data.separator.end');
  21065. seriesLabels.push(seriesLabel);
  21066. }
  21067. });
  21068. ariaLabel += seriesLabels
  21069. .join(getConfig('series.multiple.separator.middle'))
  21070. + getConfig('series.multiple.separator.end');
  21071. dom.setAttribute('aria-label', ariaLabel);
  21072. }
  21073. function replace(str, keyValues) {
  21074. if (typeof str !== 'string') {
  21075. return str;
  21076. }
  21077. var result = str;
  21078. each$1(keyValues, function (value, key) {
  21079. result = result.replace(
  21080. new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'),
  21081. value
  21082. );
  21083. });
  21084. return result;
  21085. }
  21086. function getConfig(path) {
  21087. var userConfig = ariaModel.get(path);
  21088. if (userConfig == null) {
  21089. var pathArr = path.split('.');
  21090. var result = lang.aria;
  21091. for (var i = 0; i < pathArr.length; ++i) {
  21092. result = result[pathArr[i]];
  21093. }
  21094. return result;
  21095. }
  21096. else {
  21097. return userConfig;
  21098. }
  21099. }
  21100. function getTitle() {
  21101. var title = ecModel.getModel('title').option;
  21102. if (title && title.length) {
  21103. title = title[0];
  21104. }
  21105. return title && title.text;
  21106. }
  21107. function getSeriesTypeName(type) {
  21108. return lang.series.typeNames[type] || '自定义图';
  21109. }
  21110. };
  21111. /*
  21112. * Licensed to the Apache Software Foundation (ASF) under one
  21113. * or more contributor license agreements. See the NOTICE file
  21114. * distributed with this work for additional information
  21115. * regarding copyright ownership. The ASF licenses this file
  21116. * to you under the Apache License, Version 2.0 (the
  21117. * "License"); you may not use this file except in compliance
  21118. * with the License. You may obtain a copy of the License at
  21119. *
  21120. * http://www.apache.org/licenses/LICENSE-2.0
  21121. *
  21122. * Unless required by applicable law or agreed to in writing,
  21123. * software distributed under the License is distributed on an
  21124. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21125. * KIND, either express or implied. See the License for the
  21126. * specific language governing permissions and limitations
  21127. * under the License.
  21128. */
  21129. var PI$1 = Math.PI;
  21130. /**
  21131. * @param {module:echarts/ExtensionAPI} api
  21132. * @param {Object} [opts]
  21133. * @param {string} [opts.text]
  21134. * @param {string} [opts.color]
  21135. * @param {string} [opts.textColor]
  21136. * @return {module:zrender/Element}
  21137. */
  21138. var loadingDefault = function (api, opts) {
  21139. opts = opts || {};
  21140. defaults(opts, {
  21141. text: 'loading',
  21142. color: '#c23531',
  21143. textColor: '#000',
  21144. maskColor: 'rgba(255, 255, 255, 0.8)',
  21145. zlevel: 0
  21146. });
  21147. var mask = new Rect({
  21148. style: {
  21149. fill: opts.maskColor
  21150. },
  21151. zlevel: opts.zlevel,
  21152. z: 10000
  21153. });
  21154. var arc = new Arc({
  21155. shape: {
  21156. startAngle: -PI$1 / 2,
  21157. endAngle: -PI$1 / 2 + 0.1,
  21158. r: 10
  21159. },
  21160. style: {
  21161. stroke: opts.color,
  21162. lineCap: 'round',
  21163. lineWidth: 5
  21164. },
  21165. zlevel: opts.zlevel,
  21166. z: 10001
  21167. });
  21168. var labelRect = new Rect({
  21169. style: {
  21170. fill: 'none',
  21171. text: opts.text,
  21172. textPosition: 'right',
  21173. textDistance: 10,
  21174. textFill: opts.textColor
  21175. },
  21176. zlevel: opts.zlevel,
  21177. z: 10001
  21178. });
  21179. arc.animateShape(true)
  21180. .when(1000, {
  21181. endAngle: PI$1 * 3 / 2
  21182. })
  21183. .start('circularInOut');
  21184. arc.animateShape(true)
  21185. .when(1000, {
  21186. startAngle: PI$1 * 3 / 2
  21187. })
  21188. .delay(300)
  21189. .start('circularInOut');
  21190. var group = new Group();
  21191. group.add(arc);
  21192. group.add(labelRect);
  21193. group.add(mask);
  21194. // Inject resize
  21195. group.resize = function () {
  21196. var cx = api.getWidth() / 2;
  21197. var cy = api.getHeight() / 2;
  21198. arc.setShape({
  21199. cx: cx,
  21200. cy: cy
  21201. });
  21202. var r = arc.shape.r;
  21203. labelRect.setShape({
  21204. x: cx - r,
  21205. y: cy - r,
  21206. width: r * 2,
  21207. height: r * 2
  21208. });
  21209. mask.setShape({
  21210. x: 0,
  21211. y: 0,
  21212. width: api.getWidth(),
  21213. height: api.getHeight()
  21214. });
  21215. };
  21216. group.resize();
  21217. return group;
  21218. };
  21219. /*
  21220. * Licensed to the Apache Software Foundation (ASF) under one
  21221. * or more contributor license agreements. See the NOTICE file
  21222. * distributed with this work for additional information
  21223. * regarding copyright ownership. The ASF licenses this file
  21224. * to you under the Apache License, Version 2.0 (the
  21225. * "License"); you may not use this file except in compliance
  21226. * with the License. You may obtain a copy of the License at
  21227. *
  21228. * http://www.apache.org/licenses/LICENSE-2.0
  21229. *
  21230. * Unless required by applicable law or agreed to in writing,
  21231. * software distributed under the License is distributed on an
  21232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21233. * KIND, either express or implied. See the License for the
  21234. * specific language governing permissions and limitations
  21235. * under the License.
  21236. */
  21237. /**
  21238. * @module echarts/stream/Scheduler
  21239. */
  21240. /**
  21241. * @constructor
  21242. */
  21243. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21244. this.ecInstance = ecInstance;
  21245. this.api = api;
  21246. this.unfinished;
  21247. // Fix current processors in case that in some rear cases that
  21248. // processors might be registered after echarts instance created.
  21249. // Register processors incrementally for a echarts instance is
  21250. // not supported by this stream architecture.
  21251. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21252. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21253. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21254. /**
  21255. * @private
  21256. * @type {
  21257. * [handlerUID: string]: {
  21258. * seriesTaskMap?: {
  21259. * [seriesUID: string]: Task
  21260. * },
  21261. * overallTask?: Task
  21262. * }
  21263. * }
  21264. */
  21265. this._stageTaskMap = createHashMap();
  21266. }
  21267. var proto = Scheduler.prototype;
  21268. /**
  21269. * @param {module:echarts/model/Global} ecModel
  21270. * @param {Object} payload
  21271. */
  21272. proto.restoreData = function (ecModel, payload) {
  21273. // TODO: Only restroe needed series and components, but not all components.
  21274. // Currently `restoreData` of all of the series and component will be called.
  21275. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21276. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21277. // and some components like coordinate system, axes, dataZoom, visualMap only
  21278. // need their target series refresh.
  21279. // (1) If we are implementing this feature some day, we should consider these cases:
  21280. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21281. // on the settings of `dataZoom`), it should be re-performed if the component
  21282. // is modified by `setOption`.
  21283. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21284. // it should be re-performed when the result array of `getTargetSeries` changed.
  21285. // We use `dependencies` to cover these issues.
  21286. // (3) How to update target series when coordinate system related components modified.
  21287. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21288. // and this case all of the tasks will be set as dirty.
  21289. ecModel.restoreData(payload);
  21290. // Theoretically an overall task not only depends on each of its target series, but also
  21291. // depends on all of the series.
  21292. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21293. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21294. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21295. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21296. // probably cause state chaos (consider `dataZoomProcessor`).
  21297. this._stageTaskMap.each(function (taskRecord) {
  21298. var overallTask = taskRecord.overallTask;
  21299. overallTask && overallTask.dirty();
  21300. });
  21301. };
  21302. // If seriesModel provided, incremental threshold is check by series data.
  21303. proto.getPerformArgs = function (task, isBlock) {
  21304. // For overall task
  21305. if (!task.__pipeline) {
  21306. return;
  21307. }
  21308. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21309. var pCtx = pipeline.context;
  21310. var incremental = !isBlock
  21311. && pipeline.progressiveEnabled
  21312. && (!pCtx || pCtx.progressiveRender)
  21313. && task.__idxInPipeline > pipeline.blockIndex;
  21314. var step = incremental ? pipeline.step : null;
  21315. var modDataCount = pCtx && pCtx.modDataCount;
  21316. var modBy = modDataCount != null ? Math.ceil(modDataCount / step): null;
  21317. return {step: step, modBy: modBy, modDataCount: modDataCount};
  21318. };
  21319. proto.getPipeline = function (pipelineId) {
  21320. return this._pipelineMap.get(pipelineId);
  21321. };
  21322. /**
  21323. * Current, progressive rendering starts from visual and layout.
  21324. * Always detect render mode in the same stage, avoiding that incorrect
  21325. * detection caused by data filtering.
  21326. * Caution:
  21327. * `updateStreamModes` use `seriesModel.getData()`.
  21328. */
  21329. proto.updateStreamModes = function (seriesModel, view) {
  21330. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21331. var data = seriesModel.getData();
  21332. var dataLen = data.count();
  21333. // `progressiveRender` means that can render progressively in each
  21334. // animation frame. Note that some types of series do not provide
  21335. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21336. // use the term `incremental` but not `progressive` to describe the
  21337. // case that `chart.appendData`.
  21338. var progressiveRender = pipeline.progressiveEnabled
  21339. && view.incrementalPrepareRender
  21340. && dataLen >= pipeline.threshold;
  21341. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold');
  21342. // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21343. // see `test/candlestick-large3.html`
  21344. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21345. seriesModel.pipelineContext = pipeline.context = {
  21346. progressiveRender: progressiveRender,
  21347. modDataCount: modDataCount,
  21348. large: large
  21349. };
  21350. };
  21351. proto.restorePipelines = function (ecModel) {
  21352. var scheduler = this;
  21353. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21354. ecModel.eachSeries(function (seriesModel) {
  21355. var progressive = seriesModel.getProgressive();
  21356. var pipelineId = seriesModel.uid;
  21357. pipelineMap.set(pipelineId, {
  21358. id: pipelineId,
  21359. head: null,
  21360. tail: null,
  21361. threshold: seriesModel.getProgressiveThreshold(),
  21362. progressiveEnabled: progressive
  21363. && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21364. blockIndex: -1,
  21365. step: Math.round(progressive || 700),
  21366. count: 0
  21367. });
  21368. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21369. });
  21370. };
  21371. proto.prepareStageTasks = function () {
  21372. var stageTaskMap = this._stageTaskMap;
  21373. var ecModel = this.ecInstance.getModel();
  21374. var api = this.api;
  21375. each$1(this._allHandlers, function (handler) {
  21376. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21377. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21378. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21379. }, this);
  21380. };
  21381. proto.prepareView = function (view, model, ecModel, api) {
  21382. var renderTask = view.renderTask;
  21383. var context = renderTask.context;
  21384. context.model = model;
  21385. context.ecModel = ecModel;
  21386. context.api = api;
  21387. renderTask.__block = !view.incrementalPrepareRender;
  21388. pipe(this, model, renderTask);
  21389. };
  21390. proto.performDataProcessorTasks = function (ecModel, payload) {
  21391. // If we do not use `block` here, it should be considered when to update modes.
  21392. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {block: true});
  21393. };
  21394. // opt
  21395. // opt.visualType: 'visual' or 'layout'
  21396. // opt.setDirty
  21397. proto.performVisualTasks = function (ecModel, payload, opt) {
  21398. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21399. };
  21400. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21401. opt = opt || {};
  21402. var unfinished;
  21403. each$1(stageHandlers, function (stageHandler, idx) {
  21404. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21405. return;
  21406. }
  21407. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21408. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21409. var overallTask = stageHandlerRecord.overallTask;
  21410. if (overallTask) {
  21411. var overallNeedDirty;
  21412. var agentStubMap = overallTask.agentStubMap;
  21413. agentStubMap.each(function (stub) {
  21414. if (needSetDirty(opt, stub)) {
  21415. stub.dirty();
  21416. overallNeedDirty = true;
  21417. }
  21418. });
  21419. overallNeedDirty && overallTask.dirty();
  21420. updatePayload(overallTask, payload);
  21421. var performArgs = scheduler.getPerformArgs(overallTask, opt.block);
  21422. // Execute stubs firstly, which may set the overall task dirty,
  21423. // then execute the overall task. And stub will call seriesModel.setData,
  21424. // which ensures that in the overallTask seriesModel.getData() will not
  21425. // return incorrect data.
  21426. agentStubMap.each(function (stub) {
  21427. stub.perform(performArgs);
  21428. });
  21429. unfinished |= overallTask.perform(performArgs);
  21430. }
  21431. else if (seriesTaskMap) {
  21432. seriesTaskMap.each(function (task, pipelineId) {
  21433. if (needSetDirty(opt, task)) {
  21434. task.dirty();
  21435. }
  21436. var performArgs = scheduler.getPerformArgs(task, opt.block);
  21437. performArgs.skip = !stageHandler.performRawSeries
  21438. && ecModel.isSeriesFiltered(task.context.model);
  21439. updatePayload(task, payload);
  21440. unfinished |= task.perform(performArgs);
  21441. });
  21442. }
  21443. });
  21444. function needSetDirty(opt, task) {
  21445. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21446. }
  21447. scheduler.unfinished |= unfinished;
  21448. }
  21449. proto.performSeriesTasks = function (ecModel) {
  21450. var unfinished;
  21451. ecModel.eachSeries(function (seriesModel) {
  21452. // Progress to the end for dataInit and dataRestore.
  21453. unfinished |= seriesModel.dataTask.perform();
  21454. });
  21455. this.unfinished |= unfinished;
  21456. };
  21457. proto.plan = function () {
  21458. // Travel pipelines, check block.
  21459. this._pipelineMap.each(function (pipeline) {
  21460. var task = pipeline.tail;
  21461. do {
  21462. if (task.__block) {
  21463. pipeline.blockIndex = task.__idxInPipeline;
  21464. break;
  21465. }
  21466. task = task.getUpstream();
  21467. }
  21468. while (task);
  21469. });
  21470. };
  21471. var updatePayload = proto.updatePayload = function (task, payload) {
  21472. payload !== 'remain' && (task.context.payload = payload);
  21473. };
  21474. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21475. var seriesTaskMap = stageHandlerRecord.seriesTaskMap
  21476. || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21477. var seriesType = stageHandler.seriesType;
  21478. var getTargetSeries = stageHandler.getTargetSeries;
  21479. // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21480. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21481. // it works but it may cause other irrelevant charts blocked.
  21482. if (stageHandler.createOnAllSeries) {
  21483. ecModel.eachRawSeries(create);
  21484. }
  21485. else if (seriesType) {
  21486. ecModel.eachRawSeriesByType(seriesType, create);
  21487. }
  21488. else if (getTargetSeries) {
  21489. getTargetSeries(ecModel, api).each(create);
  21490. }
  21491. function create(seriesModel) {
  21492. var pipelineId = seriesModel.uid;
  21493. // Init tasks for each seriesModel only once.
  21494. // Reuse original task instance.
  21495. var task = seriesTaskMap.get(pipelineId)
  21496. || seriesTaskMap.set(pipelineId, createTask({
  21497. plan: seriesTaskPlan,
  21498. reset: seriesTaskReset,
  21499. count: seriesTaskCount
  21500. }));
  21501. task.context = {
  21502. model: seriesModel,
  21503. ecModel: ecModel,
  21504. api: api,
  21505. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21506. plan: stageHandler.plan,
  21507. reset: stageHandler.reset,
  21508. scheduler: scheduler
  21509. };
  21510. pipe(scheduler, seriesModel, task);
  21511. }
  21512. // Clear unused series tasks.
  21513. var pipelineMap = scheduler._pipelineMap;
  21514. seriesTaskMap.each(function (task, pipelineId) {
  21515. if (!pipelineMap.get(pipelineId)) {
  21516. task.dispose();
  21517. seriesTaskMap.removeKey(pipelineId);
  21518. }
  21519. });
  21520. }
  21521. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21522. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask
  21523. // For overall task, the function only be called on reset stage.
  21524. || createTask({reset: overallTaskReset});
  21525. overallTask.context = {
  21526. ecModel: ecModel,
  21527. api: api,
  21528. overallReset: stageHandler.overallReset,
  21529. scheduler: scheduler
  21530. };
  21531. // Reuse orignal stubs.
  21532. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21533. var seriesType = stageHandler.seriesType;
  21534. var getTargetSeries = stageHandler.getTargetSeries;
  21535. var overallProgress = true;
  21536. var modifyOutputEnd = stageHandler.modifyOutputEnd;
  21537. // An overall task with seriesType detected or has `getTargetSeries`, we add
  21538. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21539. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21540. // we set the pipeline block.
  21541. if (seriesType) {
  21542. ecModel.eachRawSeriesByType(seriesType, createStub);
  21543. }
  21544. else if (getTargetSeries) {
  21545. getTargetSeries(ecModel, api).each(createStub);
  21546. }
  21547. // Otherwise, (usually it is legancy case), the overall task will only be
  21548. // executed when upstream dirty. Otherwise the progressive rendering of all
  21549. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21550. // dirty info from upsteam.
  21551. else {
  21552. overallProgress = false;
  21553. each$1(ecModel.getSeries(), createStub);
  21554. }
  21555. function createStub(seriesModel) {
  21556. var pipelineId = seriesModel.uid;
  21557. var stub = agentStubMap.get(pipelineId);
  21558. if (!stub) {
  21559. stub = agentStubMap.set(pipelineId, createTask(
  21560. {reset: stubReset, onDirty: stubOnDirty}
  21561. ));
  21562. // When the result of `getTargetSeries` changed, the overallTask
  21563. // should be set as dirty and re-performed.
  21564. overallTask.dirty();
  21565. }
  21566. stub.context = {
  21567. model: seriesModel,
  21568. overallProgress: overallProgress,
  21569. modifyOutputEnd: modifyOutputEnd
  21570. };
  21571. stub.agent = overallTask;
  21572. stub.__block = overallProgress;
  21573. pipe(scheduler, seriesModel, stub);
  21574. }
  21575. // Clear unused stubs.
  21576. var pipelineMap = scheduler._pipelineMap;
  21577. agentStubMap.each(function (stub, pipelineId) {
  21578. if (!pipelineMap.get(pipelineId)) {
  21579. stub.dispose();
  21580. // When the result of `getTargetSeries` changed, the overallTask
  21581. // should be set as dirty and re-performed.
  21582. overallTask.dirty();
  21583. agentStubMap.removeKey(pipelineId);
  21584. }
  21585. });
  21586. }
  21587. function overallTaskReset(context) {
  21588. context.overallReset(
  21589. context.ecModel, context.api, context.payload
  21590. );
  21591. }
  21592. function stubReset(context, upstreamContext) {
  21593. return context.overallProgress && stubProgress;
  21594. }
  21595. function stubProgress() {
  21596. this.agent.dirty();
  21597. this.getDownstream().dirty();
  21598. }
  21599. function stubOnDirty() {
  21600. this.agent && this.agent.dirty();
  21601. }
  21602. function seriesTaskPlan(context) {
  21603. return context.plan && context.plan(
  21604. context.model, context.ecModel, context.api, context.payload
  21605. );
  21606. }
  21607. function seriesTaskReset(context) {
  21608. if (context.useClearVisual) {
  21609. context.data.clearAllVisual();
  21610. }
  21611. var resetDefines = context.resetDefines = normalizeToArray(context.reset(
  21612. context.model, context.ecModel, context.api, context.payload
  21613. ));
  21614. return resetDefines.length > 1
  21615. ? map(resetDefines, function (v, idx) {
  21616. return makeSeriesTaskProgress(idx);
  21617. })
  21618. : singleSeriesTaskProgress;
  21619. }
  21620. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21621. function makeSeriesTaskProgress(resetDefineIdx) {
  21622. return function (params, context) {
  21623. var data = context.data;
  21624. var resetDefine = context.resetDefines[resetDefineIdx];
  21625. if (resetDefine && resetDefine.dataEach) {
  21626. for (var i = params.start; i < params.end; i++) {
  21627. resetDefine.dataEach(data, i);
  21628. }
  21629. }
  21630. else if (resetDefine && resetDefine.progress) {
  21631. resetDefine.progress(params, data);
  21632. }
  21633. };
  21634. }
  21635. function seriesTaskCount(context) {
  21636. return context.data.count();
  21637. }
  21638. function pipe(scheduler, seriesModel, task) {
  21639. var pipelineId = seriesModel.uid;
  21640. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21641. !pipeline.head && (pipeline.head = task);
  21642. pipeline.tail && pipeline.tail.pipe(task);
  21643. pipeline.tail = task;
  21644. task.__idxInPipeline = pipeline.count++;
  21645. task.__pipeline = pipeline;
  21646. }
  21647. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21648. if (isFunction$1(stageHandler)) {
  21649. stageHandler = {
  21650. overallReset: stageHandler,
  21651. seriesType: detectSeriseType(stageHandler)
  21652. };
  21653. }
  21654. stageHandler.uid = getUID('stageHandler');
  21655. visualType && (stageHandler.visualType = visualType);
  21656. return stageHandler;
  21657. };
  21658. /**
  21659. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21660. * To ensure that they can work normally, they should work in block mode, that is,
  21661. * they should not be started util the previous tasks finished. So they cause the
  21662. * progressive rendering disabled. We try to detect the series type, to narrow down
  21663. * the block range to only the series type they concern, but not all series.
  21664. */
  21665. function detectSeriseType(legacyFunc) {
  21666. seriesType = null;
  21667. try {
  21668. // Assume there is no async when calling `eachSeriesByType`.
  21669. legacyFunc(ecModelMock, apiMock);
  21670. }
  21671. catch (e) {
  21672. }
  21673. return seriesType;
  21674. }
  21675. var ecModelMock = {};
  21676. var apiMock = {};
  21677. var seriesType;
  21678. mockMethods(ecModelMock, GlobalModel);
  21679. mockMethods(apiMock, ExtensionAPI);
  21680. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21681. seriesType = type;
  21682. };
  21683. ecModelMock.eachComponent = function (cond) {
  21684. if (cond.mainType === 'series' && cond.subType) {
  21685. seriesType = cond.subType;
  21686. }
  21687. };
  21688. function mockMethods(target, Clz) {
  21689. for (var name in Clz.prototype) {
  21690. // Do not use hasOwnProperty
  21691. target[name] = noop;
  21692. }
  21693. }
  21694. /*
  21695. * Licensed to the Apache Software Foundation (ASF) under one
  21696. * or more contributor license agreements. See the NOTICE file
  21697. * distributed with this work for additional information
  21698. * regarding copyright ownership. The ASF licenses this file
  21699. * to you under the Apache License, Version 2.0 (the
  21700. * "License"); you may not use this file except in compliance
  21701. * with the License. You may obtain a copy of the License at
  21702. *
  21703. * http://www.apache.org/licenses/LICENSE-2.0
  21704. *
  21705. * Unless required by applicable law or agreed to in writing,
  21706. * software distributed under the License is distributed on an
  21707. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21708. * KIND, either express or implied. See the License for the
  21709. * specific language governing permissions and limitations
  21710. * under the License.
  21711. */
  21712. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C','#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21713. var lightTheme = {
  21714. color: colorAll,
  21715. colorLayer: [
  21716. ['#37A2DA', '#ffd85c', '#fd7b5f'],
  21717. ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'],
  21718. ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'],
  21719. colorAll
  21720. ]
  21721. };
  21722. /*
  21723. * Licensed to the Apache Software Foundation (ASF) under one
  21724. * or more contributor license agreements. See the NOTICE file
  21725. * distributed with this work for additional information
  21726. * regarding copyright ownership. The ASF licenses this file
  21727. * to you under the Apache License, Version 2.0 (the
  21728. * "License"); you may not use this file except in compliance
  21729. * with the License. You may obtain a copy of the License at
  21730. *
  21731. * http://www.apache.org/licenses/LICENSE-2.0
  21732. *
  21733. * Unless required by applicable law or agreed to in writing,
  21734. * software distributed under the License is distributed on an
  21735. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21736. * KIND, either express or implied. See the License for the
  21737. * specific language governing permissions and limitations
  21738. * under the License.
  21739. */
  21740. var contrastColor = '#eee';
  21741. var axisCommon = function () {
  21742. return {
  21743. axisLine: {
  21744. lineStyle: {
  21745. color: contrastColor
  21746. }
  21747. },
  21748. axisTick: {
  21749. lineStyle: {
  21750. color: contrastColor
  21751. }
  21752. },
  21753. axisLabel: {
  21754. textStyle: {
  21755. color: contrastColor
  21756. }
  21757. },
  21758. splitLine: {
  21759. lineStyle: {
  21760. type: 'dashed',
  21761. color: '#aaa'
  21762. }
  21763. },
  21764. splitArea: {
  21765. areaStyle: {
  21766. color: contrastColor
  21767. }
  21768. }
  21769. };
  21770. };
  21771. var colorPalette = ['#dd6b66','#759aa0','#e69d87','#8dc1a9','#ea7e53','#eedd78','#73a373','#73b9bc','#7289ab', '#91ca8c','#f49f42'];
  21772. var theme = {
  21773. color: colorPalette,
  21774. backgroundColor: '#333',
  21775. tooltip: {
  21776. axisPointer: {
  21777. lineStyle: {
  21778. color: contrastColor
  21779. },
  21780. crossStyle: {
  21781. color: contrastColor
  21782. }
  21783. }
  21784. },
  21785. legend: {
  21786. textStyle: {
  21787. color: contrastColor
  21788. }
  21789. },
  21790. textStyle: {
  21791. color: contrastColor
  21792. },
  21793. title: {
  21794. textStyle: {
  21795. color: contrastColor
  21796. }
  21797. },
  21798. toolbox: {
  21799. iconStyle: {
  21800. normal: {
  21801. borderColor: contrastColor
  21802. }
  21803. }
  21804. },
  21805. dataZoom: {
  21806. textStyle: {
  21807. color: contrastColor
  21808. }
  21809. },
  21810. visualMap: {
  21811. textStyle: {
  21812. color: contrastColor
  21813. }
  21814. },
  21815. timeline: {
  21816. lineStyle: {
  21817. color: contrastColor
  21818. },
  21819. itemStyle: {
  21820. normal: {
  21821. color: colorPalette[1]
  21822. }
  21823. },
  21824. label: {
  21825. normal: {
  21826. textStyle: {
  21827. color: contrastColor
  21828. }
  21829. }
  21830. },
  21831. controlStyle: {
  21832. normal: {
  21833. color: contrastColor,
  21834. borderColor: contrastColor
  21835. }
  21836. }
  21837. },
  21838. timeAxis: axisCommon(),
  21839. logAxis: axisCommon(),
  21840. valueAxis: axisCommon(),
  21841. categoryAxis: axisCommon(),
  21842. line: {
  21843. symbol: 'circle'
  21844. },
  21845. graph: {
  21846. color: colorPalette
  21847. },
  21848. gauge: {
  21849. title: {
  21850. textStyle: {
  21851. color: contrastColor
  21852. }
  21853. }
  21854. },
  21855. candlestick: {
  21856. itemStyle: {
  21857. normal: {
  21858. color: '#FD1050',
  21859. color0: '#0CF49B',
  21860. borderColor: '#FD1050',
  21861. borderColor0: '#0CF49B'
  21862. }
  21863. }
  21864. }
  21865. };
  21866. theme.categoryAxis.splitLine.show = false;
  21867. /*
  21868. * Licensed to the Apache Software Foundation (ASF) under one
  21869. * or more contributor license agreements. See the NOTICE file
  21870. * distributed with this work for additional information
  21871. * regarding copyright ownership. The ASF licenses this file
  21872. * to you under the Apache License, Version 2.0 (the
  21873. * "License"); you may not use this file except in compliance
  21874. * with the License. You may obtain a copy of the License at
  21875. *
  21876. * http://www.apache.org/licenses/LICENSE-2.0
  21877. *
  21878. * Unless required by applicable law or agreed to in writing,
  21879. * software distributed under the License is distributed on an
  21880. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21881. * KIND, either express or implied. See the License for the
  21882. * specific language governing permissions and limitations
  21883. * under the License.
  21884. */
  21885. /**
  21886. * This module is imported by echarts directly.
  21887. *
  21888. * Notice:
  21889. * Always keep this file exists for backward compatibility.
  21890. * Because before 4.1.0, dataset is an optional component,
  21891. * some users may import this module manually.
  21892. */
  21893. ComponentModel.extend({
  21894. type: 'dataset',
  21895. /**
  21896. * @protected
  21897. */
  21898. defaultOption: {
  21899. // 'row', 'column'
  21900. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21901. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  21902. sourceHeader: null,
  21903. dimensions: null,
  21904. source: null
  21905. },
  21906. optionUpdated: function () {
  21907. detectSourceFormat(this);
  21908. }
  21909. });
  21910. Component.extend({
  21911. type: 'dataset'
  21912. });
  21913. /*
  21914. * Licensed to the Apache Software Foundation (ASF) under one
  21915. * or more contributor license agreements. See the NOTICE file
  21916. * distributed with this work for additional information
  21917. * regarding copyright ownership. The ASF licenses this file
  21918. * to you under the Apache License, Version 2.0 (the
  21919. * "License"); you may not use this file except in compliance
  21920. * with the License. You may obtain a copy of the License at
  21921. *
  21922. * http://www.apache.org/licenses/LICENSE-2.0
  21923. *
  21924. * Unless required by applicable law or agreed to in writing,
  21925. * software distributed under the License is distributed on an
  21926. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21927. * KIND, either express or implied. See the License for the
  21928. * specific language governing permissions and limitations
  21929. * under the License.
  21930. */
  21931. var assert = assert$1;
  21932. var each = each$1;
  21933. var isFunction = isFunction$1;
  21934. var isObject = isObject$1;
  21935. var parseClassType = ComponentModel.parseClassType;
  21936. var version = '4.1.0';
  21937. var dependencies = {
  21938. zrender: '4.0.4'
  21939. };
  21940. var TEST_FRAME_REMAIN_TIME = 1;
  21941. var PRIORITY_PROCESSOR_FILTER = 1000;
  21942. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  21943. var PRIORITY_VISUAL_LAYOUT = 1000;
  21944. var PRIORITY_VISUAL_GLOBAL = 2000;
  21945. var PRIORITY_VISUAL_CHART = 3000;
  21946. var PRIORITY_VISUAL_COMPONENT = 4000;
  21947. // FIXME
  21948. // necessary?
  21949. var PRIORITY_VISUAL_BRUSH = 5000;
  21950. var PRIORITY = {
  21951. PROCESSOR: {
  21952. FILTER: PRIORITY_PROCESSOR_FILTER,
  21953. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  21954. },
  21955. VISUAL: {
  21956. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  21957. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  21958. CHART: PRIORITY_VISUAL_CHART,
  21959. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  21960. BRUSH: PRIORITY_VISUAL_BRUSH
  21961. }
  21962. };
  21963. // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  21964. // where they must not be invoked nestedly, except the only case: invoke
  21965. // dispatchAction with updateMethod "none" in main process.
  21966. // This flag is used to carry out this rule.
  21967. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  21968. var IN_MAIN_PROCESS = '__flagInMainProcess';
  21969. var OPTION_UPDATED = '__optionUpdated';
  21970. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  21971. function createRegisterEventWithLowercaseName(method) {
  21972. return function (eventName, handler, context) {
  21973. // Event name is all lowercase
  21974. eventName = eventName && eventName.toLowerCase();
  21975. Eventful.prototype[method].call(this, eventName, handler, context);
  21976. };
  21977. }
  21978. /**
  21979. * @module echarts~MessageCenter
  21980. */
  21981. function MessageCenter() {
  21982. Eventful.call(this);
  21983. }
  21984. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on');
  21985. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off');
  21986. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one');
  21987. mixin(MessageCenter, Eventful);
  21988. /**
  21989. * @module echarts~ECharts
  21990. */
  21991. function ECharts(dom, theme$$1, opts) {
  21992. opts = opts || {};
  21993. // Get theme by name
  21994. if (typeof theme$$1 === 'string') {
  21995. theme$$1 = themeStorage[theme$$1];
  21996. }
  21997. /**
  21998. * @type {string}
  21999. */
  22000. this.id;
  22001. /**
  22002. * Group id
  22003. * @type {string}
  22004. */
  22005. this.group;
  22006. /**
  22007. * @type {HTMLElement}
  22008. * @private
  22009. */
  22010. this._dom = dom;
  22011. var defaultRenderer = 'canvas';
  22012. if (__DEV__) {
  22013. defaultRenderer = (
  22014. typeof window === 'undefined' ? global : window
  22015. ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer;
  22016. }
  22017. /**
  22018. * @type {module:zrender/ZRender}
  22019. * @private
  22020. */
  22021. var zr = this._zr = init$1(dom, {
  22022. renderer: opts.renderer || defaultRenderer,
  22023. devicePixelRatio: opts.devicePixelRatio,
  22024. width: opts.width,
  22025. height: opts.height
  22026. });
  22027. /**
  22028. * Expect 60 pfs.
  22029. * @type {Function}
  22030. * @private
  22031. */
  22032. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  22033. var theme$$1 = clone(theme$$1);
  22034. theme$$1 && backwardCompat(theme$$1, true);
  22035. /**
  22036. * @type {Object}
  22037. * @private
  22038. */
  22039. this._theme = theme$$1;
  22040. /**
  22041. * @type {Array.<module:echarts/view/Chart>}
  22042. * @private
  22043. */
  22044. this._chartsViews = [];
  22045. /**
  22046. * @type {Object.<string, module:echarts/view/Chart>}
  22047. * @private
  22048. */
  22049. this._chartsMap = {};
  22050. /**
  22051. * @type {Array.<module:echarts/view/Component>}
  22052. * @private
  22053. */
  22054. this._componentsViews = [];
  22055. /**
  22056. * @type {Object.<string, module:echarts/view/Component>}
  22057. * @private
  22058. */
  22059. this._componentsMap = {};
  22060. /**
  22061. * @type {module:echarts/CoordinateSystem}
  22062. * @private
  22063. */
  22064. this._coordSysMgr = new CoordinateSystemManager();
  22065. /**
  22066. * @type {module:echarts/ExtensionAPI}
  22067. * @private
  22068. */
  22069. var api = this._api = createExtensionAPI(this);
  22070. // Sort on demand
  22071. function prioritySortFunc(a, b) {
  22072. return a.__prio - b.__prio;
  22073. }
  22074. sort(visualFuncs, prioritySortFunc);
  22075. sort(dataProcessorFuncs, prioritySortFunc);
  22076. /**
  22077. * @type {module:echarts/stream/Scheduler}
  22078. */
  22079. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22080. Eventful.call(this);
  22081. /**
  22082. * @type {module:echarts~MessageCenter}
  22083. * @private
  22084. */
  22085. this._messageCenter = new MessageCenter();
  22086. // Init mouse events
  22087. this._initEvents();
  22088. // In case some people write `window.onresize = chart.resize`
  22089. this.resize = bind(this.resize, this);
  22090. // Can't dispatch action during rendering procedure
  22091. this._pendingActions = [];
  22092. zr.animation.on('frame', this._onframe, this);
  22093. bindRenderedEvent(zr, this);
  22094. // ECharts instance can be used as value.
  22095. setAsPrimitive(this);
  22096. }
  22097. var echartsProto = ECharts.prototype;
  22098. echartsProto._onframe = function () {
  22099. if (this._disposed) {
  22100. return;
  22101. }
  22102. var scheduler = this._scheduler;
  22103. // Lazy update
  22104. if (this[OPTION_UPDATED]) {
  22105. var silent = this[OPTION_UPDATED].silent;
  22106. this[IN_MAIN_PROCESS] = true;
  22107. prepare(this);
  22108. updateMethods.update.call(this);
  22109. this[IN_MAIN_PROCESS] = false;
  22110. this[OPTION_UPDATED] = false;
  22111. flushPendingActions.call(this, silent);
  22112. triggerUpdatedEvent.call(this, silent);
  22113. }
  22114. // Avoid do both lazy update and progress in one frame.
  22115. else if (scheduler.unfinished) {
  22116. // Stream progress.
  22117. var remainTime = TEST_FRAME_REMAIN_TIME;
  22118. var ecModel = this._model;
  22119. var api = this._api;
  22120. scheduler.unfinished = false;
  22121. do {
  22122. var startTime = +new Date();
  22123. scheduler.performSeriesTasks(ecModel);
  22124. // Currently dataProcessorFuncs do not check threshold.
  22125. scheduler.performDataProcessorTasks(ecModel);
  22126. updateStreamModes(this, ecModel);
  22127. // Do not update coordinate system here. Because that coord system update in
  22128. // each frame is not a good user experience. So we follow the rule that
  22129. // the extent of the coordinate system is determin in the first frame (the
  22130. // frame is executed immedietely after task reset.
  22131. // this._coordSysMgr.update(ecModel, api);
  22132. // console.log('--- ec frame visual ---', remainTime);
  22133. scheduler.performVisualTasks(ecModel);
  22134. renderSeries(this, this._model, api, 'remain');
  22135. remainTime -= (+new Date() - startTime);
  22136. }
  22137. while (remainTime > 0 && scheduler.unfinished);
  22138. // Call flush explicitly for trigger finished event.
  22139. if (!scheduler.unfinished) {
  22140. this._zr.flush();
  22141. }
  22142. // Else, zr flushing be ensue within the same frame,
  22143. // because zr flushing is after onframe event.
  22144. }
  22145. };
  22146. /**
  22147. * @return {HTMLElement}
  22148. */
  22149. echartsProto.getDom = function () {
  22150. return this._dom;
  22151. };
  22152. /**
  22153. * @return {module:zrender~ZRender}
  22154. */
  22155. echartsProto.getZr = function () {
  22156. return this._zr;
  22157. };
  22158. /**
  22159. * Usage:
  22160. * chart.setOption(option, notMerge, lazyUpdate);
  22161. * chart.setOption(option, {
  22162. * notMerge: ...,
  22163. * lazyUpdate: ...,
  22164. * silent: ...
  22165. * });
  22166. *
  22167. * @param {Object} option
  22168. * @param {Object|boolean} [opts] opts or notMerge.
  22169. * @param {boolean} [opts.notMerge=false]
  22170. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  22171. */
  22172. echartsProto.setOption = function (option, notMerge, lazyUpdate,_callback) {
  22173. if (__DEV__) {
  22174. assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.');
  22175. }
  22176. var silent;
  22177. if (isObject(notMerge)) {
  22178. lazyUpdate = notMerge.lazyUpdate;
  22179. silent = notMerge.silent;
  22180. notMerge = notMerge.notMerge;
  22181. }
  22182. this[IN_MAIN_PROCESS] = true;
  22183. if (!this._model || notMerge) {
  22184. var optionManager = new OptionManager(this._api);
  22185. var theme$$1 = this._theme;
  22186. var ecModel = this._model = new GlobalModel(null, null, theme$$1, optionManager);
  22187. ecModel.scheduler = this._scheduler;
  22188. ecModel.init(null, null, theme$$1, optionManager);
  22189. }
  22190. this._model.setOption(option, optionPreprocessorFuncs);
  22191. if (lazyUpdate) {
  22192. this[OPTION_UPDATED] = {silent: silent};
  22193. this[IN_MAIN_PROCESS] = false;
  22194. }
  22195. else {
  22196. prepare(this);
  22197. updateMethods.update.call(this);
  22198. // Ensure zr refresh sychronously, and then pixel in canvas can be
  22199. // fetched after `setOption`.
  22200. this._zr.flush();
  22201. this[OPTION_UPDATED] = false;
  22202. this[IN_MAIN_PROCESS] = false;
  22203. flushPendingActions.call(this, silent);
  22204. triggerUpdatedEvent.call(this, silent);
  22205. }
  22206. if(_callback){
  22207. //alert("callback");
  22208. setTimeout(_callback,2000);
  22209. }
  22210. };
  22211. /**
  22212. * @DEPRECATED
  22213. */
  22214. echartsProto.setTheme = function () {
  22215. console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  22216. };
  22217. /**
  22218. * @return {module:echarts/model/Global}
  22219. */
  22220. echartsProto.getModel = function () {
  22221. return this._model;
  22222. };
  22223. /**
  22224. * @return {Object}
  22225. */
  22226. echartsProto.getOption = function () {
  22227. return this._model && this._model.getOption();
  22228. };
  22229. /**
  22230. * @return {number}
  22231. */
  22232. echartsProto.getWidth = function () {
  22233. return this._zr.getWidth();
  22234. };
  22235. /**
  22236. * @return {number}
  22237. */
  22238. echartsProto.getHeight = function () {
  22239. return this._zr.getHeight();
  22240. };
  22241. /**
  22242. * @return {number}
  22243. */
  22244. echartsProto.getDevicePixelRatio = function () {
  22245. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  22246. };
  22247. /**
  22248. * Get canvas which has all thing rendered
  22249. * @param {Object} opts
  22250. * @param {string} [opts.backgroundColor]
  22251. * @return {string}
  22252. */
  22253. echartsProto.getRenderedCanvas = function (opts) {
  22254. if (!env$1.canvasSupported) {
  22255. return;
  22256. }
  22257. opts = opts || {};
  22258. opts.pixelRatio = opts.pixelRatio || 1;
  22259. opts.backgroundColor = opts.backgroundColor
  22260. || this._model.get('backgroundColor');
  22261. var zr = this._zr;
  22262. // var list = zr.storage.getDisplayList();
  22263. // Stop animations
  22264. // Never works before in init animation, so remove it.
  22265. // zrUtil.each(list, function (el) {
  22266. // el.stopAnimation(true);
  22267. // });
  22268. return zr.painter.getRenderedCanvas(opts);
  22269. };
  22270. /**
  22271. * Get svg data url
  22272. * @return {string}
  22273. */
  22274. echartsProto.getSvgDataUrl = function () {
  22275. if (!env$1.svgSupported) {
  22276. return;
  22277. }
  22278. var zr = this._zr;
  22279. var list = zr.storage.getDisplayList();
  22280. // Stop animations
  22281. each$1(list, function (el) {
  22282. el.stopAnimation(true);
  22283. });
  22284. return zr.painter.pathToDataUrl();
  22285. };
  22286. /**
  22287. * @return {string}
  22288. * @param {Object} opts
  22289. * @param {string} [opts.type='png']
  22290. * @param {string} [opts.pixelRatio=1]
  22291. * @param {string} [opts.backgroundColor]
  22292. * @param {string} [opts.excludeComponents]
  22293. */
  22294. echartsProto.getDataURL = function (opts) {
  22295. opts = opts || {};
  22296. var excludeComponents = opts.excludeComponents;
  22297. var ecModel = this._model;
  22298. var excludesComponentViews = [];
  22299. var self = this;
  22300. each(excludeComponents, function (componentType) {
  22301. ecModel.eachComponent({
  22302. mainType: componentType
  22303. }, function (component) {
  22304. var view = self._componentsMap[component.__viewId];
  22305. if (!view.group.ignore) {
  22306. excludesComponentViews.push(view);
  22307. view.group.ignore = true;
  22308. }
  22309. });
  22310. });
  22311. var url = this._zr.painter.getType() === 'svg'
  22312. ? this.getSvgDataUrl()
  22313. : this.getRenderedCanvas(opts).toDataURL(
  22314. 'image/' + (opts && opts.type || 'png')
  22315. );
  22316. each(excludesComponentViews, function (view) {
  22317. view.group.ignore = false;
  22318. });
  22319. return url;
  22320. };
  22321. /**
  22322. * @return {string}
  22323. * @param {Object} opts
  22324. * @param {string} [opts.type='png']
  22325. * @param {string} [opts.pixelRatio=1]
  22326. * @param {string} [opts.backgroundColor]
  22327. */
  22328. echartsProto.getConnectedDataURL = function (opts) {
  22329. if (!env$1.canvasSupported) {
  22330. return;
  22331. }
  22332. var groupId = this.group;
  22333. var mathMin = Math.min;
  22334. var mathMax = Math.max;
  22335. var MAX_NUMBER = Infinity;
  22336. if (connectedGroups[groupId]) {
  22337. var left = MAX_NUMBER;
  22338. var top = MAX_NUMBER;
  22339. var right = -MAX_NUMBER;
  22340. var bottom = -MAX_NUMBER;
  22341. var canvasList = [];
  22342. var dpr = (opts && opts.pixelRatio) || 1;
  22343. each$1(instances, function (chart, id) {
  22344. if (chart.group === groupId) {
  22345. var canvas = chart.getRenderedCanvas(
  22346. clone(opts)
  22347. );
  22348. var boundingRect = chart.getDom().getBoundingClientRect();
  22349. left = mathMin(boundingRect.left, left);
  22350. top = mathMin(boundingRect.top, top);
  22351. right = mathMax(boundingRect.right, right);
  22352. bottom = mathMax(boundingRect.bottom, bottom);
  22353. canvasList.push({
  22354. dom: canvas,
  22355. left: boundingRect.left,
  22356. top: boundingRect.top
  22357. });
  22358. }
  22359. });
  22360. left *= dpr;
  22361. top *= dpr;
  22362. right *= dpr;
  22363. bottom *= dpr;
  22364. var width = right - left;
  22365. var height = bottom - top;
  22366. var targetCanvas = createCanvas();
  22367. targetCanvas.width = width;
  22368. targetCanvas.height = height;
  22369. var zr = init$1(targetCanvas);
  22370. each(canvasList, function (item) {
  22371. var img = new ZImage({
  22372. style: {
  22373. x: item.left * dpr - left,
  22374. y: item.top * dpr - top,
  22375. image: item.dom
  22376. }
  22377. });
  22378. zr.add(img);
  22379. });
  22380. zr.refreshImmediately();
  22381. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  22382. }
  22383. else {
  22384. return this.getDataURL(opts);
  22385. }
  22386. };
  22387. /**
  22388. * Convert from logical coordinate system to pixel coordinate system.
  22389. * See CoordinateSystem#convertToPixel.
  22390. * @param {string|Object} finder
  22391. * If string, e.g., 'geo', means {geoIndex: 0}.
  22392. * If Object, could contain some of these properties below:
  22393. * {
  22394. * seriesIndex / seriesId / seriesName,
  22395. * geoIndex / geoId, geoName,
  22396. * bmapIndex / bmapId / bmapName,
  22397. * xAxisIndex / xAxisId / xAxisName,
  22398. * yAxisIndex / yAxisId / yAxisName,
  22399. * gridIndex / gridId / gridName,
  22400. * ... (can be extended)
  22401. * }
  22402. * @param {Array|number} value
  22403. * @return {Array|number} result
  22404. */
  22405. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  22406. /**
  22407. * Convert from pixel coordinate system to logical coordinate system.
  22408. * See CoordinateSystem#convertFromPixel.
  22409. * @param {string|Object} finder
  22410. * If string, e.g., 'geo', means {geoIndex: 0}.
  22411. * If Object, could contain some of these properties below:
  22412. * {
  22413. * seriesIndex / seriesId / seriesName,
  22414. * geoIndex / geoId / geoName,
  22415. * bmapIndex / bmapId / bmapName,
  22416. * xAxisIndex / xAxisId / xAxisName,
  22417. * yAxisIndex / yAxisId / yAxisName
  22418. * gridIndex / gridId / gridName,
  22419. * ... (can be extended)
  22420. * }
  22421. * @param {Array|number} value
  22422. * @return {Array|number} result
  22423. */
  22424. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  22425. function doConvertPixel(methodName, finder, value) {
  22426. var ecModel = this._model;
  22427. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  22428. var result;
  22429. finder = parseFinder(ecModel, finder);
  22430. for (var i = 0; i < coordSysList.length; i++) {
  22431. var coordSys = coordSysList[i];
  22432. if (coordSys[methodName]
  22433. && (result = coordSys[methodName](ecModel, finder, value)) != null
  22434. ) {
  22435. return result;
  22436. }
  22437. }
  22438. if (__DEV__) {
  22439. console.warn(
  22440. 'No coordinate system that supports ' + methodName + ' found by the given finder.'
  22441. );
  22442. }
  22443. }
  22444. /**
  22445. * Is the specified coordinate systems or components contain the given pixel point.
  22446. * @param {string|Object} finder
  22447. * If string, e.g., 'geo', means {geoIndex: 0}.
  22448. * If Object, could contain some of these properties below:
  22449. * {
  22450. * seriesIndex / seriesId / seriesName,
  22451. * geoIndex / geoId / geoName,
  22452. * bmapIndex / bmapId / bmapName,
  22453. * xAxisIndex / xAxisId / xAxisName,
  22454. * yAxisIndex / yAxisId / yAxisName,
  22455. * gridIndex / gridId / gridName,
  22456. * ... (can be extended)
  22457. * }
  22458. * @param {Array|number} value
  22459. * @return {boolean} result
  22460. */
  22461. echartsProto.containPixel = function (finder, value) {
  22462. var ecModel = this._model;
  22463. var result;
  22464. finder = parseFinder(ecModel, finder);
  22465. each$1(finder, function (models, key) {
  22466. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  22467. var coordSys = model.coordinateSystem;
  22468. if (coordSys && coordSys.containPoint) {
  22469. result |= !!coordSys.containPoint(value);
  22470. }
  22471. else if (key === 'seriesModels') {
  22472. var view = this._chartsMap[model.__viewId];
  22473. if (view && view.containPoint) {
  22474. result |= view.containPoint(value, model);
  22475. }
  22476. else {
  22477. if (__DEV__) {
  22478. console.warn(key + ': ' + (view
  22479. ? 'The found component do not support containPoint.'
  22480. : 'No view mapping to the found component.'
  22481. ));
  22482. }
  22483. }
  22484. }
  22485. else {
  22486. if (__DEV__) {
  22487. console.warn(key + ': containPoint is not supported');
  22488. }
  22489. }
  22490. }, this);
  22491. }, this);
  22492. return !!result;
  22493. };
  22494. /**
  22495. * Get visual from series or data.
  22496. * @param {string|Object} finder
  22497. * If string, e.g., 'series', means {seriesIndex: 0}.
  22498. * If Object, could contain some of these properties below:
  22499. * {
  22500. * seriesIndex / seriesId / seriesName,
  22501. * dataIndex / dataIndexInside
  22502. * }
  22503. * If dataIndex is not specified, series visual will be fetched,
  22504. * but not data item visual.
  22505. * If all of seriesIndex, seriesId, seriesName are not specified,
  22506. * visual will be fetched from first series.
  22507. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  22508. */
  22509. echartsProto.getVisual = function (finder, visualType) {
  22510. var ecModel = this._model;
  22511. finder = parseFinder(ecModel, finder, {defaultMainType: 'series'});
  22512. var seriesModel = finder.seriesModel;
  22513. if (__DEV__) {
  22514. if (!seriesModel) {
  22515. console.warn('There is no specified seires model');
  22516. }
  22517. }
  22518. var data = seriesModel.getData();
  22519. var dataIndexInside = finder.hasOwnProperty('dataIndexInside')
  22520. ? finder.dataIndexInside
  22521. : finder.hasOwnProperty('dataIndex')
  22522. ? data.indexOfRawIndex(finder.dataIndex)
  22523. : null;
  22524. return dataIndexInside != null
  22525. ? data.getItemVisual(dataIndexInside, visualType)
  22526. : data.getVisual(visualType);
  22527. };
  22528. /**
  22529. * Get view of corresponding component model
  22530. * @param {module:echarts/model/Component} componentModel
  22531. * @return {module:echarts/view/Component}
  22532. */
  22533. echartsProto.getViewOfComponentModel = function (componentModel) {
  22534. return this._componentsMap[componentModel.__viewId];
  22535. };
  22536. /**
  22537. * Get view of corresponding series model
  22538. * @param {module:echarts/model/Series} seriesModel
  22539. * @return {module:echarts/view/Chart}
  22540. */
  22541. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  22542. return this._chartsMap[seriesModel.__viewId];
  22543. };
  22544. var updateMethods = {
  22545. prepareAndUpdate: function (payload) {
  22546. prepare(this);
  22547. updateMethods.update.call(this, payload);
  22548. },
  22549. /**
  22550. * @param {Object} payload
  22551. * @private
  22552. */
  22553. update: function (payload) {
  22554. // console.profile && console.profile('update');
  22555. var ecModel = this._model;
  22556. var api = this._api;
  22557. var zr = this._zr;
  22558. var coordSysMgr = this._coordSysMgr;
  22559. var scheduler = this._scheduler;
  22560. // update before setOption
  22561. if (!ecModel) {
  22562. return;
  22563. }
  22564. scheduler.restoreData(ecModel, payload);
  22565. scheduler.performSeriesTasks(ecModel);
  22566. // TODO
  22567. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  22568. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  22569. // Create new coordinate system each update
  22570. // In LineView may save the old coordinate system and use it to get the orignal point
  22571. coordSysMgr.create(ecModel, api);
  22572. scheduler.performDataProcessorTasks(ecModel, payload);
  22573. // Current stream render is not supported in data process. So we can update
  22574. // stream modes after data processing, where the filtered data is used to
  22575. // deteming whether use progressive rendering.
  22576. updateStreamModes(this, ecModel);
  22577. // We update stream modes before coordinate system updated, then the modes info
  22578. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  22579. // the drawback is the full coord info can not be fetched. Fortunately this full
  22580. // coord is not requied in stream mode updater currently.
  22581. coordSysMgr.update(ecModel, api);
  22582. clearColorPalette(ecModel);
  22583. scheduler.performVisualTasks(ecModel, payload);
  22584. render(this, ecModel, api, payload);
  22585. // Set background
  22586. var backgroundColor = ecModel.get('backgroundColor') || 'transparent';
  22587. // In IE8
  22588. if (!env$1.canvasSupported) {
  22589. var colorArr = parse(backgroundColor);
  22590. backgroundColor = stringify(colorArr, 'rgb');
  22591. if (colorArr[3] === 0) {
  22592. backgroundColor = 'transparent';
  22593. }
  22594. }
  22595. else {
  22596. zr.setBackgroundColor(backgroundColor);
  22597. }
  22598. performPostUpdateFuncs(ecModel, api);
  22599. // console.profile && console.profileEnd('update');
  22600. },
  22601. /**
  22602. * @param {Object} payload
  22603. * @private
  22604. */
  22605. updateTransform: function (payload) {
  22606. var ecModel = this._model;
  22607. var ecIns = this;
  22608. var api = this._api;
  22609. // update before setOption
  22610. if (!ecModel) {
  22611. return;
  22612. }
  22613. // ChartView.markUpdateMethod(payload, 'updateTransform');
  22614. var componentDirtyList = [];
  22615. ecModel.eachComponent(function (componentType, componentModel) {
  22616. var componentView = ecIns.getViewOfComponentModel(componentModel);
  22617. if (componentView && componentView.__alive) {
  22618. if (componentView.updateTransform) {
  22619. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  22620. result && result.update && componentDirtyList.push(componentView);
  22621. }
  22622. else {
  22623. componentDirtyList.push(componentView);
  22624. }
  22625. }
  22626. });
  22627. var seriesDirtyMap = createHashMap();
  22628. ecModel.eachSeries(function (seriesModel) {
  22629. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  22630. if (chartView.updateTransform) {
  22631. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  22632. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  22633. }
  22634. else {
  22635. seriesDirtyMap.set(seriesModel.uid, 1);
  22636. }
  22637. });
  22638. clearColorPalette(ecModel);
  22639. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22640. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22641. this._scheduler.performVisualTasks(
  22642. ecModel, payload, {setDirty: true, dirtyMap: seriesDirtyMap}
  22643. );
  22644. // Currently, not call render of components. Geo render cost a lot.
  22645. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  22646. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  22647. performPostUpdateFuncs(ecModel, this._api);
  22648. },
  22649. /**
  22650. * @param {Object} payload
  22651. * @private
  22652. */
  22653. updateView: function (payload) {
  22654. var ecModel = this._model;
  22655. // update before setOption
  22656. if (!ecModel) {
  22657. return;
  22658. }
  22659. Chart.markUpdateMethod(payload, 'updateView');
  22660. clearColorPalette(ecModel);
  22661. // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22662. this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  22663. render(this, this._model, this._api, payload);
  22664. performPostUpdateFuncs(ecModel, this._api);
  22665. },
  22666. /**
  22667. * @param {Object} payload
  22668. * @private
  22669. */
  22670. updateVisual: function (payload) {
  22671. updateMethods.update.call(this, payload);
  22672. // var ecModel = this._model;
  22673. // // update before setOption
  22674. // if (!ecModel) {
  22675. // return;
  22676. // }
  22677. // ChartView.markUpdateMethod(payload, 'updateVisual');
  22678. // clearColorPalette(ecModel);
  22679. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22680. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  22681. // render(this, this._model, this._api, payload);
  22682. // performPostUpdateFuncs(ecModel, this._api);
  22683. },
  22684. /**
  22685. * @param {Object} payload
  22686. * @private
  22687. */
  22688. updateLayout: function (payload) {
  22689. updateMethods.update.call(this, payload);
  22690. // var ecModel = this._model;
  22691. // // update before setOption
  22692. // if (!ecModel) {
  22693. // return;
  22694. // }
  22695. // ChartView.markUpdateMethod(payload, 'updateLayout');
  22696. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  22697. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  22698. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  22699. // render(this, this._model, this._api, payload);
  22700. // performPostUpdateFuncs(ecModel, this._api);
  22701. }
  22702. };
  22703. function prepare(ecIns) {
  22704. var ecModel = ecIns._model;
  22705. var scheduler = ecIns._scheduler;
  22706. scheduler.restorePipelines(ecModel);
  22707. scheduler.prepareStageTasks();
  22708. prepareView(ecIns, 'component', ecModel, scheduler);
  22709. prepareView(ecIns, 'chart', ecModel, scheduler);
  22710. scheduler.plan();
  22711. }
  22712. /**
  22713. * @private
  22714. */
  22715. function updateDirectly(ecIns, method, payload, mainType, subType) {
  22716. var ecModel = ecIns._model;
  22717. // broadcast
  22718. if (!mainType) {
  22719. // FIXME
  22720. // Chart will not be update directly here, except set dirty.
  22721. // But there is no such scenario now.
  22722. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  22723. return;
  22724. }
  22725. var query = {};
  22726. query[mainType + 'Id'] = payload[mainType + 'Id'];
  22727. query[mainType + 'Index'] = payload[mainType + 'Index'];
  22728. query[mainType + 'Name'] = payload[mainType + 'Name'];
  22729. var condition = {mainType: mainType, query: query};
  22730. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  22731. var excludeSeriesId = payload.excludeSeriesId;
  22732. if (excludeSeriesId != null) {
  22733. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  22734. }
  22735. // If dispatchAction before setOption, do nothing.
  22736. ecModel && ecModel.eachComponent(condition, function (model) {
  22737. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  22738. callView(ecIns[
  22739. mainType === 'series' ? '_chartsMap' : '_componentsMap'
  22740. ][model.__viewId]);
  22741. }
  22742. }, ecIns);
  22743. function callView(view) {
  22744. view && view.__alive && view[method] && view[method](
  22745. view.__model, ecModel, ecIns._api, payload
  22746. );
  22747. }
  22748. }
  22749. /**
  22750. * Resize the chart
  22751. * @param {Object} opts
  22752. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  22753. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  22754. * @param {boolean} [opts.silent=false]
  22755. */
  22756. echartsProto.resize = function (opts) {
  22757. if (__DEV__) {
  22758. assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.');
  22759. }
  22760. this._zr.resize(opts);
  22761. var ecModel = this._model;
  22762. // Resize loading effect
  22763. this._loadingFX && this._loadingFX.resize();
  22764. if (!ecModel) {
  22765. return;
  22766. }
  22767. var optionChanged = ecModel.resetOption('media');
  22768. var silent = opts && opts.silent;
  22769. this[IN_MAIN_PROCESS] = true;
  22770. optionChanged && prepare(this);
  22771. updateMethods.update.call(this);
  22772. this[IN_MAIN_PROCESS] = false;
  22773. flushPendingActions.call(this, silent);
  22774. triggerUpdatedEvent.call(this, silent);
  22775. };
  22776. function updateStreamModes(ecIns, ecModel) {
  22777. var chartsMap = ecIns._chartsMap;
  22778. var scheduler = ecIns._scheduler;
  22779. ecModel.eachSeries(function (seriesModel) {
  22780. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  22781. });
  22782. }
  22783. /**
  22784. * Show loading effect
  22785. * @param {string} [name='default']
  22786. * @param {Object} [cfg]
  22787. */
  22788. echartsProto.showLoading = function (name, cfg) {
  22789. if (isObject(name)) {
  22790. cfg = name;
  22791. name = '';
  22792. }
  22793. name = name || 'default';
  22794. this.hideLoading();
  22795. if (!loadingEffects[name]) {
  22796. if (__DEV__) {
  22797. console.warn('Loading effects ' + name + ' not exists.');
  22798. }
  22799. return;
  22800. }
  22801. var el = loadingEffects[name](this._api, cfg);
  22802. var zr = this._zr;
  22803. this._loadingFX = el;
  22804. zr.add(el);
  22805. };
  22806. /**
  22807. * Hide loading effect
  22808. */
  22809. echartsProto.hideLoading = function () {
  22810. this._loadingFX && this._zr.remove(this._loadingFX);
  22811. this._loadingFX = null;
  22812. };
  22813. /**
  22814. * @param {Object} eventObj
  22815. * @return {Object}
  22816. */
  22817. echartsProto.makeActionFromEvent = function (eventObj) {
  22818. var payload = extend({}, eventObj);
  22819. payload.type = eventActionMap[eventObj.type];
  22820. return payload;
  22821. };
  22822. /**
  22823. * @pubilc
  22824. * @param {Object} payload
  22825. * @param {string} [payload.type] Action type
  22826. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  22827. * @param {boolean} [opt.silent=false] Whether trigger events.
  22828. * @param {boolean} [opt.flush=undefined]
  22829. * true: Flush immediately, and then pixel in canvas can be fetched
  22830. * immediately. Caution: it might affect performance.
  22831. * false: Not not flush.
  22832. * undefined: Auto decide whether perform flush.
  22833. */
  22834. echartsProto.dispatchAction = function (payload, opt) {
  22835. if (!isObject(opt)) {
  22836. opt = {silent: !!opt};
  22837. }
  22838. if (!actions[payload.type]) {
  22839. return;
  22840. }
  22841. // Avoid dispatch action before setOption. Especially in `connect`.
  22842. if (!this._model) {
  22843. return;
  22844. }
  22845. // May dispatchAction in rendering procedure
  22846. if (this[IN_MAIN_PROCESS]) {
  22847. this._pendingActions.push(payload);
  22848. return;
  22849. }
  22850. doDispatchAction.call(this, payload, opt.silent);
  22851. if (opt.flush) {
  22852. this._zr.flush(true);
  22853. }
  22854. else if (opt.flush !== false && env$1.browser.weChat) {
  22855. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  22856. // hang when sliding page (on touch event), which cause that zr does not
  22857. // refresh util user interaction finished, which is not expected.
  22858. // But `dispatchAction` may be called too frequently when pan on touch
  22859. // screen, which impacts performance if do not throttle them.
  22860. this._throttledZrFlush();
  22861. }
  22862. flushPendingActions.call(this, opt.silent);
  22863. triggerUpdatedEvent.call(this, opt.silent);
  22864. };
  22865. function doDispatchAction(payload, silent) {
  22866. var payloadType = payload.type;
  22867. var escapeConnect = payload.escapeConnect;
  22868. var actionWrap = actions[payloadType];
  22869. var actionInfo = actionWrap.actionInfo;
  22870. var cptType = (actionInfo.update || 'update').split(':');
  22871. var updateMethod = cptType.pop();
  22872. cptType = cptType[0] != null && parseClassType(cptType[0]);
  22873. this[IN_MAIN_PROCESS] = true;
  22874. var payloads = [payload];
  22875. var batched = false;
  22876. // Batch action
  22877. if (payload.batch) {
  22878. batched = true;
  22879. payloads = map(payload.batch, function (item) {
  22880. item = defaults(extend({}, item), payload);
  22881. item.batch = null;
  22882. return item;
  22883. });
  22884. }
  22885. var eventObjBatch = [];
  22886. var eventObj;
  22887. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  22888. each(payloads, function (batchItem) {
  22889. // Action can specify the event by return it.
  22890. eventObj = actionWrap.action(batchItem, this._model, this._api);
  22891. // Emit event outside
  22892. eventObj = eventObj || extend({}, batchItem);
  22893. // Convert type to eventType
  22894. eventObj.type = actionInfo.event || eventObj.type;
  22895. eventObjBatch.push(eventObj);
  22896. // light update does not perform data process, layout and visual.
  22897. if (isHighDown) {
  22898. // method, payload, mainType, subType
  22899. updateDirectly(this, updateMethod, batchItem, 'series');
  22900. }
  22901. else if (cptType) {
  22902. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  22903. }
  22904. }, this);
  22905. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  22906. // Still dirty
  22907. if (this[OPTION_UPDATED]) {
  22908. // FIXME Pass payload ?
  22909. prepare(this);
  22910. updateMethods.update.call(this, payload);
  22911. this[OPTION_UPDATED] = false;
  22912. }
  22913. else {
  22914. updateMethods[updateMethod].call(this, payload);
  22915. }
  22916. }
  22917. // Follow the rule of action batch
  22918. if (batched) {
  22919. eventObj = {
  22920. type: actionInfo.event || payloadType,
  22921. escapeConnect: escapeConnect,
  22922. batch: eventObjBatch
  22923. };
  22924. }
  22925. else {
  22926. eventObj = eventObjBatch[0];
  22927. }
  22928. this[IN_MAIN_PROCESS] = false;
  22929. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  22930. }
  22931. function flushPendingActions(silent) {
  22932. var pendingActions = this._pendingActions;
  22933. while (pendingActions.length) {
  22934. var payload = pendingActions.shift();
  22935. doDispatchAction.call(this, payload, silent);
  22936. }
  22937. }
  22938. function triggerUpdatedEvent(silent) {
  22939. !silent && this.trigger('updated');
  22940. }
  22941. /**
  22942. * Event `rendered` is triggered when zr
  22943. * rendered. It is useful for realtime
  22944. * snapshot (reflect animation).
  22945. *
  22946. * Event `finished` is triggered when:
  22947. * (1) zrender rendering finished.
  22948. * (2) initial animation finished.
  22949. * (3) progressive rendering finished.
  22950. * (4) no pending action.
  22951. * (5) no delayed setOption needs to be processed.
  22952. */
  22953. function bindRenderedEvent(zr, ecIns) {
  22954. zr.on('rendered', function () {
  22955. ecIns.trigger('rendered');
  22956. // The `finished` event should not be triggered repeatly,
  22957. // so it should only be triggered when rendering indeed happend
  22958. // in zrender. (Consider the case that dipatchAction is keep
  22959. // triggering when mouse move).
  22960. if (
  22961. // Although zr is dirty if initial animation is not finished
  22962. // and this checking is called on frame, we also check
  22963. // animation finished for robustness.
  22964. zr.animation.isFinished()
  22965. && !ecIns[OPTION_UPDATED]
  22966. && !ecIns._scheduler.unfinished
  22967. && !ecIns._pendingActions.length
  22968. ) {
  22969. ecIns.trigger('finished');
  22970. }
  22971. });
  22972. }
  22973. /**
  22974. * @param {Object} params
  22975. * @param {number} params.seriesIndex
  22976. * @param {Array|TypedArray} params.data
  22977. */
  22978. echartsProto.appendData = function (params) {
  22979. var seriesIndex = params.seriesIndex;
  22980. var ecModel = this.getModel();
  22981. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  22982. if (__DEV__) {
  22983. assert(params.data && seriesModel);
  22984. }
  22985. seriesModel.appendData(params);
  22986. // Note: `appendData` does not support that update extent of coordinate
  22987. // system, util some scenario require that. In the expected usage of
  22988. // `appendData`, the initial extent of coordinate system should better
  22989. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  22990. // the extent changed while `appendData`, the location of the painted
  22991. // graphic elements have to be changed, which make the usage of
  22992. // `appendData` meaningless.
  22993. this._scheduler.unfinished = true;
  22994. };
  22995. /**
  22996. * Register event
  22997. * @method
  22998. */
  22999. echartsProto.on = createRegisterEventWithLowercaseName('on');
  23000. echartsProto.off = createRegisterEventWithLowercaseName('off');
  23001. echartsProto.one = createRegisterEventWithLowercaseName('one');
  23002. /**
  23003. * Prepare view instances of charts and components
  23004. * @param {module:echarts/model/Global} ecModel
  23005. * @private
  23006. */
  23007. function prepareView(ecIns, type, ecModel, scheduler) {
  23008. var isComponent = type === 'component';
  23009. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  23010. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  23011. var zr = ecIns._zr;
  23012. var api = ecIns._api;
  23013. for (var i = 0; i < viewList.length; i++) {
  23014. viewList[i].__alive = false;
  23015. }
  23016. isComponent
  23017. ? ecModel.eachComponent(function (componentType, model) {
  23018. componentType !== 'series' && doPrepare(model);
  23019. })
  23020. : ecModel.eachSeries(doPrepare);
  23021. function doPrepare(model) {
  23022. // Consider: id same and type changed.
  23023. var viewId = '_ec_' + model.id + '_' + model.type;
  23024. var view = viewMap[viewId];
  23025. if (!view) {
  23026. var classType = parseClassType(model.type);
  23027. var Clazz = isComponent
  23028. ? Component.getClass(classType.main, classType.sub)
  23029. : Chart.getClass(classType.sub);
  23030. if (__DEV__) {
  23031. assert(Clazz, classType.sub + ' does not exist.');
  23032. }
  23033. view = new Clazz();
  23034. view.init(ecModel, api);
  23035. viewMap[viewId] = view;
  23036. viewList.push(view);
  23037. zr.add(view.group);
  23038. }
  23039. model.__viewId = view.__id = viewId;
  23040. view.__alive = true;
  23041. view.__model = model;
  23042. view.group.__ecComponentInfo = {
  23043. mainType: model.mainType,
  23044. index: model.componentIndex
  23045. };
  23046. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23047. }
  23048. for (var i = 0; i < viewList.length;) {
  23049. var view = viewList[i];
  23050. if (!view.__alive) {
  23051. !isComponent && view.renderTask.dispose();
  23052. zr.remove(view.group);
  23053. view.dispose(ecModel, api);
  23054. viewList.splice(i, 1);
  23055. delete viewMap[view.__id];
  23056. view.__id = view.group.__ecComponentInfo = null;
  23057. }
  23058. else {
  23059. i++;
  23060. }
  23061. }
  23062. }
  23063. // /**
  23064. // * Encode visual infomation from data after data processing
  23065. // *
  23066. // * @param {module:echarts/model/Global} ecModel
  23067. // * @param {object} layout
  23068. // * @param {boolean} [layoutFilter] `true`: only layout,
  23069. // * `false`: only not layout,
  23070. // * `null`/`undefined`: all.
  23071. // * @param {string} taskBaseTag
  23072. // * @private
  23073. // */
  23074. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23075. // each(visualFuncs, function (visual, index) {
  23076. // var isLayout = visual.isLayout;
  23077. // if (layoutFilter == null
  23078. // || (layoutFilter === false && !isLayout)
  23079. // || (layoutFilter === true && isLayout)
  23080. // ) {
  23081. // visual.func(ecModel, api, payload);
  23082. // }
  23083. // });
  23084. // }
  23085. function clearColorPalette(ecModel) {
  23086. ecModel.clearColorPalette();
  23087. ecModel.eachSeries(function (seriesModel) {
  23088. seriesModel.clearColorPalette();
  23089. });
  23090. }
  23091. function render(ecIns, ecModel, api, payload) {
  23092. renderComponents(ecIns, ecModel, api, payload);
  23093. each(ecIns._chartsViews, function (chart) {
  23094. chart.__alive = false;
  23095. });
  23096. renderSeries(ecIns, ecModel, api, payload);
  23097. // Remove groups of unrendered charts
  23098. each(ecIns._chartsViews, function (chart) {
  23099. if (!chart.__alive) {
  23100. chart.remove(ecModel, api);
  23101. }
  23102. });
  23103. }
  23104. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23105. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23106. var componentModel = componentView.__model;
  23107. componentView.render(componentModel, ecModel, api, payload);
  23108. updateZ(componentModel, componentView);
  23109. });
  23110. }
  23111. /**
  23112. * Render each chart and component
  23113. * @private
  23114. */
  23115. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23116. // Render all charts
  23117. var scheduler = ecIns._scheduler;
  23118. var unfinished;
  23119. ecModel.eachSeries(function (seriesModel) {
  23120. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23121. chartView.__alive = true;
  23122. var renderTask = chartView.renderTask;
  23123. scheduler.updatePayload(renderTask, payload);
  23124. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23125. renderTask.dirty();
  23126. }
  23127. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23128. chartView.group.silent = !!seriesModel.get('silent');
  23129. updateZ(seriesModel, chartView);
  23130. updateBlend(seriesModel, chartView);
  23131. });
  23132. scheduler.unfinished |= unfinished;
  23133. // If use hover layer
  23134. updateHoverLayerStatus(ecIns._zr, ecModel);
  23135. // Add aria
  23136. aria(ecIns._zr.dom, ecModel);
  23137. }
  23138. function performPostUpdateFuncs(ecModel, api) {
  23139. each(postUpdateFuncs, function (func) {
  23140. func(ecModel, api);
  23141. });
  23142. }
  23143. var MOUSE_EVENT_NAMES = [
  23144. 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove',
  23145. 'mousedown', 'mouseup', 'globalout', 'contextmenu'
  23146. ];
  23147. /**
  23148. * @private
  23149. */
  23150. echartsProto._initEvents = function () {
  23151. each(MOUSE_EVENT_NAMES, function (eveName) {
  23152. this._zr.on(eveName, function (e) {
  23153. var ecModel = this.getModel();
  23154. var el = e.target;
  23155. var params;
  23156. // no e.target when 'globalout'.
  23157. if (eveName === 'globalout') {
  23158. params = {};
  23159. }
  23160. else if (el && el.dataIndex != null) {
  23161. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23162. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {};
  23163. }
  23164. // If element has custom eventData of components
  23165. else if (el && el.eventData) {
  23166. params = extend({}, el.eventData);
  23167. }
  23168. if (params) {
  23169. params.event = e;
  23170. params.type = eveName;
  23171. this.trigger(eveName, params);
  23172. }
  23173. }, this);
  23174. }, this);
  23175. each(eventActionMap, function (actionType, eventType) {
  23176. this._messageCenter.on(eventType, function (event) {
  23177. this.trigger(eventType, event);
  23178. }, this);
  23179. }, this);
  23180. };
  23181. /**
  23182. * @return {boolean}
  23183. */
  23184. echartsProto.isDisposed = function () {
  23185. return this._disposed;
  23186. };
  23187. /**
  23188. * Clear
  23189. */
  23190. echartsProto.clear = function () {
  23191. this.setOption({ series: [] }, true);
  23192. };
  23193. /**
  23194. * Dispose instance
  23195. */
  23196. echartsProto.dispose = function () {
  23197. if (this._disposed) {
  23198. if (__DEV__) {
  23199. console.warn('Instance ' + this.id + ' has been disposed');
  23200. }
  23201. return;
  23202. }
  23203. this._disposed = true;
  23204. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  23205. var api = this._api;
  23206. var ecModel = this._model;
  23207. each(this._componentsViews, function (component) {
  23208. component.dispose(ecModel, api);
  23209. });
  23210. each(this._chartsViews, function (chart) {
  23211. chart.dispose(ecModel, api);
  23212. });
  23213. // Dispose after all views disposed
  23214. this._zr.dispose();
  23215. delete instances[this.id];
  23216. };
  23217. mixin(ECharts, Eventful);
  23218. function updateHoverLayerStatus(zr, ecModel) {
  23219. var storage = zr.storage;
  23220. var elCount = 0;
  23221. storage.traverse(function (el) {
  23222. if (!el.isGroup) {
  23223. elCount++;
  23224. }
  23225. });
  23226. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  23227. storage.traverse(function (el) {
  23228. if (!el.isGroup) {
  23229. // Don't switch back.
  23230. el.useHoverLayer = true;
  23231. }
  23232. });
  23233. }
  23234. }
  23235. /**
  23236. * Update chart progressive and blend.
  23237. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23238. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23239. */
  23240. function updateBlend(seriesModel, chartView) {
  23241. var blendMode = seriesModel.get('blendMode') || null;
  23242. if (__DEV__) {
  23243. if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') {
  23244. console.warn('Only canvas support blendMode');
  23245. }
  23246. }
  23247. chartView.group.traverse(function (el) {
  23248. // FIXME marker and other components
  23249. if (!el.isGroup) {
  23250. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  23251. if (el.style.blend !== blendMode) {
  23252. el.setStyle('blend', blendMode);
  23253. }
  23254. }
  23255. if (el.eachPendingDisplayable) {
  23256. el.eachPendingDisplayable(function (displayable) {
  23257. displayable.setStyle('blend', blendMode);
  23258. });
  23259. }
  23260. });
  23261. }
  23262. /**
  23263. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23264. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23265. */
  23266. function updateZ(model, view) {
  23267. var z = model.get('z');
  23268. var zlevel = model.get('zlevel');
  23269. // Set z and zlevel
  23270. view.group.traverse(function (el) {
  23271. if (el.type !== 'group') {
  23272. z != null && (el.z = z);
  23273. zlevel != null && (el.zlevel = zlevel);
  23274. }
  23275. });
  23276. }
  23277. function createExtensionAPI(ecInstance) {
  23278. var coordSysMgr = ecInstance._coordSysMgr;
  23279. return extend(new ExtensionAPI(ecInstance), {
  23280. // Inject methods
  23281. getCoordinateSystems: bind(
  23282. coordSysMgr.getCoordinateSystems, coordSysMgr
  23283. ),
  23284. getComponentByElement: function (el) {
  23285. while (el) {
  23286. var modelInfo = el.__ecComponentInfo;
  23287. if (modelInfo != null) {
  23288. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  23289. }
  23290. el = el.parent;
  23291. }
  23292. }
  23293. });
  23294. }
  23295. /**
  23296. * @type {Object} key: actionType.
  23297. * @inner
  23298. */
  23299. var actions = {};
  23300. /**
  23301. * Map eventType to actionType
  23302. * @type {Object}
  23303. */
  23304. var eventActionMap = {};
  23305. /**
  23306. * Data processor functions of each stage
  23307. * @type {Array.<Object.<string, Function>>}
  23308. * @inner
  23309. */
  23310. var dataProcessorFuncs = [];
  23311. /**
  23312. * @type {Array.<Function>}
  23313. * @inner
  23314. */
  23315. var optionPreprocessorFuncs = [];
  23316. /**
  23317. * @type {Array.<Function>}
  23318. * @inner
  23319. */
  23320. var postUpdateFuncs = [];
  23321. /**
  23322. * Visual encoding functions of each stage
  23323. * @type {Array.<Object.<string, Function>>}
  23324. */
  23325. var visualFuncs = [];
  23326. /**
  23327. * Theme storage
  23328. * @type {Object.<key, Object>}
  23329. */
  23330. var themeStorage = {};
  23331. /**
  23332. * Loading effects
  23333. */
  23334. var loadingEffects = {};
  23335. var instances = {};
  23336. var connectedGroups = {};
  23337. var idBase = new Date() - 0;
  23338. var groupIdBase = new Date() - 0;
  23339. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  23340. var mapDataStores = {};
  23341. function enableConnect(chart) {
  23342. var STATUS_PENDING = 0;
  23343. var STATUS_UPDATING = 1;
  23344. var STATUS_UPDATED = 2;
  23345. var STATUS_KEY = '__connectUpdateStatus';
  23346. function updateConnectedChartsStatus(charts, status) {
  23347. for (var i = 0; i < charts.length; i++) {
  23348. var otherChart = charts[i];
  23349. otherChart[STATUS_KEY] = status;
  23350. }
  23351. }
  23352. each(eventActionMap, function (actionType, eventType) {
  23353. chart._messageCenter.on(eventType, function (event) {
  23354. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  23355. if (event && event.escapeConnect) {
  23356. return;
  23357. }
  23358. var action = chart.makeActionFromEvent(event);
  23359. var otherCharts = [];
  23360. each(instances, function (otherChart) {
  23361. if (otherChart !== chart && otherChart.group === chart.group) {
  23362. otherCharts.push(otherChart);
  23363. }
  23364. });
  23365. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  23366. each(otherCharts, function (otherChart) {
  23367. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  23368. otherChart.dispatchAction(action);
  23369. }
  23370. });
  23371. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  23372. }
  23373. });
  23374. });
  23375. }
  23376. /**
  23377. * @param {HTMLElement} dom
  23378. * @param {Object} [theme]
  23379. * @param {Object} opts
  23380. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  23381. * @param {string} [opts.renderer] Currently only 'canvas' is supported.
  23382. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  23383. * Can be 'auto' (the same as null/undefined)
  23384. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  23385. * Can be 'auto' (the same as null/undefined)
  23386. */
  23387. function init(dom, theme$$1, opts) {
  23388. if (__DEV__) {
  23389. // Check version
  23390. if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) {
  23391. throw new Error(
  23392. 'zrender/src ' + version$1
  23393. + ' is too old for ECharts ' + version
  23394. + '. Current version need ZRender '
  23395. + dependencies.zrender + '+'
  23396. );
  23397. }
  23398. if (!dom) {
  23399. throw new Error('Initialize failed: invalid dom.');
  23400. }
  23401. }
  23402. var existInstance = getInstanceByDom(dom);
  23403. if (existInstance) {
  23404. if (__DEV__) {
  23405. console.warn('There is a chart instance already initialized on the dom.');
  23406. }
  23407. return existInstance;
  23408. }
  23409. if (__DEV__) {
  23410. if (isDom(dom)
  23411. && dom.nodeName.toUpperCase() !== 'CANVAS'
  23412. && (
  23413. (!dom.clientWidth && (!opts || opts.width == null))
  23414. || (!dom.clientHeight && (!opts || opts.height == null))
  23415. )
  23416. ) {
  23417. console.warn('Can\'t get dom width or height');
  23418. }
  23419. }
  23420. var chart = new ECharts(dom, theme$$1, opts);
  23421. chart.id = 'ec_' + idBase++;
  23422. instances[chart.id] = chart;
  23423. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  23424. enableConnect(chart);
  23425. return chart;
  23426. }
  23427. /**
  23428. * @return {string|Array.<module:echarts~ECharts>} groupId
  23429. */
  23430. function connect(groupId) {
  23431. // Is array of charts
  23432. if (isArray(groupId)) {
  23433. var charts = groupId;
  23434. groupId = null;
  23435. // If any chart has group
  23436. each(charts, function (chart) {
  23437. if (chart.group != null) {
  23438. groupId = chart.group;
  23439. }
  23440. });
  23441. groupId = groupId || ('g_' + groupIdBase++);
  23442. each(charts, function (chart) {
  23443. chart.group = groupId;
  23444. });
  23445. }
  23446. connectedGroups[groupId] = true;
  23447. return groupId;
  23448. }
  23449. /**
  23450. * @DEPRECATED
  23451. * @return {string} groupId
  23452. */
  23453. function disConnect(groupId) {
  23454. connectedGroups[groupId] = false;
  23455. }
  23456. /**
  23457. * @return {string} groupId
  23458. */
  23459. var disconnect = disConnect;
  23460. /**
  23461. * Dispose a chart instance
  23462. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  23463. */
  23464. function dispose(chart) {
  23465. if (typeof chart === 'string') {
  23466. chart = instances[chart];
  23467. }
  23468. else if (!(chart instanceof ECharts)){
  23469. // Try to treat as dom
  23470. chart = getInstanceByDom(chart);
  23471. }
  23472. if ((chart instanceof ECharts) && !chart.isDisposed()) {
  23473. chart.dispose();
  23474. }
  23475. }
  23476. /**
  23477. * @param {HTMLElement} dom
  23478. * @return {echarts~ECharts}
  23479. */
  23480. function getInstanceByDom(dom) {
  23481. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  23482. }
  23483. /**
  23484. * @param {string} key
  23485. * @return {echarts~ECharts}
  23486. */
  23487. function getInstanceById(key) {
  23488. return instances[key];
  23489. }
  23490. /**
  23491. * Register theme
  23492. */
  23493. function registerTheme(name, theme$$1) {
  23494. themeStorage[name] = theme$$1;
  23495. }
  23496. /**
  23497. * Register option preprocessor
  23498. * @param {Function} preprocessorFunc
  23499. */
  23500. function registerPreprocessor(preprocessorFunc) {
  23501. optionPreprocessorFuncs.push(preprocessorFunc);
  23502. }
  23503. /**
  23504. * @param {number} [priority=1000]
  23505. * @param {Object|Function} processor
  23506. */
  23507. function registerProcessor(priority, processor) {
  23508. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  23509. }
  23510. /**
  23511. * Register postUpdater
  23512. * @param {Function} postUpdateFunc
  23513. */
  23514. function registerPostUpdate(postUpdateFunc) {
  23515. postUpdateFuncs.push(postUpdateFunc);
  23516. }
  23517. /**
  23518. * Usage:
  23519. * registerAction('someAction', 'someEvent', function () { ... });
  23520. * registerAction('someAction', function () { ... });
  23521. * registerAction(
  23522. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  23523. * function () { ... }
  23524. * );
  23525. *
  23526. * @param {(string|Object)} actionInfo
  23527. * @param {string} actionInfo.type
  23528. * @param {string} [actionInfo.event]
  23529. * @param {string} [actionInfo.update]
  23530. * @param {string} [eventName]
  23531. * @param {Function} action
  23532. */
  23533. function registerAction(actionInfo, eventName, action) {
  23534. if (typeof eventName === 'function') {
  23535. action = eventName;
  23536. eventName = '';
  23537. }
  23538. var actionType = isObject(actionInfo)
  23539. ? actionInfo.type
  23540. : ([actionInfo, actionInfo = {
  23541. event: eventName
  23542. }][0]);
  23543. // Event name is all lowercase
  23544. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  23545. eventName = actionInfo.event;
  23546. // Validate action type and event name.
  23547. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  23548. if (!actions[actionType]) {
  23549. actions[actionType] = {action: action, actionInfo: actionInfo};
  23550. }
  23551. eventActionMap[eventName] = actionType;
  23552. }
  23553. /**
  23554. * @param {string} type
  23555. * @param {*} CoordinateSystem
  23556. */
  23557. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  23558. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  23559. }
  23560. /**
  23561. * Get dimensions of specified coordinate system.
  23562. * @param {string} type
  23563. * @return {Array.<string|Object>}
  23564. */
  23565. function getCoordinateSystemDimensions(type) {
  23566. var coordSysCreator = CoordinateSystemManager.get(type);
  23567. if (coordSysCreator) {
  23568. return coordSysCreator.getDimensionsInfo
  23569. ? coordSysCreator.getDimensionsInfo()
  23570. : coordSysCreator.dimensions.slice();
  23571. }
  23572. }
  23573. /**
  23574. * Layout is a special stage of visual encoding
  23575. * Most visual encoding like color are common for different chart
  23576. * But each chart has it's own layout algorithm
  23577. *
  23578. * @param {number} [priority=1000]
  23579. * @param {Function} layoutTask
  23580. */
  23581. function registerLayout(priority, layoutTask) {
  23582. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  23583. }
  23584. /**
  23585. * @param {number} [priority=3000]
  23586. * @param {module:echarts/stream/Task} visualTask
  23587. */
  23588. function registerVisual(priority, visualTask) {
  23589. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  23590. }
  23591. /**
  23592. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  23593. */
  23594. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  23595. if (isFunction(priority) || isObject(priority)) {
  23596. fn = priority;
  23597. priority = defaultPriority;
  23598. }
  23599. if (__DEV__) {
  23600. if (isNaN(priority) || priority == null) {
  23601. throw new Error('Illegal priority');
  23602. }
  23603. // Check duplicate
  23604. each(targetList, function (wrap) {
  23605. assert(wrap.__raw !== fn);
  23606. });
  23607. }
  23608. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  23609. stageHandler.__prio = priority;
  23610. stageHandler.__raw = fn;
  23611. targetList.push(stageHandler);
  23612. return stageHandler;
  23613. }
  23614. /**
  23615. * @param {string} name
  23616. */
  23617. function registerLoading(name, loadingFx) {
  23618. loadingEffects[name] = loadingFx;
  23619. }
  23620. /**
  23621. * @param {Object} opts
  23622. * @param {string} [superClass]
  23623. */
  23624. function extendComponentModel(opts/*, superClass*/) {
  23625. // var Clazz = ComponentModel;
  23626. // if (superClass) {
  23627. // var classType = parseClassType(superClass);
  23628. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  23629. // }
  23630. return ComponentModel.extend(opts);
  23631. }
  23632. /**
  23633. * @param {Object} opts
  23634. * @param {string} [superClass]
  23635. */
  23636. function extendComponentView(opts/*, superClass*/) {
  23637. // var Clazz = ComponentView;
  23638. // if (superClass) {
  23639. // var classType = parseClassType(superClass);
  23640. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  23641. // }
  23642. return Component.extend(opts);
  23643. }
  23644. /**
  23645. * @param {Object} opts
  23646. * @param {string} [superClass]
  23647. */
  23648. function extendSeriesModel(opts/*, superClass*/) {
  23649. // var Clazz = SeriesModel;
  23650. // if (superClass) {
  23651. // superClass = 'series.' + superClass.replace('series.', '');
  23652. // var classType = parseClassType(superClass);
  23653. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  23654. // }
  23655. return SeriesModel.extend(opts);
  23656. }
  23657. /**
  23658. * @param {Object} opts
  23659. * @param {string} [superClass]
  23660. */
  23661. function extendChartView(opts/*, superClass*/) {
  23662. // var Clazz = ChartView;
  23663. // if (superClass) {
  23664. // superClass = superClass.replace('series.', '');
  23665. // var classType = parseClassType(superClass);
  23666. // Clazz = ChartView.getClass(classType.main, true);
  23667. // }
  23668. return Chart.extend(opts);
  23669. }
  23670. /**
  23671. * ZRender need a canvas context to do measureText.
  23672. * But in node environment canvas may be created by node-canvas.
  23673. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  23674. *
  23675. * Be careful of using it in the browser.
  23676. *
  23677. * @param {Function} creator
  23678. * @example
  23679. * var Canvas = require('canvas');
  23680. * var echarts = require('echarts');
  23681. * echarts.setCanvasCreator(function () {
  23682. * // Small size is enough.
  23683. * return new Canvas(32, 32);
  23684. * });
  23685. */
  23686. function setCanvasCreator(creator) {
  23687. $override('createCanvas', creator);
  23688. }
  23689. /**
  23690. * @param {string} mapName
  23691. * @param {Object|string} geoJson
  23692. * @param {Object} [specialAreas]
  23693. *
  23694. * @example
  23695. * $.get('USA.json', function (geoJson) {
  23696. * echarts.registerMap('USA', geoJson);
  23697. * // Or
  23698. * echarts.registerMap('USA', {
  23699. * geoJson: geoJson,
  23700. * specialAreas: {}
  23701. * })
  23702. * });
  23703. */
  23704. function registerMap(mapName, geoJson, specialAreas) {
  23705. if (geoJson.geoJson && !geoJson.features) {
  23706. specialAreas = geoJson.specialAreas;
  23707. geoJson = geoJson.geoJson;
  23708. }
  23709. if (typeof geoJson === 'string') {
  23710. geoJson = (typeof JSON !== 'undefined' && JSON.parse)
  23711. ? JSON.parse(geoJson) : (new Function('return (' + geoJson + ');'))();
  23712. }
  23713. mapDataStores[mapName] = {
  23714. geoJson: geoJson,
  23715. specialAreas: specialAreas
  23716. };
  23717. }
  23718. /**
  23719. * @param {string} mapName
  23720. * @return {Object}
  23721. */
  23722. function getMap(mapName) {
  23723. return mapDataStores[mapName];
  23724. }
  23725. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  23726. registerPreprocessor(backwardCompat);
  23727. registerProcessor(PRIORITY_PROCESSOR_STATISTIC, dataStack);
  23728. registerLoading('default', loadingDefault);
  23729. // Default actions
  23730. registerAction({
  23731. type: 'highlight',
  23732. event: 'highlight',
  23733. update: 'highlight'
  23734. }, noop);
  23735. registerAction({
  23736. type: 'downplay',
  23737. event: 'downplay',
  23738. update: 'downplay'
  23739. }, noop);
  23740. // Default theme
  23741. registerTheme('light', lightTheme);
  23742. registerTheme('dark', theme);
  23743. // For backward compatibility, where the namespace `dataTool` will
  23744. // be mounted on `echarts` is the extension `dataTool` is imported.
  23745. var dataTool = {};
  23746. /*
  23747. * Licensed to the Apache Software Foundation (ASF) under one
  23748. * or more contributor license agreements. See the NOTICE file
  23749. * distributed with this work for additional information
  23750. * regarding copyright ownership. The ASF licenses this file
  23751. * to you under the Apache License, Version 2.0 (the
  23752. * "License"); you may not use this file except in compliance
  23753. * with the License. You may obtain a copy of the License at
  23754. *
  23755. * http://www.apache.org/licenses/LICENSE-2.0
  23756. *
  23757. * Unless required by applicable law or agreed to in writing,
  23758. * software distributed under the License is distributed on an
  23759. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23760. * KIND, either express or implied. See the License for the
  23761. * specific language governing permissions and limitations
  23762. * under the License.
  23763. */
  23764. function defaultKeyGetter(item) {
  23765. return item;
  23766. }
  23767. /**
  23768. * @param {Array} oldArr
  23769. * @param {Array} newArr
  23770. * @param {Function} oldKeyGetter
  23771. * @param {Function} newKeyGetter
  23772. * @param {Object} [context] Can be visited by this.context in callback.
  23773. */
  23774. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  23775. this._old = oldArr;
  23776. this._new = newArr;
  23777. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  23778. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  23779. this.context = context;
  23780. }
  23781. DataDiffer.prototype = {
  23782. constructor: DataDiffer,
  23783. /**
  23784. * Callback function when add a data
  23785. */
  23786. add: function (func) {
  23787. this._add = func;
  23788. return this;
  23789. },
  23790. /**
  23791. * Callback function when update a data
  23792. */
  23793. update: function (func) {
  23794. this._update = func;
  23795. return this;
  23796. },
  23797. /**
  23798. * Callback function when remove a data
  23799. */
  23800. remove: function (func) {
  23801. this._remove = func;
  23802. return this;
  23803. },
  23804. execute: function () {
  23805. var oldArr = this._old;
  23806. var newArr = this._new;
  23807. var oldDataIndexMap = {};
  23808. var newDataIndexMap = {};
  23809. var oldDataKeyArr = [];
  23810. var newDataKeyArr = [];
  23811. var i;
  23812. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  23813. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  23814. // Travel by inverted order to make sure order consistency
  23815. // when duplicate keys exists (consider newDataIndex.pop() below).
  23816. // For performance consideration, these code below do not look neat.
  23817. for (i = 0; i < oldArr.length; i++) {
  23818. var key = oldDataKeyArr[i];
  23819. var idx = newDataIndexMap[key];
  23820. // idx can never be empty array here. see 'set null' logic below.
  23821. if (idx != null) {
  23822. // Consider there is duplicate key (for example, use dataItem.name as key).
  23823. // We should make sure every item in newArr and oldArr can be visited.
  23824. var len = idx.length;
  23825. if (len) {
  23826. len === 1 && (newDataIndexMap[key] = null);
  23827. idx = idx.unshift();
  23828. }
  23829. else {
  23830. newDataIndexMap[key] = null;
  23831. }
  23832. this._update && this._update(idx, i);
  23833. }
  23834. else {
  23835. this._remove && this._remove(i);
  23836. }
  23837. }
  23838. for (var i = 0; i < newDataKeyArr.length; i++) {
  23839. var key = newDataKeyArr[i];
  23840. if (newDataIndexMap.hasOwnProperty(key)) {
  23841. var idx = newDataIndexMap[key];
  23842. if (idx == null) {
  23843. continue;
  23844. }
  23845. // idx can never be empty array here. see 'set null' logic above.
  23846. if (!idx.length) {
  23847. this._add && this._add(idx);
  23848. }
  23849. else {
  23850. for (var j = 0, len = idx.length; j < len; j++) {
  23851. this._add && this._add(idx[j]);
  23852. }
  23853. }
  23854. }
  23855. }
  23856. }
  23857. };
  23858. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  23859. for (var i = 0; i < arr.length; i++) {
  23860. // Add prefix to avoid conflict with Object.prototype.
  23861. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  23862. var existence = map[key];
  23863. if (existence == null) {
  23864. keyArr.push(key);
  23865. map[key] = i;
  23866. }
  23867. else {
  23868. if (!existence.length) {
  23869. map[key] = existence = [existence];
  23870. }
  23871. existence.push(i);
  23872. }
  23873. }
  23874. }
  23875. /*
  23876. * Licensed to the Apache Software Foundation (ASF) under one
  23877. * or more contributor license agreements. See the NOTICE file
  23878. * distributed with this work for additional information
  23879. * regarding copyright ownership. The ASF licenses this file
  23880. * to you under the Apache License, Version 2.0 (the
  23881. * "License"); you may not use this file except in compliance
  23882. * with the License. You may obtain a copy of the License at
  23883. *
  23884. * http://www.apache.org/licenses/LICENSE-2.0
  23885. *
  23886. * Unless required by applicable law or agreed to in writing,
  23887. * software distributed under the License is distributed on an
  23888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  23889. * KIND, either express or implied. See the License for the
  23890. * specific language governing permissions and limitations
  23891. * under the License.
  23892. */
  23893. var OTHER_DIMENSIONS = createHashMap([
  23894. 'tooltip', 'label', 'itemName', 'itemId', 'seriesName'
  23895. ]);
  23896. function summarizeDimensions(data) {
  23897. var summary = {};
  23898. var encode = summary.encode = {};
  23899. var notExtraCoordDimMap = createHashMap();
  23900. var defaultedLabel = [];
  23901. var defaultedTooltip = [];
  23902. each$1(data.dimensions, function (dimName) {
  23903. var dimItem = data.getDimensionInfo(dimName);
  23904. var coordDim = dimItem.coordDim;
  23905. if (coordDim) {
  23906. if (__DEV__) {
  23907. assert$1(OTHER_DIMENSIONS.get(coordDim) == null);
  23908. }
  23909. var coordDimArr = encode[coordDim];
  23910. if (!encode.hasOwnProperty(coordDim)) {
  23911. coordDimArr = encode[coordDim] = [];
  23912. }
  23913. coordDimArr[dimItem.coordDimIndex] = dimName;
  23914. if (!dimItem.isExtraCoord) {
  23915. notExtraCoordDimMap.set(coordDim, 1);
  23916. // Use the last coord dim (and label friendly) as default label,
  23917. // because when dataset is used, it is hard to guess which dimension
  23918. // can be value dimension. If both show x, y on label is not look good,
  23919. // and conventionally y axis is focused more.
  23920. if (mayLabelDimType(dimItem.type)) {
  23921. defaultedLabel[0] = dimName;
  23922. }
  23923. }
  23924. if (dimItem.defaultTooltip) {
  23925. defaultedTooltip.push(dimName);
  23926. }
  23927. }
  23928. OTHER_DIMENSIONS.each(function (v, otherDim) {
  23929. var otherDimArr = encode[otherDim];
  23930. if (!encode.hasOwnProperty(otherDim)) {
  23931. otherDimArr = encode[otherDim] = [];
  23932. }
  23933. var dimIndex = dimItem.otherDims[otherDim];
  23934. if (dimIndex != null && dimIndex !== false) {
  23935. otherDimArr[dimIndex] = dimItem.name;
  23936. }
  23937. });
  23938. });
  23939. var dataDimsOnCoord = [];
  23940. var encodeFirstDimNotExtra = {};
  23941. notExtraCoordDimMap.each(function (v, coordDim) {
  23942. var dimArr = encode[coordDim];
  23943. // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  23944. // But should fix the case that radar axes: simplify the logic
  23945. // of `completeDimension`, remove `extraPrefix`.
  23946. encodeFirstDimNotExtra[coordDim] = dimArr[0];
  23947. // Not necessary to remove duplicate, because a data
  23948. // dim canot on more than one coordDim.
  23949. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  23950. });
  23951. summary.dataDimsOnCoord = dataDimsOnCoord;
  23952. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  23953. var encodeLabel = encode.label;
  23954. // FIXME `encode.label` is not recommanded, because formatter can not be set
  23955. // in this way. Use label.formatter instead. May be remove this approach someday.
  23956. if (encodeLabel && encodeLabel.length) {
  23957. defaultedLabel = encodeLabel.slice();
  23958. }
  23959. var encodeTooltip = encode.tooltip;
  23960. if (encodeTooltip && encodeTooltip.length) {
  23961. defaultedTooltip = encodeTooltip.slice();
  23962. }
  23963. else if (!defaultedTooltip.length) {
  23964. defaultedTooltip = defaultedLabel.slice();
  23965. }
  23966. encode.defaultedLabel = defaultedLabel;
  23967. encode.defaultedTooltip = defaultedTooltip;
  23968. return summary;
  23969. }
  23970. function getDimensionTypeByAxis(axisType) {
  23971. return axisType === 'category'
  23972. ? 'ordinal'
  23973. : axisType === 'time'
  23974. ? 'time'
  23975. : 'float';
  23976. }
  23977. function mayLabelDimType(dimType) {
  23978. // In most cases, ordinal and time do not suitable for label.
  23979. // Ordinal info can be displayed on axis. Time is too long.
  23980. return !(dimType === 'ordinal' || dimType === 'time');
  23981. }
  23982. // function findTheLastDimMayLabel(data) {
  23983. // // Get last value dim
  23984. // var dimensions = data.dimensions.slice();
  23985. // var valueType;
  23986. // var valueDim;
  23987. // while (dimensions.length && (
  23988. // valueDim = dimensions.pop(),
  23989. // valueType = data.getDimensionInfo(valueDim).type,
  23990. // valueType === 'ordinal' || valueType === 'time'
  23991. // )) {} // jshint ignore:line
  23992. // return valueDim;
  23993. // }
  23994. /*
  23995. * Licensed to the Apache Software Foundation (ASF) under one
  23996. * or more contributor license agreements. See the NOTICE file
  23997. * distributed with this work for additional information
  23998. * regarding copyright ownership. The ASF licenses this file
  23999. * to you under the Apache License, Version 2.0 (the
  24000. * "License"); you may not use this file except in compliance
  24001. * with the License. You may obtain a copy of the License at
  24002. *
  24003. * http://www.apache.org/licenses/LICENSE-2.0
  24004. *
  24005. * Unless required by applicable law or agreed to in writing,
  24006. * software distributed under the License is distributed on an
  24007. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24008. * KIND, either express or implied. See the License for the
  24009. * specific language governing permissions and limitations
  24010. * under the License.
  24011. */
  24012. /**
  24013. * List for data storage
  24014. * @module echarts/data/List
  24015. */
  24016. var isObject$4 = isObject$1;
  24017. var UNDEFINED = 'undefined';
  24018. // Use prefix to avoid index to be the same as otherIdList[idx],
  24019. // which will cause weird update animation.
  24020. var ID_PREFIX = 'e\0\0';
  24021. var dataCtors = {
  24022. 'float': typeof Float64Array === UNDEFINED
  24023. ? Array : Float64Array,
  24024. 'int': typeof Int32Array === UNDEFINED
  24025. ? Array : Int32Array,
  24026. // Ordinal data type can be string or int
  24027. 'ordinal': Array,
  24028. 'number': Array,
  24029. 'time': Array
  24030. };
  24031. // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  24032. // different from the Ctor of typed array.
  24033. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  24034. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  24035. function getIndicesCtor(list) {
  24036. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  24037. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  24038. }
  24039. function cloneChunk(originalChunk) {
  24040. var Ctor = originalChunk.constructor;
  24041. // Only shallow clone is enough when Array.
  24042. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  24043. }
  24044. var TRANSFERABLE_PROPERTIES = [
  24045. 'hasItemOption', '_nameList', '_idList', '_invertedIndicesMap',
  24046. '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter',
  24047. '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'
  24048. ];
  24049. var CLONE_PROPERTIES = [
  24050. '_extent', '_approximateExtent', '_rawExtent'
  24051. ];
  24052. function transferProperties(target, source) {
  24053. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  24054. if (source.hasOwnProperty(propName)) {
  24055. target[propName] = source[propName];
  24056. }
  24057. });
  24058. target.__wrappedMethods = source.__wrappedMethods;
  24059. each$1(CLONE_PROPERTIES, function (propName) {
  24060. target[propName] = clone(source[propName]);
  24061. });
  24062. target._calculationInfo = extend(source._calculationInfo);
  24063. }
  24064. /**
  24065. * @constructor
  24066. * @alias module:echarts/data/List
  24067. *
  24068. * @param {Array.<string|Object>} dimensions
  24069. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  24070. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  24071. * Spetial fields: {
  24072. * ordinalMeta: <module:echarts/data/OrdinalMeta>
  24073. * createInvertedIndices: <boolean>
  24074. * }
  24075. * @param {module:echarts/model/Model} hostModel
  24076. */
  24077. var List = function (dimensions, hostModel) {
  24078. dimensions = dimensions || ['x', 'y'];
  24079. var dimensionInfos = {};
  24080. var dimensionNames = [];
  24081. var invertedIndicesMap = {};
  24082. for (var i = 0; i < dimensions.length; i++) {
  24083. // Use the original dimensions[i], where other flag props may exists.
  24084. var dimensionInfo = dimensions[i];
  24085. if (isString(dimensionInfo)) {
  24086. dimensionInfo = {name: dimensionInfo};
  24087. }
  24088. var dimensionName = dimensionInfo.name;
  24089. dimensionInfo.type = dimensionInfo.type || 'float';
  24090. if (!dimensionInfo.coordDim) {
  24091. dimensionInfo.coordDim = dimensionName;
  24092. dimensionInfo.coordDimIndex = 0;
  24093. }
  24094. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  24095. dimensionNames.push(dimensionName);
  24096. dimensionInfos[dimensionName] = dimensionInfo;
  24097. dimensionInfo.index = i;
  24098. if (dimensionInfo.createInvertedIndices) {
  24099. invertedIndicesMap[dimensionName] = [];
  24100. }
  24101. }
  24102. /**
  24103. * @readOnly
  24104. * @type {Array.<string>}
  24105. */
  24106. this.dimensions = dimensionNames;
  24107. /**
  24108. * Infomation of each data dimension, like data type.
  24109. * @type {Object}
  24110. */
  24111. this._dimensionInfos = dimensionInfos;
  24112. /**
  24113. * @type {module:echarts/model/Model}
  24114. */
  24115. this.hostModel = hostModel;
  24116. /**
  24117. * @type {module:echarts/model/Model}
  24118. */
  24119. this.dataType;
  24120. /**
  24121. * Indices stores the indices of data subset after filtered.
  24122. * This data subset will be used in chart.
  24123. * @type {Array.<number>}
  24124. * @readOnly
  24125. */
  24126. this._indices = null;
  24127. this._count = 0;
  24128. this._rawCount = 0;
  24129. /**
  24130. * Data storage
  24131. * @type {Object.<key, Array.<TypedArray|Array>>}
  24132. * @private
  24133. */
  24134. this._storage = {};
  24135. /**
  24136. * @type {Array.<string>}
  24137. */
  24138. this._nameList = [];
  24139. /**
  24140. * @type {Array.<string>}
  24141. */
  24142. this._idList = [];
  24143. /**
  24144. * Models of data option is stored sparse for optimizing memory cost
  24145. * @type {Array.<module:echarts/model/Model>}
  24146. * @private
  24147. */
  24148. this._optionModels = [];
  24149. /**
  24150. * Global visual properties after visual coding
  24151. * @type {Object}
  24152. * @private
  24153. */
  24154. this._visual = {};
  24155. /**
  24156. * Globel layout properties.
  24157. * @type {Object}
  24158. * @private
  24159. */
  24160. this._layout = {};
  24161. /**
  24162. * Item visual properties after visual coding
  24163. * @type {Array.<Object>}
  24164. * @private
  24165. */
  24166. this._itemVisuals = [];
  24167. /**
  24168. * Key: visual type, Value: boolean
  24169. * @type {Object}
  24170. * @readOnly
  24171. */
  24172. this.hasItemVisual = {};
  24173. /**
  24174. * Item layout properties after layout
  24175. * @type {Array.<Object>}
  24176. * @private
  24177. */
  24178. this._itemLayouts = [];
  24179. /**
  24180. * Graphic elemnents
  24181. * @type {Array.<module:zrender/Element>}
  24182. * @private
  24183. */
  24184. this._graphicEls = [];
  24185. /**
  24186. * Max size of each chunk.
  24187. * @type {number}
  24188. * @private
  24189. */
  24190. this._chunkSize = 1e5;
  24191. /**
  24192. * @type {number}
  24193. * @private
  24194. */
  24195. this._chunkCount = 0;
  24196. /**
  24197. * @type {Array.<Array|Object>}
  24198. * @private
  24199. */
  24200. this._rawData;
  24201. /**
  24202. * Raw extent will not be cloned, but only transfered.
  24203. * It will not be calculated util needed.
  24204. * key: dim,
  24205. * value: {end: number, extent: Array.<number>}
  24206. * @type {Object}
  24207. * @private
  24208. */
  24209. this._rawExtent = {};
  24210. /**
  24211. * @type {Object}
  24212. * @private
  24213. */
  24214. this._extent = {};
  24215. /**
  24216. * key: dim
  24217. * value: extent
  24218. * @type {Object}
  24219. * @private
  24220. */
  24221. this._approximateExtent = {};
  24222. /**
  24223. * Cache summary info for fast visit. See "dimensionHelper".
  24224. * @type {Object}
  24225. * @private
  24226. */
  24227. this._dimensionsSummary = summarizeDimensions(this);
  24228. /**
  24229. * @type {Object.<Array|TypedArray>}
  24230. * @private
  24231. */
  24232. this._invertedIndicesMap = invertedIndicesMap;
  24233. /**
  24234. * @type {Object}
  24235. * @private
  24236. */
  24237. this._calculationInfo = {};
  24238. };
  24239. var listProto = List.prototype;
  24240. listProto.type = 'list';
  24241. /**
  24242. * If each data item has it's own option
  24243. * @type {boolean}
  24244. */
  24245. listProto.hasItemOption = true;
  24246. /**
  24247. * Get dimension name
  24248. * @param {string|number} dim
  24249. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24250. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24251. * @return {string} Concrete dim name.
  24252. */
  24253. listProto.getDimension = function (dim) {
  24254. if (!isNaN(dim)) {
  24255. dim = this.dimensions[dim] || dim;
  24256. }
  24257. return dim;
  24258. };
  24259. /**
  24260. * Get type and calculation info of particular dimension
  24261. * @param {string|number} dim
  24262. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24263. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24264. */
  24265. listProto.getDimensionInfo = function (dim) {
  24266. // Do not clone, because there may be categories in dimInfo.
  24267. return this._dimensionInfos[this.getDimension(dim)];
  24268. };
  24269. /**
  24270. * @return {Array.<string>} concrete dimension name list on coord.
  24271. */
  24272. listProto.getDimensionsOnCoord = function () {
  24273. return this._dimensionsSummary.dataDimsOnCoord.slice();
  24274. };
  24275. /**
  24276. * @param {string} coordDim
  24277. * @param {number} [idx] A coordDim may map to more than one data dim.
  24278. * If idx is `true`, return a array of all mapped dims.
  24279. * If idx is not specified, return the first dim not extra.
  24280. * @return {string|Array.<string>} concrete data dim.
  24281. * If idx is number, and not found, return null/undefined.
  24282. * If idx is `true`, and not found, return empty array (always return array).
  24283. */
  24284. listProto.mapDimension = function (coordDim, idx) {
  24285. var dimensionsSummary = this._dimensionsSummary;
  24286. if (idx == null) {
  24287. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  24288. }
  24289. var dims = dimensionsSummary.encode[coordDim];
  24290. return idx === true
  24291. // always return array if idx is `true`
  24292. ? (dims || []).slice()
  24293. : (dims && dims[idx]);
  24294. };
  24295. /**
  24296. * Initialize from data
  24297. * @param {Array.<Object|number|Array>} data source or data or data provider.
  24298. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  24299. * defualt label/tooltip.
  24300. * A name can be specified in encode.itemName,
  24301. * or dataItem.name (only for series option data),
  24302. * or provided in nameList from outside.
  24303. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  24304. */
  24305. listProto.initData = function (data, nameList, dimValueGetter) {
  24306. var notProvider = Source.isInstance(data) || isArrayLike(data);
  24307. if (notProvider) {
  24308. data = new DefaultDataProvider(data, this.dimensions.length);
  24309. }
  24310. if (__DEV__) {
  24311. if (!notProvider && (typeof data.getItem != 'function' || typeof data.count != 'function')) {
  24312. throw new Error('Inavlid data provider.');
  24313. }
  24314. }
  24315. this._rawData = data;
  24316. // Clear
  24317. this._storage = {};
  24318. this._indices = null;
  24319. this._nameList = nameList || [];
  24320. this._idList = [];
  24321. this._nameRepeatCount = {};
  24322. if (!dimValueGetter) {
  24323. this.hasItemOption = false;
  24324. }
  24325. /**
  24326. * @readOnly
  24327. */
  24328. this.defaultDimValueGetter = defaultDimValueGetters[
  24329. this._rawData.getSource().sourceFormat
  24330. ];
  24331. // Default dim value getter
  24332. this._dimValueGetter = dimValueGetter = dimValueGetter
  24333. || this.defaultDimValueGetter;
  24334. // Reset raw extent.
  24335. this._rawExtent = {};
  24336. this._initDataFromProvider(0, data.count());
  24337. // If data has no item option.
  24338. if (data.pure) {
  24339. this.hasItemOption = false;
  24340. }
  24341. };
  24342. listProto.getProvider = function () {
  24343. return this._rawData;
  24344. };
  24345. listProto.appendData = function (data) {
  24346. if (__DEV__) {
  24347. assert$1(!this._indices, 'appendData can only be called on raw data.');
  24348. }
  24349. var rawData = this._rawData;
  24350. var start = this.count();
  24351. rawData.appendData(data);
  24352. var end = rawData.count();
  24353. if (!rawData.persistent) {
  24354. end += start;
  24355. }
  24356. this._initDataFromProvider(start, end);
  24357. };
  24358. listProto._initDataFromProvider = function (start, end) {
  24359. // Optimize.
  24360. if (start >= end) {
  24361. return;
  24362. }
  24363. var chunkSize = this._chunkSize;
  24364. var rawData = this._rawData;
  24365. var storage = this._storage;
  24366. var dimensions = this.dimensions;
  24367. var dimLen = dimensions.length;
  24368. var dimensionInfoMap = this._dimensionInfos;
  24369. var nameList = this._nameList;
  24370. var idList = this._idList;
  24371. var rawExtent = this._rawExtent;
  24372. var nameRepeatCount = this._nameRepeatCount = {};
  24373. var nameDimIdx;
  24374. var chunkCount = this._chunkCount;
  24375. var lastChunkIndex = chunkCount - 1;
  24376. for (var i = 0; i < dimLen; i++) {
  24377. var dim = dimensions[i];
  24378. if (!rawExtent[dim]) {
  24379. rawExtent[dim] = getInitialExtent();
  24380. }
  24381. var dimInfo = dimensionInfoMap[dim];
  24382. if (dimInfo.otherDims.itemName === 0) {
  24383. nameDimIdx = this._nameDimIdx = i;
  24384. }
  24385. if (dimInfo.otherDims.itemId === 0) {
  24386. this._idDimIdx = i;
  24387. }
  24388. var DataCtor = dataCtors[dimInfo.type];
  24389. if (!storage[dim]) {
  24390. storage[dim] = [];
  24391. }
  24392. var resizeChunkArray = storage[dim][lastChunkIndex];
  24393. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  24394. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize));
  24395. // The cost of the copy is probably inconsiderable
  24396. // within the initial chunkSize.
  24397. for (var j = 0; j < resizeChunkArray.length; j++) {
  24398. newStore[j] = resizeChunkArray[j];
  24399. }
  24400. storage[dim][lastChunkIndex] = newStore;
  24401. }
  24402. // Create new chunks.
  24403. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  24404. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  24405. }
  24406. this._chunkCount = storage[dim].length;
  24407. }
  24408. var dataItem = new Array(dimLen);
  24409. for (var idx = start; idx < end; idx++) {
  24410. // NOTICE: Try not to write things into dataItem
  24411. dataItem = rawData.getItem(idx, dataItem);
  24412. // Each data item is value
  24413. // [1, 2]
  24414. // 2
  24415. // Bar chart, line chart which uses category axis
  24416. // only gives the 'y' value. 'x' value is the indices of category
  24417. // Use a tempValue to normalize the value to be a (x, y) value
  24418. var chunkIndex = Math.floor(idx / chunkSize);
  24419. var chunkOffset = idx % chunkSize;
  24420. // Store the data by dimensions
  24421. for (var k = 0; k < dimLen; k++) {
  24422. var dim = dimensions[k];
  24423. var dimStorage = storage[dim][chunkIndex];
  24424. // PENDING NULL is empty or zero
  24425. var val = this._dimValueGetter(dataItem, dim, idx, k);
  24426. dimStorage[chunkOffset] = val;
  24427. var dimRawExtent = rawExtent[dim];
  24428. if (val < dimRawExtent[0]) {
  24429. dimRawExtent[0] = val;
  24430. }
  24431. if (val > dimRawExtent[1]) {
  24432. dimRawExtent[1] = val;
  24433. }
  24434. }
  24435. // ??? FIXME not check by pure but sourceFormat?
  24436. // TODO refactor these logic.
  24437. if (!rawData.pure) {
  24438. var name = nameList[idx];
  24439. if (dataItem && name == null) {
  24440. // If dataItem is {name: ...}, it has highest priority.
  24441. // That is appropriate for many common cases.
  24442. if (dataItem.name != null) {
  24443. // There is no other place to persistent dataItem.name,
  24444. // so save it to nameList.
  24445. nameList[idx] = name = dataItem.name;
  24446. }
  24447. else if (nameDimIdx != null) {
  24448. var nameDim = dimensions[nameDimIdx];
  24449. var nameDimChunk = storage[nameDim][chunkIndex];
  24450. if (nameDimChunk) {
  24451. name = nameDimChunk[chunkOffset];
  24452. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  24453. if (ordinalMeta && ordinalMeta.categories.length) {
  24454. name = ordinalMeta.categories[name];
  24455. }
  24456. }
  24457. }
  24458. }
  24459. // Try using the id in option
  24460. // id or name is used on dynamical data, mapping old and new items.
  24461. var id = dataItem == null ? null : dataItem.id;
  24462. if (id == null && name != null) {
  24463. // Use name as id and add counter to avoid same name
  24464. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  24465. id = name;
  24466. if (nameRepeatCount[name] > 0) {
  24467. id += '__ec__' + nameRepeatCount[name];
  24468. }
  24469. nameRepeatCount[name]++;
  24470. }
  24471. id != null && (idList[idx] = id);
  24472. }
  24473. }
  24474. if (!rawData.persistent && rawData.clean) {
  24475. // Clean unused data if data source is typed array.
  24476. rawData.clean();
  24477. }
  24478. this._rawCount = this._count = end;
  24479. // Reset data extent
  24480. this._extent = {};
  24481. prepareInvertedIndex(this);
  24482. };
  24483. function prepareInvertedIndex(list) {
  24484. var invertedIndicesMap = list._invertedIndicesMap;
  24485. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  24486. var dimInfo = list._dimensionInfos[dim];
  24487. // Currently, only dimensions that has ordinalMeta can create inverted indices.
  24488. var ordinalMeta = dimInfo.ordinalMeta;
  24489. if (ordinalMeta) {
  24490. invertedIndices = invertedIndicesMap[dim] = new CtorUint32Array(
  24491. ordinalMeta.categories.length
  24492. );
  24493. // The default value of TypedArray is 0. To avoid miss
  24494. // mapping to 0, we should set it as NaN.
  24495. for (var i = 0; i < invertedIndices.length; i++) {
  24496. invertedIndices[i] = NaN;
  24497. }
  24498. for (var i = 0; i < list._count; i++) {
  24499. // Only support the case that all values are distinct.
  24500. invertedIndices[list.get(dim, i)] = i;
  24501. }
  24502. }
  24503. });
  24504. }
  24505. function getRawValueFromStore(list, dimIndex, rawIndex) {
  24506. var val;
  24507. if (dimIndex != null) {
  24508. var chunkSize = list._chunkSize;
  24509. var chunkIndex = Math.floor(rawIndex / chunkSize);
  24510. var chunkOffset = rawIndex % chunkSize;
  24511. var dim = list.dimensions[dimIndex];
  24512. var chunk = list._storage[dim][chunkIndex];
  24513. if (chunk) {
  24514. val = chunk[chunkOffset];
  24515. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  24516. if (ordinalMeta && ordinalMeta.categories.length) {
  24517. val = ordinalMeta.categories[val];
  24518. }
  24519. }
  24520. }
  24521. return val;
  24522. }
  24523. /**
  24524. * @return {number}
  24525. */
  24526. listProto.count = function () {
  24527. return this._count;
  24528. };
  24529. listProto.getIndices = function () {
  24530. var newIndices;
  24531. var indices = this._indices;
  24532. if (indices) {
  24533. var Ctor = indices.constructor;
  24534. var thisCount = this._count;
  24535. // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  24536. if (Ctor === Array) {
  24537. newIndices = new Ctor(thisCount);
  24538. for (var i = 0; i < thisCount; i++) {
  24539. newIndices[i] = indices[i];
  24540. }
  24541. }
  24542. else {
  24543. newIndices = new Ctor(indices.buffer, 0, thisCount);
  24544. }
  24545. }
  24546. else {
  24547. var Ctor = getIndicesCtor(this);
  24548. var newIndices = new Ctor(this.count());
  24549. for (var i = 0; i < newIndices.length; i++) {
  24550. newIndices[i] = i;
  24551. }
  24552. }
  24553. return newIndices;
  24554. };
  24555. /**
  24556. * Get value. Return NaN if idx is out of range.
  24557. * @param {string} dim Dim must be concrete name.
  24558. * @param {number} idx
  24559. * @param {boolean} stack
  24560. * @return {number}
  24561. */
  24562. listProto.get = function (dim, idx /*, stack */) {
  24563. if (!(idx >= 0 && idx < this._count)) {
  24564. return NaN;
  24565. }
  24566. var storage = this._storage;
  24567. if (!storage[dim]) {
  24568. // TODO Warn ?
  24569. return NaN;
  24570. }
  24571. idx = this.getRawIndex(idx);
  24572. var chunkIndex = Math.floor(idx / this._chunkSize);
  24573. var chunkOffset = idx % this._chunkSize;
  24574. var chunkStore = storage[dim][chunkIndex];
  24575. var value = chunkStore[chunkOffset];
  24576. // FIXME ordinal data type is not stackable
  24577. // if (stack) {
  24578. // var dimensionInfo = this._dimensionInfos[dim];
  24579. // if (dimensionInfo && dimensionInfo.stackable) {
  24580. // var stackedOn = this.stackedOn;
  24581. // while (stackedOn) {
  24582. // // Get no stacked data of stacked on
  24583. // var stackedValue = stackedOn.get(dim, idx);
  24584. // // Considering positive stack, negative stack and empty data
  24585. // if ((value >= 0 && stackedValue > 0) // Positive stack
  24586. // || (value <= 0 && stackedValue < 0) // Negative stack
  24587. // ) {
  24588. // value += stackedValue;
  24589. // }
  24590. // stackedOn = stackedOn.stackedOn;
  24591. // }
  24592. // }
  24593. // }
  24594. return value;
  24595. };
  24596. /**
  24597. * @param {string} dim concrete dim
  24598. * @param {number} rawIndex
  24599. * @return {number|string}
  24600. */
  24601. listProto.getByRawIndex = function (dim, rawIdx) {
  24602. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  24603. return NaN;
  24604. }
  24605. var dimStore = this._storage[dim];
  24606. if (!dimStore) {
  24607. // TODO Warn ?
  24608. return NaN;
  24609. }
  24610. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  24611. var chunkOffset = rawIdx % this._chunkSize;
  24612. var chunkStore = dimStore[chunkIndex];
  24613. return chunkStore[chunkOffset];
  24614. };
  24615. /**
  24616. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  24617. * Hack a much simpler _getFast
  24618. * @private
  24619. */
  24620. listProto._getFast = function (dim, rawIdx) {
  24621. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  24622. var chunkOffset = rawIdx % this._chunkSize;
  24623. var chunkStore = this._storage[dim][chunkIndex];
  24624. return chunkStore[chunkOffset];
  24625. };
  24626. /**
  24627. * Get value for multi dimensions.
  24628. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  24629. * @param {number} idx
  24630. * @return {number}
  24631. */
  24632. listProto.getValues = function (dimensions, idx /*, stack */) {
  24633. var values = [];
  24634. if (!isArray(dimensions)) {
  24635. // stack = idx;
  24636. idx = dimensions;
  24637. dimensions = this.dimensions;
  24638. }
  24639. for (var i = 0, len = dimensions.length; i < len; i++) {
  24640. values.push(this.get(dimensions[i], idx /*, stack */));
  24641. }
  24642. return values;
  24643. };
  24644. /**
  24645. * If value is NaN. Inlcuding '-'
  24646. * Only check the coord dimensions.
  24647. * @param {string} dim
  24648. * @param {number} idx
  24649. * @return {number}
  24650. */
  24651. listProto.hasValue = function (idx) {
  24652. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  24653. var dimensionInfos = this._dimensionInfos;
  24654. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  24655. if (
  24656. // Ordinal type can be string or number
  24657. dimensionInfos[dataDimsOnCoord[i]].type !== 'ordinal'
  24658. // FIXME check ordinal when using index?
  24659. && isNaN(this.get(dataDimsOnCoord[i], idx))
  24660. ) {
  24661. return false;
  24662. }
  24663. }
  24664. return true;
  24665. };
  24666. /**
  24667. * Get extent of data in one dimension
  24668. * @param {string} dim
  24669. * @param {boolean} stack
  24670. */
  24671. listProto.getDataExtent = function (dim /*, stack */) {
  24672. // Make sure use concrete dim as cache name.
  24673. dim = this.getDimension(dim);
  24674. var dimData = this._storage[dim];
  24675. var initialExtent = getInitialExtent();
  24676. // stack = !!((stack || false) && this.getCalculationInfo(dim));
  24677. if (!dimData) {
  24678. return initialExtent;
  24679. }
  24680. // Make more strict checkings to ensure hitting cache.
  24681. var currEnd = this.count();
  24682. // var cacheName = [dim, !!stack].join('_');
  24683. // var cacheName = dim;
  24684. // Consider the most cases when using data zoom, `getDataExtent`
  24685. // happened before filtering. We cache raw extent, which is not
  24686. // necessary to be cleared and recalculated when restore data.
  24687. var useRaw = !this._indices; // && !stack;
  24688. var dimExtent;
  24689. if (useRaw) {
  24690. return this._rawExtent[dim].slice();
  24691. }
  24692. dimExtent = this._extent[dim];
  24693. if (dimExtent) {
  24694. return dimExtent.slice();
  24695. }
  24696. dimExtent = initialExtent;
  24697. var min = dimExtent[0];
  24698. var max = dimExtent[1];
  24699. for (var i = 0; i < currEnd; i++) {
  24700. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  24701. var value = this._getFast(dim, this.getRawIndex(i));
  24702. value < min && (min = value);
  24703. value > max && (max = value);
  24704. }
  24705. dimExtent = [min, max];
  24706. this._extent[dim] = dimExtent;
  24707. return dimExtent;
  24708. };
  24709. /**
  24710. * Optimize for the scenario that data is filtered by a given extent.
  24711. * Consider that if data amount is more than hundreds of thousand,
  24712. * extent calculation will cost more than 10ms and the cache will
  24713. * be erased because of the filtering.
  24714. */
  24715. listProto.getApproximateExtent = function (dim /*, stack */) {
  24716. dim = this.getDimension(dim);
  24717. return this._approximateExtent[dim] || this.getDataExtent(dim /*, stack */);
  24718. };
  24719. listProto.setApproximateExtent = function (extent, dim /*, stack */) {
  24720. dim = this.getDimension(dim);
  24721. this._approximateExtent[dim] = extent.slice();
  24722. };
  24723. /**
  24724. * @param {string} key
  24725. * @return {*}
  24726. */
  24727. listProto.getCalculationInfo = function (key) {
  24728. return this._calculationInfo[key];
  24729. };
  24730. /**
  24731. * @param {string|Object} key or k-v object
  24732. * @param {*} [value]
  24733. */
  24734. listProto.setCalculationInfo = function (key, value) {
  24735. isObject$4(key)
  24736. ? extend(this._calculationInfo, key)
  24737. : (this._calculationInfo[key] = value);
  24738. };
  24739. /**
  24740. * Get sum of data in one dimension
  24741. * @param {string} dim
  24742. */
  24743. listProto.getSum = function (dim /*, stack */) {
  24744. var dimData = this._storage[dim];
  24745. var sum = 0;
  24746. if (dimData) {
  24747. for (var i = 0, len = this.count(); i < len; i++) {
  24748. var value = this.get(dim, i /*, stack */);
  24749. if (!isNaN(value)) {
  24750. sum += value;
  24751. }
  24752. }
  24753. }
  24754. return sum;
  24755. };
  24756. /**
  24757. * Get median of data in one dimension
  24758. * @param {string} dim
  24759. */
  24760. listProto.getMedian = function (dim /*, stack */) {
  24761. var dimDataArray = [];
  24762. // map all data of one dimension
  24763. this.each(dim, function (val, idx) {
  24764. if (!isNaN(val)) {
  24765. dimDataArray.push(val);
  24766. }
  24767. });
  24768. // TODO
  24769. // Use quick select?
  24770. // immutability & sort
  24771. var sortedDimDataArray = [].concat(dimDataArray).sort(function(a, b) {
  24772. return a - b;
  24773. });
  24774. var len = this.count();
  24775. // calculate median
  24776. return len === 0 ? 0 :
  24777. len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] :
  24778. (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  24779. };
  24780. // /**
  24781. // * Retreive the index with given value
  24782. // * @param {string} dim Concrete dimension.
  24783. // * @param {number} value
  24784. // * @return {number}
  24785. // */
  24786. // Currently incorrect: should return dataIndex but not rawIndex.
  24787. // Do not fix it until this method is to be used somewhere.
  24788. // FIXME Precision of float value
  24789. // listProto.indexOf = function (dim, value) {
  24790. // var storage = this._storage;
  24791. // var dimData = storage[dim];
  24792. // var chunkSize = this._chunkSize;
  24793. // if (dimData) {
  24794. // for (var i = 0, len = this.count(); i < len; i++) {
  24795. // var chunkIndex = Math.floor(i / chunkSize);
  24796. // var chunkOffset = i % chunkSize;
  24797. // if (dimData[chunkIndex][chunkOffset] === value) {
  24798. // return i;
  24799. // }
  24800. // }
  24801. // }
  24802. // return -1;
  24803. // };
  24804. /**
  24805. * Only support the dimension which inverted index created.
  24806. * Do not support other cases until required.
  24807. * @param {string} concrete dim
  24808. * @param {number|string} value
  24809. * @return {number} rawIndex
  24810. */
  24811. listProto.rawIndexOf = function (dim, value) {
  24812. var invertedIndices = dim && this._invertedIndicesMap[dim];
  24813. if (__DEV__) {
  24814. if (!invertedIndices) {
  24815. throw new Error('Do not supported yet');
  24816. }
  24817. }
  24818. var rawIndex = invertedIndices[value];
  24819. if (rawIndex == null || isNaN(rawIndex)) {
  24820. return -1;
  24821. }
  24822. return rawIndex;
  24823. };
  24824. /**
  24825. * Retreive the index with given name
  24826. * @param {number} idx
  24827. * @param {number} name
  24828. * @return {number}
  24829. */
  24830. listProto.indexOfName = function (name) {
  24831. for (var i = 0, len = this.count(); i < len; i++) {
  24832. if (this.getName(i) === name) {
  24833. return i;
  24834. }
  24835. }
  24836. return -1;
  24837. };
  24838. /**
  24839. * Retreive the index with given raw data index
  24840. * @param {number} idx
  24841. * @param {number} name
  24842. * @return {number}
  24843. */
  24844. listProto.indexOfRawIndex = function (rawIndex) {
  24845. if (!this._indices) {
  24846. return rawIndex;
  24847. }
  24848. if (rawIndex >= this._rawCount || rawIndex < 0) {
  24849. return -1;
  24850. }
  24851. // Indices are ascending
  24852. var indices = this._indices;
  24853. // If rawIndex === dataIndex
  24854. var rawDataIndex = indices[rawIndex];
  24855. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  24856. return rawIndex;
  24857. }
  24858. var left = 0;
  24859. var right = this._count - 1;
  24860. while (left <= right) {
  24861. var mid = (left + right) / 2 | 0;
  24862. if (indices[mid] < rawIndex) {
  24863. left = mid + 1;
  24864. }
  24865. else if (indices[mid] > rawIndex) {
  24866. right = mid - 1;
  24867. }
  24868. else {
  24869. return mid;
  24870. }
  24871. }
  24872. return -1;
  24873. };
  24874. /**
  24875. * Retreive the index of nearest value
  24876. * @param {string} dim
  24877. * @param {number} value
  24878. * @param {number} [maxDistance=Infinity]
  24879. * @return {Array.<number>} Considere multiple points has the same value.
  24880. */
  24881. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  24882. var storage = this._storage;
  24883. var dimData = storage[dim];
  24884. var nearestIndices = [];
  24885. if (!dimData) {
  24886. return nearestIndices;
  24887. }
  24888. if (maxDistance == null) {
  24889. maxDistance = Infinity;
  24890. }
  24891. var minDist = Number.MAX_VALUE;
  24892. var minDiff = -1;
  24893. for (var i = 0, len = this.count(); i < len; i++) {
  24894. var diff = value - this.get(dim, i /*, stack */);
  24895. var dist = Math.abs(diff);
  24896. if (diff <= maxDistance && dist <= minDist) {
  24897. // For the case of two data are same on xAxis, which has sequence data.
  24898. // Show the nearest index
  24899. // https://github.com/ecomfe/echarts/issues/2869
  24900. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  24901. minDist = dist;
  24902. minDiff = diff;
  24903. nearestIndices.length = 0;
  24904. }
  24905. nearestIndices.push(i);
  24906. }
  24907. }
  24908. return nearestIndices;
  24909. };
  24910. /**
  24911. * Get raw data index
  24912. * @param {number} idx
  24913. * @return {number}
  24914. */
  24915. listProto.getRawIndex = getRawIndexWithoutIndices;
  24916. function getRawIndexWithoutIndices(idx) {
  24917. return idx;
  24918. }
  24919. function getRawIndexWithIndices(idx) {
  24920. if (idx < this._count && idx >= 0) {
  24921. return this._indices[idx];
  24922. }
  24923. return -1;
  24924. }
  24925. /**
  24926. * Get raw data item
  24927. * @param {number} idx
  24928. * @return {number}
  24929. */
  24930. listProto.getRawDataItem = function (idx) {
  24931. if (!this._rawData.persistent) {
  24932. var val = [];
  24933. for (var i = 0; i < this.dimensions.length; i++) {
  24934. var dim = this.dimensions[i];
  24935. val.push(this.get(dim, idx));
  24936. }
  24937. return val;
  24938. }
  24939. else {
  24940. return this._rawData.getItem(this.getRawIndex(idx));
  24941. }
  24942. };
  24943. /**
  24944. * @param {number} idx
  24945. * @param {boolean} [notDefaultIdx=false]
  24946. * @return {string}
  24947. */
  24948. listProto.getName = function (idx) {
  24949. var rawIndex = this.getRawIndex(idx);
  24950. return this._nameList[rawIndex]
  24951. || getRawValueFromStore(this, this._nameDimIdx, rawIndex)
  24952. || '';
  24953. };
  24954. /**
  24955. * @param {number} idx
  24956. * @param {boolean} [notDefaultIdx=false]
  24957. * @return {string}
  24958. */
  24959. listProto.getId = function (idx) {
  24960. return getId(this, this.getRawIndex(idx));
  24961. };
  24962. function getId(list, rawIndex) {
  24963. var id = list._idList[rawIndex];
  24964. if (id == null) {
  24965. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  24966. }
  24967. if (id == null) {
  24968. // FIXME Check the usage in graph, should not use prefix.
  24969. id = ID_PREFIX + rawIndex;
  24970. }
  24971. return id;
  24972. }
  24973. function normalizeDimensions(dimensions) {
  24974. if (!isArray(dimensions)) {
  24975. dimensions = [dimensions];
  24976. }
  24977. return dimensions;
  24978. }
  24979. function validateDimensions(list, dims) {
  24980. for (var i = 0; i < dims.length; i++) {
  24981. // stroage may be empty when no data, so use
  24982. // dimensionInfos to check.
  24983. if (!list._dimensionInfos[dims[i]]) {
  24984. console.error('Unkown dimension ' + dims[i]);
  24985. }
  24986. }
  24987. }
  24988. /**
  24989. * Data iteration
  24990. * @param {string|Array.<string>}
  24991. * @param {Function} cb
  24992. * @param {*} [context=this]
  24993. *
  24994. * @example
  24995. * list.each('x', function (x, idx) {});
  24996. * list.each(['x', 'y'], function (x, y, idx) {});
  24997. * list.each(function (idx) {})
  24998. */
  24999. listProto.each = function (dims, cb, context, contextCompat) {
  25000. 'use strict';
  25001. if (!this._count) {
  25002. return;
  25003. }
  25004. if (typeof dims === 'function') {
  25005. contextCompat = context;
  25006. context = cb;
  25007. cb = dims;
  25008. dims = [];
  25009. }
  25010. // contextCompat just for compat echarts3
  25011. context = context || contextCompat || this;
  25012. dims = map(normalizeDimensions(dims), this.getDimension, this);
  25013. if (__DEV__) {
  25014. validateDimensions(this, dims);
  25015. }
  25016. var dimSize = dims.length;
  25017. for (var i = 0; i < this.count(); i++) {
  25018. // Simple optimization
  25019. switch (dimSize) {
  25020. case 0:
  25021. cb.call(context, i);
  25022. break;
  25023. case 1:
  25024. cb.call(context, this.get(dims[0], i), i);
  25025. break;
  25026. case 2:
  25027. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  25028. break;
  25029. default:
  25030. var k = 0;
  25031. var value = [];
  25032. for (; k < dimSize; k++) {
  25033. value[k] = this.get(dims[k], i);
  25034. }
  25035. // Index
  25036. value[k] = i;
  25037. cb.apply(context, value);
  25038. }
  25039. }
  25040. };
  25041. /**
  25042. * Data filter
  25043. * @param {string|Array.<string>}
  25044. * @param {Function} cb
  25045. * @param {*} [context=this]
  25046. */
  25047. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  25048. 'use strict';
  25049. if (!this._count) {
  25050. return;
  25051. }
  25052. if (typeof dimensions === 'function') {
  25053. contextCompat = context;
  25054. context = cb;
  25055. cb = dimensions;
  25056. dimensions = [];
  25057. }
  25058. // contextCompat just for compat echarts3
  25059. context = context || contextCompat || this;
  25060. dimensions = map(
  25061. normalizeDimensions(dimensions), this.getDimension, this
  25062. );
  25063. if (__DEV__) {
  25064. validateDimensions(this, dimensions);
  25065. }
  25066. var count = this.count();
  25067. var Ctor = getIndicesCtor(this);
  25068. var newIndices = new Ctor(count);
  25069. var value = [];
  25070. var dimSize = dimensions.length;
  25071. var offset = 0;
  25072. var dim0 = dimensions[0];
  25073. for (var i = 0; i < count; i++) {
  25074. var keep;
  25075. var rawIdx = this.getRawIndex(i);
  25076. // Simple optimization
  25077. if (dimSize === 0) {
  25078. keep = cb.call(context, i);
  25079. }
  25080. else if (dimSize === 1) {
  25081. var val = this._getFast(dim0, rawIdx);
  25082. keep = cb.call(context, val, i);
  25083. }
  25084. else {
  25085. for (var k = 0; k < dimSize; k++) {
  25086. value[k] = this._getFast(dim0, rawIdx);
  25087. }
  25088. value[k] = i;
  25089. keep = cb.apply(context, value);
  25090. }
  25091. if (keep) {
  25092. newIndices[offset++] = rawIdx;
  25093. }
  25094. }
  25095. // Set indices after filtered.
  25096. if (offset < count) {
  25097. this._indices = newIndices;
  25098. }
  25099. this._count = offset;
  25100. // Reset data extent
  25101. this._extent = {};
  25102. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25103. return this;
  25104. };
  25105. /**
  25106. * Select data in range. (For optimization of filter)
  25107. * (Manually inline code, support 5 million data filtering in data zoom.)
  25108. */
  25109. listProto.selectRange = function (range) {
  25110. 'use strict';
  25111. if (!this._count) {
  25112. return;
  25113. }
  25114. var dimensions = [];
  25115. for (var dim in range) {
  25116. if (range.hasOwnProperty(dim)) {
  25117. dimensions.push(dim);
  25118. }
  25119. }
  25120. if (__DEV__) {
  25121. validateDimensions(this, dimensions);
  25122. }
  25123. var dimSize = dimensions.length;
  25124. if (!dimSize) {
  25125. return;
  25126. }
  25127. var originalCount = this.count();
  25128. var Ctor = getIndicesCtor(this);
  25129. var newIndices = new Ctor(originalCount);
  25130. var offset = 0;
  25131. var dim0 = dimensions[0];
  25132. var min = range[dim0][0];
  25133. var max = range[dim0][1];
  25134. var quickFinished = false;
  25135. if (!this._indices) {
  25136. // Extreme optimization for common case. About 2x faster in chrome.
  25137. var idx = 0;
  25138. if (dimSize === 1) {
  25139. var dimStorage = this._storage[dimensions[0]];
  25140. for (var k = 0; k < this._chunkCount; k++) {
  25141. var chunkStorage = dimStorage[k];
  25142. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25143. for (var i = 0; i < len; i++) {
  25144. var val = chunkStorage[i];
  25145. // NaN will not be filtered. Consider the case, in line chart, empty
  25146. // value indicates the line should be broken. But for the case like
  25147. // scatter plot, a data item with empty value will not be rendered,
  25148. // but the axis extent may be effected if some other dim of the data
  25149. // item has value. Fortunately it is not a significant negative effect.
  25150. if (
  25151. (val >= min && val <= max) || isNaN(val)
  25152. ) {
  25153. newIndices[offset++] = idx;
  25154. }
  25155. idx++;
  25156. }
  25157. }
  25158. quickFinished = true;
  25159. }
  25160. else if (dimSize === 2) {
  25161. var dimStorage = this._storage[dim0];
  25162. var dimStorage2 = this._storage[dimensions[1]];
  25163. var min2 = range[dimensions[1]][0];
  25164. var max2 = range[dimensions[1]][1];
  25165. for (var k = 0; k < this._chunkCount; k++) {
  25166. var chunkStorage = dimStorage[k];
  25167. var chunkStorage2= dimStorage2[k];
  25168. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25169. for (var i = 0; i < len; i++) {
  25170. var val = chunkStorage[i];
  25171. var val2 = chunkStorage2[i];
  25172. // Do not filter NaN, see comment above.
  25173. if ((
  25174. (val >= min && val <= max) || isNaN(val)
  25175. )
  25176. && (
  25177. (val2 >= min2 && val2 <= max2) || isNaN(val2)
  25178. )
  25179. ) {
  25180. newIndices[offset++] = idx;
  25181. }
  25182. idx++;
  25183. }
  25184. }
  25185. quickFinished = true;
  25186. }
  25187. }
  25188. if (!quickFinished) {
  25189. if (dimSize === 1) {
  25190. for (var i = 0; i < originalCount; i++) {
  25191. var rawIndex = this.getRawIndex(i);
  25192. var val = this._getFast(dim0, rawIndex);
  25193. // Do not filter NaN, see comment above.
  25194. if (
  25195. (val >= min && val <= max) || isNaN(val)
  25196. ) {
  25197. newIndices[offset++] = rawIndex;
  25198. }
  25199. }
  25200. }
  25201. else {
  25202. for (var i = 0; i < originalCount; i++) {
  25203. var keep = true;
  25204. var rawIndex = this.getRawIndex(i);
  25205. for (var k = 0; k < dimSize; k++) {
  25206. var dimk = dimensions[k];
  25207. var val = this._getFast(dim, rawIndex);
  25208. // Do not filter NaN, see comment above.
  25209. if (val < range[dimk][0] || val > range[dimk][1]) {
  25210. keep = false;
  25211. }
  25212. }
  25213. if (keep) {
  25214. newIndices[offset++] = this.getRawIndex(i);
  25215. }
  25216. }
  25217. }
  25218. }
  25219. // Set indices after filtered.
  25220. if (offset < originalCount) {
  25221. this._indices = newIndices;
  25222. }
  25223. this._count = offset;
  25224. // Reset data extent
  25225. this._extent = {};
  25226. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25227. return this;
  25228. };
  25229. /**
  25230. * Data mapping to a plain array
  25231. * @param {string|Array.<string>} [dimensions]
  25232. * @param {Function} cb
  25233. * @param {*} [context=this]
  25234. * @return {Array}
  25235. */
  25236. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  25237. 'use strict';
  25238. if (typeof dimensions === 'function') {
  25239. contextCompat = context;
  25240. context = cb;
  25241. cb = dimensions;
  25242. dimensions = [];
  25243. }
  25244. // contextCompat just for compat echarts3
  25245. context = context || contextCompat || this;
  25246. var result = [];
  25247. this.each(dimensions, function () {
  25248. result.push(cb && cb.apply(this, arguments));
  25249. }, context);
  25250. return result;
  25251. };
  25252. // Data in excludeDimensions is copied, otherwise transfered.
  25253. function cloneListForMapAndSample(original, excludeDimensions) {
  25254. var allDimensions = original.dimensions;
  25255. var list = new List(
  25256. map(allDimensions, original.getDimensionInfo, original),
  25257. original.hostModel
  25258. );
  25259. // FIXME If needs stackedOn, value may already been stacked
  25260. transferProperties(list, original);
  25261. var storage = list._storage = {};
  25262. var originalStorage = original._storage;
  25263. // Init storage
  25264. for (var i = 0; i < allDimensions.length; i++) {
  25265. var dim = allDimensions[i];
  25266. if (originalStorage[dim]) {
  25267. // Notice that we do not reset invertedIndicesMap here, becuase
  25268. // there is no scenario of mapping or sampling ordinal dimension.
  25269. if (indexOf(excludeDimensions, dim) >= 0) {
  25270. storage[dim] = cloneDimStore(originalStorage[dim]);
  25271. list._rawExtent[dim] = getInitialExtent();
  25272. list._extent[dim] = null;
  25273. }
  25274. else {
  25275. // Direct reference for other dimensions
  25276. storage[dim] = originalStorage[dim];
  25277. }
  25278. }
  25279. }
  25280. return list;
  25281. }
  25282. function cloneDimStore(originalDimStore) {
  25283. var newDimStore = new Array(originalDimStore.length);
  25284. for (var j = 0; j < originalDimStore.length; j++) {
  25285. newDimStore[j] = cloneChunk(originalDimStore[j]);
  25286. }
  25287. return newDimStore;
  25288. }
  25289. function getInitialExtent() {
  25290. return [Infinity, -Infinity];
  25291. }
  25292. /**
  25293. * Data mapping to a new List with given dimensions
  25294. * @param {string|Array.<string>} dimensions
  25295. * @param {Function} cb
  25296. * @param {*} [context=this]
  25297. * @return {Array}
  25298. */
  25299. listProto.map = function (dimensions, cb, context, contextCompat) {
  25300. 'use strict';
  25301. // contextCompat just for compat echarts3
  25302. context = context || contextCompat || this;
  25303. dimensions = map(
  25304. normalizeDimensions(dimensions), this.getDimension, this
  25305. );
  25306. if (__DEV__) {
  25307. validateDimensions(this, dimensions);
  25308. }
  25309. var list = cloneListForMapAndSample(this, dimensions);
  25310. // Following properties are all immutable.
  25311. // So we can reference to the same value
  25312. list._indices = this._indices;
  25313. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25314. var storage = list._storage;
  25315. var tmpRetValue = [];
  25316. var chunkSize = this._chunkSize;
  25317. var dimSize = dimensions.length;
  25318. var dataCount = this.count();
  25319. var values = [];
  25320. var rawExtent = list._rawExtent;
  25321. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  25322. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  25323. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex /*, stack */);
  25324. }
  25325. values[dimSize] = dataIndex;
  25326. var retValue = cb && cb.apply(context, values);
  25327. if (retValue != null) {
  25328. // a number or string (in oridinal dimension)?
  25329. if (typeof retValue !== 'object') {
  25330. tmpRetValue[0] = retValue;
  25331. retValue = tmpRetValue;
  25332. }
  25333. var rawIndex = this.getRawIndex(dataIndex);
  25334. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25335. var chunkOffset = rawIndex % chunkSize;
  25336. for (var i = 0; i < retValue.length; i++) {
  25337. var dim = dimensions[i];
  25338. var val = retValue[i];
  25339. var rawExtentOnDim = rawExtent[dim];
  25340. var dimStore = storage[dim];
  25341. if (dimStore) {
  25342. dimStore[chunkIndex][chunkOffset] = val;
  25343. }
  25344. if (val < rawExtentOnDim[0]) {
  25345. rawExtentOnDim[0] = val;
  25346. }
  25347. if (val > rawExtentOnDim[1]) {
  25348. rawExtentOnDim[1] = val;
  25349. }
  25350. }
  25351. }
  25352. }
  25353. return list;
  25354. };
  25355. /**
  25356. * Large data down sampling on given dimension
  25357. * @param {string} dimension
  25358. * @param {number} rate
  25359. * @param {Function} sampleValue
  25360. * @param {Function} sampleIndex Sample index for name and id
  25361. */
  25362. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  25363. var list = cloneListForMapAndSample(this, [dimension]);
  25364. var targetStorage = list._storage;
  25365. var frameValues = [];
  25366. var frameSize = Math.floor(1 / rate);
  25367. var dimStore = targetStorage[dimension];
  25368. var len = this.count();
  25369. var chunkSize = this._chunkSize;
  25370. var rawExtentOnDim = list._rawExtent[dimension];
  25371. var newIndices = new (getIndicesCtor(this))(len);
  25372. var offset = 0;
  25373. for (var i = 0; i < len; i += frameSize) {
  25374. // Last frame
  25375. if (frameSize > len - i) {
  25376. frameSize = len - i;
  25377. frameValues.length = frameSize;
  25378. }
  25379. for (var k = 0; k < frameSize; k++) {
  25380. var dataIdx = this.getRawIndex(i + k);
  25381. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  25382. var originalChunkOffset = dataIdx % chunkSize;
  25383. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  25384. }
  25385. var value = sampleValue(frameValues);
  25386. var sampleFrameIdx = this.getRawIndex(
  25387. Math.min(i + sampleIndex(frameValues, value) || 0, len - 1)
  25388. );
  25389. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  25390. var sampleChunkOffset = sampleFrameIdx % chunkSize;
  25391. // Only write value on the filtered data
  25392. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  25393. if (value < rawExtentOnDim[0]) {
  25394. rawExtentOnDim[0] = value;
  25395. }
  25396. if (value > rawExtentOnDim[1]) {
  25397. rawExtentOnDim[1] = value;
  25398. }
  25399. newIndices[offset++] = sampleFrameIdx;
  25400. }
  25401. list._count = offset;
  25402. list._indices = newIndices;
  25403. list.getRawIndex = getRawIndexWithIndices;
  25404. return list;
  25405. };
  25406. /**
  25407. * Get model of one data item.
  25408. *
  25409. * @param {number} idx
  25410. */
  25411. // FIXME Model proxy ?
  25412. listProto.getItemModel = function (idx) {
  25413. var hostModel = this.hostModel;
  25414. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  25415. };
  25416. /**
  25417. * Create a data differ
  25418. * @param {module:echarts/data/List} otherList
  25419. * @return {module:echarts/data/DataDiffer}
  25420. */
  25421. listProto.diff = function (otherList) {
  25422. var thisList = this;
  25423. return new DataDiffer(
  25424. otherList ? otherList.getIndices() : [],
  25425. this.getIndices(),
  25426. function (idx) {
  25427. return getId(otherList, idx);
  25428. },
  25429. function (idx) {
  25430. return getId(thisList, idx);
  25431. }
  25432. );
  25433. };
  25434. /**
  25435. * Get visual property.
  25436. * @param {string} key
  25437. */
  25438. listProto.getVisual = function (key) {
  25439. var visual = this._visual;
  25440. return visual && visual[key];
  25441. };
  25442. /**
  25443. * Set visual property
  25444. * @param {string|Object} key
  25445. * @param {*} [value]
  25446. *
  25447. * @example
  25448. * setVisual('color', color);
  25449. * setVisual({
  25450. * 'color': color
  25451. * });
  25452. */
  25453. listProto.setVisual = function (key, val) {
  25454. if (isObject$4(key)) {
  25455. for (var name in key) {
  25456. if (key.hasOwnProperty(name)) {
  25457. this.setVisual(name, key[name]);
  25458. }
  25459. }
  25460. return;
  25461. }
  25462. this._visual = this._visual || {};
  25463. this._visual[key] = val;
  25464. };
  25465. /**
  25466. * Set layout property.
  25467. * @param {string|Object} key
  25468. * @param {*} [val]
  25469. */
  25470. listProto.setLayout = function (key, val) {
  25471. if (isObject$4(key)) {
  25472. for (var name in key) {
  25473. if (key.hasOwnProperty(name)) {
  25474. this.setLayout(name, key[name]);
  25475. }
  25476. }
  25477. return;
  25478. }
  25479. this._layout[key] = val;
  25480. };
  25481. /**
  25482. * Get layout property.
  25483. * @param {string} key.
  25484. * @return {*}
  25485. */
  25486. listProto.getLayout = function (key) {
  25487. return this._layout[key];
  25488. };
  25489. /**
  25490. * Get layout of single data item
  25491. * @param {number} idx
  25492. */
  25493. listProto.getItemLayout = function (idx) {
  25494. return this._itemLayouts[idx];
  25495. };
  25496. /**
  25497. * Set layout of single data item
  25498. * @param {number} idx
  25499. * @param {Object} layout
  25500. * @param {boolean=} [merge=false]
  25501. */
  25502. listProto.setItemLayout = function (idx, layout, merge$$1) {
  25503. this._itemLayouts[idx] = merge$$1
  25504. ? extend(this._itemLayouts[idx] || {}, layout)
  25505. : layout;
  25506. };
  25507. /**
  25508. * Clear all layout of single data item
  25509. */
  25510. listProto.clearItemLayouts = function () {
  25511. this._itemLayouts.length = 0;
  25512. };
  25513. /**
  25514. * Get visual property of single data item
  25515. * @param {number} idx
  25516. * @param {string} key
  25517. * @param {boolean} [ignoreParent=false]
  25518. */
  25519. listProto.getItemVisual = function (idx, key, ignoreParent) {
  25520. var itemVisual = this._itemVisuals[idx];
  25521. var val = itemVisual && itemVisual[key];
  25522. if (val == null && !ignoreParent) {
  25523. // Use global visual property
  25524. return this.getVisual(key);
  25525. }
  25526. return val;
  25527. };
  25528. /**
  25529. * Set visual property of single data item
  25530. *
  25531. * @param {number} idx
  25532. * @param {string|Object} key
  25533. * @param {*} [value]
  25534. *
  25535. * @example
  25536. * setItemVisual(0, 'color', color);
  25537. * setItemVisual(0, {
  25538. * 'color': color
  25539. * });
  25540. */
  25541. listProto.setItemVisual = function (idx, key, value) {
  25542. var itemVisual = this._itemVisuals[idx] || {};
  25543. var hasItemVisual = this.hasItemVisual;
  25544. this._itemVisuals[idx] = itemVisual;
  25545. if (isObject$4(key)) {
  25546. for (var name in key) {
  25547. if (key.hasOwnProperty(name)) {
  25548. itemVisual[name] = key[name];
  25549. hasItemVisual[name] = true;
  25550. }
  25551. }
  25552. return;
  25553. }
  25554. itemVisual[key] = value;
  25555. hasItemVisual[key] = true;
  25556. };
  25557. /**
  25558. * Clear itemVisuals and list visual.
  25559. */
  25560. listProto.clearAllVisual = function () {
  25561. this._visual = {};
  25562. this._itemVisuals = [];
  25563. this.hasItemVisual = {};
  25564. };
  25565. var setItemDataAndSeriesIndex = function (child) {
  25566. child.seriesIndex = this.seriesIndex;
  25567. child.dataIndex = this.dataIndex;
  25568. child.dataType = this.dataType;
  25569. };
  25570. /**
  25571. * Set graphic element relative to data. It can be set as null
  25572. * @param {number} idx
  25573. * @param {module:zrender/Element} [el]
  25574. */
  25575. listProto.setItemGraphicEl = function (idx, el) {
  25576. var hostModel = this.hostModel;
  25577. if (el) {
  25578. // Add data index and series index for indexing the data by element
  25579. // Useful in tooltip
  25580. el.dataIndex = idx;
  25581. el.dataType = this.dataType;
  25582. el.seriesIndex = hostModel && hostModel.seriesIndex;
  25583. if (el.type === 'group') {
  25584. el.traverse(setItemDataAndSeriesIndex, el);
  25585. }
  25586. }
  25587. this._graphicEls[idx] = el;
  25588. };
  25589. /**
  25590. * @param {number} idx
  25591. * @return {module:zrender/Element}
  25592. */
  25593. listProto.getItemGraphicEl = function (idx) {
  25594. return this._graphicEls[idx];
  25595. };
  25596. /**
  25597. * @param {Function} cb
  25598. * @param {*} context
  25599. */
  25600. listProto.eachItemGraphicEl = function (cb, context) {
  25601. each$1(this._graphicEls, function (el, idx) {
  25602. if (el) {
  25603. cb && cb.call(context, el, idx);
  25604. }
  25605. });
  25606. };
  25607. /**
  25608. * Shallow clone a new list except visual and layout properties, and graph elements.
  25609. * New list only change the indices.
  25610. */
  25611. listProto.cloneShallow = function (list) {
  25612. if (!list) {
  25613. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  25614. list = new List(dimensionInfoList, this.hostModel);
  25615. }
  25616. // FIXME
  25617. list._storage = this._storage;
  25618. transferProperties(list, this);
  25619. // Clone will not change the data extent and indices
  25620. if (this._indices) {
  25621. var Ctor = this._indices.constructor;
  25622. list._indices = new Ctor(this._indices);
  25623. }
  25624. else {
  25625. list._indices = null;
  25626. }
  25627. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25628. return list;
  25629. };
  25630. /**
  25631. * Wrap some method to add more feature
  25632. * @param {string} methodName
  25633. * @param {Function} injectFunction
  25634. */
  25635. listProto.wrapMethod = function (methodName, injectFunction) {
  25636. var originalMethod = this[methodName];
  25637. if (typeof originalMethod !== 'function') {
  25638. return;
  25639. }
  25640. this.__wrappedMethods = this.__wrappedMethods || [];
  25641. this.__wrappedMethods.push(methodName);
  25642. this[methodName] = function () {
  25643. var res = originalMethod.apply(this, arguments);
  25644. return injectFunction.apply(this, [res].concat(slice(arguments)));
  25645. };
  25646. };
  25647. // Methods that create a new list based on this list should be listed here.
  25648. // Notice that those method should `RETURN` the new list.
  25649. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map'];
  25650. // Methods that change indices of this list should be listed here.
  25651. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  25652. /*
  25653. * Licensed to the Apache Software Foundation (ASF) under one
  25654. * or more contributor license agreements. See the NOTICE file
  25655. * distributed with this work for additional information
  25656. * regarding copyright ownership. The ASF licenses this file
  25657. * to you under the Apache License, Version 2.0 (the
  25658. * "License"); you may not use this file except in compliance
  25659. * with the License. You may obtain a copy of the License at
  25660. *
  25661. * http://www.apache.org/licenses/LICENSE-2.0
  25662. *
  25663. * Unless required by applicable law or agreed to in writing,
  25664. * software distributed under the License is distributed on an
  25665. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25666. * KIND, either express or implied. See the License for the
  25667. * specific language governing permissions and limitations
  25668. * under the License.
  25669. */
  25670. /**
  25671. * @deprecated
  25672. * Use `echarts/data/helper/createDimensions` instead.
  25673. */
  25674. /**
  25675. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  25676. *
  25677. * Complete the dimensions array, by user defined `dimension` and `encode`,
  25678. * and guessing from the data structure.
  25679. * If no 'value' dimension specified, the first no-named dimension will be
  25680. * named as 'value'.
  25681. *
  25682. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  25683. * provides not only dim template, but also default order.
  25684. * properties: 'name', 'type', 'displayName'.
  25685. * `name` of each item provides default coord name.
  25686. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  25687. * provide dims count that the sysDim required.
  25688. * [{ordinalMeta}] can be specified.
  25689. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  25690. * @param {Object} [opt]
  25691. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  25692. * For example: ['asdf', {name, type}, ...].
  25693. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  25694. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  25695. * If not specified, extra dim names will be:
  25696. * 'value', 'value0', 'value1', ...
  25697. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  25698. * If `generateCoordCount` specified, the generated dim names will be:
  25699. * `generateCoord` + 0, `generateCoord` + 1, ...
  25700. * can be Infinity, indicate that use all of the remain columns.
  25701. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  25702. * @param {number} [opt.encodeDefaulter] If not specified, auto find the next available data dim.
  25703. * @return {Array.<Object>} [{
  25704. * name: string mandatory,
  25705. * displayName: string, the origin name in dimsDef, see source helper.
  25706. * If displayName given, the tooltip will displayed vertically.
  25707. * coordDim: string mandatory,
  25708. * coordDimIndex: number mandatory,
  25709. * type: string optional,
  25710. * otherDims: { never null/undefined
  25711. * tooltip: number optional,
  25712. * label: number optional,
  25713. * itemName: number optional,
  25714. * seriesName: number optional,
  25715. * },
  25716. * isExtraCoord: boolean true if coord is generated
  25717. * (not specified in encode and not series specified)
  25718. * other props ...
  25719. * }]
  25720. */
  25721. function completeDimensions(sysDims, source, opt) {
  25722. if (!Source.isInstance(source)) {
  25723. source = Source.seriesDataToSource(source);
  25724. }
  25725. opt = opt || {};
  25726. sysDims = (sysDims || []).slice();
  25727. var dimsDef = (opt.dimsDef || []).slice();
  25728. var encodeDef = createHashMap(opt.encodeDef);
  25729. var dataDimNameMap = createHashMap();
  25730. var coordDimNameMap = createHashMap();
  25731. // var valueCandidate;
  25732. var result = [];
  25733. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount);
  25734. // Apply user defined dims (`name` and `type`) and init result.
  25735. for (var i = 0; i < dimCount; i++) {
  25736. var dimDefItem = dimsDef[i] = extend(
  25737. {}, isObject$1(dimsDef[i]) ? dimsDef[i] : {name: dimsDef[i]}
  25738. );
  25739. var userDimName = dimDefItem.name;
  25740. var resultItem = result[i] = {otherDims: {}};
  25741. // Name will be applied later for avoiding duplication.
  25742. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  25743. // Only if `series.dimensions` is defined in option
  25744. // displayName, will be set, and dimension will be diplayed vertically in
  25745. // tooltip by default.
  25746. resultItem.name = resultItem.displayName = userDimName;
  25747. dataDimNameMap.set(userDimName, i);
  25748. }
  25749. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  25750. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  25751. }
  25752. // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  25753. encodeDef.each(function (dataDims, coordDim) {
  25754. dataDims = normalizeToArray(dataDims).slice();
  25755. var validDataDims = encodeDef.set(coordDim, []);
  25756. each$1(dataDims, function (resultDimIdx, idx) {
  25757. // The input resultDimIdx can be dim name or index.
  25758. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  25759. if (resultDimIdx != null && resultDimIdx < dimCount) {
  25760. validDataDims[idx] = resultDimIdx;
  25761. applyDim(result[resultDimIdx], coordDim, idx);
  25762. }
  25763. });
  25764. });
  25765. // Apply templetes and default order from `sysDims`.
  25766. var availDimIdx = 0;
  25767. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  25768. var coordDim;
  25769. var sysDimItem;
  25770. var sysDimItemDimsDef;
  25771. var sysDimItemOtherDims;
  25772. if (isString(sysDimItem)) {
  25773. coordDim = sysDimItem;
  25774. sysDimItem = {};
  25775. }
  25776. else {
  25777. coordDim = sysDimItem.name;
  25778. var ordinalMeta = sysDimItem.ordinalMeta;
  25779. sysDimItem.ordinalMeta = null;
  25780. sysDimItem = clone(sysDimItem);
  25781. sysDimItem.ordinalMeta = ordinalMeta;
  25782. // `coordDimIndex` should not be set directly.
  25783. sysDimItemDimsDef = sysDimItem.dimsDef;
  25784. sysDimItemOtherDims = sysDimItem.otherDims;
  25785. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex
  25786. = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  25787. }
  25788. var dataDims = normalizeToArray(encodeDef.get(coordDim));
  25789. // dimensions provides default dim sequences.
  25790. if (!dataDims.length) {
  25791. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  25792. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  25793. availDimIdx++;
  25794. }
  25795. availDimIdx < result.length && dataDims.push(availDimIdx++);
  25796. }
  25797. }
  25798. // Apply templates.
  25799. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  25800. var resultItem = result[resultDimIdx];
  25801. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  25802. if (resultItem.name == null && sysDimItemDimsDef) {
  25803. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  25804. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {name: sysDimItemDimsDefItem});
  25805. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  25806. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  25807. }
  25808. // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  25809. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  25810. });
  25811. });
  25812. function applyDim(resultItem, coordDim, coordDimIndex) {
  25813. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  25814. resultItem.otherDims[coordDim] = coordDimIndex;
  25815. }
  25816. else {
  25817. resultItem.coordDim = coordDim;
  25818. resultItem.coordDimIndex = coordDimIndex;
  25819. coordDimNameMap.set(coordDim, true);
  25820. }
  25821. }
  25822. // Make sure the first extra dim is 'value'.
  25823. var generateCoord = opt.generateCoord;
  25824. var generateCoordCount = opt.generateCoordCount;
  25825. var fromZero = generateCoordCount != null;
  25826. generateCoordCount = generateCoord ? (generateCoordCount || 1) : 0;
  25827. var extra = generateCoord || 'value';
  25828. // Set dim `name` and other `coordDim` and other props.
  25829. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  25830. var resultItem = result[resultDimIdx] = result[resultDimIdx] || {};
  25831. var coordDim = resultItem.coordDim;
  25832. if (coordDim == null) {
  25833. resultItem.coordDim = genName(
  25834. extra, coordDimNameMap, fromZero
  25835. );
  25836. resultItem.coordDimIndex = 0;
  25837. if (!generateCoord || generateCoordCount <= 0) {
  25838. resultItem.isExtraCoord = true;
  25839. }
  25840. generateCoordCount--;
  25841. }
  25842. resultItem.name == null && (resultItem.name = genName(
  25843. resultItem.coordDim,
  25844. dataDimNameMap
  25845. ));
  25846. if (resultItem.type == null && guessOrdinal(source, resultDimIdx, resultItem.name)) {
  25847. resultItem.type = 'ordinal';
  25848. }
  25849. }
  25850. return result;
  25851. }
  25852. // ??? TODO
  25853. // Originally detect dimCount by data[0]. Should we
  25854. // optimize it to only by sysDims and dimensions and encode.
  25855. // So only necessary dims will be initialized.
  25856. // But
  25857. // (1) custom series should be considered. where other dims
  25858. // may be visited.
  25859. // (2) sometimes user need to calcualte bubble size or use visualMap
  25860. // on other dimensions besides coordSys needed.
  25861. // So, dims that is not used by system, should be shared in storage?
  25862. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  25863. // Note that the result dimCount should not small than columns count
  25864. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  25865. var dimCount = Math.max(
  25866. source.dimensionsDetectCount || 1,
  25867. sysDims.length,
  25868. dimsDef.length,
  25869. optDimCount || 0
  25870. );
  25871. each$1(sysDims, function (sysDimItem) {
  25872. var sysDimItemDimsDef = sysDimItem.dimsDef;
  25873. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  25874. });
  25875. return dimCount;
  25876. }
  25877. function genName(name, map$$1, fromZero) {
  25878. if (fromZero || map$$1.get(name) != null) {
  25879. var i = 0;
  25880. while (map$$1.get(name + i) != null) {
  25881. i++;
  25882. }
  25883. name += i;
  25884. }
  25885. map$$1.set(name, true);
  25886. return name;
  25887. }
  25888. /*
  25889. * Licensed to the Apache Software Foundation (ASF) under one
  25890. * or more contributor license agreements. See the NOTICE file
  25891. * distributed with this work for additional information
  25892. * regarding copyright ownership. The ASF licenses this file
  25893. * to you under the Apache License, Version 2.0 (the
  25894. * "License"); you may not use this file except in compliance
  25895. * with the License. You may obtain a copy of the License at
  25896. *
  25897. * http://www.apache.org/licenses/LICENSE-2.0
  25898. *
  25899. * Unless required by applicable law or agreed to in writing,
  25900. * software distributed under the License is distributed on an
  25901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25902. * KIND, either express or implied. See the License for the
  25903. * specific language governing permissions and limitations
  25904. * under the License.
  25905. */
  25906. /**
  25907. * Substitute `completeDimensions`.
  25908. * `completeDimensions` is to be deprecated.
  25909. */
  25910. /**
  25911. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  25912. * @param {Object|Array} [opt]
  25913. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  25914. * @param {number} [opt.dimensionsCount]
  25915. * @param {string} [opt.generateCoord]
  25916. * @param {string} [opt.generateCoordCount]
  25917. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  25918. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  25919. * @return {Array.<Object>} dimensionsInfo
  25920. */
  25921. var createDimensions = function (source, opt) {
  25922. opt = opt || {};
  25923. return completeDimensions(opt.coordDimensions || [], source, {
  25924. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  25925. encodeDef: opt.encodeDefine || source.encodeDefine,
  25926. dimCount: opt.dimensionsCount,
  25927. generateCoord: opt.generateCoord,
  25928. generateCoordCount: opt.generateCoordCount
  25929. });
  25930. };
  25931. /*
  25932. * Licensed to the Apache Software Foundation (ASF) under one
  25933. * or more contributor license agreements. See the NOTICE file
  25934. * distributed with this work for additional information
  25935. * regarding copyright ownership. The ASF licenses this file
  25936. * to you under the Apache License, Version 2.0 (the
  25937. * "License"); you may not use this file except in compliance
  25938. * with the License. You may obtain a copy of the License at
  25939. *
  25940. * http://www.apache.org/licenses/LICENSE-2.0
  25941. *
  25942. * Unless required by applicable law or agreed to in writing,
  25943. * software distributed under the License is distributed on an
  25944. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  25945. * KIND, either express or implied. See the License for the
  25946. * specific language governing permissions and limitations
  25947. * under the License.
  25948. */
  25949. /**
  25950. * Note that it is too complicated to support 3d stack by value
  25951. * (have to create two-dimension inverted index), so in 3d case
  25952. * we just support that stacked by index.
  25953. *
  25954. * @param {module:echarts/model/Series} seriesModel
  25955. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  25956. * The input dimensionInfoList will be modified.
  25957. * @param {Object} [opt]
  25958. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  25959. * @param {boolean} [opt.byIndex=false]
  25960. * @return {Object} calculationInfo
  25961. * {
  25962. * stackedDimension: string
  25963. * stackedByDimension: string
  25964. * isStackedByIndex: boolean
  25965. * stackedOverDimension: string
  25966. * stackResultDimension: string
  25967. * }
  25968. */
  25969. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  25970. opt = opt || {};
  25971. var byIndex = opt.byIndex;
  25972. var stackedCoordDimension = opt.stackedCoordDimension;
  25973. // Compatibal: when `stack` is set as '', do not stack.
  25974. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  25975. var stackedByDimInfo;
  25976. var stackedDimInfo;
  25977. var stackResultDimension;
  25978. var stackedOverDimension;
  25979. each$1(dimensionInfoList, function (dimensionInfo, index) {
  25980. if (isString(dimensionInfo)) {
  25981. dimensionInfoList[index] = dimensionInfo = {name: dimensionInfo};
  25982. }
  25983. if (mayStack && !dimensionInfo.isExtraCoord) {
  25984. // Find the first ordinal dimension as the stackedByDimInfo.
  25985. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  25986. stackedByDimInfo = dimensionInfo;
  25987. }
  25988. // Find the first stackable dimension as the stackedDimInfo.
  25989. if (!stackedDimInfo
  25990. && dimensionInfo.type !== 'ordinal'
  25991. && dimensionInfo.type !== 'time'
  25992. && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)
  25993. ) {
  25994. stackedDimInfo = dimensionInfo;
  25995. }
  25996. }
  25997. });
  25998. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  25999. // Compatible with previous design, value axis (time axis) only stack by index.
  26000. // It may make sense if the user provides elaborately constructed data.
  26001. byIndex = true;
  26002. }
  26003. // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  26004. // That put stack logic in List is for using conveniently in echarts extensions, but it
  26005. // might not be a good way.
  26006. if (stackedDimInfo) {
  26007. // Use a weird name that not duplicated with other names.
  26008. stackResultDimension = '__\0ecstackresult';
  26009. stackedOverDimension = '__\0ecstackedover';
  26010. // Create inverted index to fast query index by value.
  26011. if (stackedByDimInfo) {
  26012. stackedByDimInfo.createInvertedIndices = true;
  26013. }
  26014. var stackedDimCoordDim = stackedDimInfo.coordDim;
  26015. var stackedDimType = stackedDimInfo.type;
  26016. var stackedDimCoordIndex = 0;
  26017. each$1(dimensionInfoList, function (dimensionInfo) {
  26018. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  26019. stackedDimCoordIndex++;
  26020. }
  26021. });
  26022. dimensionInfoList.push({
  26023. name: stackResultDimension,
  26024. coordDim: stackedDimCoordDim,
  26025. coordDimIndex: stackedDimCoordIndex,
  26026. type: stackedDimType,
  26027. isExtraCoord: true,
  26028. isCalculationCoord: true
  26029. });
  26030. stackedDimCoordIndex++;
  26031. dimensionInfoList.push({
  26032. name: stackedOverDimension,
  26033. // This dimension contains stack base (generally, 0), so do not set it as
  26034. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  26035. coordDim: stackedOverDimension,
  26036. coordDimIndex: stackedDimCoordIndex,
  26037. type: stackedDimType,
  26038. isExtraCoord: true,
  26039. isCalculationCoord: true
  26040. });
  26041. }
  26042. return {
  26043. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  26044. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  26045. isStackedByIndex: byIndex,
  26046. stackedOverDimension: stackedOverDimension,
  26047. stackResultDimension: stackResultDimension
  26048. };
  26049. }
  26050. /**
  26051. * @param {module:echarts/data/List} data
  26052. * @param {string} stackedDim
  26053. */
  26054. function isDimensionStacked(data, stackedDim /*, stackedByDim*/) {
  26055. // Each single series only maps to one pair of axis. So we do not need to
  26056. // check stackByDim, whatever stacked by a dimension or stacked by index.
  26057. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension');
  26058. // && (
  26059. // stackedByDim != null
  26060. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  26061. // : data.getCalculationInfo('isStackedByIndex')
  26062. // );
  26063. }
  26064. /**
  26065. * @param {module:echarts/data/List} data
  26066. * @param {string} targetDim
  26067. * @param {string} [stackedByDim] If not input this parameter, check whether
  26068. * stacked by index.
  26069. * @return {string} dimension
  26070. */
  26071. function getStackedDimension(data, targetDim) {
  26072. return isDimensionStacked(data, targetDim)
  26073. ? data.getCalculationInfo('stackResultDimension')
  26074. : targetDim;
  26075. }
  26076. /*
  26077. * Licensed to the Apache Software Foundation (ASF) under one
  26078. * or more contributor license agreements. See the NOTICE file
  26079. * distributed with this work for additional information
  26080. * regarding copyright ownership. The ASF licenses this file
  26081. * to you under the Apache License, Version 2.0 (the
  26082. * "License"); you may not use this file except in compliance
  26083. * with the License. You may obtain a copy of the License at
  26084. *
  26085. * http://www.apache.org/licenses/LICENSE-2.0
  26086. *
  26087. * Unless required by applicable law or agreed to in writing,
  26088. * software distributed under the License is distributed on an
  26089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26090. * KIND, either express or implied. See the License for the
  26091. * specific language governing permissions and limitations
  26092. * under the License.
  26093. */
  26094. /**
  26095. * @param {module:echarts/data/Source|Array} source Or raw data.
  26096. * @param {module:echarts/model/Series} seriesModel
  26097. * @param {Object} [opt]
  26098. * @param {string} [opt.generateCoord]
  26099. */
  26100. function createListFromArray(source, seriesModel, opt) {
  26101. opt = opt || {};
  26102. if (!Source.isInstance(source)) {
  26103. source = Source.seriesDataToSource(source);
  26104. }
  26105. var coordSysName = seriesModel.get('coordinateSystem');
  26106. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  26107. var coordSysDefine = getCoordSysDefineBySeries(seriesModel);
  26108. var coordSysDimDefs;
  26109. if (coordSysDefine) {
  26110. coordSysDimDefs = map(coordSysDefine.coordSysDims, function (dim) {
  26111. var dimInfo = {name: dim};
  26112. var axisModel = coordSysDefine.axisMap.get(dim);
  26113. if (axisModel) {
  26114. var axisType = axisModel.get('type');
  26115. dimInfo.type = getDimensionTypeByAxis(axisType);
  26116. // dimInfo.stackable = isStackable(axisType);
  26117. }
  26118. return dimInfo;
  26119. });
  26120. }
  26121. if (!coordSysDimDefs) {
  26122. // Get dimensions from registered coordinate system
  26123. coordSysDimDefs = (registeredCoordSys && (
  26124. registeredCoordSys.getDimensionsInfo
  26125. ? registeredCoordSys.getDimensionsInfo()
  26126. : registeredCoordSys.dimensions.slice()
  26127. )) || ['x', 'y'];
  26128. }
  26129. var dimInfoList = createDimensions(source, {
  26130. coordDimensions: coordSysDimDefs,
  26131. generateCoord: opt.generateCoord
  26132. });
  26133. var firstCategoryDimIndex;
  26134. var hasNameEncode;
  26135. coordSysDefine && each$1(dimInfoList, function (dimInfo, dimIndex) {
  26136. var coordDim = dimInfo.coordDim;
  26137. var categoryAxisModel = coordSysDefine.categoryAxisMap.get(coordDim);
  26138. if (categoryAxisModel) {
  26139. if (firstCategoryDimIndex == null) {
  26140. firstCategoryDimIndex = dimIndex;
  26141. }
  26142. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  26143. }
  26144. if (dimInfo.otherDims.itemName != null) {
  26145. hasNameEncode = true;
  26146. }
  26147. });
  26148. if (!hasNameEncode && firstCategoryDimIndex != null) {
  26149. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  26150. }
  26151. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  26152. var list = new List(dimInfoList, seriesModel);
  26153. list.setCalculationInfo(stackCalculationInfo);
  26154. var dimValueGetter = (firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source))
  26155. ? function (itemOpt, dimName, dataIndex, dimIndex) {
  26156. // Use dataIndex as ordinal value in categoryAxis
  26157. return dimIndex === firstCategoryDimIndex
  26158. ? dataIndex
  26159. : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  26160. }
  26161. : null;
  26162. list.hasItemOption = false;
  26163. list.initData(source, null, dimValueGetter);
  26164. return list;
  26165. }
  26166. function isNeedCompleteOrdinalData(source) {
  26167. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  26168. var sampleItem = firstDataNotNull(source.data || []);
  26169. return sampleItem != null
  26170. && !isArray(getDataItemValue(sampleItem));
  26171. }
  26172. }
  26173. function firstDataNotNull(data) {
  26174. var i = 0;
  26175. while (i < data.length && data[i] == null) {
  26176. i++;
  26177. }
  26178. return data[i];
  26179. }
  26180. /*
  26181. * Licensed to the Apache Software Foundation (ASF) under one
  26182. * or more contributor license agreements. See the NOTICE file
  26183. * distributed with this work for additional information
  26184. * regarding copyright ownership. The ASF licenses this file
  26185. * to you under the Apache License, Version 2.0 (the
  26186. * "License"); you may not use this file except in compliance
  26187. * with the License. You may obtain a copy of the License at
  26188. *
  26189. * http://www.apache.org/licenses/LICENSE-2.0
  26190. *
  26191. * Unless required by applicable law or agreed to in writing,
  26192. * software distributed under the License is distributed on an
  26193. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26194. * KIND, either express or implied. See the License for the
  26195. * specific language governing permissions and limitations
  26196. * under the License.
  26197. */
  26198. /**
  26199. * // Scale class management
  26200. * @module echarts/scale/Scale
  26201. */
  26202. /**
  26203. * @param {Object} [setting]
  26204. */
  26205. function Scale(setting) {
  26206. this._setting = setting || {};
  26207. /**
  26208. * Extent
  26209. * @type {Array.<number>}
  26210. * @protected
  26211. */
  26212. this._extent = [Infinity, -Infinity];
  26213. /**
  26214. * Step is calculated in adjustExtent
  26215. * @type {Array.<number>}
  26216. * @protected
  26217. */
  26218. this._interval = 0;
  26219. this.init && this.init.apply(this, arguments);
  26220. }
  26221. /**
  26222. * Parse input val to valid inner number.
  26223. * @param {*} val
  26224. * @return {number}
  26225. */
  26226. Scale.prototype.parse = function (val) {
  26227. // Notice: This would be a trap here, If the implementation
  26228. // of this method depends on extent, and this method is used
  26229. // before extent set (like in dataZoom), it would be wrong.
  26230. // Nevertheless, parse does not depend on extent generally.
  26231. return val;
  26232. };
  26233. Scale.prototype.getSetting = function (name) {
  26234. return this._setting[name];
  26235. };
  26236. Scale.prototype.contain = function (val) {
  26237. var extent = this._extent;
  26238. return val >= extent[0] && val <= extent[1];
  26239. };
  26240. /**
  26241. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  26242. * @param {number} val
  26243. * @return {number}
  26244. */
  26245. Scale.prototype.normalize = function (val) {
  26246. var extent = this._extent;
  26247. if (extent[1] === extent[0]) {
  26248. return 0.5;
  26249. }
  26250. return (val - extent[0]) / (extent[1] - extent[0]);
  26251. };
  26252. /**
  26253. * Scale normalized value
  26254. * @param {number} val
  26255. * @return {number}
  26256. */
  26257. Scale.prototype.scale = function (val) {
  26258. var extent = this._extent;
  26259. return val * (extent[1] - extent[0]) + extent[0];
  26260. };
  26261. /**
  26262. * Set extent from data
  26263. * @param {Array.<number>} other
  26264. */
  26265. Scale.prototype.unionExtent = function (other) {
  26266. var extent = this._extent;
  26267. other[0] < extent[0] && (extent[0] = other[0]);
  26268. other[1] > extent[1] && (extent[1] = other[1]);
  26269. // not setExtent because in log axis it may transformed to power
  26270. // this.setExtent(extent[0], extent[1]);
  26271. };
  26272. /**
  26273. * Set extent from data
  26274. * @param {module:echarts/data/List} data
  26275. * @param {string} dim
  26276. */
  26277. Scale.prototype.unionExtentFromData = function (data, dim) {
  26278. this.unionExtent(data.getApproximateExtent(dim));
  26279. };
  26280. /**
  26281. * Get extent
  26282. * @return {Array.<number>}
  26283. */
  26284. Scale.prototype.getExtent = function () {
  26285. return this._extent.slice();
  26286. };
  26287. /**
  26288. * Set extent
  26289. * @param {number} start
  26290. * @param {number} end
  26291. */
  26292. Scale.prototype.setExtent = function (start, end) {
  26293. var thisExtent = this._extent;
  26294. if (!isNaN(start)) {
  26295. thisExtent[0] = start;
  26296. }
  26297. if (!isNaN(end)) {
  26298. thisExtent[1] = end;
  26299. }
  26300. };
  26301. /**
  26302. * When axis extent depends on data and no data exists,
  26303. * axis ticks should not be drawn, which is named 'blank'.
  26304. */
  26305. Scale.prototype.isBlank = function () {
  26306. return this._isBlank;
  26307. },
  26308. /**
  26309. * When axis extent depends on data and no data exists,
  26310. * axis ticks should not be drawn, which is named 'blank'.
  26311. */
  26312. Scale.prototype.setBlank = function (isBlank) {
  26313. this._isBlank = isBlank;
  26314. };
  26315. /**
  26316. * @abstract
  26317. * @param {*} tick
  26318. * @return {string} label of the tick.
  26319. */
  26320. Scale.prototype.getLabel = null;
  26321. enableClassExtend(Scale);
  26322. enableClassManagement(Scale, {
  26323. registerWhenExtend: true
  26324. });
  26325. /*
  26326. * Licensed to the Apache Software Foundation (ASF) under one
  26327. * or more contributor license agreements. See the NOTICE file
  26328. * distributed with this work for additional information
  26329. * regarding copyright ownership. The ASF licenses this file
  26330. * to you under the Apache License, Version 2.0 (the
  26331. * "License"); you may not use this file except in compliance
  26332. * with the License. You may obtain a copy of the License at
  26333. *
  26334. * http://www.apache.org/licenses/LICENSE-2.0
  26335. *
  26336. * Unless required by applicable law or agreed to in writing,
  26337. * software distributed under the License is distributed on an
  26338. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26339. * KIND, either express or implied. See the License for the
  26340. * specific language governing permissions and limitations
  26341. * under the License.
  26342. */
  26343. /**
  26344. * @constructor
  26345. * @param {Object} [opt]
  26346. * @param {Object} [opt.categories=[]]
  26347. * @param {Object} [opt.needCollect=false]
  26348. * @param {Object} [opt.deduplication=false]
  26349. */
  26350. function OrdinalMeta(opt) {
  26351. /**
  26352. * @readOnly
  26353. * @type {Array.<string>}
  26354. */
  26355. this.categories = opt.categories || [];
  26356. /**
  26357. * @private
  26358. * @type {boolean}
  26359. */
  26360. this._needCollect = opt.needCollect;
  26361. /**
  26362. * @private
  26363. * @type {boolean}
  26364. */
  26365. this._deduplication = opt.deduplication;
  26366. /**
  26367. * @private
  26368. * @type {boolean}
  26369. */
  26370. this._map;
  26371. }
  26372. /**
  26373. * @param {module:echarts/model/Model} axisModel
  26374. * @return {module:echarts/data/OrdinalMeta}
  26375. */
  26376. OrdinalMeta.createByAxisModel = function (axisModel) {
  26377. var option = axisModel.option;
  26378. var data = option.data;
  26379. var categories = data && map(data, getName);
  26380. return new OrdinalMeta({
  26381. categories: categories,
  26382. needCollect: !categories,
  26383. // deduplication is default in axis.
  26384. deduplication: option.dedplication !== false
  26385. });
  26386. };
  26387. var proto$1 = OrdinalMeta.prototype;
  26388. /**
  26389. * @param {string} category
  26390. * @return {number} ordinal
  26391. */
  26392. proto$1.getOrdinal = function (category) {
  26393. return getOrCreateMap(this).get(category);
  26394. };
  26395. /**
  26396. * @param {*} category
  26397. * @return {number} The ordinal. If not found, return NaN.
  26398. */
  26399. proto$1.parseAndCollect = function (category) {
  26400. var index;
  26401. var needCollect = this._needCollect;
  26402. // The value of category dim can be the index of the given category set.
  26403. // This feature is only supported when !needCollect, because we should
  26404. // consider a common case: a value is 2017, which is a number but is
  26405. // expected to be tread as a category. This case usually happen in dataset,
  26406. // where it happent to be no need of the index feature.
  26407. if (typeof category !== 'string' && !needCollect) {
  26408. return category;
  26409. }
  26410. // Optimize for the scenario:
  26411. // category is ['2012-01-01', '2012-01-02', ...], where the input
  26412. // data has been ensured not duplicate and is large data.
  26413. // Notice, if a dataset dimension provide categroies, usually echarts
  26414. // should remove duplication except user tell echarts dont do that
  26415. // (set axis.deduplication = false), because echarts do not know whether
  26416. // the values in the category dimension has duplication (consider the
  26417. // parallel-aqi example)
  26418. if (needCollect && !this._deduplication) {
  26419. index = this.categories.length;
  26420. this.categories[index] = category;
  26421. return index;
  26422. }
  26423. var map$$1 = getOrCreateMap(this);
  26424. index = map$$1.get(category);
  26425. if (index == null) {
  26426. if (needCollect) {
  26427. index = this.categories.length;
  26428. this.categories[index] = category;
  26429. map$$1.set(category, index);
  26430. }
  26431. else {
  26432. index = NaN;
  26433. }
  26434. }
  26435. return index;
  26436. };
  26437. // Consider big data, do not create map until needed.
  26438. function getOrCreateMap(ordinalMeta) {
  26439. return ordinalMeta._map || (
  26440. ordinalMeta._map = createHashMap(ordinalMeta.categories)
  26441. );
  26442. }
  26443. function getName(obj) {
  26444. if (isObject$1(obj) && obj.value != null) {
  26445. return obj.value;
  26446. }
  26447. else {
  26448. return obj + '';
  26449. }
  26450. }
  26451. /*
  26452. * Licensed to the Apache Software Foundation (ASF) under one
  26453. * or more contributor license agreements. See the NOTICE file
  26454. * distributed with this work for additional information
  26455. * regarding copyright ownership. The ASF licenses this file
  26456. * to you under the Apache License, Version 2.0 (the
  26457. * "License"); you may not use this file except in compliance
  26458. * with the License. You may obtain a copy of the License at
  26459. *
  26460. * http://www.apache.org/licenses/LICENSE-2.0
  26461. *
  26462. * Unless required by applicable law or agreed to in writing,
  26463. * software distributed under the License is distributed on an
  26464. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26465. * KIND, either express or implied. See the License for the
  26466. * specific language governing permissions and limitations
  26467. * under the License.
  26468. */
  26469. /**
  26470. * Linear continuous scale
  26471. * @module echarts/coord/scale/Ordinal
  26472. *
  26473. * http://en.wikipedia.org/wiki/Level_of_measurement
  26474. */
  26475. // FIXME only one data
  26476. var scaleProto = Scale.prototype;
  26477. var OrdinalScale = Scale.extend({
  26478. type: 'ordinal',
  26479. /**
  26480. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  26481. */
  26482. init: function (ordinalMeta, extent) {
  26483. // Caution: Should not use instanceof, consider ec-extensions using
  26484. // import approach to get OrdinalMeta class.
  26485. if (!ordinalMeta || isArray(ordinalMeta)) {
  26486. ordinalMeta = new OrdinalMeta({categories: ordinalMeta});
  26487. }
  26488. this._ordinalMeta = ordinalMeta;
  26489. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  26490. },
  26491. parse: function (val) {
  26492. return typeof val === 'string'
  26493. ? this._ordinalMeta.getOrdinal(val)
  26494. // val might be float.
  26495. : Math.round(val);
  26496. },
  26497. contain: function (rank) {
  26498. rank = this.parse(rank);
  26499. return scaleProto.contain.call(this, rank)
  26500. && this._ordinalMeta.categories[rank] != null;
  26501. },
  26502. /**
  26503. * Normalize given rank or name to linear [0, 1]
  26504. * @param {number|string} [val]
  26505. * @return {number}
  26506. */
  26507. normalize: function (val) {
  26508. return scaleProto.normalize.call(this, this.parse(val));
  26509. },
  26510. scale: function (val) {
  26511. return Math.round(scaleProto.scale.call(this, val));
  26512. },
  26513. /**
  26514. * @return {Array}
  26515. */
  26516. getTicks: function () {
  26517. var ticks = [];
  26518. var extent = this._extent;
  26519. var rank = extent[0];
  26520. while (rank <= extent[1]) {
  26521. ticks.push(rank);
  26522. rank++;
  26523. }
  26524. return ticks;
  26525. },
  26526. /**
  26527. * Get item on rank n
  26528. * @param {number} n
  26529. * @return {string}
  26530. */
  26531. getLabel: function (n) {
  26532. if (!this.isBlank()) {
  26533. // Note that if no data, ordinalMeta.categories is an empty array.
  26534. return this._ordinalMeta.categories[n];
  26535. }
  26536. },
  26537. /**
  26538. * @return {number}
  26539. */
  26540. count: function () {
  26541. return this._extent[1] - this._extent[0] + 1;
  26542. },
  26543. /**
  26544. * @override
  26545. */
  26546. unionExtentFromData: function (data, dim) {
  26547. this.unionExtent(data.getApproximateExtent(dim));
  26548. },
  26549. getOrdinalMeta: function () {
  26550. return this._ordinalMeta;
  26551. },
  26552. niceTicks: noop,
  26553. niceExtent: noop
  26554. });
  26555. /**
  26556. * @return {module:echarts/scale/Time}
  26557. */
  26558. OrdinalScale.create = function () {
  26559. return new OrdinalScale();
  26560. };
  26561. /*
  26562. * Licensed to the Apache Software Foundation (ASF) under one
  26563. * or more contributor license agreements. See the NOTICE file
  26564. * distributed with this work for additional information
  26565. * regarding copyright ownership. The ASF licenses this file
  26566. * to you under the Apache License, Version 2.0 (the
  26567. * "License"); you may not use this file except in compliance
  26568. * with the License. You may obtain a copy of the License at
  26569. *
  26570. * http://www.apache.org/licenses/LICENSE-2.0
  26571. *
  26572. * Unless required by applicable law or agreed to in writing,
  26573. * software distributed under the License is distributed on an
  26574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26575. * KIND, either express or implied. See the License for the
  26576. * specific language governing permissions and limitations
  26577. * under the License.
  26578. */
  26579. /**
  26580. * For testable.
  26581. */
  26582. var roundNumber$1 = round$1;
  26583. /**
  26584. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  26585. * Should be extent[0] < extent[1].
  26586. * @param {number} splitNumber splitNumber should be >= 1.
  26587. * @param {number} [minInterval]
  26588. * @param {number} [maxInterval]
  26589. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  26590. */
  26591. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  26592. var result = {};
  26593. var span = extent[1] - extent[0];
  26594. var interval = result.interval = nice(span / splitNumber, true);
  26595. if (minInterval != null && interval < minInterval) {
  26596. interval = result.interval = minInterval;
  26597. }
  26598. if (maxInterval != null && interval > maxInterval) {
  26599. interval = result.interval = maxInterval;
  26600. }
  26601. // Tow more digital for tick.
  26602. var precision = result.intervalPrecision = getIntervalPrecision(interval);
  26603. // Niced extent inside original extent
  26604. var niceTickExtent = result.niceTickExtent = [
  26605. roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision),
  26606. roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)
  26607. ];
  26608. fixExtent(niceTickExtent, extent);
  26609. return result;
  26610. }
  26611. /**
  26612. * @param {number} interval
  26613. * @return {number} interval precision
  26614. */
  26615. function getIntervalPrecision(interval) {
  26616. // Tow more digital for tick.
  26617. return getPrecisionSafe(interval) + 2;
  26618. }
  26619. function clamp(niceTickExtent, idx, extent) {
  26620. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  26621. }
  26622. // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  26623. function fixExtent(niceTickExtent, extent) {
  26624. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  26625. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  26626. clamp(niceTickExtent, 0, extent);
  26627. clamp(niceTickExtent, 1, extent);
  26628. if (niceTickExtent[0] > niceTickExtent[1]) {
  26629. niceTickExtent[0] = niceTickExtent[1];
  26630. }
  26631. }
  26632. function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) {
  26633. var ticks = [];
  26634. // If interval is 0, return [];
  26635. if (!interval) {
  26636. return ticks;
  26637. }
  26638. // Consider this case: using dataZoom toolbox, zoom and zoom.
  26639. var safeLimit = 10000;
  26640. if (extent[0] < niceTickExtent[0]) {
  26641. ticks.push(extent[0]);
  26642. }
  26643. var tick = niceTickExtent[0];
  26644. while (tick <= niceTickExtent[1]) {
  26645. ticks.push(tick);
  26646. // Avoid rounding error
  26647. tick = roundNumber$1(tick + interval, intervalPrecision);
  26648. if (tick === ticks[ticks.length - 1]) {
  26649. // Consider out of safe float point, e.g.,
  26650. // -3711126.9907707 + 2e-10 === -3711126.9907707
  26651. break;
  26652. }
  26653. if (ticks.length > safeLimit) {
  26654. return [];
  26655. }
  26656. }
  26657. // Consider this case: the last item of ticks is smaller
  26658. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  26659. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) {
  26660. ticks.push(extent[1]);
  26661. }
  26662. return ticks;
  26663. }
  26664. /*
  26665. * Licensed to the Apache Software Foundation (ASF) under one
  26666. * or more contributor license agreements. See the NOTICE file
  26667. * distributed with this work for additional information
  26668. * regarding copyright ownership. The ASF licenses this file
  26669. * to you under the Apache License, Version 2.0 (the
  26670. * "License"); you may not use this file except in compliance
  26671. * with the License. You may obtain a copy of the License at
  26672. *
  26673. * http://www.apache.org/licenses/LICENSE-2.0
  26674. *
  26675. * Unless required by applicable law or agreed to in writing,
  26676. * software distributed under the License is distributed on an
  26677. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26678. * KIND, either express or implied. See the License for the
  26679. * specific language governing permissions and limitations
  26680. * under the License.
  26681. */
  26682. /**
  26683. * Interval scale
  26684. * @module echarts/scale/Interval
  26685. */
  26686. var roundNumber = round$1;
  26687. /**
  26688. * @alias module:echarts/coord/scale/Interval
  26689. * @constructor
  26690. */
  26691. var IntervalScale = Scale.extend({
  26692. type: 'interval',
  26693. _interval: 0,
  26694. _intervalPrecision: 2,
  26695. setExtent: function (start, end) {
  26696. var thisExtent = this._extent;
  26697. //start,end may be a Number like '25',so...
  26698. if (!isNaN(start)) {
  26699. thisExtent[0] = parseFloat(start);
  26700. }
  26701. if (!isNaN(end)) {
  26702. thisExtent[1] = parseFloat(end);
  26703. }
  26704. },
  26705. unionExtent: function (other) {
  26706. var extent = this._extent;
  26707. other[0] < extent[0] && (extent[0] = other[0]);
  26708. other[1] > extent[1] && (extent[1] = other[1]);
  26709. // unionExtent may called by it's sub classes
  26710. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  26711. },
  26712. /**
  26713. * Get interval
  26714. */
  26715. getInterval: function () {
  26716. return this._interval;
  26717. },
  26718. /**
  26719. * Set interval
  26720. */
  26721. setInterval: function (interval) {
  26722. this._interval = interval;
  26723. // Dropped auto calculated niceExtent and use user setted extent
  26724. // We assume user wan't to set both interval, min, max to get a better result
  26725. this._niceExtent = this._extent.slice();
  26726. this._intervalPrecision = getIntervalPrecision(interval);
  26727. },
  26728. /**
  26729. * @return {Array.<number>}
  26730. */
  26731. getTicks: function () {
  26732. return intervalScaleGetTicks(
  26733. this._interval, this._extent, this._niceExtent, this._intervalPrecision
  26734. );
  26735. },
  26736. /**
  26737. * @param {number} data
  26738. * @param {Object} [opt]
  26739. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  26740. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  26741. * @return {string}
  26742. */
  26743. getLabel: function (data, opt) {
  26744. if (data == null) {
  26745. return '';
  26746. }
  26747. var precision = opt && opt.precision;
  26748. if (precision == null) {
  26749. precision = getPrecisionSafe(data) || 0;
  26750. }
  26751. else if (precision === 'auto') {
  26752. // Should be more precise then tick.
  26753. precision = this._intervalPrecision;
  26754. }
  26755. // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  26756. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  26757. data = roundNumber(data, precision, true);
  26758. return addCommas(data);
  26759. },
  26760. /**
  26761. * Update interval and extent of intervals for nice ticks
  26762. *
  26763. * @param {number} [splitNumber = 5] Desired number of ticks
  26764. * @param {number} [minInterval]
  26765. * @param {number} [maxInterval]
  26766. */
  26767. niceTicks: function (splitNumber, minInterval, maxInterval) {
  26768. splitNumber = splitNumber || 5;
  26769. var extent = this._extent;
  26770. var span = extent[1] - extent[0];
  26771. if (!isFinite(span)) {
  26772. return;
  26773. }
  26774. // User may set axis min 0 and data are all negative
  26775. // FIXME If it needs to reverse ?
  26776. if (span < 0) {
  26777. span = -span;
  26778. extent.reverse();
  26779. }
  26780. var result = intervalScaleNiceTicks(
  26781. extent, splitNumber, minInterval, maxInterval
  26782. );
  26783. this._intervalPrecision = result.intervalPrecision;
  26784. this._interval = result.interval;
  26785. this._niceExtent = result.niceTickExtent;
  26786. },
  26787. /**
  26788. * Nice extent.
  26789. * @param {Object} opt
  26790. * @param {number} [opt.splitNumber = 5] Given approx tick number
  26791. * @param {boolean} [opt.fixMin=false]
  26792. * @param {boolean} [opt.fixMax=false]
  26793. * @param {boolean} [opt.minInterval]
  26794. * @param {boolean} [opt.maxInterval]
  26795. */
  26796. niceExtent: function (opt) {
  26797. var extent = this._extent;
  26798. // If extent start and end are same, expand them
  26799. if (extent[0] === extent[1]) {
  26800. if (extent[0] !== 0) {
  26801. // Expand extent
  26802. var expandSize = extent[0];
  26803. // In the fowllowing case
  26804. // Axis has been fixed max 100
  26805. // Plus data are all 100 and axis extent are [100, 100].
  26806. // Extend to the both side will cause expanded max is larger than fixed max.
  26807. // So only expand to the smaller side.
  26808. if (!opt.fixMax) {
  26809. extent[1] += expandSize / 2;
  26810. extent[0] -= expandSize / 2;
  26811. }
  26812. else {
  26813. extent[0] -= expandSize / 2;
  26814. }
  26815. }
  26816. else {
  26817. extent[1] = 1;
  26818. }
  26819. }
  26820. var span = extent[1] - extent[0];
  26821. // If there are no data and extent are [Infinity, -Infinity]
  26822. if (!isFinite(span)) {
  26823. extent[0] = 0;
  26824. extent[1] = 1;
  26825. }
  26826. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  26827. // var extent = this._extent;
  26828. var interval = this._interval;
  26829. if (!opt.fixMin) {
  26830. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  26831. }
  26832. if (!opt.fixMax) {
  26833. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  26834. }
  26835. }
  26836. });
  26837. /**
  26838. * @return {module:echarts/scale/Time}
  26839. */
  26840. IntervalScale.create = function () {
  26841. return new IntervalScale();
  26842. };
  26843. /*
  26844. * Licensed to the Apache Software Foundation (ASF) under one
  26845. * or more contributor license agreements. See the NOTICE file
  26846. * distributed with this work for additional information
  26847. * regarding copyright ownership. The ASF licenses this file
  26848. * to you under the Apache License, Version 2.0 (the
  26849. * "License"); you may not use this file except in compliance
  26850. * with the License. You may obtain a copy of the License at
  26851. *
  26852. * http://www.apache.org/licenses/LICENSE-2.0
  26853. *
  26854. * Unless required by applicable law or agreed to in writing,
  26855. * software distributed under the License is distributed on an
  26856. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26857. * KIND, either express or implied. See the License for the
  26858. * specific language governing permissions and limitations
  26859. * under the License.
  26860. */
  26861. var STACK_PREFIX = '__ec_stack_';
  26862. var LARGE_BAR_MIN_WIDTH = 0.5;
  26863. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  26864. function getSeriesStackId(seriesModel) {
  26865. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  26866. }
  26867. function getAxisKey(axis) {
  26868. return axis.dim + axis.index;
  26869. }
  26870. /**
  26871. * @param {Object} opt
  26872. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  26873. * @param {number} opt.count Positive interger.
  26874. * @param {number} [opt.barWidth]
  26875. * @param {number} [opt.barMaxWidth]
  26876. * @param {number} [opt.barGap]
  26877. * @param {number} [opt.barCategoryGap]
  26878. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  26879. */
  26880. function getLayoutOnAxis(opt) {
  26881. var params = [];
  26882. var baseAxis = opt.axis;
  26883. var axisKey = 'axis0';
  26884. if (baseAxis.type !== 'category') {
  26885. return;
  26886. }
  26887. var bandWidth = baseAxis.getBandWidth();
  26888. for (var i = 0; i < opt.count || 0; i++) {
  26889. params.push(defaults({
  26890. bandWidth: bandWidth,
  26891. axisKey: axisKey,
  26892. stackId: STACK_PREFIX + i
  26893. }, opt));
  26894. }
  26895. var widthAndOffsets = doCalBarWidthAndOffset(params);
  26896. var result = [];
  26897. for (var i = 0; i < opt.count; i++) {
  26898. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  26899. item.offsetCenter = item.offset + item.width / 2;
  26900. result.push(item);
  26901. }
  26902. return result;
  26903. }
  26904. function prepareLayoutBarSeries(seriesType, ecModel) {
  26905. var seriesModels = [];
  26906. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  26907. // Check series coordinate, do layout for cartesian2d only
  26908. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  26909. seriesModels.push(seriesModel);
  26910. }
  26911. });
  26912. return seriesModels;
  26913. }
  26914. function makeColumnLayout(barSeries) {
  26915. var seriesInfoList = [];
  26916. each$1(barSeries, function (seriesModel) {
  26917. var data = seriesModel.getData();
  26918. var cartesian = seriesModel.coordinateSystem;
  26919. var baseAxis = cartesian.getBaseAxis();
  26920. var axisExtent = baseAxis.getExtent();
  26921. var bandWidth = baseAxis.type === 'category'
  26922. ? baseAxis.getBandWidth()
  26923. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  26924. var barWidth = parsePercent$1(
  26925. seriesModel.get('barWidth'), bandWidth
  26926. );
  26927. var barMaxWidth = parsePercent$1(
  26928. seriesModel.get('barMaxWidth'), bandWidth
  26929. );
  26930. var barGap = seriesModel.get('barGap');
  26931. var barCategoryGap = seriesModel.get('barCategoryGap');
  26932. seriesInfoList.push({
  26933. bandWidth: bandWidth,
  26934. barWidth: barWidth,
  26935. barMaxWidth: barMaxWidth,
  26936. barGap: barGap,
  26937. barCategoryGap: barCategoryGap,
  26938. axisKey: getAxisKey(baseAxis),
  26939. stackId: getSeriesStackId(seriesModel)
  26940. });
  26941. });
  26942. return doCalBarWidthAndOffset(seriesInfoList);
  26943. }
  26944. function doCalBarWidthAndOffset(seriesInfoList) {
  26945. // Columns info on each category axis. Key is cartesian name
  26946. var columnsMap = {};
  26947. each$1(seriesInfoList, function (seriesInfo, idx) {
  26948. var axisKey = seriesInfo.axisKey;
  26949. var bandWidth = seriesInfo.bandWidth;
  26950. var columnsOnAxis = columnsMap[axisKey] || {
  26951. bandWidth: bandWidth,
  26952. remainedWidth: bandWidth,
  26953. autoWidthCount: 0,
  26954. categoryGap: '20%',
  26955. gap: '30%',
  26956. stacks: {}
  26957. };
  26958. var stacks = columnsOnAxis.stacks;
  26959. columnsMap[axisKey] = columnsOnAxis;
  26960. var stackId = seriesInfo.stackId;
  26961. if (!stacks[stackId]) {
  26962. columnsOnAxis.autoWidthCount++;
  26963. }
  26964. stacks[stackId] = stacks[stackId] || {
  26965. width: 0,
  26966. maxWidth: 0
  26967. };
  26968. // Caution: In a single coordinate system, these barGrid attributes
  26969. // will be shared by series. Consider that they have default values,
  26970. // only the attributes set on the last series will work.
  26971. // Do not change this fact unless there will be a break change.
  26972. // TODO
  26973. var barWidth = seriesInfo.barWidth;
  26974. if (barWidth && !stacks[stackId].width) {
  26975. // See #6312, do not restrict width.
  26976. stacks[stackId].width = barWidth;
  26977. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  26978. columnsOnAxis.remainedWidth -= barWidth;
  26979. }
  26980. var barMaxWidth = seriesInfo.barMaxWidth;
  26981. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  26982. var barGap = seriesInfo.barGap;
  26983. (barGap != null) && (columnsOnAxis.gap = barGap);
  26984. var barCategoryGap = seriesInfo.barCategoryGap;
  26985. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  26986. });
  26987. var result = {};
  26988. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  26989. result[coordSysName] = {};
  26990. var stacks = columnsOnAxis.stacks;
  26991. var bandWidth = columnsOnAxis.bandWidth;
  26992. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  26993. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  26994. var remainedWidth = columnsOnAxis.remainedWidth;
  26995. var autoWidthCount = columnsOnAxis.autoWidthCount;
  26996. var autoWidth = (remainedWidth - categoryGap)
  26997. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  26998. autoWidth = Math.max(autoWidth, 0);
  26999. // Find if any auto calculated bar exceeded maxBarWidth
  27000. each$1(stacks, function (column, stack) {
  27001. var maxWidth = column.maxWidth;
  27002. if (maxWidth && maxWidth < autoWidth) {
  27003. maxWidth = Math.min(maxWidth, remainedWidth);
  27004. if (column.width) {
  27005. maxWidth = Math.min(maxWidth, column.width);
  27006. }
  27007. remainedWidth -= maxWidth;
  27008. column.width = maxWidth;
  27009. autoWidthCount--;
  27010. }
  27011. });
  27012. // Recalculate width again
  27013. autoWidth = (remainedWidth - categoryGap)
  27014. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27015. autoWidth = Math.max(autoWidth, 0);
  27016. var widthSum = 0;
  27017. var lastColumn;
  27018. each$1(stacks, function (column, idx) {
  27019. if (!column.width) {
  27020. column.width = autoWidth;
  27021. }
  27022. lastColumn = column;
  27023. widthSum += column.width * (1 + barGapPercent);
  27024. });
  27025. if (lastColumn) {
  27026. widthSum -= lastColumn.width * barGapPercent;
  27027. }
  27028. var offset = -widthSum / 2;
  27029. each$1(stacks, function (column, stackId) {
  27030. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  27031. offset: offset,
  27032. width: column.width
  27033. };
  27034. offset += column.width * (1 + barGapPercent);
  27035. });
  27036. });
  27037. return result;
  27038. }
  27039. /**
  27040. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  27041. * @param {module:echarts/coord/Axis} axis
  27042. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  27043. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  27044. */
  27045. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  27046. if (barWidthAndOffset && axis) {
  27047. var result = barWidthAndOffset[getAxisKey(axis)];
  27048. if (result != null && seriesModel != null) {
  27049. result = result[getSeriesStackId(seriesModel)];
  27050. }
  27051. return result;
  27052. }
  27053. }
  27054. /**
  27055. * @param {string} seriesType
  27056. * @param {module:echarts/model/Global} ecModel
  27057. */
  27058. function layout(seriesType, ecModel) {
  27059. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  27060. var barWidthAndOffset = makeColumnLayout(seriesModels);
  27061. var lastStackCoords = {};
  27062. each$1(seriesModels, function (seriesModel) {
  27063. var data = seriesModel.getData();
  27064. var cartesian = seriesModel.coordinateSystem;
  27065. var baseAxis = cartesian.getBaseAxis();
  27066. var stackId = getSeriesStackId(seriesModel);
  27067. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27068. var columnOffset = columnLayoutInfo.offset;
  27069. var columnWidth = columnLayoutInfo.width;
  27070. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27071. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27072. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27073. data.setLayout({
  27074. offset: columnOffset,
  27075. size: columnWidth
  27076. });
  27077. var valueDim = data.mapDimension(valueAxis.dim);
  27078. var baseDim = data.mapDimension(baseAxis.dim);
  27079. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  27080. var isValueAxisH = valueAxis.isHorizontal();
  27081. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  27082. for (var idx = 0, len = data.count(); idx < len; idx++) {
  27083. var value = data.get(valueDim, idx);
  27084. var baseValue = data.get(baseDim, idx);
  27085. if (isNaN(value)) {
  27086. continue;
  27087. }
  27088. var sign = value >= 0 ? 'p' : 'n';
  27089. var baseCoord = valueAxisStart;
  27090. // Because of the barMinHeight, we can not use the value in
  27091. // stackResultDimension directly.
  27092. if (stacked) {
  27093. // Only ordinal axis can be stacked.
  27094. if (!lastStackCoords[stackId][baseValue]) {
  27095. lastStackCoords[stackId][baseValue] = {
  27096. p: valueAxisStart, // Positive stack
  27097. n: valueAxisStart // Negative stack
  27098. };
  27099. }
  27100. // Should also consider #4243
  27101. baseCoord = lastStackCoords[stackId][baseValue][sign];
  27102. }
  27103. var x;
  27104. var y;
  27105. var width;
  27106. var height;
  27107. if (isValueAxisH) {
  27108. var coord = cartesian.dataToPoint([value, baseValue]);
  27109. x = baseCoord;
  27110. y = coord[1] + columnOffset;
  27111. width = coord[0] - valueAxisStart;
  27112. height = columnWidth;
  27113. if (Math.abs(width) < barMinHeight) {
  27114. width = (width < 0 ? -1 : 1) * barMinHeight;
  27115. }
  27116. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  27117. }
  27118. else {
  27119. var coord = cartesian.dataToPoint([baseValue, value]);
  27120. x = coord[0] + columnOffset;
  27121. y = baseCoord;
  27122. width = columnWidth;
  27123. height = coord[1] - valueAxisStart;
  27124. if (Math.abs(height) < barMinHeight) {
  27125. // Include zero to has a positive bar
  27126. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27127. }
  27128. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  27129. }
  27130. data.setItemLayout(idx, {
  27131. x: x,
  27132. y: y,
  27133. width: width,
  27134. height: height
  27135. });
  27136. }
  27137. }, this);
  27138. }
  27139. // TODO: Do not support stack in large mode yet.
  27140. var largeLayout = {
  27141. seriesType: 'bar',
  27142. plan: createRenderPlanner(),
  27143. reset: function (seriesModel) {
  27144. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  27145. return;
  27146. }
  27147. var data = seriesModel.getData();
  27148. var cartesian = seriesModel.coordinateSystem;
  27149. var baseAxis = cartesian.getBaseAxis();
  27150. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27151. var valueDim = data.mapDimension(valueAxis.dim);
  27152. var baseDim = data.mapDimension(baseAxis.dim);
  27153. var valueAxisHorizontal = valueAxis.isHorizontal();
  27154. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  27155. var barWidth = retrieveColumnLayout(
  27156. makeColumnLayout([seriesModel]), baseAxis, seriesModel
  27157. ).width;
  27158. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) { // jshint ignore:line
  27159. barWidth = LARGE_BAR_MIN_WIDTH;
  27160. }
  27161. return {progress: progress};
  27162. function progress(params, data) {
  27163. var largePoints = new LargeArr(params.count * 2);
  27164. var dataIndex;
  27165. var coord = [];
  27166. var valuePair = [];
  27167. var offset = 0;
  27168. while ((dataIndex = params.next()) != null) {
  27169. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  27170. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  27171. coord = cartesian.dataToPoint(valuePair, null, coord);
  27172. largePoints[offset++] = coord[0];
  27173. largePoints[offset++] = coord[1];
  27174. }
  27175. data.setLayout({
  27176. largePoints: largePoints,
  27177. barWidth: barWidth,
  27178. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  27179. valueAxisHorizontal: valueAxisHorizontal
  27180. });
  27181. }
  27182. }
  27183. };
  27184. function isOnCartesian(seriesModel) {
  27185. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  27186. }
  27187. function isInLargeMode(seriesModel) {
  27188. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  27189. }
  27190. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  27191. return (
  27192. indexOf(baseAxis.getAxesOnZeroOf(), valueAxis) >= 0
  27193. || stacked
  27194. )
  27195. ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0))
  27196. : valueAxis.getGlobalExtent()[0];
  27197. }
  27198. /*
  27199. * Licensed to the Apache Software Foundation (ASF) under one
  27200. * or more contributor license agreements. See the NOTICE file
  27201. * distributed with this work for additional information
  27202. * regarding copyright ownership. The ASF licenses this file
  27203. * to you under the Apache License, Version 2.0 (the
  27204. * "License"); you may not use this file except in compliance
  27205. * with the License. You may obtain a copy of the License at
  27206. *
  27207. * http://www.apache.org/licenses/LICENSE-2.0
  27208. *
  27209. * Unless required by applicable law or agreed to in writing,
  27210. * software distributed under the License is distributed on an
  27211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27212. * KIND, either express or implied. See the License for the
  27213. * specific language governing permissions and limitations
  27214. * under the License.
  27215. */
  27216. /*
  27217. * The `scaleLevels` references to d3.js. The use of the source
  27218. * code of this file is also subject to the terms and consitions
  27219. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  27220. */
  27221. // [About UTC and local time zone]:
  27222. // In most cases, `number.parseDate` will treat input data string as local time
  27223. // (except time zone is specified in time string). And `format.formateTime` returns
  27224. // local time by default. option.useUTC is false by default. This design have
  27225. // concidered these common case:
  27226. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  27227. // in local time by default.
  27228. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  27229. // as its original time, without any time difference.
  27230. var intervalScaleProto = IntervalScale.prototype;
  27231. var mathCeil = Math.ceil;
  27232. var mathFloor = Math.floor;
  27233. var ONE_SECOND = 1000;
  27234. var ONE_MINUTE = ONE_SECOND * 60;
  27235. var ONE_HOUR = ONE_MINUTE * 60;
  27236. var ONE_DAY = ONE_HOUR * 24;
  27237. // FIXME 公用?
  27238. var bisect = function (a, x, lo, hi) {
  27239. while (lo < hi) {
  27240. var mid = lo + hi >>> 1;
  27241. if (a[mid][1] < x) {
  27242. lo = mid + 1;
  27243. }
  27244. else {
  27245. hi = mid;
  27246. }
  27247. }
  27248. return lo;
  27249. };
  27250. /**
  27251. * @alias module:echarts/coord/scale/Time
  27252. * @constructor
  27253. */
  27254. var TimeScale = IntervalScale.extend({
  27255. type: 'time',
  27256. /**
  27257. * @override
  27258. */
  27259. getLabel: function (val) {
  27260. var stepLvl = this._stepLvl;
  27261. var date = new Date(val);
  27262. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  27263. },
  27264. /**
  27265. * @override
  27266. */
  27267. niceExtent: function (opt) {
  27268. var extent = this._extent;
  27269. // If extent start and end are same, expand them
  27270. if (extent[0] === extent[1]) {
  27271. // Expand extent
  27272. extent[0] -= ONE_DAY;
  27273. extent[1] += ONE_DAY;
  27274. }
  27275. // If there are no data and extent are [Infinity, -Infinity]
  27276. if (extent[1] === -Infinity && extent[0] === Infinity) {
  27277. var d = new Date();
  27278. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  27279. extent[0] = extent[1] - ONE_DAY;
  27280. }
  27281. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval);
  27282. // var extent = this._extent;
  27283. var interval = this._interval;
  27284. if (!opt.fixMin) {
  27285. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  27286. }
  27287. if (!opt.fixMax) {
  27288. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  27289. }
  27290. },
  27291. /**
  27292. * @override
  27293. */
  27294. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  27295. approxTickNum = approxTickNum || 10;
  27296. var extent = this._extent;
  27297. var span = extent[1] - extent[0];
  27298. var approxInterval = span / approxTickNum;
  27299. if (minInterval != null && approxInterval < minInterval) {
  27300. approxInterval = minInterval;
  27301. }
  27302. if (maxInterval != null && approxInterval > maxInterval) {
  27303. approxInterval = maxInterval;
  27304. }
  27305. var scaleLevelsLen = scaleLevels.length;
  27306. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  27307. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  27308. var interval = level[1];
  27309. // Same with interval scale if span is much larger than 1 year
  27310. if (level[0] === 'year') {
  27311. var yearSpan = span / interval;
  27312. // From "Nice Numbers for Graph Labels" of Graphic Gems
  27313. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  27314. var yearStep = nice(yearSpan / approxTickNum, true);
  27315. interval *= yearStep;
  27316. }
  27317. var timezoneOffset = this.getSetting('useUTC')
  27318. ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000;
  27319. var niceExtent = [
  27320. Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset),
  27321. Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)
  27322. ];
  27323. fixExtent(niceExtent, extent);
  27324. this._stepLvl = level;
  27325. // Interval will be used in getTicks
  27326. this._interval = interval;
  27327. this._niceExtent = niceExtent;
  27328. },
  27329. parse: function (val) {
  27330. // val might be float.
  27331. return +parseDate(val);
  27332. }
  27333. });
  27334. each$1(['contain', 'normalize'], function (methodName) {
  27335. TimeScale.prototype[methodName] = function (val) {
  27336. return intervalScaleProto[methodName].call(this, this.parse(val));
  27337. };
  27338. });
  27339. // Steps from d3, see the license statement at the top of this file.
  27340. var scaleLevels = [
  27341. // Format interval
  27342. ['hh:mm:ss', ONE_SECOND], // 1s
  27343. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  27344. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  27345. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  27346. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  27347. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  27348. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  27349. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  27350. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  27351. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  27352. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  27353. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  27354. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  27355. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  27356. ['MM-dd\nyyyy', ONE_DAY], // 1d
  27357. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  27358. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  27359. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  27360. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  27361. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  27362. ['week', ONE_DAY * 7], // 7d
  27363. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  27364. ['week', ONE_DAY * 14], // 2w
  27365. ['week', ONE_DAY * 21], // 3w
  27366. ['month', ONE_DAY * 31], // 1M
  27367. ['week', ONE_DAY * 42], // 6w
  27368. ['month', ONE_DAY * 62], // 2M
  27369. ['week', ONE_DAY * 42], // 10w
  27370. ['quarter', ONE_DAY * 380 / 4], // 3M
  27371. ['month', ONE_DAY * 31 * 4], // 4M
  27372. ['month', ONE_DAY * 31 * 5], // 5M
  27373. ['half-year', ONE_DAY * 380 / 2], // 6M
  27374. ['month', ONE_DAY * 31 * 8], // 8M
  27375. ['month', ONE_DAY * 31 * 10], // 10M
  27376. ['year', ONE_DAY * 380] // 1Y
  27377. ];
  27378. /**
  27379. * @param {module:echarts/model/Model}
  27380. * @return {module:echarts/scale/Time}
  27381. */
  27382. TimeScale.create = function (model) {
  27383. return new TimeScale({useUTC: model.ecModel.get('useUTC')});
  27384. };
  27385. /*
  27386. * Licensed to the Apache Software Foundation (ASF) under one
  27387. * or more contributor license agreements. See the NOTICE file
  27388. * distributed with this work for additional information
  27389. * regarding copyright ownership. The ASF licenses this file
  27390. * to you under the Apache License, Version 2.0 (the
  27391. * "License"); you may not use this file except in compliance
  27392. * with the License. You may obtain a copy of the License at
  27393. *
  27394. * http://www.apache.org/licenses/LICENSE-2.0
  27395. *
  27396. * Unless required by applicable law or agreed to in writing,
  27397. * software distributed under the License is distributed on an
  27398. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27399. * KIND, either express or implied. See the License for the
  27400. * specific language governing permissions and limitations
  27401. * under the License.
  27402. */
  27403. /**
  27404. * Log scale
  27405. * @module echarts/scale/Log
  27406. */
  27407. // Use some method of IntervalScale
  27408. var scaleProto$1 = Scale.prototype;
  27409. var intervalScaleProto$1 = IntervalScale.prototype;
  27410. var getPrecisionSafe$1 = getPrecisionSafe;
  27411. var roundingErrorFix = round$1;
  27412. var mathFloor$1 = Math.floor;
  27413. var mathCeil$1 = Math.ceil;
  27414. var mathPow$1 = Math.pow;
  27415. var mathLog = Math.log;
  27416. var LogScale = Scale.extend({
  27417. type: 'log',
  27418. base: 10,
  27419. $constructor: function () {
  27420. Scale.apply(this, arguments);
  27421. this._originalScale = new IntervalScale();
  27422. },
  27423. /**
  27424. * @return {Array.<number>}
  27425. */
  27426. getTicks: function () {
  27427. var originalScale = this._originalScale;
  27428. var extent = this._extent;
  27429. var originalExtent = originalScale.getExtent();
  27430. return map(intervalScaleProto$1.getTicks.call(this), function (val) {
  27431. var powVal = round$1(mathPow$1(this.base, val));
  27432. // Fix #4158
  27433. powVal = (val === extent[0] && originalScale.__fixMin)
  27434. ? fixRoundingError(powVal, originalExtent[0])
  27435. : powVal;
  27436. powVal = (val === extent[1] && originalScale.__fixMax)
  27437. ? fixRoundingError(powVal, originalExtent[1])
  27438. : powVal;
  27439. return powVal;
  27440. }, this);
  27441. },
  27442. /**
  27443. * @param {number} val
  27444. * @return {string}
  27445. */
  27446. getLabel: intervalScaleProto$1.getLabel,
  27447. /**
  27448. * @param {number} val
  27449. * @return {number}
  27450. */
  27451. scale: function (val) {
  27452. val = scaleProto$1.scale.call(this, val);
  27453. return mathPow$1(this.base, val);
  27454. },
  27455. /**
  27456. * @param {number} start
  27457. * @param {number} end
  27458. */
  27459. setExtent: function (start, end) {
  27460. var base = this.base;
  27461. start = mathLog(start) / mathLog(base);
  27462. end = mathLog(end) / mathLog(base);
  27463. intervalScaleProto$1.setExtent.call(this, start, end);
  27464. },
  27465. /**
  27466. * @return {number} end
  27467. */
  27468. getExtent: function () {
  27469. var base = this.base;
  27470. var extent = scaleProto$1.getExtent.call(this);
  27471. extent[0] = mathPow$1(base, extent[0]);
  27472. extent[1] = mathPow$1(base, extent[1]);
  27473. // Fix #4158
  27474. var originalScale = this._originalScale;
  27475. var originalExtent = originalScale.getExtent();
  27476. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  27477. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  27478. return extent;
  27479. },
  27480. /**
  27481. * @param {Array.<number>} extent
  27482. */
  27483. unionExtent: function (extent) {
  27484. this._originalScale.unionExtent(extent);
  27485. var base = this.base;
  27486. extent[0] = mathLog(extent[0]) / mathLog(base);
  27487. extent[1] = mathLog(extent[1]) / mathLog(base);
  27488. scaleProto$1.unionExtent.call(this, extent);
  27489. },
  27490. /**
  27491. * @override
  27492. */
  27493. unionExtentFromData: function (data, dim) {
  27494. // TODO
  27495. // filter value that <= 0
  27496. this.unionExtent(data.getApproximateExtent(dim));
  27497. },
  27498. /**
  27499. * Update interval and extent of intervals for nice ticks
  27500. * @param {number} [approxTickNum = 10] Given approx tick number
  27501. */
  27502. niceTicks: function (approxTickNum) {
  27503. approxTickNum = approxTickNum || 10;
  27504. var extent = this._extent;
  27505. var span = extent[1] - extent[0];
  27506. if (span === Infinity || span <= 0) {
  27507. return;
  27508. }
  27509. var interval = quantity(span);
  27510. var err = approxTickNum / span * interval;
  27511. // Filter ticks to get closer to the desired count.
  27512. if (err <= 0.5) {
  27513. interval *= 10;
  27514. }
  27515. // Interval should be integer
  27516. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  27517. interval *= 10;
  27518. }
  27519. var niceExtent = [
  27520. round$1(mathCeil$1(extent[0] / interval) * interval),
  27521. round$1(mathFloor$1(extent[1] / interval) * interval)
  27522. ];
  27523. this._interval = interval;
  27524. this._niceExtent = niceExtent;
  27525. },
  27526. /**
  27527. * Nice extent.
  27528. * @override
  27529. */
  27530. niceExtent: function (opt) {
  27531. intervalScaleProto$1.niceExtent.call(this, opt);
  27532. var originalScale = this._originalScale;
  27533. originalScale.__fixMin = opt.fixMin;
  27534. originalScale.__fixMax = opt.fixMax;
  27535. }
  27536. });
  27537. each$1(['contain', 'normalize'], function (methodName) {
  27538. LogScale.prototype[methodName] = function (val) {
  27539. val = mathLog(val) / mathLog(this.base);
  27540. return scaleProto$1[methodName].call(this, val);
  27541. };
  27542. });
  27543. LogScale.create = function () {
  27544. return new LogScale();
  27545. };
  27546. function fixRoundingError(val, originalVal) {
  27547. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  27548. }
  27549. /*
  27550. * Licensed to the Apache Software Foundation (ASF) under one
  27551. * or more contributor license agreements. See the NOTICE file
  27552. * distributed with this work for additional information
  27553. * regarding copyright ownership. The ASF licenses this file
  27554. * to you under the Apache License, Version 2.0 (the
  27555. * "License"); you may not use this file except in compliance
  27556. * with the License. You may obtain a copy of the License at
  27557. *
  27558. * http://www.apache.org/licenses/LICENSE-2.0
  27559. *
  27560. * Unless required by applicable law or agreed to in writing,
  27561. * software distributed under the License is distributed on an
  27562. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27563. * KIND, either express or implied. See the License for the
  27564. * specific language governing permissions and limitations
  27565. * under the License.
  27566. */
  27567. /**
  27568. * Get axis scale extent before niced.
  27569. * Item of returned array can only be number (including Infinity and NaN).
  27570. */
  27571. function getScaleExtent(scale, model) {
  27572. var scaleType = scale.type;
  27573. var min = model.getMin();
  27574. var max = model.getMax();
  27575. var fixMin = min != null;
  27576. var fixMax = max != null;
  27577. var originalExtent = scale.getExtent();
  27578. var axisDataLen;
  27579. var boundaryGap;
  27580. var span;
  27581. if (scaleType === 'ordinal') {
  27582. axisDataLen = model.getCategories().length;
  27583. }
  27584. else {
  27585. boundaryGap = model.get('boundaryGap');
  27586. if (!isArray(boundaryGap)) {
  27587. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  27588. }
  27589. if (typeof boundaryGap[0] === 'boolean') {
  27590. if (__DEV__) {
  27591. console.warn('Boolean type for boundaryGap is only '
  27592. + 'allowed for ordinal axis. Please use string in '
  27593. + 'percentage instead, e.g., "20%". Currently, '
  27594. + 'boundaryGap is set to be 0.');
  27595. }
  27596. boundaryGap = [0, 0];
  27597. }
  27598. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  27599. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  27600. span = (originalExtent[1] - originalExtent[0])
  27601. || Math.abs(originalExtent[0]);
  27602. }
  27603. // Notice: When min/max is not set (that is, when there are null/undefined,
  27604. // which is the most common case), these cases should be ensured:
  27605. // (1) For 'ordinal', show all axis.data.
  27606. // (2) For others:
  27607. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  27608. // disabled).
  27609. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  27610. // be the result that originalExtent enlarged by boundaryGap.
  27611. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  27612. // FIXME
  27613. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  27614. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  27615. // that the results processed by boundaryGap are positive/negative?
  27616. if (min == null) {
  27617. min = scaleType === 'ordinal'
  27618. ? (axisDataLen ? 0 : NaN)
  27619. : originalExtent[0] - boundaryGap[0] * span;
  27620. }
  27621. if (max == null) {
  27622. max = scaleType === 'ordinal'
  27623. ? (axisDataLen ? axisDataLen - 1 : NaN)
  27624. : originalExtent[1] + boundaryGap[1] * span;
  27625. }
  27626. if (min === 'dataMin') {
  27627. min = originalExtent[0];
  27628. }
  27629. else if (typeof min === 'function') {
  27630. min = min({
  27631. min: originalExtent[0],
  27632. max: originalExtent[1]
  27633. });
  27634. }
  27635. if (max === 'dataMax') {
  27636. max = originalExtent[1];
  27637. }
  27638. else if (typeof max === 'function') {
  27639. max = max({
  27640. min: originalExtent[0],
  27641. max: originalExtent[1]
  27642. });
  27643. }
  27644. (min == null || !isFinite(min)) && (min = NaN);
  27645. (max == null || !isFinite(max)) && (max = NaN);
  27646. scale.setBlank(
  27647. eqNaN(min)
  27648. || eqNaN(max)
  27649. || (scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length)
  27650. );
  27651. // Evaluate if axis needs cross zero
  27652. if (model.getNeedCrossZero()) {
  27653. // Axis is over zero and min is not set
  27654. if (min > 0 && max > 0 && !fixMin) {
  27655. min = 0;
  27656. }
  27657. // Axis is under zero and max is not set
  27658. if (min < 0 && max < 0 && !fixMax) {
  27659. max = 0;
  27660. }
  27661. }
  27662. // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  27663. // is base axis
  27664. // FIXME
  27665. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  27666. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  27667. // Should not depend on series type `bar`?
  27668. // (3) Fix that might overlap when using dataZoom.
  27669. // (4) Consider other chart types using `barGrid`?
  27670. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  27671. var ecModel = model.ecModel;
  27672. if (ecModel && (scaleType === 'time' /*|| scaleType === 'interval' */)) {
  27673. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  27674. var isBaseAxisAndHasBarSeries;
  27675. each$1(barSeriesModels, function (seriesModel) {
  27676. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  27677. });
  27678. if (isBaseAxisAndHasBarSeries) {
  27679. // Calculate placement of bars on axis
  27680. var barWidthAndOffset = makeColumnLayout(barSeriesModels);
  27681. // Adjust axis min and max to account for overflow
  27682. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  27683. min = adjustedScale.min;
  27684. max = adjustedScale.max;
  27685. }
  27686. }
  27687. return [min, max];
  27688. }
  27689. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  27690. // Get Axis Length
  27691. var axisExtent = model.axis.getExtent();
  27692. var axisLength = axisExtent[1] - axisExtent[0];
  27693. // Get bars on current base axis and calculate min and max overflow
  27694. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  27695. if (barsOnCurrentAxis === undefined) {
  27696. return {min: min, max: max};
  27697. }
  27698. var minOverflow = Infinity;
  27699. each$1(barsOnCurrentAxis, function (item) {
  27700. minOverflow = Math.min(item.offset, minOverflow);
  27701. });
  27702. var maxOverflow = -Infinity;
  27703. each$1(barsOnCurrentAxis, function (item) {
  27704. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  27705. });
  27706. minOverflow = Math.abs(minOverflow);
  27707. maxOverflow = Math.abs(maxOverflow);
  27708. var totalOverFlow = minOverflow + maxOverflow;
  27709. // Calulate required buffer based on old range and overflow
  27710. var oldRange = max - min;
  27711. var oldRangePercentOfNew = (1 - (minOverflow + maxOverflow) / axisLength);
  27712. var overflowBuffer = ((oldRange / oldRangePercentOfNew) - oldRange);
  27713. max += overflowBuffer * (maxOverflow / totalOverFlow);
  27714. min -= overflowBuffer * (minOverflow / totalOverFlow);
  27715. return {min: min, max: max};
  27716. }
  27717. function niceScaleExtent(scale, model) {
  27718. var extent = getScaleExtent(scale, model);
  27719. var fixMin = model.getMin() != null;
  27720. var fixMax = model.getMax() != null;
  27721. var splitNumber = model.get('splitNumber');
  27722. if (scale.type === 'log') {
  27723. scale.base = model.get('logBase');
  27724. }
  27725. var scaleType = scale.type;
  27726. scale.setExtent(extent[0], extent[1]);
  27727. scale.niceExtent({
  27728. splitNumber: splitNumber,
  27729. fixMin: fixMin,
  27730. fixMax: fixMax,
  27731. minInterval: (scaleType === 'interval' || scaleType === 'time')
  27732. ? model.get('minInterval') : null,
  27733. maxInterval: (scaleType === 'interval' || scaleType === 'time')
  27734. ? model.get('maxInterval') : null
  27735. });
  27736. // If some one specified the min, max. And the default calculated interval
  27737. // is not good enough. He can specify the interval. It is often appeared
  27738. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  27739. // to be 60.
  27740. // FIXME
  27741. var interval = model.get('interval');
  27742. if (interval != null) {
  27743. scale.setInterval && scale.setInterval(interval);
  27744. }
  27745. }
  27746. /**
  27747. * @param {module:echarts/model/Model} model
  27748. * @param {string} [axisType] Default retrieve from model.type
  27749. * @return {module:echarts/scale/*}
  27750. */
  27751. function createScaleByModel(model, axisType) {
  27752. axisType = axisType || model.get('type');
  27753. if (axisType) {
  27754. switch (axisType) {
  27755. // Buildin scale
  27756. case 'category':
  27757. return new OrdinalScale(
  27758. model.getOrdinalMeta
  27759. ? model.getOrdinalMeta()
  27760. : model.getCategories(),
  27761. [Infinity, -Infinity]
  27762. );
  27763. case 'value':
  27764. return new IntervalScale();
  27765. // Extended scale, like time and log
  27766. default:
  27767. return (Scale.getClass(axisType) || IntervalScale).create(model);
  27768. }
  27769. }
  27770. }
  27771. /**
  27772. * Check if the axis corss 0
  27773. */
  27774. function ifAxisCrossZero(axis) {
  27775. var dataExtent = axis.scale.getExtent();
  27776. var min = dataExtent[0];
  27777. var max = dataExtent[1];
  27778. return !((min > 0 && max > 0) || (min < 0 && max < 0));
  27779. }
  27780. /**
  27781. * @param {module:echarts/coord/Axis} axis
  27782. * @return {Function} Label formatter function.
  27783. * param: {number} tickValue,
  27784. * param: {number} idx, the index in all ticks.
  27785. * If category axis, this param is not requied.
  27786. * return: {string} label string.
  27787. */
  27788. function makeLabelFormatter(axis) {
  27789. var labelFormatter = axis.getLabelModel().get('formatter');
  27790. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  27791. if (typeof labelFormatter === 'string') {
  27792. labelFormatter = (function (tpl) {
  27793. return function (val) {
  27794. return tpl.replace('{value}', val != null ? val : '');
  27795. };
  27796. })(labelFormatter);
  27797. // Consider empty array
  27798. return labelFormatter;
  27799. }
  27800. else if (typeof labelFormatter === 'function') {
  27801. return function (tickValue, idx) {
  27802. // The original intention of `idx` is "the index of the tick in all ticks".
  27803. // But the previous implementation of category axis do not consider the
  27804. // `axisLabel.interval`, which cause that, for example, the `interval` is
  27805. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  27806. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  27807. // the definition here for back compatibility.
  27808. if (categoryTickStart != null) {
  27809. idx = tickValue - categoryTickStart;
  27810. }
  27811. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  27812. };
  27813. }
  27814. else {
  27815. return function (tick) {
  27816. return axis.scale.getLabel(tick);
  27817. };
  27818. }
  27819. }
  27820. function getAxisRawValue(axis, value) {
  27821. // In category axis with data zoom, tick is not the original
  27822. // index of axis.data. So tick should not be exposed to user
  27823. // in category axis.
  27824. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  27825. }
  27826. /**
  27827. * @param {module:echarts/coord/Axis} axis
  27828. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  27829. */
  27830. function estimateLabelUnionRect(axis) {
  27831. var axisModel = axis.model;
  27832. var scale = axis.scale;
  27833. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  27834. return;
  27835. }
  27836. var isCategory = axis.type === 'category';
  27837. var realNumberScaleTicks;
  27838. var tickCount;
  27839. var categoryScaleExtent = scale.getExtent();
  27840. // Optimize for large category data, avoid call `getTicks()`.
  27841. if (isCategory) {
  27842. tickCount = scale.count();
  27843. }
  27844. else {
  27845. realNumberScaleTicks = scale.getTicks();
  27846. tickCount = realNumberScaleTicks.length;
  27847. }
  27848. var axisLabelModel = axis.getLabelModel();
  27849. var labelFormatter = makeLabelFormatter(axis);
  27850. var rect;
  27851. var step = 1;
  27852. // Simple optimization for large amount of labels
  27853. if (tickCount > 40) {
  27854. step = Math.ceil(tickCount / 40);
  27855. }
  27856. for (var i = 0; i < tickCount; i += step) {
  27857. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  27858. var label = labelFormatter(tickValue);
  27859. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  27860. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  27861. rect ? rect.union(singleRect) : (rect = singleRect);
  27862. }
  27863. return rect;
  27864. }
  27865. function rotateTextRect(textRect, rotate) {
  27866. var rotateRadians = rotate * Math.PI / 180;
  27867. var boundingBox = textRect.plain();
  27868. var beforeWidth = boundingBox.width;
  27869. var beforeHeight = boundingBox.height;
  27870. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  27871. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  27872. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  27873. return rotatedRect;
  27874. }
  27875. /*
  27876. * Licensed to the Apache Software Foundation (ASF) under one
  27877. * or more contributor license agreements. See the NOTICE file
  27878. * distributed with this work for additional information
  27879. * regarding copyright ownership. The ASF licenses this file
  27880. * to you under the Apache License, Version 2.0 (the
  27881. * "License"); you may not use this file except in compliance
  27882. * with the License. You may obtain a copy of the License at
  27883. *
  27884. * http://www.apache.org/licenses/LICENSE-2.0
  27885. *
  27886. * Unless required by applicable law or agreed to in writing,
  27887. * software distributed under the License is distributed on an
  27888. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27889. * KIND, either express or implied. See the License for the
  27890. * specific language governing permissions and limitations
  27891. * under the License.
  27892. */
  27893. var axisModelCommonMixin = {
  27894. /**
  27895. * @param {boolean} origin
  27896. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  27897. */
  27898. getMin: function (origin) {
  27899. var option = this.option;
  27900. var min = (!origin && option.rangeStart != null)
  27901. ? option.rangeStart : option.min;
  27902. if (this.axis
  27903. && min != null
  27904. && min !== 'dataMin'
  27905. && typeof min !== 'function'
  27906. && !eqNaN(min)
  27907. ) {
  27908. min = this.axis.scale.parse(min);
  27909. }
  27910. return min;
  27911. },
  27912. /**
  27913. * @param {boolean} origin
  27914. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  27915. */
  27916. getMax: function (origin) {
  27917. var option = this.option;
  27918. var max = (!origin && option.rangeEnd != null)
  27919. ? option.rangeEnd : option.max;
  27920. if (this.axis
  27921. && max != null
  27922. && max !== 'dataMax'
  27923. && typeof max !== 'function'
  27924. && !eqNaN(max)
  27925. ) {
  27926. max = this.axis.scale.parse(max);
  27927. }
  27928. return max;
  27929. },
  27930. /**
  27931. * @return {boolean}
  27932. */
  27933. getNeedCrossZero: function () {
  27934. var option = this.option;
  27935. return (option.rangeStart != null || option.rangeEnd != null)
  27936. ? false : !option.scale;
  27937. },
  27938. /**
  27939. * Should be implemented by each axis model if necessary.
  27940. * @return {module:echarts/model/Component} coordinate system model
  27941. */
  27942. getCoordSysModel: noop,
  27943. /**
  27944. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  27945. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  27946. */
  27947. setRange: function (rangeStart, rangeEnd) {
  27948. this.option.rangeStart = rangeStart;
  27949. this.option.rangeEnd = rangeEnd;
  27950. },
  27951. /**
  27952. * Reset range
  27953. */
  27954. resetRange: function () {
  27955. // rangeStart and rangeEnd is readonly.
  27956. this.option.rangeStart = this.option.rangeEnd = null;
  27957. }
  27958. };
  27959. /*
  27960. * Licensed to the Apache Software Foundation (ASF) under one
  27961. * or more contributor license agreements. See the NOTICE file
  27962. * distributed with this work for additional information
  27963. * regarding copyright ownership. The ASF licenses this file
  27964. * to you under the Apache License, Version 2.0 (the
  27965. * "License"); you may not use this file except in compliance
  27966. * with the License. You may obtain a copy of the License at
  27967. *
  27968. * http://www.apache.org/licenses/LICENSE-2.0
  27969. *
  27970. * Unless required by applicable law or agreed to in writing,
  27971. * software distributed under the License is distributed on an
  27972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27973. * KIND, either express or implied. See the License for the
  27974. * specific language governing permissions and limitations
  27975. * under the License.
  27976. */
  27977. // Symbol factory
  27978. /**
  27979. * Triangle shape
  27980. * @inner
  27981. */
  27982. var Triangle = extendShape({
  27983. type: 'triangle',
  27984. shape: {
  27985. cx: 0,
  27986. cy: 0,
  27987. width: 0,
  27988. height: 0
  27989. },
  27990. buildPath: function (path, shape) {
  27991. var cx = shape.cx;
  27992. var cy = shape.cy;
  27993. var width = shape.width / 2;
  27994. var height = shape.height / 2;
  27995. path.moveTo(cx, cy - height);
  27996. path.lineTo(cx + width, cy + height);
  27997. path.lineTo(cx - width, cy + height);
  27998. path.closePath();
  27999. }
  28000. });
  28001. /**
  28002. * Diamond shape
  28003. * @inner
  28004. */
  28005. var Diamond = extendShape({
  28006. type: 'diamond',
  28007. shape: {
  28008. cx: 0,
  28009. cy: 0,
  28010. width: 0,
  28011. height: 0
  28012. },
  28013. buildPath: function (path, shape) {
  28014. var cx = shape.cx;
  28015. var cy = shape.cy;
  28016. var width = shape.width / 2;
  28017. var height = shape.height / 2;
  28018. path.moveTo(cx, cy - height);
  28019. path.lineTo(cx + width, cy);
  28020. path.lineTo(cx, cy + height);
  28021. path.lineTo(cx - width, cy);
  28022. path.closePath();
  28023. }
  28024. });
  28025. /**
  28026. * Pin shape
  28027. * @inner
  28028. */
  28029. var Pin = extendShape({
  28030. type: 'pin',
  28031. shape: {
  28032. // x, y on the cusp
  28033. x: 0,
  28034. y: 0,
  28035. width: 0,
  28036. height: 0
  28037. },
  28038. buildPath: function (path, shape) {
  28039. var x = shape.x;
  28040. var y = shape.y;
  28041. var w = shape.width / 5 * 3;
  28042. // Height must be larger than width
  28043. var h = Math.max(w, shape.height);
  28044. var r = w / 2;
  28045. // Dist on y with tangent point and circle center
  28046. var dy = r * r / (h - r);
  28047. var cy = y - h + r + dy;
  28048. var angle = Math.asin(dy / r);
  28049. // Dist on x with tangent point and circle center
  28050. var dx = Math.cos(angle) * r;
  28051. var tanX = Math.sin(angle);
  28052. var tanY = Math.cos(angle);
  28053. var cpLen = r * 0.6;
  28054. var cpLen2 = r * 0.7;
  28055. path.moveTo(x - dx, cy + dy);
  28056. path.arc(
  28057. x, cy, r,
  28058. Math.PI - angle,
  28059. Math.PI * 2 + angle
  28060. );
  28061. path.bezierCurveTo(
  28062. x + dx - tanX * cpLen, cy + dy + tanY * cpLen,
  28063. x, y - cpLen2,
  28064. x, y
  28065. );
  28066. path.bezierCurveTo(
  28067. x, y - cpLen2,
  28068. x - dx + tanX * cpLen, cy + dy + tanY * cpLen,
  28069. x - dx, cy + dy
  28070. );
  28071. path.closePath();
  28072. }
  28073. });
  28074. /**
  28075. * Arrow shape
  28076. * @inner
  28077. */
  28078. var Arrow = extendShape({
  28079. type: 'arrow',
  28080. shape: {
  28081. x: 0,
  28082. y: 0,
  28083. width: 0,
  28084. height: 0
  28085. },
  28086. buildPath: function (ctx, shape) {
  28087. var height = shape.height;
  28088. var width = shape.width;
  28089. var x = shape.x;
  28090. var y = shape.y;
  28091. var dx = width / 3 * 2;
  28092. ctx.moveTo(x, y);
  28093. ctx.lineTo(x + dx, y + height);
  28094. ctx.lineTo(x, y + height / 4 * 3);
  28095. ctx.lineTo(x - dx, y + height);
  28096. ctx.lineTo(x, y);
  28097. ctx.closePath();
  28098. }
  28099. });
  28100. /**
  28101. * Map of path contructors
  28102. * @type {Object.<string, module:zrender/graphic/Path>}
  28103. */
  28104. var symbolCtors = {
  28105. line: Line,
  28106. rect: Rect,
  28107. roundRect: Rect,
  28108. square: Rect,
  28109. circle: Circle,
  28110. diamond: Diamond,
  28111. pin: Pin,
  28112. arrow: Arrow,
  28113. triangle: Triangle
  28114. };
  28115. var symbolShapeMakers = {
  28116. line: function (x, y, w, h, shape) {
  28117. // FIXME
  28118. shape.x1 = x;
  28119. shape.y1 = y + h / 2;
  28120. shape.x2 = x + w;
  28121. shape.y2 = y + h / 2;
  28122. },
  28123. rect: function (x, y, w, h, shape) {
  28124. shape.x = x;
  28125. shape.y = y;
  28126. shape.width = w;
  28127. shape.height = h;
  28128. },
  28129. roundRect: function (x, y, w, h, shape) {
  28130. shape.x = x;
  28131. shape.y = y;
  28132. shape.width = w;
  28133. shape.height = h;
  28134. shape.r = Math.min(w, h) / 4;
  28135. },
  28136. square: function (x, y, w, h, shape) {
  28137. var size = Math.min(w, h);
  28138. shape.x = x;
  28139. shape.y = y;
  28140. shape.width = size;
  28141. shape.height = size;
  28142. },
  28143. circle: function (x, y, w, h, shape) {
  28144. // Put circle in the center of square
  28145. shape.cx = x + w / 2;
  28146. shape.cy = y + h / 2;
  28147. shape.r = Math.min(w, h) / 2;
  28148. },
  28149. diamond: function (x, y, w, h, shape) {
  28150. shape.cx = x + w / 2;
  28151. shape.cy = y + h / 2;
  28152. shape.width = w;
  28153. shape.height = h;
  28154. },
  28155. pin: function (x, y, w, h, shape) {
  28156. shape.x = x + w / 2;
  28157. shape.y = y + h / 2;
  28158. shape.width = w;
  28159. shape.height = h;
  28160. },
  28161. arrow: function (x, y, w, h, shape) {
  28162. shape.x = x + w / 2;
  28163. shape.y = y + h / 2;
  28164. shape.width = w;
  28165. shape.height = h;
  28166. },
  28167. triangle: function (x, y, w, h, shape) {
  28168. shape.cx = x + w / 2;
  28169. shape.cy = y + h / 2;
  28170. shape.width = w;
  28171. shape.height = h;
  28172. }
  28173. };
  28174. var symbolBuildProxies = {};
  28175. each$1(symbolCtors, function (Ctor, name) {
  28176. symbolBuildProxies[name] = new Ctor();
  28177. });
  28178. var SymbolClz = extendShape({
  28179. type: 'symbol',
  28180. shape: {
  28181. symbolType: '',
  28182. x: 0,
  28183. y: 0,
  28184. width: 0,
  28185. height: 0
  28186. },
  28187. beforeBrush: function () {
  28188. var style = this.style;
  28189. var shape = this.shape;
  28190. // FIXME
  28191. if (shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28192. style.textPosition = ['50%', '40%'];
  28193. style.textAlign = 'center';
  28194. style.textVerticalAlign = 'middle';
  28195. }
  28196. },
  28197. buildPath: function (ctx, shape, inBundle) {
  28198. var symbolType = shape.symbolType;
  28199. var proxySymbol = symbolBuildProxies[symbolType];
  28200. if (shape.symbolType !== 'none') {
  28201. if (!proxySymbol) {
  28202. // Default rect
  28203. symbolType = 'rect';
  28204. proxySymbol = symbolBuildProxies[symbolType];
  28205. }
  28206. symbolShapeMakers[symbolType](
  28207. shape.x, shape.y, shape.width, shape.height, proxySymbol.shape
  28208. );
  28209. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28210. }
  28211. }
  28212. });
  28213. // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28214. function symbolPathSetColor(color, innerColor) {
  28215. if (this.type !== 'image') {
  28216. var symbolStyle = this.style;
  28217. var symbolShape = this.shape;
  28218. if (symbolShape && symbolShape.symbolType === 'line') {
  28219. symbolStyle.stroke = color;
  28220. }
  28221. else if (this.__isEmptyBrush) {
  28222. symbolStyle.stroke = color;
  28223. symbolStyle.fill = innerColor || '#fff';
  28224. }
  28225. else {
  28226. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28227. symbolStyle.fill && (symbolStyle.fill = color);
  28228. symbolStyle.stroke && (symbolStyle.stroke = color);
  28229. }
  28230. this.dirty(false);
  28231. }
  28232. }
  28233. /**
  28234. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28235. * @param {string} symbolType
  28236. * @param {number} x
  28237. * @param {number} y
  28238. * @param {number} w
  28239. * @param {number} h
  28240. * @param {string} color
  28241. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  28242. * for path and image only.
  28243. */
  28244. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  28245. // TODO Support image object, DynamicImage.
  28246. var isEmpty = symbolType.indexOf('empty') === 0;
  28247. if (isEmpty) {
  28248. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  28249. }
  28250. var symbolPath;
  28251. if (symbolType.indexOf('image://') === 0) {
  28252. symbolPath = makeImage(
  28253. symbolType.slice(8),
  28254. new BoundingRect(x, y, w, h),
  28255. keepAspect ? 'center' : 'cover'
  28256. );
  28257. }
  28258. else if (symbolType.indexOf('path://') === 0) {
  28259. symbolPath = makePath(
  28260. symbolType.slice(7),
  28261. {},
  28262. new BoundingRect(x, y, w, h),
  28263. keepAspect ? 'center' : 'cover'
  28264. );
  28265. }
  28266. else {
  28267. symbolPath = new SymbolClz({
  28268. shape: {
  28269. symbolType: symbolType,
  28270. x: x,
  28271. y: y,
  28272. width: w,
  28273. height: h
  28274. }
  28275. });
  28276. }
  28277. symbolPath.__isEmptyBrush = isEmpty;
  28278. symbolPath.setColor = symbolPathSetColor;
  28279. symbolPath.setColor(color);
  28280. return symbolPath;
  28281. }
  28282. /*
  28283. * Licensed to the Apache Software Foundation (ASF) under one
  28284. * or more contributor license agreements. See the NOTICE file
  28285. * distributed with this work for additional information
  28286. * regarding copyright ownership. The ASF licenses this file
  28287. * to you under the Apache License, Version 2.0 (the
  28288. * "License"); you may not use this file except in compliance
  28289. * with the License. You may obtain a copy of the License at
  28290. *
  28291. * http://www.apache.org/licenses/LICENSE-2.0
  28292. *
  28293. * Unless required by applicable law or agreed to in writing,
  28294. * software distributed under the License is distributed on an
  28295. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28296. * KIND, either express or implied. See the License for the
  28297. * specific language governing permissions and limitations
  28298. * under the License.
  28299. */
  28300. // import createGraphFromNodeEdge from './chart/helper/createGraphFromNodeEdge';
  28301. /**
  28302. * Create a muti dimension List structure from seriesModel.
  28303. * @param {module:echarts/model/Model} seriesModel
  28304. * @return {module:echarts/data/List} list
  28305. */
  28306. function createList(seriesModel) {
  28307. return createListFromArray(seriesModel.getSource(), seriesModel);
  28308. }
  28309. var dataStack$1 = {
  28310. isDimensionStacked: isDimensionStacked,
  28311. enableDataStack: enableDataStack,
  28312. getStackedDimension: getStackedDimension
  28313. };
  28314. /**
  28315. * Create scale
  28316. * @param {Array.<number>} dataExtent
  28317. * @param {Object|module:echarts/Model} option
  28318. */
  28319. function createScale(dataExtent, option) {
  28320. var axisModel = option;
  28321. if (!Model.isInstance(option)) {
  28322. axisModel = new Model(option);
  28323. mixin(axisModel, axisModelCommonMixin);
  28324. }
  28325. var scale = createScaleByModel(axisModel);
  28326. scale.setExtent(dataExtent[0], dataExtent[1]);
  28327. niceScaleExtent(scale, axisModel);
  28328. return scale;
  28329. }
  28330. /**
  28331. * Mixin common methods to axis model,
  28332. *
  28333. * Inlcude methods
  28334. * `getFormattedLabels() => Array.<string>`
  28335. * `getCategories() => Array.<string>`
  28336. * `getMin(origin: boolean) => number`
  28337. * `getMax(origin: boolean) => number`
  28338. * `getNeedCrossZero() => boolean`
  28339. * `setRange(start: number, end: number)`
  28340. * `resetRange()`
  28341. */
  28342. function mixinAxisModelCommonMethods(Model$$1) {
  28343. mixin(Model$$1, axisModelCommonMixin);
  28344. }
  28345. var helper = (Object.freeze || Object)({
  28346. createList: createList,
  28347. getLayoutRect: getLayoutRect,
  28348. dataStack: dataStack$1,
  28349. createScale: createScale,
  28350. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  28351. completeDimensions: completeDimensions,
  28352. createDimensions: createDimensions,
  28353. createSymbol: createSymbol
  28354. });
  28355. var EPSILON$3 = 1e-8;
  28356. function isAroundEqual$1(a, b) {
  28357. return Math.abs(a - b) < EPSILON$3;
  28358. }
  28359. function contain$1(points, x, y) {
  28360. var w = 0;
  28361. var p = points[0];
  28362. if (!p) {
  28363. return false;
  28364. }
  28365. for (var i = 1; i < points.length; i++) {
  28366. var p2 = points[i];
  28367. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  28368. p = p2;
  28369. }
  28370. // Close polygon
  28371. var p0 = points[0];
  28372. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  28373. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  28374. }
  28375. return w !== 0;
  28376. }
  28377. /*
  28378. * Licensed to the Apache Software Foundation (ASF) under one
  28379. * or more contributor license agreements. See the NOTICE file
  28380. * distributed with this work for additional information
  28381. * regarding copyright ownership. The ASF licenses this file
  28382. * to you under the Apache License, Version 2.0 (the
  28383. * "License"); you may not use this file except in compliance
  28384. * with the License. You may obtain a copy of the License at
  28385. *
  28386. * http://www.apache.org/licenses/LICENSE-2.0
  28387. *
  28388. * Unless required by applicable law or agreed to in writing,
  28389. * software distributed under the License is distributed on an
  28390. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28391. * KIND, either express or implied. See the License for the
  28392. * specific language governing permissions and limitations
  28393. * under the License.
  28394. */
  28395. /**
  28396. * @module echarts/coord/geo/Region
  28397. */
  28398. /**
  28399. * @param {string} name
  28400. * @param {Array} geometries
  28401. * @param {Array.<number>} cp
  28402. */
  28403. function Region(name, geometries, cp) {
  28404. /**
  28405. * @type {string}
  28406. * @readOnly
  28407. */
  28408. this.name = name;
  28409. /**
  28410. * @type {Array.<Array>}
  28411. * @readOnly
  28412. */
  28413. this.geometries = geometries;
  28414. if (!cp) {
  28415. var rect = this.getBoundingRect();
  28416. cp = [
  28417. rect.x + rect.width / 2,
  28418. rect.y + rect.height / 2
  28419. ];
  28420. }
  28421. else {
  28422. cp = [cp[0], cp[1]];
  28423. }
  28424. /**
  28425. * @type {Array.<number>}
  28426. */
  28427. this.center = cp;
  28428. }
  28429. Region.prototype = {
  28430. constructor: Region,
  28431. properties: null,
  28432. /**
  28433. * @return {module:zrender/core/BoundingRect}
  28434. */
  28435. getBoundingRect: function () {
  28436. var rect = this._rect;
  28437. if (rect) {
  28438. return rect;
  28439. }
  28440. var MAX_NUMBER = Number.MAX_VALUE;
  28441. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  28442. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  28443. var min2 = [];
  28444. var max2 = [];
  28445. var geometries = this.geometries;
  28446. for (var i = 0; i < geometries.length; i++) {
  28447. // Only support polygon
  28448. if (geometries[i].type !== 'polygon') {
  28449. continue;
  28450. }
  28451. // Doesn't consider hole
  28452. var exterior = geometries[i].exterior;
  28453. fromPoints(exterior, min2, max2);
  28454. min(min$$1, min$$1, min2);
  28455. max(max$$1, max$$1, max2);
  28456. }
  28457. // No data
  28458. if (i === 0) {
  28459. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  28460. }
  28461. return (this._rect = new BoundingRect(
  28462. min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]
  28463. ));
  28464. },
  28465. /**
  28466. * @param {<Array.<number>} coord
  28467. * @return {boolean}
  28468. */
  28469. contain: function (coord) {
  28470. var rect = this.getBoundingRect();
  28471. var geometries = this.geometries;
  28472. if (!rect.contain(coord[0], coord[1])) {
  28473. return false;
  28474. }
  28475. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  28476. // Only support polygon.
  28477. if (geometries[i].type !== 'polygon') {
  28478. continue;
  28479. }
  28480. var exterior = geometries[i].exterior;
  28481. var interiors = geometries[i].interiors;
  28482. if (contain$1(exterior, coord[0], coord[1])) {
  28483. // Not in the region if point is in the hole.
  28484. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  28485. if (contain$1(interiors[k])) {
  28486. continue loopGeo;
  28487. }
  28488. }
  28489. return true;
  28490. }
  28491. }
  28492. return false;
  28493. },
  28494. transformTo: function (x, y, width, height) {
  28495. var rect = this.getBoundingRect();
  28496. var aspect = rect.width / rect.height;
  28497. if (!width) {
  28498. width = aspect * height;
  28499. }
  28500. else if (!height) {
  28501. height = width / aspect ;
  28502. }
  28503. var target = new BoundingRect(x, y, width, height);
  28504. var transform = rect.calculateTransform(target);
  28505. var geometries = this.geometries;
  28506. for (var i = 0; i < geometries.length; i++) {
  28507. // Only support polygon.
  28508. if (geometries[i].type !== 'polygon') {
  28509. continue;
  28510. }
  28511. var exterior = geometries[i].exterior;
  28512. var interiors = geometries[i].interiors;
  28513. for (var p = 0; p < exterior.length; p++) {
  28514. applyTransform(exterior[p], exterior[p], transform);
  28515. }
  28516. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  28517. for (var p = 0; p < interiors[h].length; p++) {
  28518. applyTransform(interiors[h][p], interiors[h][p], transform);
  28519. }
  28520. }
  28521. }
  28522. rect = this._rect;
  28523. rect.copy(target);
  28524. // Update center
  28525. this.center = [
  28526. rect.x + rect.width / 2,
  28527. rect.y + rect.height / 2
  28528. ];
  28529. }
  28530. };
  28531. /*
  28532. * Licensed to the Apache Software Foundation (ASF) under one
  28533. * or more contributor license agreements. See the NOTICE file
  28534. * distributed with this work for additional information
  28535. * regarding copyright ownership. The ASF licenses this file
  28536. * to you under the Apache License, Version 2.0 (the
  28537. * "License"); you may not use this file except in compliance
  28538. * with the License. You may obtain a copy of the License at
  28539. *
  28540. * http://www.apache.org/licenses/LICENSE-2.0
  28541. *
  28542. * Unless required by applicable law or agreed to in writing,
  28543. * software distributed under the License is distributed on an
  28544. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28545. * KIND, either express or implied. See the License for the
  28546. * specific language governing permissions and limitations
  28547. * under the License.
  28548. */
  28549. /**
  28550. * Parse and decode geo json
  28551. * @module echarts/coord/geo/parseGeoJson
  28552. */
  28553. function decode(json) {
  28554. if (!json.UTF8Encoding) {
  28555. return json;
  28556. }
  28557. var encodeScale = json.UTF8Scale;
  28558. if (encodeScale == null) {
  28559. encodeScale = 1024;
  28560. }
  28561. var features = json.features;
  28562. for (var f = 0; f < features.length; f++) {
  28563. var feature = features[f];
  28564. var geometry = feature.geometry;
  28565. var coordinates = geometry.coordinates;
  28566. var encodeOffsets = geometry.encodeOffsets;
  28567. for (var c = 0; c < coordinates.length; c++) {
  28568. var coordinate = coordinates[c];
  28569. if (geometry.type === 'Polygon') {
  28570. coordinates[c] = decodePolygon(
  28571. coordinate,
  28572. encodeOffsets[c],
  28573. encodeScale
  28574. );
  28575. }
  28576. else if (geometry.type === 'MultiPolygon') {
  28577. for (var c2 = 0; c2 < coordinate.length; c2++) {
  28578. var polygon = coordinate[c2];
  28579. coordinate[c2] = decodePolygon(
  28580. polygon,
  28581. encodeOffsets[c][c2],
  28582. encodeScale
  28583. );
  28584. }
  28585. }
  28586. }
  28587. }
  28588. // Has been decoded
  28589. json.UTF8Encoding = false;
  28590. return json;
  28591. }
  28592. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  28593. var result = [];
  28594. var prevX = encodeOffsets[0];
  28595. var prevY = encodeOffsets[1];
  28596. for (var i = 0; i < coordinate.length; i += 2) {
  28597. var x = coordinate.charCodeAt(i) - 64;
  28598. var y = coordinate.charCodeAt(i + 1) - 64;
  28599. // ZigZag decoding
  28600. x = (x >> 1) ^ (-(x & 1));
  28601. y = (y >> 1) ^ (-(y & 1));
  28602. // Delta deocding
  28603. x += prevX;
  28604. y += prevY;
  28605. prevX = x;
  28606. prevY = y;
  28607. // Dequantize
  28608. result.push([x / encodeScale, y / encodeScale]);
  28609. }
  28610. return result;
  28611. }
  28612. /**
  28613. * @alias module:echarts/coord/geo/parseGeoJson
  28614. * @param {Object} geoJson
  28615. * @return {module:zrender/container/Group}
  28616. */
  28617. var parseGeoJson$1 = function (geoJson) {
  28618. decode(geoJson);
  28619. return map(filter(geoJson.features, function (featureObj) {
  28620. // Output of mapshaper may have geometry null
  28621. return featureObj.geometry
  28622. && featureObj.properties
  28623. && featureObj.geometry.coordinates.length > 0;
  28624. }), function (featureObj) {
  28625. var properties = featureObj.properties;
  28626. var geo = featureObj.geometry;
  28627. var coordinates = geo.coordinates;
  28628. var geometries = [];
  28629. if (geo.type === 'Polygon') {
  28630. geometries.push({
  28631. type: 'polygon',
  28632. // According to the GeoJSON specification.
  28633. // First must be exterior, and the rest are all interior(holes).
  28634. exterior: coordinates[0],
  28635. interiors: coordinates.slice(1)
  28636. });
  28637. }
  28638. if (geo.type === 'MultiPolygon') {
  28639. each$1(coordinates, function (item) {
  28640. if (item[0]) {
  28641. geometries.push({
  28642. type: 'polygon',
  28643. exterior: item[0],
  28644. interiors: item.slice(1)
  28645. });
  28646. }
  28647. });
  28648. }
  28649. var region = new Region(
  28650. properties.name,
  28651. geometries,
  28652. properties.cp
  28653. );
  28654. region.properties = properties;
  28655. return region;
  28656. });
  28657. };
  28658. /*
  28659. * Licensed to the Apache Software Foundation (ASF) under one
  28660. * or more contributor license agreements. See the NOTICE file
  28661. * distributed with this work for additional information
  28662. * regarding copyright ownership. The ASF licenses this file
  28663. * to you under the Apache License, Version 2.0 (the
  28664. * "License"); you may not use this file except in compliance
  28665. * with the License. You may obtain a copy of the License at
  28666. *
  28667. * http://www.apache.org/licenses/LICENSE-2.0
  28668. *
  28669. * Unless required by applicable law or agreed to in writing,
  28670. * software distributed under the License is distributed on an
  28671. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28672. * KIND, either express or implied. See the License for the
  28673. * specific language governing permissions and limitations
  28674. * under the License.
  28675. */
  28676. var inner$6 = makeInner();
  28677. /**
  28678. * @param {module:echats/coord/Axis} axis
  28679. * @return {Object} {
  28680. * labels: [{
  28681. * formattedLabel: string,
  28682. * rawLabel: string,
  28683. * tickValue: number
  28684. * }, ...],
  28685. * labelCategoryInterval: number
  28686. * }
  28687. */
  28688. function createAxisLabels(axis) {
  28689. // Only ordinal scale support tick interval
  28690. return axis.type === 'category'
  28691. ? makeCategoryLabels(axis)
  28692. : makeRealNumberLabels(axis);
  28693. }
  28694. /**
  28695. * @param {module:echats/coord/Axis} axis
  28696. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  28697. * @return {Object} {
  28698. * ticks: Array.<number>
  28699. * tickCategoryInterval: number
  28700. * }
  28701. */
  28702. function createAxisTicks(axis, tickModel) {
  28703. // Only ordinal scale support tick interval
  28704. return axis.type === 'category'
  28705. ? makeCategoryTicks(axis, tickModel)
  28706. : {ticks: axis.scale.getTicks()};
  28707. }
  28708. function makeCategoryLabels(axis) {
  28709. var labelModel = axis.getLabelModel();
  28710. var result = makeCategoryLabelsActually(axis, labelModel);
  28711. return (!labelModel.get('show') || axis.scale.isBlank())
  28712. ? {labels: [], labelCategoryInterval: result.labelCategoryInterval}
  28713. : result;
  28714. }
  28715. function makeCategoryLabelsActually(axis, labelModel) {
  28716. var labelsCache = getListCache(axis, 'labels');
  28717. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  28718. var result = listCacheGet(labelsCache, optionLabelInterval);
  28719. if (result) {
  28720. return result;
  28721. }
  28722. var labels;
  28723. var numericLabelInterval;
  28724. if (isFunction$1(optionLabelInterval)) {
  28725. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  28726. }
  28727. else {
  28728. numericLabelInterval = optionLabelInterval === 'auto'
  28729. ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  28730. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  28731. }
  28732. // Cache to avoid calling interval function repeatly.
  28733. return listCacheSet(labelsCache, optionLabelInterval, {
  28734. labels: labels, labelCategoryInterval: numericLabelInterval
  28735. });
  28736. }
  28737. function makeCategoryTicks(axis, tickModel) {
  28738. var ticksCache = getListCache(axis, 'ticks');
  28739. var optionTickInterval = getOptionCategoryInterval(tickModel);
  28740. var result = listCacheGet(ticksCache, optionTickInterval);
  28741. if (result) {
  28742. return result;
  28743. }
  28744. var ticks;
  28745. var tickCategoryInterval;
  28746. // Optimize for the case that large category data and no label displayed,
  28747. // we should not return all ticks.
  28748. if (!tickModel.get('show') || axis.scale.isBlank()) {
  28749. ticks = [];
  28750. }
  28751. if (isFunction$1(optionTickInterval)) {
  28752. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  28753. }
  28754. // Always use label interval by default despite label show. Consider this
  28755. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  28756. // labels. `splitLine` and `axisTick` should be consistent in this case.
  28757. else if (optionTickInterval === 'auto') {
  28758. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  28759. tickCategoryInterval = labelsResult.labelCategoryInterval;
  28760. ticks = map(labelsResult.labels, function (labelItem) {
  28761. return labelItem.tickValue;
  28762. });
  28763. }
  28764. else {
  28765. tickCategoryInterval = optionTickInterval;
  28766. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  28767. }
  28768. // Cache to avoid calling interval function repeatly.
  28769. return listCacheSet(ticksCache, optionTickInterval, {
  28770. ticks: ticks, tickCategoryInterval: tickCategoryInterval
  28771. });
  28772. }
  28773. function makeRealNumberLabels(axis) {
  28774. var ticks = axis.scale.getTicks();
  28775. var labelFormatter = makeLabelFormatter(axis);
  28776. return {
  28777. labels: map(ticks, function (tickValue, idx) {
  28778. return {
  28779. formattedLabel: labelFormatter(tickValue, idx),
  28780. rawLabel: axis.scale.getLabel(tickValue),
  28781. tickValue: tickValue
  28782. };
  28783. })
  28784. };
  28785. }
  28786. // Large category data calculation is performence sensitive, and ticks and label
  28787. // probably be fetched by multiple times. So we cache the result.
  28788. // axis is created each time during a ec process, so we do not need to clear cache.
  28789. function getListCache(axis, prop) {
  28790. // Because key can be funciton, and cache size always be small, we use array cache.
  28791. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  28792. }
  28793. function listCacheGet(cache, key) {
  28794. for (var i = 0; i < cache.length; i++) {
  28795. if (cache[i].key === key) {
  28796. return cache[i].value;
  28797. }
  28798. }
  28799. }
  28800. function listCacheSet(cache, key, value) {
  28801. cache.push({key: key, value: value});
  28802. return value;
  28803. }
  28804. function makeAutoCategoryInterval(axis) {
  28805. var result = inner$6(axis).autoInterval;
  28806. return result != null
  28807. ? result
  28808. : (inner$6(axis).autoInterval = axis.calculateCategoryInterval());
  28809. }
  28810. /**
  28811. * Calculate interval for category axis ticks and labels.
  28812. * To get precise result, at least one of `getRotate` and `isHorizontal`
  28813. * should be implemented in axis.
  28814. */
  28815. function calculateCategoryInterval(axis) {
  28816. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  28817. var labelFormatter = makeLabelFormatter(axis);
  28818. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  28819. var ordinalScale = axis.scale;
  28820. var ordinalExtent = ordinalScale.getExtent();
  28821. // Providing this method is for optimization:
  28822. // avoid generating a long array by `getTicks`
  28823. // in large category data case.
  28824. var tickCount = ordinalScale.count();
  28825. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  28826. return 0;
  28827. }
  28828. var step = 1;
  28829. // Simple optimization. Empirical value: tick count should less than 40.
  28830. if (tickCount > 40) {
  28831. step = Math.max(1, Math.floor(tickCount / 40));
  28832. }
  28833. var tickValue = ordinalExtent[0];
  28834. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  28835. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  28836. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  28837. var maxW = 0;
  28838. var maxH = 0;
  28839. // Caution: Performance sensitive for large category data.
  28840. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  28841. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  28842. var width = 0;
  28843. var height = 0;
  28844. // Polar is also calculated in assumptive linear layout here.
  28845. // Not precise, do not consider align and vertical align
  28846. // and each distance from axis line yet.
  28847. var rect = getBoundingRect(
  28848. labelFormatter(tickValue), params.font, 'center', 'top'
  28849. );
  28850. // Magic number
  28851. width = rect.width * 1.3;
  28852. height = rect.height * 1.3;
  28853. // Min size, void long loop.
  28854. maxW = Math.max(maxW, width, 7);
  28855. maxH = Math.max(maxH, height, 7);
  28856. }
  28857. var dw = maxW / unitW;
  28858. var dh = maxH / unitH;
  28859. // 0/0 is NaN, 1/0 is Infinity.
  28860. isNaN(dw) && (dw = Infinity);
  28861. isNaN(dh) && (dh = Infinity);
  28862. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  28863. var cache = inner$6(axis.model);
  28864. var lastAutoInterval = cache.lastAutoInterval;
  28865. var lastTickCount = cache.lastTickCount;
  28866. // Use cache to keep interval stable while moving zoom window,
  28867. // otherwise the calculated interval might jitter when the zoom
  28868. // window size is close to the interval-changing size.
  28869. if (lastAutoInterval != null
  28870. && lastTickCount != null
  28871. && Math.abs(lastAutoInterval - interval) <= 1
  28872. && Math.abs(lastTickCount - tickCount) <= 1
  28873. // Always choose the bigger one, otherwise the critical
  28874. // point is not the same when zooming in or zooming out.
  28875. && lastAutoInterval > interval
  28876. ) {
  28877. interval = lastAutoInterval;
  28878. }
  28879. // Only update cache if cache not used, otherwise the
  28880. // changing of interval is too insensitive.
  28881. else {
  28882. cache.lastTickCount = tickCount;
  28883. cache.lastAutoInterval = interval;
  28884. }
  28885. return interval;
  28886. }
  28887. function fetchAutoCategoryIntervalCalculationParams(axis) {
  28888. var labelModel = axis.getLabelModel();
  28889. return {
  28890. axisRotate: axis.getRotate
  28891. ? axis.getRotate()
  28892. : (axis.isHorizontal && !axis.isHorizontal())
  28893. ? 90
  28894. : 0,
  28895. labelRotate: labelModel.get('rotate') || 0,
  28896. font: labelModel.getFont()
  28897. };
  28898. }
  28899. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  28900. var labelFormatter = makeLabelFormatter(axis);
  28901. var ordinalScale = axis.scale;
  28902. var ordinalExtent = ordinalScale.getExtent();
  28903. var labelModel = axis.getLabelModel();
  28904. var result = [];
  28905. // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  28906. var step = Math.max((categoryInterval || 0) + 1, 1);
  28907. var startTick = ordinalExtent[0];
  28908. var tickCount = ordinalScale.count();
  28909. // Calculate start tick based on zero if possible to keep label consistent
  28910. // while zooming and moving while interval > 0. Otherwise the selection
  28911. // of displayable ticks and symbols probably keep changing.
  28912. // 3 is empirical value.
  28913. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  28914. startTick = Math.round(Math.ceil(startTick / step) * step);
  28915. }
  28916. // (1) Only add min max label here but leave overlap checking
  28917. // to render stage, which also ensure the returned list
  28918. // suitable for splitLine and splitArea rendering.
  28919. // (2) Scales except category always contain min max label so
  28920. // do not need to perform this process.
  28921. var showMinMax = {
  28922. min: labelModel.get('showMinLabel'),
  28923. max: labelModel.get('showMaxLabel')
  28924. };
  28925. if (showMinMax.min && startTick !== ordinalExtent[0]) {
  28926. addItem(ordinalExtent[0]);
  28927. }
  28928. // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  28929. var tickValue = startTick;
  28930. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  28931. addItem(tickValue);
  28932. }
  28933. if (showMinMax.max && tickValue !== ordinalExtent[1]) {
  28934. addItem(ordinalExtent[1]);
  28935. }
  28936. function addItem(tVal) {
  28937. result.push(onlyTick
  28938. ? tVal
  28939. : {
  28940. formattedLabel: labelFormatter(tVal),
  28941. rawLabel: ordinalScale.getLabel(tVal),
  28942. tickValue: tVal
  28943. }
  28944. );
  28945. }
  28946. return result;
  28947. }
  28948. // When interval is function, the result `false` means ignore the tick.
  28949. // It is time consuming for large category data.
  28950. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  28951. var ordinalScale = axis.scale;
  28952. var labelFormatter = makeLabelFormatter(axis);
  28953. var result = [];
  28954. each$1(ordinalScale.getTicks(), function (tickValue) {
  28955. var rawLabel = ordinalScale.getLabel(tickValue);
  28956. if (categoryInterval(tickValue, rawLabel)) {
  28957. result.push(onlyTick
  28958. ? tickValue
  28959. : {
  28960. formattedLabel: labelFormatter(tickValue),
  28961. rawLabel: rawLabel,
  28962. tickValue: tickValue
  28963. }
  28964. );
  28965. }
  28966. });
  28967. return result;
  28968. }
  28969. // Can be null|'auto'|number|function
  28970. function getOptionCategoryInterval(model) {
  28971. var interval = model.get('interval');
  28972. return interval == null ? 'auto' : interval;
  28973. }
  28974. /*
  28975. * Licensed to the Apache Software Foundation (ASF) under one
  28976. * or more contributor license agreements. See the NOTICE file
  28977. * distributed with this work for additional information
  28978. * regarding copyright ownership. The ASF licenses this file
  28979. * to you under the Apache License, Version 2.0 (the
  28980. * "License"); you may not use this file except in compliance
  28981. * with the License. You may obtain a copy of the License at
  28982. *
  28983. * http://www.apache.org/licenses/LICENSE-2.0
  28984. *
  28985. * Unless required by applicable law or agreed to in writing,
  28986. * software distributed under the License is distributed on an
  28987. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28988. * KIND, either express or implied. See the License for the
  28989. * specific language governing permissions and limitations
  28990. * under the License.
  28991. */
  28992. var NORMALIZED_EXTENT = [0, 1];
  28993. /**
  28994. * Base class of Axis.
  28995. * @constructor
  28996. */
  28997. var Axis = function (dim, scale, extent) {
  28998. /**
  28999. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  29000. * @type {string}
  29001. */
  29002. this.dim = dim;
  29003. /**
  29004. * Axis scale
  29005. * @type {module:echarts/coord/scale/*}
  29006. */
  29007. this.scale = scale;
  29008. /**
  29009. * @type {Array.<number>}
  29010. * @private
  29011. */
  29012. this._extent = extent || [0, 0];
  29013. /**
  29014. * @type {boolean}
  29015. */
  29016. this.inverse = false;
  29017. /**
  29018. * Usually true when axis has a ordinal scale
  29019. * @type {boolean}
  29020. */
  29021. this.onBand = false;
  29022. };
  29023. Axis.prototype = {
  29024. constructor: Axis,
  29025. /**
  29026. * If axis extent contain given coord
  29027. * @param {number} coord
  29028. * @return {boolean}
  29029. */
  29030. contain: function (coord) {
  29031. var extent = this._extent;
  29032. var min = Math.min(extent[0], extent[1]);
  29033. var max = Math.max(extent[0], extent[1]);
  29034. return coord >= min && coord <= max;
  29035. },
  29036. /**
  29037. * If axis extent contain given data
  29038. * @param {number} data
  29039. * @return {boolean}
  29040. */
  29041. containData: function (data) {
  29042. return this.contain(this.dataToCoord(data));
  29043. },
  29044. /**
  29045. * Get coord extent.
  29046. * @return {Array.<number>}
  29047. */
  29048. getExtent: function () {
  29049. return this._extent.slice();
  29050. },
  29051. /**
  29052. * Get precision used for formatting
  29053. * @param {Array.<number>} [dataExtent]
  29054. * @return {number}
  29055. */
  29056. getPixelPrecision: function (dataExtent) {
  29057. return getPixelPrecision(
  29058. dataExtent || this.scale.getExtent(),
  29059. this._extent
  29060. );
  29061. },
  29062. /**
  29063. * Set coord extent
  29064. * @param {number} start
  29065. * @param {number} end
  29066. */
  29067. setExtent: function (start, end) {
  29068. var extent = this._extent;
  29069. extent[0] = start;
  29070. extent[1] = end;
  29071. },
  29072. /**
  29073. * Convert data to coord. Data is the rank if it has an ordinal scale
  29074. * @param {number} data
  29075. * @param {boolean} clamp
  29076. * @return {number}
  29077. */
  29078. dataToCoord: function (data, clamp) {
  29079. var extent = this._extent;
  29080. var scale = this.scale;
  29081. data = scale.normalize(data);
  29082. if (this.onBand && scale.type === 'ordinal') {
  29083. extent = extent.slice();
  29084. fixExtentWithBands(extent, scale.count());
  29085. }
  29086. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  29087. },
  29088. /**
  29089. * Convert coord to data. Data is the rank if it has an ordinal scale
  29090. * @param {number} coord
  29091. * @param {boolean} clamp
  29092. * @return {number}
  29093. */
  29094. coordToData: function (coord, clamp) {
  29095. var extent = this._extent;
  29096. var scale = this.scale;
  29097. if (this.onBand && scale.type === 'ordinal') {
  29098. extent = extent.slice();
  29099. fixExtentWithBands(extent, scale.count());
  29100. }
  29101. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  29102. return this.scale.scale(t);
  29103. },
  29104. /**
  29105. * Convert pixel point to data in axis
  29106. * @param {Array.<number>} point
  29107. * @param {boolean} clamp
  29108. * @return {number} data
  29109. */
  29110. pointToData: function (point, clamp) {
  29111. // Should be implemented in derived class if necessary.
  29112. },
  29113. /**
  29114. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  29115. * `axis.getTicksCoords` considers `onBand`, which is used by
  29116. * `boundaryGap:true` of category axis and splitLine and splitArea.
  29117. * @param {Object} [opt]
  29118. * @param {number} [opt.tickModel=axis.model.getModel('axisTick')]
  29119. * @param {boolean} [opt.clamp] If `true`, the first and the last
  29120. * tick must be at the axis end points. Otherwise, clip ticks
  29121. * that outside the axis extent.
  29122. * @return {Array.<Object>} [{
  29123. * coord: ...,
  29124. * tickValue: ...
  29125. * }, ...]
  29126. */
  29127. getTicksCoords: function (opt) {
  29128. opt = opt || {};
  29129. var tickModel = opt.tickModel || this.getTickModel();
  29130. var result = createAxisTicks(this, tickModel);
  29131. var ticks = result.ticks;
  29132. var ticksCoords = map(ticks, function (tickValue) {
  29133. return {
  29134. coord: this.dataToCoord(tickValue),
  29135. tickValue: tickValue
  29136. };
  29137. }, this);
  29138. var alignWithLabel = tickModel.get('alignWithLabel');
  29139. fixOnBandTicksCoords(
  29140. this, ticksCoords, result.tickCategoryInterval, alignWithLabel, opt.clamp
  29141. );
  29142. return ticksCoords;
  29143. },
  29144. /**
  29145. * @return {Array.<Object>} [{
  29146. * formattedLabel: string,
  29147. * rawLabel: axis.scale.getLabel(tickValue)
  29148. * tickValue: number
  29149. * }, ...]
  29150. */
  29151. getViewLabels: function () {
  29152. return createAxisLabels(this).labels;
  29153. },
  29154. /**
  29155. * @return {module:echarts/coord/model/Model}
  29156. */
  29157. getLabelModel: function () {
  29158. return this.model.getModel('axisLabel');
  29159. },
  29160. /**
  29161. * Notice here we only get the default tick model. For splitLine
  29162. * or splitArea, we should pass the splitLineModel or splitAreaModel
  29163. * manually when calling `getTicksCoords`.
  29164. * In GL, this method may be overrided to:
  29165. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  29166. * @return {module:echarts/coord/model/Model}
  29167. */
  29168. getTickModel: function () {
  29169. return this.model.getModel('axisTick');
  29170. },
  29171. /**
  29172. * Get width of band
  29173. * @return {number}
  29174. */
  29175. getBandWidth: function () {
  29176. var axisExtent = this._extent;
  29177. var dataExtent = this.scale.getExtent();
  29178. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0);
  29179. // Fix #2728, avoid NaN when only one data.
  29180. len === 0 && (len = 1);
  29181. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  29182. return Math.abs(size) / len;
  29183. },
  29184. /**
  29185. * @abstract
  29186. * @return {boolean} Is horizontal
  29187. */
  29188. isHorizontal: null,
  29189. /**
  29190. * @abstract
  29191. * @return {number} Get axis rotate, by degree.
  29192. */
  29193. getRotate: null,
  29194. /**
  29195. * Only be called in category axis.
  29196. * Can be overrided, consider other axes like in 3D.
  29197. * @return {number} Auto interval for cateogry axis tick and label
  29198. */
  29199. calculateCategoryInterval: function () {
  29200. return calculateCategoryInterval(this);
  29201. }
  29202. };
  29203. function fixExtentWithBands(extent, nTick) {
  29204. var size = extent[1] - extent[0];
  29205. var len = nTick;
  29206. var margin = size / len / 2;
  29207. extent[0] += margin;
  29208. extent[1] -= margin;
  29209. }
  29210. // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  29211. // |---1---|---2---|---3---|---4---|.
  29212. // So the displayed ticks and splitLine/splitArea should between
  29213. // each data item, otherwise cause misleading (e.g., split tow bars
  29214. // of a single data item when there are two bar series).
  29215. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  29216. // splitLine/spliteArea should layout appropriately corresponding
  29217. // to displayed labels. (So we should not use `getBandWidth` in this
  29218. // case).
  29219. function fixOnBandTicksCoords(axis, ticksCoords, tickCategoryInterval, alignWithLabel, clamp) {
  29220. var ticksLen = ticksCoords.length;
  29221. if (!axis.onBand || alignWithLabel || !ticksLen) {
  29222. return;
  29223. }
  29224. var axisExtent = axis.getExtent();
  29225. var last;
  29226. if (ticksLen === 1) {
  29227. ticksCoords[0].coord = axisExtent[0];
  29228. last = ticksCoords[1] = {coord: axisExtent[0]};
  29229. }
  29230. else {
  29231. var shift = (ticksCoords[1].coord - ticksCoords[0].coord);
  29232. each$1(ticksCoords, function (ticksItem) {
  29233. ticksItem.coord -= shift / 2;
  29234. var tickCategoryInterval = tickCategoryInterval || 0;
  29235. // Avoid split a single data item when odd interval.
  29236. if (tickCategoryInterval % 2 > 0) {
  29237. ticksItem.coord -= shift / ((tickCategoryInterval + 1) * 2);
  29238. }
  29239. });
  29240. last = {coord: ticksCoords[ticksLen - 1].coord + shift};
  29241. ticksCoords.push(last);
  29242. }
  29243. var inverse = axisExtent[0] > axisExtent[1];
  29244. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  29245. clamp ? (ticksCoords[0].coord = axisExtent[0]) : ticksCoords.shift();
  29246. }
  29247. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  29248. ticksCoords.unshift({coord: axisExtent[0]});
  29249. }
  29250. if (littleThan(axisExtent[1], last.coord)) {
  29251. clamp ? (last.coord = axisExtent[1]) : ticksCoords.pop();
  29252. }
  29253. if (clamp && littleThan(last.coord, axisExtent[1])) {
  29254. ticksCoords.push({coord: axisExtent[1]});
  29255. }
  29256. function littleThan(a, b) {
  29257. return inverse ? a > b : a < b;
  29258. }
  29259. }
  29260. /*
  29261. * Licensed to the Apache Software Foundation (ASF) under one
  29262. * or more contributor license agreements. See the NOTICE file
  29263. * distributed with this work for additional information
  29264. * regarding copyright ownership. The ASF licenses this file
  29265. * to you under the Apache License, Version 2.0 (the
  29266. * "License"); you may not use this file except in compliance
  29267. * with the License. You may obtain a copy of the License at
  29268. *
  29269. * http://www.apache.org/licenses/LICENSE-2.0
  29270. *
  29271. * Unless required by applicable law or agreed to in writing,
  29272. * software distributed under the License is distributed on an
  29273. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29274. * KIND, either express or implied. See the License for the
  29275. * specific language governing permissions and limitations
  29276. * under the License.
  29277. */
  29278. /**
  29279. * Do not mount those modules on 'src/echarts' for better tree shaking.
  29280. */
  29281. var parseGeoJson = parseGeoJson$1;
  29282. var ecUtil = {};
  29283. each$1([
  29284. 'map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter',
  29285. 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction',
  29286. 'extend', 'defaults', 'clone', 'merge'
  29287. ],
  29288. function (name) {
  29289. ecUtil[name] = zrUtil[name];
  29290. }
  29291. );
  29292. /*
  29293. * Licensed to the Apache Software Foundation (ASF) under one
  29294. * or more contributor license agreements. See the NOTICE file
  29295. * distributed with this work for additional information
  29296. * regarding copyright ownership. The ASF licenses this file
  29297. * to you under the Apache License, Version 2.0 (the
  29298. * "License"); you may not use this file except in compliance
  29299. * with the License. You may obtain a copy of the License at
  29300. *
  29301. * http://www.apache.org/licenses/LICENSE-2.0
  29302. *
  29303. * Unless required by applicable law or agreed to in writing,
  29304. * software distributed under the License is distributed on an
  29305. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29306. * KIND, either express or implied. See the License for the
  29307. * specific language governing permissions and limitations
  29308. * under the License.
  29309. */
  29310. SeriesModel.extend({
  29311. type: 'series.line',
  29312. dependencies: ['grid', 'polar'],
  29313. getInitialData: function (option, ecModel) {
  29314. if (__DEV__) {
  29315. var coordSys = option.coordinateSystem;
  29316. if (coordSys !== 'polar' && coordSys !== 'cartesian2d') {
  29317. throw new Error('Line not support coordinateSystem besides cartesian and polar');
  29318. }
  29319. }
  29320. return createListFromArray(this.getSource(), this);
  29321. },
  29322. defaultOption: {
  29323. zlevel: 0,
  29324. z: 2,
  29325. coordinateSystem: 'cartesian2d',
  29326. legendHoverLink: true,
  29327. hoverAnimation: true,
  29328. // stack: null
  29329. // xAxisIndex: 0,
  29330. // yAxisIndex: 0,
  29331. // polarIndex: 0,
  29332. // If clip the overflow value
  29333. clipOverflow: true,
  29334. // cursor: null,
  29335. /*label: {
  29336. position: 'top'
  29337. },*/
  29338. label: {
  29339. position: 'top',
  29340. show:true,
  29341. formatter:'{c}'
  29342. },
  29343. // itemStyle: {
  29344. // },
  29345. lineStyle: {
  29346. width: 2,
  29347. type: 'solid'
  29348. },
  29349. // areaStyle: {
  29350. // origin of areaStyle. Valid values:
  29351. // `'auto'/null/undefined`: from axisLine to data
  29352. // `'start'`: from min to data
  29353. // `'end'`: from data to max
  29354. // origin: 'auto'
  29355. // },
  29356. // false, 'start', 'end', 'middle'
  29357. step: false,
  29358. // Disabled if step is true
  29359. smooth: false,
  29360. smoothMonotone: null,
  29361. symbol: 'emptyCircle',
  29362. symbolSize: 4,
  29363. symbolRotate: null,
  29364. showSymbol: true,
  29365. // `false`: follow the label interval strategy.
  29366. // `true`: show all symbols.
  29367. // `'auto'`: If possible, show all symbols, otherwise
  29368. // follow the label interval strategy.
  29369. showAllSymbol: 'auto',
  29370. // Whether to connect break point.
  29371. connectNulls: false,
  29372. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  29373. sampling: 'none',
  29374. animationEasing: 'linear',
  29375. // Disable progressive
  29376. progressive: 0,
  29377. hoverLayerThreshold: Infinity
  29378. }
  29379. });
  29380. /*
  29381. * Licensed to the Apache Software Foundation (ASF) under one
  29382. * or more contributor license agreements. See the NOTICE file
  29383. * distributed with this work for additional information
  29384. * regarding copyright ownership. The ASF licenses this file
  29385. * to you under the Apache License, Version 2.0 (the
  29386. * "License"); you may not use this file except in compliance
  29387. * with the License. You may obtain a copy of the License at
  29388. *
  29389. * http://www.apache.org/licenses/LICENSE-2.0
  29390. *
  29391. * Unless required by applicable law or agreed to in writing,
  29392. * software distributed under the License is distributed on an
  29393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29394. * KIND, either express or implied. See the License for the
  29395. * specific language governing permissions and limitations
  29396. * under the License.
  29397. */
  29398. /**
  29399. * @param {module:echarts/data/List} data
  29400. * @param {number} dataIndex
  29401. * @return {string} label string. Not null/undefined
  29402. */
  29403. function getDefaultLabel(data, dataIndex) {
  29404. var labelDims = data.mapDimension('defaultedLabel', true);
  29405. var len = labelDims.length;
  29406. // Simple optimization (in lots of cases, label dims length is 1)
  29407. if (len === 1) {
  29408. return retrieveRawValue(data, dataIndex, labelDims[0]);
  29409. }
  29410. else if (len) {
  29411. var vals = [];
  29412. for (var i = 0; i < labelDims.length; i++) {
  29413. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  29414. vals.push(val);
  29415. }
  29416. return vals.join(' ');
  29417. }
  29418. }
  29419. /*
  29420. * Licensed to the Apache Software Foundation (ASF) under one
  29421. * or more contributor license agreements. See the NOTICE file
  29422. * distributed with this work for additional information
  29423. * regarding copyright ownership. The ASF licenses this file
  29424. * to you under the Apache License, Version 2.0 (the
  29425. * "License"); you may not use this file except in compliance
  29426. * with the License. You may obtain a copy of the License at
  29427. *
  29428. * http://www.apache.org/licenses/LICENSE-2.0
  29429. *
  29430. * Unless required by applicable law or agreed to in writing,
  29431. * software distributed under the License is distributed on an
  29432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29433. * KIND, either express or implied. See the License for the
  29434. * specific language governing permissions and limitations
  29435. * under the License.
  29436. */
  29437. /**
  29438. * @module echarts/chart/helper/Symbol
  29439. */
  29440. /**
  29441. * @constructor
  29442. * @alias {module:echarts/chart/helper/Symbol}
  29443. * @param {module:echarts/data/List} data
  29444. * @param {number} idx
  29445. * @extends {module:zrender/graphic/Group}
  29446. */
  29447. function SymbolClz$1(data, idx, seriesScope) {
  29448. Group.call(this);
  29449. this.updateData(data, idx, seriesScope);
  29450. }
  29451. var symbolProto = SymbolClz$1.prototype;
  29452. /**
  29453. * @public
  29454. * @static
  29455. * @param {module:echarts/data/List} data
  29456. * @param {number} dataIndex
  29457. * @return {Array.<number>} [width, height]
  29458. */
  29459. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  29460. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  29461. return symbolSize instanceof Array
  29462. ? symbolSize.slice()
  29463. : [+symbolSize, +symbolSize];
  29464. };
  29465. function getScale(symbolSize) {
  29466. return [symbolSize[0] / 2, symbolSize[1] / 2];
  29467. }
  29468. function driftSymbol(dx, dy) {
  29469. this.parent.drift(dx, dy);
  29470. }
  29471. symbolProto._createSymbol = function (
  29472. symbolType,
  29473. data,
  29474. idx,
  29475. symbolSize,
  29476. keepAspect
  29477. ) {
  29478. // Remove paths created before
  29479. this.removeAll();
  29480. var color = data.getItemVisual(idx, 'color');
  29481. // var symbolPath = createSymbol(
  29482. // symbolType, -0.5, -0.5, 1, 1, color
  29483. // );
  29484. // If width/height are set too small (e.g., set to 1) on ios10
  29485. // and macOS Sierra, a circle stroke become a rect, no matter what
  29486. // the scale is set. So we set width/height as 2. See #4150.
  29487. var symbolPath = createSymbol(
  29488. symbolType, -1, -1, 2, 2, color, keepAspect
  29489. );
  29490. symbolPath.attr({
  29491. z2: 100,
  29492. culling: true,
  29493. scale: getScale(symbolSize)
  29494. });
  29495. // Rewrite drift method
  29496. symbolPath.drift = driftSymbol;
  29497. this._symbolType = symbolType;
  29498. this.add(symbolPath);
  29499. };
  29500. /**
  29501. * Stop animation
  29502. * @param {boolean} toLastFrame
  29503. */
  29504. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  29505. this.childAt(0).stopAnimation(toLastFrame);
  29506. };
  29507. /**
  29508. * FIXME:
  29509. * Caution: This method breaks the encapsulation of this module,
  29510. * but it indeed brings convenience. So do not use the method
  29511. * unless you detailedly know all the implements of `Symbol`,
  29512. * especially animation.
  29513. *
  29514. * Get symbol path element.
  29515. */
  29516. symbolProto.getSymbolPath = function () {
  29517. return this.childAt(0);
  29518. };
  29519. /**
  29520. * Get scale(aka, current symbol size).
  29521. * Including the change caused by animation
  29522. */
  29523. symbolProto.getScale = function () {
  29524. return this.childAt(0).scale;
  29525. };
  29526. /**
  29527. * Highlight symbol
  29528. */
  29529. symbolProto.highlight = function () {
  29530. this.childAt(0).trigger('emphasis');
  29531. };
  29532. /**
  29533. * Downplay symbol
  29534. */
  29535. symbolProto.downplay = function () {
  29536. this.childAt(0).trigger('normal');
  29537. };
  29538. /**
  29539. * @param {number} zlevel
  29540. * @param {number} z
  29541. */
  29542. symbolProto.setZ = function (zlevel, z) {
  29543. var symbolPath = this.childAt(0);
  29544. symbolPath.zlevel = zlevel;
  29545. symbolPath.z = z;
  29546. };
  29547. symbolProto.setDraggable = function (draggable) {
  29548. var symbolPath = this.childAt(0);
  29549. symbolPath.draggable = draggable;
  29550. symbolPath.cursor = draggable ? 'move' : 'pointer';
  29551. };
  29552. /**
  29553. * Update symbol properties
  29554. * @param {module:echarts/data/List} data
  29555. * @param {number} idx
  29556. * @param {Object} [seriesScope]
  29557. * @param {Object} [seriesScope.itemStyle]
  29558. * @param {Object} [seriesScope.hoverItemStyle]
  29559. * @param {Object} [seriesScope.symbolRotate]
  29560. * @param {Object} [seriesScope.symbolOffset]
  29561. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  29562. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  29563. * @param {boolean} [seriesScope.hoverAnimation]
  29564. * @param {Object} [seriesScope.cursorStyle]
  29565. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  29566. * @param {string} [seriesScope.symbolInnerColor]
  29567. * @param {Object} [seriesScope.fadeIn=false]
  29568. */
  29569. symbolProto.updateData = function (data, idx, seriesScope) {
  29570. this.silent = false;
  29571. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  29572. var seriesModel = data.hostModel;
  29573. var symbolSize = getSymbolSize(data, idx);
  29574. var isInit = symbolType !== this._symbolType;
  29575. if (isInit) {
  29576. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  29577. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  29578. }
  29579. else {
  29580. var symbolPath = this.childAt(0);
  29581. symbolPath.silent = false;
  29582. updateProps(symbolPath, {
  29583. scale: getScale(symbolSize)
  29584. }, seriesModel, idx);
  29585. }
  29586. this._updateCommon(data, idx, symbolSize, seriesScope);
  29587. if (isInit) {
  29588. var symbolPath = this.childAt(0);
  29589. var fadeIn = seriesScope && seriesScope.fadeIn;
  29590. var target = {scale: symbolPath.scale.slice()};
  29591. fadeIn && (target.style = {opacity: symbolPath.style.opacity});
  29592. symbolPath.scale = [0, 0];
  29593. fadeIn && (symbolPath.style.opacity = 0);
  29594. initProps(symbolPath, target, seriesModel, idx);
  29595. }
  29596. this._seriesModel = seriesModel;
  29597. };
  29598. // Update common properties
  29599. var normalStyleAccessPath = ['itemStyle'];
  29600. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  29601. var normalLabelAccessPath = ['label'];
  29602. var emphasisLabelAccessPath = ['emphasis', 'label'];
  29603. /**
  29604. * @param {module:echarts/data/List} data
  29605. * @param {number} idx
  29606. * @param {Array.<number>} symbolSize
  29607. * @param {Object} [seriesScope]
  29608. */
  29609. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  29610. var symbolPath = this.childAt(0);
  29611. var seriesModel = data.hostModel;
  29612. var color = data.getItemVisual(idx, 'color');
  29613. // Reset style
  29614. if (symbolPath.type !== 'image') {
  29615. symbolPath.useStyle({
  29616. strokeNoScale: true
  29617. });
  29618. }
  29619. var itemStyle = seriesScope && seriesScope.itemStyle;
  29620. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  29621. var symbolRotate = seriesScope && seriesScope.symbolRotate;
  29622. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  29623. var labelModel = seriesScope && seriesScope.labelModel;
  29624. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  29625. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  29626. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  29627. if (!seriesScope || data.hasItemOption) {
  29628. var itemModel = (seriesScope && seriesScope.itemModel)
  29629. ? seriesScope.itemModel : data.getItemModel(idx);
  29630. // Color must be excluded.
  29631. // Because symbol provide setColor individually to set fill and stroke
  29632. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  29633. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  29634. symbolRotate = itemModel.getShallow('symbolRotate');
  29635. symbolOffset = itemModel.getShallow('symbolOffset');
  29636. labelModel = itemModel.getModel(normalLabelAccessPath);
  29637. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  29638. hoverAnimation = itemModel.getShallow('hoverAnimation');
  29639. cursorStyle = itemModel.getShallow('cursor');
  29640. }
  29641. else {
  29642. hoverItemStyle = extend({}, hoverItemStyle);
  29643. }
  29644. var elStyle = symbolPath.style;
  29645. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  29646. if (symbolOffset) {
  29647. symbolPath.attr('position', [
  29648. parsePercent$1(symbolOffset[0], symbolSize[0]),
  29649. parsePercent$1(symbolOffset[1], symbolSize[1])
  29650. ]);
  29651. }
  29652. cursorStyle && symbolPath.attr('cursor', cursorStyle);
  29653. // PENDING setColor before setStyle!!!
  29654. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  29655. symbolPath.setStyle(itemStyle);
  29656. var opacity = data.getItemVisual(idx, 'opacity');
  29657. if (opacity != null) {
  29658. elStyle.opacity = opacity;
  29659. }
  29660. var liftZ = data.getItemVisual(idx, 'liftZ');
  29661. var z2Origin = symbolPath.__z2Origin;
  29662. if (liftZ != null) {
  29663. if (z2Origin == null) {
  29664. symbolPath.__z2Origin = symbolPath.z2;
  29665. symbolPath.z2 += liftZ;
  29666. }
  29667. }
  29668. else if (z2Origin != null) {
  29669. symbolPath.z2 = z2Origin;
  29670. symbolPath.__z2Origin = null;
  29671. }
  29672. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  29673. setLabelStyle(
  29674. elStyle, hoverItemStyle, labelModel, hoverLabelModel,
  29675. {
  29676. labelFetcher: seriesModel,
  29677. labelDataIndex: idx,
  29678. defaultText: getLabelDefaultText,
  29679. isRectText: true,
  29680. autoColor: color
  29681. }
  29682. );
  29683. // Do not execute util needed.
  29684. function getLabelDefaultText(idx, opt) {
  29685. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  29686. }
  29687. symbolPath.off('mouseover')
  29688. .off('mouseout')
  29689. .off('emphasis')
  29690. .off('normal');
  29691. symbolPath.hoverStyle = hoverItemStyle;
  29692. // FIXME
  29693. // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead.
  29694. setHoverStyle(symbolPath);
  29695. var scale = getScale(symbolSize);
  29696. if (hoverAnimation && seriesModel.isAnimationEnabled()) {
  29697. var onEmphasis = function() {
  29698. // Do not support this hover animation util some scenario required.
  29699. // Animation can only be supported in hover layer when using `el.incremetal`.
  29700. if (this.incremental) {
  29701. return;
  29702. }
  29703. var ratio = scale[1] / scale[0];
  29704. this.animateTo({
  29705. scale: [
  29706. Math.max(scale[0] * 1.1, scale[0] + 3),
  29707. Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)
  29708. ]
  29709. }, 400, 'elasticOut');
  29710. };
  29711. var onNormal = function() {
  29712. if (this.incremental) {
  29713. return;
  29714. }
  29715. this.animateTo({
  29716. scale: scale
  29717. }, 400, 'elasticOut');
  29718. };
  29719. symbolPath.on('mouseover', onEmphasis)
  29720. .on('mouseout', onNormal)
  29721. .on('emphasis', onEmphasis)
  29722. .on('normal', onNormal);
  29723. }
  29724. };
  29725. /**
  29726. * @param {Function} cb
  29727. * @param {Object} [opt]
  29728. * @param {Object} [opt.keepLabel=true]
  29729. */
  29730. symbolProto.fadeOut = function (cb, opt) {
  29731. var symbolPath = this.childAt(0);
  29732. // Avoid mistaken hover when fading out
  29733. this.silent = symbolPath.silent = true;
  29734. // Not show text when animating
  29735. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  29736. updateProps(
  29737. symbolPath,
  29738. {
  29739. style: {opacity: 0},
  29740. scale: [0, 0]
  29741. },
  29742. this._seriesModel,
  29743. this.dataIndex,
  29744. cb
  29745. );
  29746. };
  29747. inherits(SymbolClz$1, Group);
  29748. /*
  29749. * Licensed to the Apache Software Foundation (ASF) under one
  29750. * or more contributor license agreements. See the NOTICE file
  29751. * distributed with this work for additional information
  29752. * regarding copyright ownership. The ASF licenses this file
  29753. * to you under the Apache License, Version 2.0 (the
  29754. * "License"); you may not use this file except in compliance
  29755. * with the License. You may obtain a copy of the License at
  29756. *
  29757. * http://www.apache.org/licenses/LICENSE-2.0
  29758. *
  29759. * Unless required by applicable law or agreed to in writing,
  29760. * software distributed under the License is distributed on an
  29761. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29762. * KIND, either express or implied. See the License for the
  29763. * specific language governing permissions and limitations
  29764. * under the License.
  29765. */
  29766. /**
  29767. * @module echarts/chart/helper/SymbolDraw
  29768. */
  29769. /**
  29770. * @constructor
  29771. * @alias module:echarts/chart/helper/SymbolDraw
  29772. * @param {module:zrender/graphic/Group} [symbolCtor]
  29773. */
  29774. function SymbolDraw(symbolCtor) {
  29775. this.group = new Group();
  29776. this._symbolCtor = symbolCtor || SymbolClz$1;
  29777. }
  29778. var symbolDrawProto = SymbolDraw.prototype;
  29779. function symbolNeedsDraw(data, point, idx, opt) {
  29780. return point && !isNaN(point[0]) && !isNaN(point[1])
  29781. && !(opt.isIgnore && opt.isIgnore(idx))
  29782. // We do not set clipShape on group, because it will cut part of
  29783. // the symbol element shape. We use the same clip shape here as
  29784. // the line clip.
  29785. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1]))
  29786. && data.getItemVisual(idx, 'symbol') !== 'none';
  29787. }
  29788. /**
  29789. * Update symbols draw by new data
  29790. * @param {module:echarts/data/List} data
  29791. * @param {Object} [opt] Or isIgnore
  29792. * @param {Function} [opt.isIgnore]
  29793. * @param {Object} [opt.clipShape]
  29794. */
  29795. symbolDrawProto.updateData = function (data, opt) {
  29796. opt = normalizeUpdateOpt(opt);
  29797. var group = this.group;
  29798. var seriesModel = data.hostModel;
  29799. var oldData = this._data;
  29800. var SymbolCtor = this._symbolCtor;
  29801. var seriesScope = makeSeriesScope(data);
  29802. // There is no oldLineData only when first rendering or switching from
  29803. // stream mode to normal mode, where previous elements should be removed.
  29804. if (!oldData) {
  29805. group.removeAll();
  29806. }
  29807. data.diff(oldData)
  29808. .add(function (newIdx) {
  29809. var point = data.getItemLayout(newIdx);
  29810. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  29811. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  29812. symbolEl.attr('position', point);
  29813. data.setItemGraphicEl(newIdx, symbolEl);
  29814. group.add(symbolEl);
  29815. }
  29816. })
  29817. .update(function (newIdx, oldIdx) {
  29818. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  29819. var point = data.getItemLayout(newIdx);
  29820. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  29821. group.remove(symbolEl);
  29822. return;
  29823. }
  29824. if (!symbolEl) {
  29825. symbolEl = new SymbolCtor(data, newIdx);
  29826. symbolEl.attr('position', point);
  29827. }
  29828. else {
  29829. symbolEl.updateData(data, newIdx, seriesScope);
  29830. updateProps(symbolEl, {
  29831. position: point
  29832. }, seriesModel);
  29833. }
  29834. // Add back
  29835. group.add(symbolEl);
  29836. data.setItemGraphicEl(newIdx, symbolEl);
  29837. })
  29838. .remove(function (oldIdx) {
  29839. var el = oldData.getItemGraphicEl(oldIdx);
  29840. el && el.fadeOut(function () {
  29841. group.remove(el);
  29842. });
  29843. })
  29844. .execute();
  29845. this._data = data;
  29846. };
  29847. symbolDrawProto.isPersistent = function () {
  29848. return true;
  29849. };
  29850. symbolDrawProto.updateLayout = function () {
  29851. var data = this._data;
  29852. if (data) {
  29853. // Not use animation
  29854. data.eachItemGraphicEl(function (el, idx) {
  29855. var point = data.getItemLayout(idx);
  29856. el.attr('position', point);
  29857. });
  29858. }
  29859. };
  29860. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  29861. this._seriesScope = makeSeriesScope(data);
  29862. this._data = null;
  29863. this.group.removeAll();
  29864. };
  29865. /**
  29866. * Update symbols draw by new data
  29867. * @param {module:echarts/data/List} data
  29868. * @param {Object} [opt] Or isIgnore
  29869. * @param {Function} [opt.isIgnore]
  29870. * @param {Object} [opt.clipShape]
  29871. */
  29872. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  29873. opt = normalizeUpdateOpt(opt);
  29874. function updateIncrementalAndHover(el) {
  29875. if (!el.isGroup) {
  29876. el.incremental = el.useHoverLayer = true;
  29877. }
  29878. }
  29879. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  29880. var point = data.getItemLayout(idx);
  29881. if (symbolNeedsDraw(data, point, idx, opt)) {
  29882. var el = new this._symbolCtor(data, idx, this._seriesScope);
  29883. el.traverse(updateIncrementalAndHover);
  29884. el.attr('position', point);
  29885. this.group.add(el);
  29886. data.setItemGraphicEl(idx, el);
  29887. }
  29888. }
  29889. };
  29890. function normalizeUpdateOpt(opt) {
  29891. if (opt != null && !isObject$1(opt)) {
  29892. opt = {isIgnore: opt};
  29893. }
  29894. return opt || {};
  29895. }
  29896. symbolDrawProto.remove = function (enableAnimation) {
  29897. var group = this.group;
  29898. var data = this._data;
  29899. // Incremental model do not have this._data.
  29900. if (data && enableAnimation) {
  29901. data.eachItemGraphicEl(function (el) {
  29902. el.fadeOut(function () {
  29903. group.remove(el);
  29904. });
  29905. });
  29906. }
  29907. else {
  29908. group.removeAll();
  29909. }
  29910. };
  29911. function makeSeriesScope(data) {
  29912. var seriesModel = data.hostModel;
  29913. return {
  29914. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  29915. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  29916. symbolRotate: seriesModel.get('symbolRotate'),
  29917. symbolOffset: seriesModel.get('symbolOffset'),
  29918. hoverAnimation: seriesModel.get('hoverAnimation'),
  29919. labelModel: seriesModel.getModel('label'),
  29920. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  29921. cursorStyle: seriesModel.get('cursor')
  29922. };
  29923. }
  29924. /*
  29925. * Licensed to the Apache Software Foundation (ASF) under one
  29926. * or more contributor license agreements. See the NOTICE file
  29927. * distributed with this work for additional information
  29928. * regarding copyright ownership. The ASF licenses this file
  29929. * to you under the Apache License, Version 2.0 (the
  29930. * "License"); you may not use this file except in compliance
  29931. * with the License. You may obtain a copy of the License at
  29932. *
  29933. * http://www.apache.org/licenses/LICENSE-2.0
  29934. *
  29935. * Unless required by applicable law or agreed to in writing,
  29936. * software distributed under the License is distributed on an
  29937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29938. * KIND, either express or implied. See the License for the
  29939. * specific language governing permissions and limitations
  29940. * under the License.
  29941. */
  29942. /**
  29943. * @param {Object} coordSys
  29944. * @param {module:echarts/data/List} data
  29945. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  29946. */
  29947. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  29948. var baseAxis = coordSys.getBaseAxis();
  29949. var valueAxis = coordSys.getOtherAxis(baseAxis);
  29950. var valueStart = getValueStart(valueAxis, valueOrigin);
  29951. var baseAxisDim = baseAxis.dim;
  29952. var valueAxisDim = valueAxis.dim;
  29953. var valueDim = data.mapDimension(valueAxisDim);
  29954. var baseDim = data.mapDimension(baseAxisDim);
  29955. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  29956. var dims = map(coordSys.dimensions, function (coordDim) {
  29957. return data.mapDimension(coordDim);
  29958. });
  29959. var stacked;
  29960. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  29961. if (stacked |= isDimensionStacked(data, dims[0] /*, dims[1]*/)) { // jshint ignore:line
  29962. dims[0] = stackResultDim;
  29963. }
  29964. if (stacked |= isDimensionStacked(data, dims[1] /*, dims[0]*/)) { // jshint ignore:line
  29965. dims[1] = stackResultDim;
  29966. }
  29967. return {
  29968. dataDimsForPoint: dims,
  29969. valueStart: valueStart,
  29970. valueAxisDim: valueAxisDim,
  29971. baseAxisDim: baseAxisDim,
  29972. stacked: !!stacked,
  29973. valueDim: valueDim,
  29974. baseDim: baseDim,
  29975. baseDataOffset: baseDataOffset,
  29976. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  29977. };
  29978. }
  29979. function getValueStart(valueAxis, valueOrigin) {
  29980. var valueStart = 0;
  29981. var extent = valueAxis.scale.getExtent();
  29982. if (valueOrigin === 'start') {
  29983. valueStart = extent[0];
  29984. }
  29985. else if (valueOrigin === 'end') {
  29986. valueStart = extent[1];
  29987. }
  29988. // auto
  29989. else {
  29990. // Both positive
  29991. if (extent[0] > 0) {
  29992. valueStart = extent[0];
  29993. }
  29994. // Both negative
  29995. else if (extent[1] < 0) {
  29996. valueStart = extent[1];
  29997. }
  29998. // If is one positive, and one negative, onZero shall be true
  29999. }
  30000. return valueStart;
  30001. }
  30002. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  30003. var value = NaN;
  30004. if (dataCoordInfo.stacked) {
  30005. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  30006. }
  30007. if (isNaN(value)) {
  30008. value = dataCoordInfo.valueStart;
  30009. }
  30010. var baseDataOffset = dataCoordInfo.baseDataOffset;
  30011. var stackedData = [];
  30012. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  30013. stackedData[1 - baseDataOffset] = value;
  30014. return coordSys.dataToPoint(stackedData);
  30015. }
  30016. /*
  30017. * Licensed to the Apache Software Foundation (ASF) under one
  30018. * or more contributor license agreements. See the NOTICE file
  30019. * distributed with this work for additional information
  30020. * regarding copyright ownership. The ASF licenses this file
  30021. * to you under the Apache License, Version 2.0 (the
  30022. * "License"); you may not use this file except in compliance
  30023. * with the License. You may obtain a copy of the License at
  30024. *
  30025. * http://www.apache.org/licenses/LICENSE-2.0
  30026. *
  30027. * Unless required by applicable law or agreed to in writing,
  30028. * software distributed under the License is distributed on an
  30029. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30030. * KIND, either express or implied. See the License for the
  30031. * specific language governing permissions and limitations
  30032. * under the License.
  30033. */
  30034. // var arrayDiff = require('zrender/src/core/arrayDiff');
  30035. // 'zrender/src/core/arrayDiff' has been used before, but it did
  30036. // not do well in performance when roam with fixed dataZoom window.
  30037. // function convertToIntId(newIdList, oldIdList) {
  30038. // // Generate int id instead of string id.
  30039. // // Compare string maybe slow in score function of arrDiff
  30040. // // Assume id in idList are all unique
  30041. // var idIndicesMap = {};
  30042. // var idx = 0;
  30043. // for (var i = 0; i < newIdList.length; i++) {
  30044. // idIndicesMap[newIdList[i]] = idx;
  30045. // newIdList[i] = idx++;
  30046. // }
  30047. // for (var i = 0; i < oldIdList.length; i++) {
  30048. // var oldId = oldIdList[i];
  30049. // // Same with newIdList
  30050. // if (idIndicesMap[oldId]) {
  30051. // oldIdList[i] = idIndicesMap[oldId];
  30052. // }
  30053. // else {
  30054. // oldIdList[i] = idx++;
  30055. // }
  30056. // }
  30057. // }
  30058. function diffData(oldData, newData) {
  30059. var diffResult = [];
  30060. newData.diff(oldData)
  30061. .add(function (idx) {
  30062. diffResult.push({cmd: '+', idx: idx});
  30063. })
  30064. .update(function (newIdx, oldIdx) {
  30065. diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx});
  30066. })
  30067. .remove(function (idx) {
  30068. diffResult.push({cmd: '-', idx: idx});
  30069. })
  30070. .execute();
  30071. return diffResult;
  30072. }
  30073. var lineAnimationDiff = function (
  30074. oldData, newData,
  30075. oldStackedOnPoints, newStackedOnPoints,
  30076. oldCoordSys, newCoordSys,
  30077. oldValueOrigin, newValueOrigin
  30078. ) {
  30079. var diff = diffData(oldData, newData);
  30080. // var newIdList = newData.mapArray(newData.getId);
  30081. // var oldIdList = oldData.mapArray(oldData.getId);
  30082. // convertToIntId(newIdList, oldIdList);
  30083. // // FIXME One data ?
  30084. // diff = arrayDiff(oldIdList, newIdList);
  30085. var currPoints = [];
  30086. var nextPoints = [];
  30087. // Points for stacking base line
  30088. var currStackedPoints = [];
  30089. var nextStackedPoints = [];
  30090. var status = [];
  30091. var sortedIndices = [];
  30092. var rawIndices = [];
  30093. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  30094. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  30095. for (var i = 0; i < diff.length; i++) {
  30096. var diffItem = diff[i];
  30097. var pointAdded = true;
  30098. // FIXME, animation is not so perfect when dataZoom window moves fast
  30099. // Which is in case remvoing or add more than one data in the tail or head
  30100. switch (diffItem.cmd) {
  30101. case '=':
  30102. var currentPt = oldData.getItemLayout(diffItem.idx);
  30103. var nextPt = newData.getItemLayout(diffItem.idx1);
  30104. // If previous data is NaN, use next point directly
  30105. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  30106. currentPt = nextPt.slice();
  30107. }
  30108. currPoints.push(currentPt);
  30109. nextPoints.push(nextPt);
  30110. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  30111. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  30112. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  30113. break;
  30114. case '+':
  30115. var idx = diffItem.idx;
  30116. currPoints.push(
  30117. oldCoordSys.dataToPoint([
  30118. newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx),
  30119. newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)
  30120. ])
  30121. );
  30122. nextPoints.push(newData.getItemLayout(idx).slice());
  30123. currStackedPoints.push(
  30124. getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx)
  30125. );
  30126. nextStackedPoints.push(newStackedOnPoints[idx]);
  30127. rawIndices.push(newData.getRawIndex(idx));
  30128. break;
  30129. case '-':
  30130. var idx = diffItem.idx;
  30131. var rawIndex = oldData.getRawIndex(idx);
  30132. // Data is replaced. In the case of dynamic data queue
  30133. // FIXME FIXME FIXME
  30134. if (rawIndex !== idx) {
  30135. currPoints.push(oldData.getItemLayout(idx));
  30136. nextPoints.push(newCoordSys.dataToPoint([
  30137. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx),
  30138. oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)
  30139. ]));
  30140. currStackedPoints.push(oldStackedOnPoints[idx]);
  30141. nextStackedPoints.push(
  30142. getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx)
  30143. );
  30144. rawIndices.push(rawIndex);
  30145. }
  30146. else {
  30147. pointAdded = false;
  30148. }
  30149. }
  30150. // Original indices
  30151. if (pointAdded) {
  30152. status.push(diffItem);
  30153. sortedIndices.push(sortedIndices.length);
  30154. }
  30155. }
  30156. // Diff result may be crossed if all items are changed
  30157. // Sort by data index
  30158. sortedIndices.sort(function (a, b) {
  30159. return rawIndices[a] - rawIndices[b];
  30160. });
  30161. var sortedCurrPoints = [];
  30162. var sortedNextPoints = [];
  30163. var sortedCurrStackedPoints = [];
  30164. var sortedNextStackedPoints = [];
  30165. var sortedStatus = [];
  30166. for (var i = 0; i < sortedIndices.length; i++) {
  30167. var idx = sortedIndices[i];
  30168. sortedCurrPoints[i] = currPoints[idx];
  30169. sortedNextPoints[i] = nextPoints[idx];
  30170. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  30171. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  30172. sortedStatus[i] = status[idx];
  30173. }
  30174. return {
  30175. current: sortedCurrPoints,
  30176. next: sortedNextPoints,
  30177. stackedOnCurrent: sortedCurrStackedPoints,
  30178. stackedOnNext: sortedNextStackedPoints,
  30179. status: sortedStatus
  30180. };
  30181. };
  30182. /*
  30183. * Licensed to the Apache Software Foundation (ASF) under one
  30184. * or more contributor license agreements. See the NOTICE file
  30185. * distributed with this work for additional information
  30186. * regarding copyright ownership. The ASF licenses this file
  30187. * to you under the Apache License, Version 2.0 (the
  30188. * "License"); you may not use this file except in compliance
  30189. * with the License. You may obtain a copy of the License at
  30190. *
  30191. * http://www.apache.org/licenses/LICENSE-2.0
  30192. *
  30193. * Unless required by applicable law or agreed to in writing,
  30194. * software distributed under the License is distributed on an
  30195. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30196. * KIND, either express or implied. See the License for the
  30197. * specific language governing permissions and limitations
  30198. * under the License.
  30199. */
  30200. // Poly path support NaN point
  30201. var vec2Min = min;
  30202. var vec2Max = max;
  30203. var scaleAndAdd$1 = scaleAndAdd;
  30204. var v2Copy = copy;
  30205. // Temporary variable
  30206. var v = [];
  30207. var cp0 = [];
  30208. var cp1 = [];
  30209. function isPointNull(p) {
  30210. return isNaN(p[0]) || isNaN(p[1]);
  30211. }
  30212. function drawSegment(
  30213. ctx, points, start, segLen, allLen,
  30214. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30215. ) {
  30216. // if (smoothMonotone == null) {
  30217. // if (isMono(points, 'x')) {
  30218. // return drawMono(ctx, points, start, segLen, allLen,
  30219. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  30220. // }
  30221. // else if (isMono(points, 'y')) {
  30222. // return drawMono(ctx, points, start, segLen, allLen,
  30223. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  30224. // }
  30225. // else {
  30226. // return drawNonMono.apply(this, arguments);
  30227. // }
  30228. // }
  30229. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  30230. // return drawMono.apply(this, arguments);
  30231. // }
  30232. // else {
  30233. // return drawNonMono.apply(this, arguments);
  30234. // }
  30235. if (smoothMonotone === 'none' || !smoothMonotone) {
  30236. return drawNonMono.apply(this, arguments);
  30237. }
  30238. else {
  30239. return drawMono.apply(this, arguments);
  30240. }
  30241. }
  30242. /**
  30243. * Check if points is in monotone.
  30244. *
  30245. * @param {number[][]} points Array of points which is in [x, y] form
  30246. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  30247. * dimension that is checking.
  30248. * If is 'none', `drawNonMono` should be
  30249. * called.
  30250. * If is undefined, either being monotone
  30251. * in 'x' or 'y' will call `drawMono`.
  30252. */
  30253. // function isMono(points, smoothMonotone) {
  30254. // if (points.length <= 1) {
  30255. // return true;
  30256. // }
  30257. // var dim = smoothMonotone === 'x' ? 0 : 1;
  30258. // var last = points[0][dim];
  30259. // var lastDiff = 0;
  30260. // for (var i = 1; i < points.length; ++i) {
  30261. // var diff = points[i][dim] - last;
  30262. // if (!isNaN(diff) && !isNaN(lastDiff)
  30263. // && diff !== 0 && lastDiff !== 0
  30264. // && ((diff >= 0) !== (lastDiff >= 0))
  30265. // ) {
  30266. // return false;
  30267. // }
  30268. // if (!isNaN(diff) && diff !== 0) {
  30269. // lastDiff = diff;
  30270. // last = points[i][dim];
  30271. // }
  30272. // }
  30273. // return true;
  30274. // }
  30275. /**
  30276. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  30277. * control points will be used. This should be used when points are monotone
  30278. * either in x or y dimension.
  30279. */
  30280. function drawMono(
  30281. ctx, points, start, segLen, allLen,
  30282. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30283. ) {
  30284. var prevIdx = 0;
  30285. var idx = start;
  30286. for (var k = 0; k < segLen; k++) {
  30287. var p = points[idx];
  30288. if (idx >= allLen || idx < 0) {
  30289. break;
  30290. }
  30291. if (isPointNull(p)) {
  30292. if (connectNulls) {
  30293. idx += dir;
  30294. continue;
  30295. }
  30296. break;
  30297. }
  30298. if (idx === start) {
  30299. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  30300. }
  30301. else {
  30302. if (smooth > 0) {
  30303. var prevP = points[prevIdx];
  30304. var dim = smoothMonotone === 'y' ? 1 : 0;
  30305. // Length of control point to p, either in x or y, but not both
  30306. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  30307. v2Copy(cp0, prevP);
  30308. cp0[dim] = prevP[dim] + ctrlLen;
  30309. v2Copy(cp1, p);
  30310. cp1[dim] = p[dim] - ctrlLen;
  30311. ctx.bezierCurveTo(
  30312. cp0[0], cp0[1],
  30313. cp1[0], cp1[1],
  30314. p[0], p[1]
  30315. );
  30316. }
  30317. else {
  30318. ctx.lineTo(p[0], p[1]);
  30319. }
  30320. }
  30321. prevIdx = idx;
  30322. idx += dir;
  30323. }
  30324. return k;
  30325. }
  30326. /**
  30327. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  30328. * situations. This should be used when points are non-monotone neither in x or
  30329. * y dimension.
  30330. */
  30331. function drawNonMono(
  30332. ctx, points, start, segLen, allLen,
  30333. dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls
  30334. ) {
  30335. var prevIdx = 0;
  30336. var idx = start;
  30337. for (var k = 0; k < segLen; k++) {
  30338. var p = points[idx];
  30339. if (idx >= allLen || idx < 0) {
  30340. break;
  30341. }
  30342. if (isPointNull(p)) {
  30343. if (connectNulls) {
  30344. idx += dir;
  30345. continue;
  30346. }
  30347. break;
  30348. }
  30349. if (idx === start) {
  30350. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  30351. v2Copy(cp0, p);
  30352. }
  30353. else {
  30354. if (smooth > 0) {
  30355. var nextIdx = idx + dir;
  30356. var nextP = points[nextIdx];
  30357. if (connectNulls) {
  30358. // Find next point not null
  30359. while (nextP && isPointNull(points[nextIdx])) {
  30360. nextIdx += dir;
  30361. nextP = points[nextIdx];
  30362. }
  30363. }
  30364. var ratioNextSeg = 0.5;
  30365. var prevP = points[prevIdx];
  30366. var nextP = points[nextIdx];
  30367. // Last point
  30368. if (!nextP || isPointNull(nextP)) {
  30369. v2Copy(cp1, p);
  30370. }
  30371. else {
  30372. // If next data is null in not connect case
  30373. if (isPointNull(nextP) && !connectNulls) {
  30374. nextP = p;
  30375. }
  30376. sub(v, nextP, prevP);
  30377. var lenPrevSeg;
  30378. var lenNextSeg;
  30379. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  30380. var dim = smoothMonotone === 'x' ? 0 : 1;
  30381. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  30382. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  30383. }
  30384. else {
  30385. lenPrevSeg = dist(p, prevP);
  30386. lenNextSeg = dist(p, nextP);
  30387. }
  30388. // Use ratio of seg length
  30389. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  30390. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  30391. }
  30392. // Smooth constraint
  30393. vec2Min(cp0, cp0, smoothMax);
  30394. vec2Max(cp0, cp0, smoothMin);
  30395. vec2Min(cp1, cp1, smoothMax);
  30396. vec2Max(cp1, cp1, smoothMin);
  30397. ctx.bezierCurveTo(
  30398. cp0[0], cp0[1],
  30399. cp1[0], cp1[1],
  30400. p[0], p[1]
  30401. );
  30402. // cp0 of next segment
  30403. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  30404. }
  30405. else {
  30406. ctx.lineTo(p[0], p[1]);
  30407. }
  30408. }
  30409. prevIdx = idx;
  30410. idx += dir;
  30411. }
  30412. return k;
  30413. }
  30414. function getBoundingBox(points, smoothConstraint) {
  30415. var ptMin = [Infinity, Infinity];
  30416. var ptMax = [-Infinity, -Infinity];
  30417. if (smoothConstraint) {
  30418. for (var i = 0; i < points.length; i++) {
  30419. var pt = points[i];
  30420. if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; }
  30421. if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; }
  30422. if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; }
  30423. if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; }
  30424. }
  30425. }
  30426. return {
  30427. min: smoothConstraint ? ptMin : ptMax,
  30428. max: smoothConstraint ? ptMax : ptMin
  30429. };
  30430. }
  30431. var Polyline$1 = Path.extend({
  30432. type: 'ec-polyline',
  30433. shape: {
  30434. points: [],
  30435. smooth: 0,
  30436. smoothConstraint: true,
  30437. smoothMonotone: null,
  30438. connectNulls: false
  30439. },
  30440. style: {
  30441. fill: null,
  30442. stroke: '#000'
  30443. },
  30444. brush: fixClipWithShadow(Path.prototype.brush),
  30445. buildPath: function (ctx, shape) {
  30446. var points = shape.points;
  30447. var i = 0;
  30448. var len$$1 = points.length;
  30449. var result = getBoundingBox(points, shape.smoothConstraint);
  30450. if (shape.connectNulls) {
  30451. // Must remove first and last null values avoid draw error in polygon
  30452. for (; len$$1 > 0; len$$1--) {
  30453. if (!isPointNull(points[len$$1 - 1])) {
  30454. break;
  30455. }
  30456. }
  30457. for (; i < len$$1; i++) {
  30458. if (!isPointNull(points[i])) {
  30459. break;
  30460. }
  30461. }
  30462. }
  30463. while (i < len$$1) {
  30464. i += drawSegment(
  30465. ctx, points, i, len$$1, len$$1,
  30466. 1, result.min, result.max, shape.smooth,
  30467. shape.smoothMonotone, shape.connectNulls
  30468. ) + 1;
  30469. }
  30470. }
  30471. });
  30472. var Polygon$1 = Path.extend({
  30473. type: 'ec-polygon',
  30474. shape: {
  30475. points: [],
  30476. // Offset between stacked base points and points
  30477. stackedOnPoints: [],
  30478. smooth: 0,
  30479. stackedOnSmooth: 0,
  30480. smoothConstraint: true,
  30481. smoothMonotone: null,
  30482. connectNulls: false
  30483. },
  30484. brush: fixClipWithShadow(Path.prototype.brush),
  30485. buildPath: function (ctx, shape) {
  30486. var points = shape.points;
  30487. var stackedOnPoints = shape.stackedOnPoints;
  30488. var i = 0;
  30489. var len$$1 = points.length;
  30490. var smoothMonotone = shape.smoothMonotone;
  30491. var bbox = getBoundingBox(points, shape.smoothConstraint);
  30492. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  30493. if (shape.connectNulls) {
  30494. // Must remove first and last null values avoid draw error in polygon
  30495. for (; len$$1 > 0; len$$1--) {
  30496. if (!isPointNull(points[len$$1 - 1])) {
  30497. break;
  30498. }
  30499. }
  30500. for (; i < len$$1; i++) {
  30501. if (!isPointNull(points[i])) {
  30502. break;
  30503. }
  30504. }
  30505. }
  30506. while (i < len$$1) {
  30507. var k = drawSegment(
  30508. ctx, points, i, len$$1, len$$1,
  30509. 1, bbox.min, bbox.max, shape.smooth,
  30510. smoothMonotone, shape.connectNulls
  30511. );
  30512. drawSegment(
  30513. ctx, stackedOnPoints, i + k - 1, k, len$$1,
  30514. -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth,
  30515. smoothMonotone, shape.connectNulls
  30516. );
  30517. i += k + 1;
  30518. ctx.closePath();
  30519. }
  30520. }
  30521. });
  30522. /*
  30523. * Licensed to the Apache Software Foundation (ASF) under one
  30524. * or more contributor license agreements. See the NOTICE file
  30525. * distributed with this work for additional information
  30526. * regarding copyright ownership. The ASF licenses this file
  30527. * to you under the Apache License, Version 2.0 (the
  30528. * "License"); you may not use this file except in compliance
  30529. * with the License. You may obtain a copy of the License at
  30530. *
  30531. * http://www.apache.org/licenses/LICENSE-2.0
  30532. *
  30533. * Unless required by applicable law or agreed to in writing,
  30534. * software distributed under the License is distributed on an
  30535. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30536. * KIND, either express or implied. See the License for the
  30537. * specific language governing permissions and limitations
  30538. * under the License.
  30539. */
  30540. // FIXME step not support polar
  30541. function isPointsSame(points1, points2) {
  30542. if (points1.length !== points2.length) {
  30543. return;
  30544. }
  30545. for (var i = 0; i < points1.length; i++) {
  30546. var p1 = points1[i];
  30547. var p2 = points2[i];
  30548. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  30549. return;
  30550. }
  30551. }
  30552. return true;
  30553. }
  30554. function getSmooth(smooth) {
  30555. return typeof (smooth) === 'number' ? smooth : (smooth ? 0.5 : 0);
  30556. }
  30557. function getAxisExtentWithGap(axis) {
  30558. var extent = axis.getGlobalExtent();
  30559. if (axis.onBand) {
  30560. // Remove extra 1px to avoid line miter in clipped edge
  30561. var halfBandWidth = axis.getBandWidth() / 2 - 1;
  30562. var dir = extent[1] > extent[0] ? 1 : -1;
  30563. extent[0] += dir * halfBandWidth;
  30564. extent[1] -= dir * halfBandWidth;
  30565. }
  30566. return extent;
  30567. }
  30568. /**
  30569. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  30570. * @param {module:echarts/data/List} data
  30571. * @param {Object} dataCoordInfo
  30572. * @param {Array.<Array.<number>>} points
  30573. */
  30574. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  30575. if (!dataCoordInfo.valueDim) {
  30576. return [];
  30577. }
  30578. var points = [];
  30579. for (var idx = 0, len = data.count(); idx < len; idx++) {
  30580. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  30581. }
  30582. return points;
  30583. }
  30584. function createGridClipShape(cartesian, hasAnimation, forSymbol, seriesModel) {
  30585. var xExtent = getAxisExtentWithGap(cartesian.getAxis('x'));
  30586. var yExtent = getAxisExtentWithGap(cartesian.getAxis('y'));
  30587. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  30588. var x = Math.min(xExtent[0], xExtent[1]);
  30589. var y = Math.min(yExtent[0], yExtent[1]);
  30590. var width = Math.max(xExtent[0], xExtent[1]) - x;
  30591. var height = Math.max(yExtent[0], yExtent[1]) - y;
  30592. // Avoid float number rounding error for symbol on the edge of axis extent.
  30593. // See #7913 and `test/dataZoom-clip.html`.
  30594. if (forSymbol) {
  30595. x -= 0.5;
  30596. width += 0.5;
  30597. y -= 0.5;
  30598. height += 0.5;
  30599. }
  30600. else {
  30601. var lineWidth = seriesModel.get('lineStyle.width') || 2;
  30602. // Expand clip shape to avoid clipping when line value exceeds axis
  30603. var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height);
  30604. if (isHorizontal) {
  30605. y -= expandSize;
  30606. height += expandSize * 2;
  30607. }
  30608. else {
  30609. x -= expandSize;
  30610. width += expandSize * 2;
  30611. }
  30612. }
  30613. var clipPath = new Rect({
  30614. shape: {
  30615. x: x,
  30616. y: y,
  30617. width: width,
  30618. height: height
  30619. }
  30620. });
  30621. if (hasAnimation) {
  30622. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  30623. initProps(clipPath, {
  30624. shape: {
  30625. width: width,
  30626. height: height
  30627. }
  30628. }, seriesModel);
  30629. }
  30630. return clipPath;
  30631. }
  30632. function createPolarClipShape(polar, hasAnimation, forSymbol, seriesModel) {
  30633. var angleAxis = polar.getAngleAxis();
  30634. var radiusAxis = polar.getRadiusAxis();
  30635. var radiusExtent = radiusAxis.getExtent().slice();
  30636. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  30637. var angleExtent = angleAxis.getExtent();
  30638. var RADIAN = Math.PI / 180;
  30639. // Avoid float number rounding error for symbol on the edge of axis extent.
  30640. if (forSymbol) {
  30641. radiusExtent[0] -= 0.5;
  30642. radiusExtent[1] += 0.5;
  30643. }
  30644. var clipPath = new Sector({
  30645. shape: {
  30646. cx: round$1(polar.cx, 1),
  30647. cy: round$1(polar.cy, 1),
  30648. r0: round$1(radiusExtent[0], 1),
  30649. r: round$1(radiusExtent[1], 1),
  30650. startAngle: -angleExtent[0] * RADIAN,
  30651. endAngle: -angleExtent[1] * RADIAN,
  30652. clockwise: angleAxis.inverse
  30653. }
  30654. });
  30655. if (hasAnimation) {
  30656. clipPath.shape.endAngle = -angleExtent[0] * RADIAN;
  30657. initProps(clipPath, {
  30658. shape: {
  30659. endAngle: -angleExtent[1] * RADIAN
  30660. }
  30661. }, seriesModel);
  30662. }
  30663. return clipPath;
  30664. }
  30665. function createClipShape(coordSys, hasAnimation, forSymbol, seriesModel) {
  30666. return coordSys.type === 'polar'
  30667. ? createPolarClipShape(coordSys, hasAnimation, forSymbol, seriesModel)
  30668. : createGridClipShape(coordSys, hasAnimation, forSymbol, seriesModel);
  30669. }
  30670. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  30671. var baseAxis = coordSys.getBaseAxis();
  30672. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  30673. var stepPoints = [];
  30674. for (var i = 0; i < points.length - 1; i++) {
  30675. var nextPt = points[i + 1];
  30676. var pt = points[i];
  30677. stepPoints.push(pt);
  30678. var stepPt = [];
  30679. switch (stepTurnAt) {
  30680. case 'end':
  30681. stepPt[baseIndex] = nextPt[baseIndex];
  30682. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30683. // default is start
  30684. stepPoints.push(stepPt);
  30685. break;
  30686. case 'middle':
  30687. // default is start
  30688. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  30689. var stepPt2 = [];
  30690. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  30691. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  30692. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  30693. stepPoints.push(stepPt);
  30694. stepPoints.push(stepPt2);
  30695. break;
  30696. default:
  30697. stepPt[baseIndex] = pt[baseIndex];
  30698. stepPt[1 - baseIndex] = nextPt[1 - baseIndex];
  30699. // default is start
  30700. stepPoints.push(stepPt);
  30701. }
  30702. }
  30703. // Last points
  30704. points[i] && stepPoints.push(points[i]);
  30705. return stepPoints;
  30706. }
  30707. function getVisualGradient(data, coordSys) {
  30708. var visualMetaList = data.getVisual('visualMeta');
  30709. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  30710. // When data.count() is 0, gradient range can not be calculated.
  30711. return;
  30712. }
  30713. if (coordSys.type !== 'cartesian2d') {
  30714. if (__DEV__) {
  30715. console.warn('Visual map on line style is only supported on cartesian2d.');
  30716. }
  30717. return;
  30718. }
  30719. var coordDim;
  30720. var visualMeta;
  30721. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  30722. var dimIndex = visualMetaList[i].dimension;
  30723. var dimName = data.dimensions[dimIndex];
  30724. var dimInfo = data.getDimensionInfo(dimName);
  30725. coordDim = dimInfo && dimInfo.coordDim;
  30726. // Can only be x or y
  30727. if (coordDim === 'x' || coordDim === 'y') {
  30728. visualMeta = visualMetaList[i];
  30729. break;
  30730. }
  30731. }
  30732. if (!visualMeta) {
  30733. if (__DEV__) {
  30734. console.warn('Visual map on line style only support x or y dimension.');
  30735. }
  30736. return;
  30737. }
  30738. // If the area to be rendered is bigger than area defined by LinearGradient,
  30739. // the canvas spec prescribes that the color of the first stop and the last
  30740. // stop should be used. But if two stops are added at offset 0, in effect
  30741. // browsers use the color of the second stop to render area outside
  30742. // LinearGradient. So we can only infinitesimally extend area defined in
  30743. // LinearGradient to render `outerColors`.
  30744. var axis = coordSys.getAxis(coordDim);
  30745. // dataToCoor mapping may not be linear, but must be monotonic.
  30746. var colorStops = map(visualMeta.stops, function (stop) {
  30747. return {
  30748. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  30749. color: stop.color
  30750. };
  30751. });
  30752. var stopLen = colorStops.length;
  30753. var outerColors = visualMeta.outerColors.slice();
  30754. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  30755. colorStops.reverse();
  30756. outerColors.reverse();
  30757. }
  30758. var tinyExtent = 10; // Arbitrary value: 10px
  30759. var minCoord = colorStops[0].coord - tinyExtent;
  30760. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  30761. var coordSpan = maxCoord - minCoord;
  30762. if (coordSpan < 1e-3) {
  30763. return 'transparent';
  30764. }
  30765. each$1(colorStops, function (stop) {
  30766. stop.offset = (stop.coord - minCoord) / coordSpan;
  30767. });
  30768. colorStops.push({
  30769. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  30770. color: outerColors[1] || 'transparent'
  30771. });
  30772. colorStops.unshift({ // notice colorStops.length have been changed.
  30773. offset: stopLen ? colorStops[0].offset : 0.5,
  30774. color: outerColors[0] || 'transparent'
  30775. });
  30776. // zrUtil.each(colorStops, function (colorStop) {
  30777. // // Make sure each offset has rounded px to avoid not sharp edge
  30778. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  30779. // });
  30780. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  30781. gradient[coordDim] = minCoord;
  30782. gradient[coordDim + '2'] = maxCoord;
  30783. return gradient;
  30784. }
  30785. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  30786. var showAllSymbol = seriesModel.get('showAllSymbol');
  30787. var isAuto = showAllSymbol === 'auto';
  30788. if (showAllSymbol && !isAuto) {
  30789. return;
  30790. }
  30791. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  30792. if (!categoryAxis) {
  30793. return;
  30794. }
  30795. // Note that category label interval strategy might bring some weird effect
  30796. // in some scenario: users may wonder why some of the symbols are not
  30797. // displayed. So we show all symbols as possible as we can.
  30798. if (isAuto
  30799. // Simplify the logic, do not determine label overlap here.
  30800. && canShowAllSymbolForCategory(categoryAxis, data)
  30801. ) {
  30802. return;
  30803. }
  30804. // Otherwise follow the label interval strategy on category axis.
  30805. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  30806. var labelMap = {};
  30807. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  30808. labelMap[labelItem.tickValue] = 1;
  30809. });
  30810. return function (dataIndex) {
  30811. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  30812. };
  30813. }
  30814. function canShowAllSymbolForCategory(categoryAxis, data) {
  30815. // In mose cases, line is monotonous on category axis, and the label size
  30816. // is close with each other. So we check the symbol size and some of the
  30817. // label size alone with the category axis to estimate whether all symbol
  30818. // can be shown without overlap.
  30819. var axisExtent = categoryAxis.getExtent();
  30820. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  30821. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  30822. // Sampling some points, max 5.
  30823. var dataLen = data.count();
  30824. var step = Math.max(1, Math.round(dataLen / 5));
  30825. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  30826. if (SymbolClz$1.getSymbolSize(
  30827. data, dataIndex
  30828. // Only for cartesian, where `isHorizontal` exists.
  30829. )[categoryAxis.isHorizontal() ? 1 : 0]
  30830. // Empirical number
  30831. * 1.5 > availSize
  30832. ) {
  30833. return false;
  30834. }
  30835. }
  30836. return true;
  30837. }
  30838. Chart.extend({
  30839. type: 'line',
  30840. init: function () {
  30841. var lineGroup = new Group();
  30842. var symbolDraw = new SymbolDraw();
  30843. this.group.add(symbolDraw.group);
  30844. this._symbolDraw = symbolDraw;
  30845. this._lineGroup = lineGroup;
  30846. },
  30847. render: function (seriesModel, ecModel, api) {
  30848. var coordSys = seriesModel.coordinateSystem;
  30849. var group = this.group;
  30850. var data = seriesModel.getData();
  30851. var lineStyleModel = seriesModel.getModel('lineStyle');
  30852. var areaStyleModel = seriesModel.getModel('areaStyle');
  30853. var points = data.mapArray(data.getItemLayout);
  30854. var isCoordSysPolar = coordSys.type === 'polar';
  30855. var prevCoordSys = this._coordSys;
  30856. var symbolDraw = this._symbolDraw;
  30857. var polyline = this._polyline;
  30858. var polygon = this._polygon;
  30859. var lineGroup = this._lineGroup;
  30860. var hasAnimation = seriesModel.get('animation');
  30861. var isAreaChart = !areaStyleModel.isEmpty();
  30862. var valueOrigin = areaStyleModel.get('origin');
  30863. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  30864. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  30865. var showSymbol = seriesModel.get('showSymbol');
  30866. var isIgnoreFunc = showSymbol && !isCoordSysPolar
  30867. && getIsIgnoreFunc(seriesModel, data, coordSys);
  30868. // Remove temporary symbols
  30869. var oldData = this._data;
  30870. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  30871. if (el.__temp) {
  30872. group.remove(el);
  30873. oldData.setItemGraphicEl(idx, null);
  30874. }
  30875. });
  30876. // Remove previous created symbols if showSymbol changed to false
  30877. if (!showSymbol) {
  30878. symbolDraw.remove();
  30879. }
  30880. group.add(lineGroup);
  30881. // FIXME step not support polar
  30882. var step = !isCoordSysPolar && seriesModel.get('step');
  30883. // Initialization animation or coordinate system changed
  30884. if (
  30885. !(polyline && prevCoordSys.type === coordSys.type && step === this._step)
  30886. ) {
  30887. showSymbol && symbolDraw.updateData(data, {
  30888. isIgnore: isIgnoreFunc,
  30889. clipShape: createClipShape(coordSys, false, true, seriesModel)
  30890. });
  30891. if (step) {
  30892. // TODO If stacked series is not step
  30893. points = turnPointsIntoStep(points, coordSys, step);
  30894. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30895. }
  30896. polyline = this._newPolyline(points, coordSys, hasAnimation);
  30897. if (isAreaChart) {
  30898. polygon = this._newPolygon(
  30899. points, stackedOnPoints,
  30900. coordSys, hasAnimation
  30901. );
  30902. }
  30903. lineGroup.setClipPath(createClipShape(coordSys, true, false, seriesModel));
  30904. }
  30905. else {
  30906. if (isAreaChart && !polygon) {
  30907. // If areaStyle is added
  30908. polygon = this._newPolygon(
  30909. points, stackedOnPoints,
  30910. coordSys, hasAnimation
  30911. );
  30912. }
  30913. else if (polygon && !isAreaChart) {
  30914. // If areaStyle is removed
  30915. lineGroup.remove(polygon);
  30916. polygon = this._polygon = null;
  30917. }
  30918. // Update clipPath
  30919. lineGroup.setClipPath(createClipShape(coordSys, false, false, seriesModel));
  30920. // Always update, or it is wrong in the case turning on legend
  30921. // because points are not changed
  30922. showSymbol && symbolDraw.updateData(data, {
  30923. isIgnore: isIgnoreFunc,
  30924. clipShape: createClipShape(coordSys, false, true, seriesModel)
  30925. });
  30926. // Stop symbol animation and sync with line points
  30927. // FIXME performance?
  30928. data.eachItemGraphicEl(function (el) {
  30929. el.stopAnimation(true);
  30930. });
  30931. // In the case data zoom triggerred refreshing frequently
  30932. // Data may not change if line has a category axis. So it should animate nothing
  30933. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints)
  30934. || !isPointsSame(this._points, points)
  30935. ) {
  30936. if (hasAnimation) {
  30937. this._updateAnimation(
  30938. data, stackedOnPoints, coordSys, api, step, valueOrigin
  30939. );
  30940. }
  30941. else {
  30942. // Not do it in update with animation
  30943. if (step) {
  30944. // TODO If stacked series is not step
  30945. points = turnPointsIntoStep(points, coordSys, step);
  30946. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  30947. }
  30948. polyline.setShape({
  30949. points: points
  30950. });
  30951. polygon && polygon.setShape({
  30952. points: points,
  30953. stackedOnPoints: stackedOnPoints
  30954. });
  30955. }
  30956. }
  30957. }
  30958. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  30959. polyline.useStyle(defaults(
  30960. // Use color in lineStyle first
  30961. lineStyleModel.getLineStyle(),
  30962. {
  30963. fill: 'none',
  30964. stroke: visualColor,
  30965. lineJoin: 'bevel'
  30966. }
  30967. ));
  30968. var smooth = seriesModel.get('smooth');
  30969. smooth = getSmooth(seriesModel.get('smooth'));
  30970. polyline.setShape({
  30971. smooth: smooth,
  30972. smoothMonotone: seriesModel.get('smoothMonotone'),
  30973. connectNulls: seriesModel.get('connectNulls')
  30974. });
  30975. if (polygon) {
  30976. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  30977. var stackedOnSmooth = 0;
  30978. polygon.useStyle(defaults(
  30979. areaStyleModel.getAreaStyle(),
  30980. {
  30981. fill: visualColor,
  30982. opacity: 0.7,
  30983. lineJoin: 'bevel'
  30984. }
  30985. ));
  30986. if (stackedOnSeries) {
  30987. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  30988. }
  30989. polygon.setShape({
  30990. smooth: smooth,
  30991. stackedOnSmooth: stackedOnSmooth,
  30992. smoothMonotone: seriesModel.get('smoothMonotone'),
  30993. connectNulls: seriesModel.get('connectNulls')
  30994. });
  30995. }
  30996. this._data = data;
  30997. // Save the coordinate system for transition animation when data changed
  30998. this._coordSys = coordSys;
  30999. this._stackedOnPoints = stackedOnPoints;
  31000. this._points = points;
  31001. this._step = step;
  31002. this._valueOrigin = valueOrigin;
  31003. },
  31004. dispose: function () {},
  31005. highlight: function (seriesModel, ecModel, api, payload) {
  31006. var data = seriesModel.getData();
  31007. var dataIndex = queryDataIndex(data, payload);
  31008. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  31009. var symbol = data.getItemGraphicEl(dataIndex);
  31010. if (!symbol) {
  31011. // Create a temporary symbol if it is not exists
  31012. var pt = data.getItemLayout(dataIndex);
  31013. if (!pt) {
  31014. // Null data
  31015. return;
  31016. }
  31017. symbol = new SymbolClz$1(data, dataIndex);
  31018. symbol.position = pt;
  31019. symbol.setZ(
  31020. seriesModel.get('zlevel'),
  31021. seriesModel.get('z')
  31022. );
  31023. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  31024. symbol.__temp = true;
  31025. data.setItemGraphicEl(dataIndex, symbol);
  31026. // Stop scale animation
  31027. symbol.stopSymbolAnimation(true);
  31028. this.group.add(symbol);
  31029. }
  31030. symbol.highlight();
  31031. }
  31032. else {
  31033. // Highlight whole series
  31034. Chart.prototype.highlight.call(
  31035. this, seriesModel, ecModel, api, payload
  31036. );
  31037. }
  31038. },
  31039. downplay: function (seriesModel, ecModel, api, payload) {
  31040. var data = seriesModel.getData();
  31041. var dataIndex = queryDataIndex(data, payload);
  31042. if (dataIndex != null && dataIndex >= 0) {
  31043. var symbol = data.getItemGraphicEl(dataIndex);
  31044. if (symbol) {
  31045. if (symbol.__temp) {
  31046. data.setItemGraphicEl(dataIndex, null);
  31047. this.group.remove(symbol);
  31048. }
  31049. else {
  31050. symbol.downplay();
  31051. }
  31052. }
  31053. }
  31054. else {
  31055. // FIXME
  31056. // can not downplay completely.
  31057. // Downplay whole series
  31058. Chart.prototype.downplay.call(
  31059. this, seriesModel, ecModel, api, payload
  31060. );
  31061. }
  31062. },
  31063. /**
  31064. * @param {module:zrender/container/Group} group
  31065. * @param {Array.<Array.<number>>} points
  31066. * @private
  31067. */
  31068. _newPolyline: function (points) {
  31069. var polyline = this._polyline;
  31070. // Remove previous created polyline
  31071. if (polyline) {
  31072. this._lineGroup.remove(polyline);
  31073. }
  31074. polyline = new Polyline$1({
  31075. shape: {
  31076. points: points
  31077. },
  31078. silent: true,
  31079. z2: 10
  31080. });
  31081. this._lineGroup.add(polyline);
  31082. this._polyline = polyline;
  31083. return polyline;
  31084. },
  31085. /**
  31086. * @param {module:zrender/container/Group} group
  31087. * @param {Array.<Array.<number>>} stackedOnPoints
  31088. * @param {Array.<Array.<number>>} points
  31089. * @private
  31090. */
  31091. _newPolygon: function (points, stackedOnPoints) {
  31092. var polygon = this._polygon;
  31093. // Remove previous created polygon
  31094. if (polygon) {
  31095. this._lineGroup.remove(polygon);
  31096. }
  31097. polygon = new Polygon$1({
  31098. shape: {
  31099. points: points,
  31100. stackedOnPoints: stackedOnPoints
  31101. },
  31102. silent: true
  31103. });
  31104. this._lineGroup.add(polygon);
  31105. this._polygon = polygon;
  31106. return polygon;
  31107. },
  31108. /**
  31109. * @private
  31110. */
  31111. // FIXME Two value axis
  31112. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  31113. var polyline = this._polyline;
  31114. var polygon = this._polygon;
  31115. var seriesModel = data.hostModel;
  31116. var diff = lineAnimationDiff(
  31117. this._data, data,
  31118. this._stackedOnPoints, stackedOnPoints,
  31119. this._coordSys, coordSys,
  31120. this._valueOrigin, valueOrigin
  31121. );
  31122. var current = diff.current;
  31123. var stackedOnCurrent = diff.stackedOnCurrent;
  31124. var next = diff.next;
  31125. var stackedOnNext = diff.stackedOnNext;
  31126. if (step) {
  31127. // TODO If stacked series is not step
  31128. current = turnPointsIntoStep(diff.current, coordSys, step);
  31129. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  31130. next = turnPointsIntoStep(diff.next, coordSys, step);
  31131. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  31132. }
  31133. // `diff.current` is subset of `current` (which should be ensured by
  31134. // turnPointsIntoStep), so points in `__points` can be updated when
  31135. // points in `current` are update during animation.
  31136. polyline.shape.__points = diff.current;
  31137. polyline.shape.points = current;
  31138. updateProps(polyline, {
  31139. shape: {
  31140. points: next
  31141. }
  31142. }, seriesModel);
  31143. if (polygon) {
  31144. polygon.setShape({
  31145. points: current,
  31146. stackedOnPoints: stackedOnCurrent
  31147. });
  31148. updateProps(polygon, {
  31149. shape: {
  31150. points: next,
  31151. stackedOnPoints: stackedOnNext
  31152. }
  31153. }, seriesModel);
  31154. }
  31155. var updatedDataInfo = [];
  31156. var diffStatus = diff.status;
  31157. for (var i = 0; i < diffStatus.length; i++) {
  31158. var cmd = diffStatus[i].cmd;
  31159. if (cmd === '=') {
  31160. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  31161. if (el) {
  31162. updatedDataInfo.push({
  31163. el: el,
  31164. ptIdx: i // Index of points
  31165. });
  31166. }
  31167. }
  31168. }
  31169. if (polyline.animators && polyline.animators.length) {
  31170. polyline.animators[0].during(function () {
  31171. for (var i = 0; i < updatedDataInfo.length; i++) {
  31172. var el = updatedDataInfo[i].el;
  31173. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  31174. }
  31175. });
  31176. }
  31177. },
  31178. remove: function (ecModel) {
  31179. var group = this.group;
  31180. var oldData = this._data;
  31181. this._lineGroup.removeAll();
  31182. this._symbolDraw.remove(true);
  31183. // Remove temporary created elements when highlighting
  31184. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  31185. if (el.__temp) {
  31186. group.remove(el);
  31187. oldData.setItemGraphicEl(idx, null);
  31188. }
  31189. });
  31190. this._polyline =
  31191. this._polygon =
  31192. this._coordSys =
  31193. this._points =
  31194. this._stackedOnPoints =
  31195. this._data = null;
  31196. }
  31197. });
  31198. /*
  31199. * Licensed to the Apache Software Foundation (ASF) under one
  31200. * or more contributor license agreements. See the NOTICE file
  31201. * distributed with this work for additional information
  31202. * regarding copyright ownership. The ASF licenses this file
  31203. * to you under the Apache License, Version 2.0 (the
  31204. * "License"); you may not use this file except in compliance
  31205. * with the License. You may obtain a copy of the License at
  31206. *
  31207. * http://www.apache.org/licenses/LICENSE-2.0
  31208. *
  31209. * Unless required by applicable law or agreed to in writing,
  31210. * software distributed under the License is distributed on an
  31211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31212. * KIND, either express or implied. See the License for the
  31213. * specific language governing permissions and limitations
  31214. * under the License.
  31215. */
  31216. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  31217. // Encoding visual for all series include which is filtered for legend drawing
  31218. return {
  31219. seriesType: seriesType,
  31220. // For legend.
  31221. performRawSeries: true,
  31222. reset: function (seriesModel, ecModel, api) {
  31223. var data = seriesModel.getData();
  31224. var symbolType = seriesModel.get('symbol') || defaultSymbolType;
  31225. var symbolSize = seriesModel.get('symbolSize');
  31226. var keepAspect = seriesModel.get('symbolKeepAspect');
  31227. data.setVisual({
  31228. legendSymbol: legendSymbol || symbolType,
  31229. symbol: symbolType,
  31230. symbolSize: symbolSize,
  31231. symbolKeepAspect: keepAspect
  31232. });
  31233. // Only visible series has each data be visual encoded
  31234. if (ecModel.isSeriesFiltered(seriesModel)) {
  31235. return;
  31236. }
  31237. var hasCallback = typeof symbolSize === 'function';
  31238. function dataEach(data, idx) {
  31239. if (typeof symbolSize === 'function') {
  31240. var rawValue = seriesModel.getRawValue(idx);
  31241. // FIXME
  31242. var params = seriesModel.getDataParams(idx);
  31243. data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  31244. }
  31245. if (data.hasItemOption) {
  31246. var itemModel = data.getItemModel(idx);
  31247. var itemSymbolType = itemModel.getShallow('symbol', true);
  31248. var itemSymbolSize = itemModel.getShallow('symbolSize',
  31249. true);
  31250. var itemSymbolKeepAspect =
  31251. itemModel.getShallow('symbolKeepAspect',true);
  31252. // If has item symbol
  31253. if (itemSymbolType != null) {
  31254. data.setItemVisual(idx, 'symbol', itemSymbolType);
  31255. }
  31256. if (itemSymbolSize != null) {
  31257. // PENDING Transform symbolSize ?
  31258. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  31259. }
  31260. if (itemSymbolKeepAspect != null) {
  31261. data.setItemVisual(idx, 'symbolKeepAspect',
  31262. itemSymbolKeepAspect);
  31263. }
  31264. }
  31265. }
  31266. return { dataEach: (data.hasItemOption || hasCallback) ? dataEach : null };
  31267. }
  31268. };
  31269. };
  31270. /*
  31271. * Licensed to the Apache Software Foundation (ASF) under one
  31272. * or more contributor license agreements. See the NOTICE file
  31273. * distributed with this work for additional information
  31274. * regarding copyright ownership. The ASF licenses this file
  31275. * to you under the Apache License, Version 2.0 (the
  31276. * "License"); you may not use this file except in compliance
  31277. * with the License. You may obtain a copy of the License at
  31278. *
  31279. * http://www.apache.org/licenses/LICENSE-2.0
  31280. *
  31281. * Unless required by applicable law or agreed to in writing,
  31282. * software distributed under the License is distributed on an
  31283. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31284. * KIND, either express or implied. See the License for the
  31285. * specific language governing permissions and limitations
  31286. * under the License.
  31287. */
  31288. var pointsLayout = function (seriesType) {
  31289. return {
  31290. seriesType: seriesType,
  31291. plan: createRenderPlanner(),
  31292. reset: function (seriesModel) {
  31293. var data = seriesModel.getData();
  31294. var coordSys = seriesModel.coordinateSystem;
  31295. var pipelineContext = seriesModel.pipelineContext;
  31296. var isLargeRender = pipelineContext.large;
  31297. if (!coordSys) {
  31298. return;
  31299. }
  31300. var dims = map(coordSys.dimensions, function (dim) {
  31301. return data.mapDimension(dim);
  31302. }).slice(0, 2);
  31303. var dimLen = dims.length;
  31304. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  31305. if (isDimensionStacked(data, dims[0] /*, dims[1]*/)) {
  31306. dims[0] = stackResultDim;
  31307. }
  31308. if (isDimensionStacked(data, dims[1] /*, dims[0]*/)) {
  31309. dims[1] = stackResultDim;
  31310. }
  31311. function progress(params, data) {
  31312. var segCount = params.end - params.start;
  31313. var points = isLargeRender && new Float32Array(segCount * dimLen);
  31314. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  31315. var point;
  31316. if (dimLen === 1) {
  31317. var x = data.get(dims[0], i);
  31318. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  31319. }
  31320. else {
  31321. var x = tmpIn[0] = data.get(dims[0], i);
  31322. var y = tmpIn[1] = data.get(dims[1], i);
  31323. // Also {Array.<number>}, not undefined to avoid if...else... statement
  31324. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  31325. }
  31326. if (isLargeRender) {
  31327. points[offset++] = point ? point[0] : NaN;
  31328. points[offset++] = point ? point[1] : NaN;
  31329. }
  31330. else {
  31331. data.setItemLayout(i, (point && point.slice()) || [NaN, NaN]);
  31332. }
  31333. }
  31334. isLargeRender && data.setLayout('symbolPoints', points);
  31335. }
  31336. return dimLen && {progress: progress};
  31337. }
  31338. };
  31339. };
  31340. /*
  31341. * Licensed to the Apache Software Foundation (ASF) under one
  31342. * or more contributor license agreements. See the NOTICE file
  31343. * distributed with this work for additional information
  31344. * regarding copyright ownership. The ASF licenses this file
  31345. * to you under the Apache License, Version 2.0 (the
  31346. * "License"); you may not use this file except in compliance
  31347. * with the License. You may obtain a copy of the License at
  31348. *
  31349. * http://www.apache.org/licenses/LICENSE-2.0
  31350. *
  31351. * Unless required by applicable law or agreed to in writing,
  31352. * software distributed under the License is distributed on an
  31353. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31354. * KIND, either express or implied. See the License for the
  31355. * specific language governing permissions and limitations
  31356. * under the License.
  31357. */
  31358. var samplers = {
  31359. average: function (frame) {
  31360. var sum = 0;
  31361. var count = 0;
  31362. for (var i = 0; i < frame.length; i++) {
  31363. if (!isNaN(frame[i])) {
  31364. sum += frame[i];
  31365. count++;
  31366. }
  31367. }
  31368. // Return NaN if count is 0
  31369. return count === 0 ? NaN : sum / count;
  31370. },
  31371. sum: function (frame) {
  31372. var sum = 0;
  31373. for (var i = 0; i < frame.length; i++) {
  31374. // Ignore NaN
  31375. sum += frame[i] || 0;
  31376. }
  31377. return sum;
  31378. },
  31379. max: function (frame) {
  31380. var max = -Infinity;
  31381. for (var i = 0; i < frame.length; i++) {
  31382. frame[i] > max && (max = frame[i]);
  31383. }
  31384. // NaN will cause illegal axis extent.
  31385. return isFinite(max) ? max : NaN;
  31386. },
  31387. min: function (frame) {
  31388. var min = Infinity;
  31389. for (var i = 0; i < frame.length; i++) {
  31390. frame[i] < min && (min = frame[i]);
  31391. }
  31392. // NaN will cause illegal axis extent.
  31393. return isFinite(min) ? min : NaN;
  31394. },
  31395. // TODO
  31396. // Median
  31397. nearest: function (frame) {
  31398. return frame[0];
  31399. }
  31400. };
  31401. var indexSampler = function (frame, value) {
  31402. return Math.round(frame.length / 2);
  31403. };
  31404. var dataSample = function (seriesType) {
  31405. return {
  31406. seriesType: seriesType,
  31407. modifyOutputEnd: true,
  31408. reset: function (seriesModel, ecModel, api) {
  31409. var data = seriesModel.getData();
  31410. var sampling = seriesModel.get('sampling');
  31411. var coordSys = seriesModel.coordinateSystem;
  31412. // Only cartesian2d support down sampling
  31413. if (coordSys.type === 'cartesian2d' && sampling) {
  31414. var baseAxis = coordSys.getBaseAxis();
  31415. var valueAxis = coordSys.getOtherAxis(baseAxis);
  31416. var extent = baseAxis.getExtent();
  31417. // Coordinste system has been resized
  31418. var size = extent[1] - extent[0];
  31419. var rate = Math.round(data.count() / size);
  31420. if (rate > 1) {
  31421. var sampler;
  31422. if (typeof sampling === 'string') {
  31423. sampler = samplers[sampling];
  31424. }
  31425. else if (typeof sampling === 'function') {
  31426. sampler = sampling;
  31427. }
  31428. if (sampler) {
  31429. // Only support sample the first dim mapped from value axis.
  31430. seriesModel.setData(data.downSample(
  31431. data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler
  31432. ));
  31433. }
  31434. }
  31435. }
  31436. }
  31437. };
  31438. };
  31439. /*
  31440. * Licensed to the Apache Software Foundation (ASF) under one
  31441. * or more contributor license agreements. See the NOTICE file
  31442. * distributed with this work for additional information
  31443. * regarding copyright ownership. The ASF licenses this file
  31444. * to you under the Apache License, Version 2.0 (the
  31445. * "License"); you may not use this file except in compliance
  31446. * with the License. You may obtain a copy of the License at
  31447. *
  31448. * http://www.apache.org/licenses/LICENSE-2.0
  31449. *
  31450. * Unless required by applicable law or agreed to in writing,
  31451. * software distributed under the License is distributed on an
  31452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31453. * KIND, either express or implied. See the License for the
  31454. * specific language governing permissions and limitations
  31455. * under the License.
  31456. */
  31457. /**
  31458. * Cartesian coordinate system
  31459. * @module echarts/coord/Cartesian
  31460. *
  31461. */
  31462. function dimAxisMapper(dim) {
  31463. return this._axes[dim];
  31464. }
  31465. /**
  31466. * @alias module:echarts/coord/Cartesian
  31467. * @constructor
  31468. */
  31469. var Cartesian = function (name) {
  31470. this._axes = {};
  31471. this._dimList = [];
  31472. /**
  31473. * @type {string}
  31474. */
  31475. this.name = name || '';
  31476. };
  31477. Cartesian.prototype = {
  31478. constructor: Cartesian,
  31479. type: 'cartesian',
  31480. /**
  31481. * Get axis
  31482. * @param {number|string} dim
  31483. * @return {module:echarts/coord/Cartesian~Axis}
  31484. */
  31485. getAxis: function (dim) {
  31486. return this._axes[dim];
  31487. },
  31488. /**
  31489. * Get axes list
  31490. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  31491. */
  31492. getAxes: function () {
  31493. return map(this._dimList, dimAxisMapper, this);
  31494. },
  31495. /**
  31496. * Get axes list by given scale type
  31497. */
  31498. getAxesByScale: function (scaleType) {
  31499. scaleType = scaleType.toLowerCase();
  31500. return filter(
  31501. this.getAxes(),
  31502. function (axis) {
  31503. return axis.scale.type === scaleType;
  31504. }
  31505. );
  31506. },
  31507. /**
  31508. * Add axis
  31509. * @param {module:echarts/coord/Cartesian.Axis}
  31510. */
  31511. addAxis: function (axis) {
  31512. var dim = axis.dim;
  31513. this._axes[dim] = axis;
  31514. this._dimList.push(dim);
  31515. },
  31516. /**
  31517. * Convert data to coord in nd space
  31518. * @param {Array.<number>|Object.<string, number>} val
  31519. * @return {Array.<number>|Object.<string, number>}
  31520. */
  31521. dataToCoord: function (val) {
  31522. return this._dataCoordConvert(val, 'dataToCoord');
  31523. },
  31524. /**
  31525. * Convert coord in nd space to data
  31526. * @param {Array.<number>|Object.<string, number>} val
  31527. * @return {Array.<number>|Object.<string, number>}
  31528. */
  31529. coordToData: function (val) {
  31530. return this._dataCoordConvert(val, 'coordToData');
  31531. },
  31532. _dataCoordConvert: function (input, method) {
  31533. var dimList = this._dimList;
  31534. var output = input instanceof Array ? [] : {};
  31535. for (var i = 0; i < dimList.length; i++) {
  31536. var dim = dimList[i];
  31537. var axis = this._axes[dim];
  31538. output[dim] = axis[method](input[dim]);
  31539. }
  31540. return output;
  31541. }
  31542. };
  31543. /*
  31544. * Licensed to the Apache Software Foundation (ASF) under one
  31545. * or more contributor license agreements. See the NOTICE file
  31546. * distributed with this work for additional information
  31547. * regarding copyright ownership. The ASF licenses this file
  31548. * to you under the Apache License, Version 2.0 (the
  31549. * "License"); you may not use this file except in compliance
  31550. * with the License. You may obtain a copy of the License at
  31551. *
  31552. * http://www.apache.org/licenses/LICENSE-2.0
  31553. *
  31554. * Unless required by applicable law or agreed to in writing,
  31555. * software distributed under the License is distributed on an
  31556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31557. * KIND, either express or implied. See the License for the
  31558. * specific language governing permissions and limitations
  31559. * under the License.
  31560. */
  31561. function Cartesian2D(name) {
  31562. Cartesian.call(this, name);
  31563. }
  31564. Cartesian2D.prototype = {
  31565. constructor: Cartesian2D,
  31566. type: 'cartesian2d',
  31567. /**
  31568. * @type {Array.<string>}
  31569. * @readOnly
  31570. */
  31571. dimensions: ['x', 'y'],
  31572. /**
  31573. * Base axis will be used on stacking.
  31574. *
  31575. * @return {module:echarts/coord/cartesian/Axis2D}
  31576. */
  31577. getBaseAxis: function () {
  31578. return this.getAxesByScale('ordinal')[0]
  31579. || this.getAxesByScale('time')[0]
  31580. || this.getAxis('x');
  31581. },
  31582. /**
  31583. * If contain point
  31584. * @param {Array.<number>} point
  31585. * @return {boolean}
  31586. */
  31587. containPoint: function (point) {
  31588. var axisX = this.getAxis('x');
  31589. var axisY = this.getAxis('y');
  31590. return axisX.contain(axisX.toLocalCoord(point[0]))
  31591. && axisY.contain(axisY.toLocalCoord(point[1]));
  31592. },
  31593. /**
  31594. * If contain data
  31595. * @param {Array.<number>} data
  31596. * @return {boolean}
  31597. */
  31598. containData: function (data) {
  31599. return this.getAxis('x').containData(data[0])
  31600. && this.getAxis('y').containData(data[1]);
  31601. },
  31602. /**
  31603. * @param {Array.<number>} data
  31604. * @param {Array.<number>} out
  31605. * @return {Array.<number>}
  31606. */
  31607. dataToPoint: function (data, reserved, out) {
  31608. var xAxis = this.getAxis('x');
  31609. var yAxis = this.getAxis('y');
  31610. out = out || [];
  31611. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  31612. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  31613. return out;
  31614. },
  31615. /**
  31616. * @param {Array.<number>} data
  31617. * @param {Array.<number>} out
  31618. * @return {Array.<number>}
  31619. */
  31620. clampData: function (data, out) {
  31621. var xScale = this.getAxis('x').scale;
  31622. var yScale = this.getAxis('y').scale;
  31623. var xAxisExtent = xScale.getExtent();
  31624. var yAxisExtent = yScale.getExtent();
  31625. var x = xScale.parse(data[0]);
  31626. var y = yScale.parse(data[1]);
  31627. out = out || [];
  31628. out[0] = Math.min(
  31629. Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x),
  31630. Math.max(xAxisExtent[0], xAxisExtent[1])
  31631. );
  31632. out[1] = Math.min(
  31633. Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y),
  31634. Math.max(yAxisExtent[0], yAxisExtent[1])
  31635. );
  31636. return out;
  31637. },
  31638. /**
  31639. * @param {Array.<number>} point
  31640. * @param {Array.<number>} out
  31641. * @return {Array.<number>}
  31642. */
  31643. pointToData: function (point, out) {
  31644. var xAxis = this.getAxis('x');
  31645. var yAxis = this.getAxis('y');
  31646. out = out || [];
  31647. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  31648. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  31649. return out;
  31650. },
  31651. /**
  31652. * Get other axis
  31653. * @param {module:echarts/coord/cartesian/Axis2D} axis
  31654. */
  31655. getOtherAxis: function (axis) {
  31656. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  31657. }
  31658. };
  31659. inherits(Cartesian2D, Cartesian);
  31660. /*
  31661. * Licensed to the Apache Software Foundation (ASF) under one
  31662. * or more contributor license agreements. See the NOTICE file
  31663. * distributed with this work for additional information
  31664. * regarding copyright ownership. The ASF licenses this file
  31665. * to you under the Apache License, Version 2.0 (the
  31666. * "License"); you may not use this file except in compliance
  31667. * with the License. You may obtain a copy of the License at
  31668. *
  31669. * http://www.apache.org/licenses/LICENSE-2.0
  31670. *
  31671. * Unless required by applicable law or agreed to in writing,
  31672. * software distributed under the License is distributed on an
  31673. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31674. * KIND, either express or implied. See the License for the
  31675. * specific language governing permissions and limitations
  31676. * under the License.
  31677. */
  31678. /**
  31679. * Extend axis 2d
  31680. * @constructor module:echarts/coord/cartesian/Axis2D
  31681. * @extends {module:echarts/coord/cartesian/Axis}
  31682. * @param {string} dim
  31683. * @param {*} scale
  31684. * @param {Array.<number>} coordExtent
  31685. * @param {string} axisType
  31686. * @param {string} position
  31687. */
  31688. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  31689. Axis.call(this, dim, scale, coordExtent);
  31690. /**
  31691. * Axis type
  31692. * - 'category'
  31693. * - 'value'
  31694. * - 'time'
  31695. * - 'log'
  31696. * @type {string}
  31697. */
  31698. this.type = axisType || 'value';
  31699. /**
  31700. * Axis position
  31701. * - 'top'
  31702. * - 'bottom'
  31703. * - 'left'
  31704. * - 'right'
  31705. */
  31706. this.position = position || 'bottom';
  31707. };
  31708. Axis2D.prototype = {
  31709. constructor: Axis2D,
  31710. /**
  31711. * Index of axis, can be used as key
  31712. */
  31713. index: 0,
  31714. /**
  31715. * Implemented in <module:echarts/coord/cartesian/Grid>.
  31716. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  31717. * If not on zero of other axis, return null/undefined.
  31718. * If no axes, return an empty array.
  31719. */
  31720. getAxesOnZeroOf: null,
  31721. /**
  31722. * Axis model
  31723. * @param {module:echarts/coord/cartesian/AxisModel}
  31724. */
  31725. model: null,
  31726. isHorizontal: function () {
  31727. var position = this.position;
  31728. return position === 'top' || position === 'bottom';
  31729. },
  31730. /**
  31731. * Each item cooresponds to this.getExtent(), which
  31732. * means globalExtent[0] may greater than globalExtent[1],
  31733. * unless `asc` is input.
  31734. *
  31735. * @param {boolean} [asc]
  31736. * @return {Array.<number>}
  31737. */
  31738. getGlobalExtent: function (asc) {
  31739. var ret = this.getExtent();
  31740. ret[0] = this.toGlobalCoord(ret[0]);
  31741. ret[1] = this.toGlobalCoord(ret[1]);
  31742. asc && ret[0] > ret[1] && ret.reverse();
  31743. return ret;
  31744. },
  31745. getOtherAxis: function () {
  31746. this.grid.getOtherAxis();
  31747. },
  31748. /**
  31749. * @override
  31750. */
  31751. pointToData: function (point, clamp) {
  31752. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  31753. },
  31754. /**
  31755. * Transform global coord to local coord,
  31756. * i.e. var localCoord = axis.toLocalCoord(80);
  31757. * designate by module:echarts/coord/cartesian/Grid.
  31758. * @type {Function}
  31759. */
  31760. toLocalCoord: null,
  31761. /**
  31762. * Transform global coord to local coord,
  31763. * i.e. var globalCoord = axis.toLocalCoord(40);
  31764. * designate by module:echarts/coord/cartesian/Grid.
  31765. * @type {Function}
  31766. */
  31767. toGlobalCoord: null
  31768. };
  31769. inherits(Axis2D, Axis);
  31770. /*
  31771. * Licensed to the Apache Software Foundation (ASF) under one
  31772. * or more contributor license agreements. See the NOTICE file
  31773. * distributed with this work for additional information
  31774. * regarding copyright ownership. The ASF licenses this file
  31775. * to you under the Apache License, Version 2.0 (the
  31776. * "License"); you may not use this file except in compliance
  31777. * with the License. You may obtain a copy of the License at
  31778. *
  31779. * http://www.apache.org/licenses/LICENSE-2.0
  31780. *
  31781. * Unless required by applicable law or agreed to in writing,
  31782. * software distributed under the License is distributed on an
  31783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31784. * KIND, either express or implied. See the License for the
  31785. * specific language governing permissions and limitations
  31786. * under the License.
  31787. */
  31788. var defaultOption = {
  31789. show: true,
  31790. zlevel: 0,
  31791. z: 0,
  31792. // Inverse the axis.
  31793. inverse: false,
  31794. // Axis name displayed.
  31795. name: '',
  31796. // 'start' | 'middle' | 'end'
  31797. nameLocation: 'end',
  31798. // By degree. By defualt auto rotate by nameLocation.
  31799. nameRotate: null,
  31800. nameTruncate: {
  31801. maxWidth: null,
  31802. ellipsis: '...',
  31803. placeholder: '.'
  31804. },
  31805. // Use global text style by default.
  31806. nameTextStyle: {},
  31807. // The gap between axisName and axisLine.
  31808. nameGap: 15,
  31809. // Default `false` to support tooltip.
  31810. silent: false,
  31811. // Default `false` to avoid legacy user event listener fail.
  31812. triggerEvent: false,
  31813. tooltip: {
  31814. show: false
  31815. },
  31816. axisPointer: {},
  31817. axisLine: {
  31818. show: true,
  31819. onZero: true,
  31820. onZeroAxisIndex: null,
  31821. lineStyle: {
  31822. color: '#333',
  31823. width: 1,
  31824. type: 'solid'
  31825. },
  31826. // The arrow at both ends the the axis.
  31827. symbol: ['none', 'none'],
  31828. symbolSize: [10, 15]
  31829. },
  31830. axisTick: {
  31831. show: true,
  31832. // Whether axisTick is inside the grid or outside the grid.
  31833. inside: false,
  31834. // The length of axisTick.
  31835. length: 5,
  31836. lineStyle: {
  31837. width: 1
  31838. }
  31839. },
  31840. axisLabel: {
  31841. show: true,
  31842. // Whether axisLabel is inside the grid or outside the grid.
  31843. inside: false,
  31844. rotate: 0,
  31845. // true | false | null/undefined (auto)
  31846. showMinLabel: null,
  31847. // true | false | null/undefined (auto)
  31848. showMaxLabel: null,
  31849. margin: 8,
  31850. // formatter: null,
  31851. fontSize: 12
  31852. },
  31853. splitLine: {
  31854. show: true,
  31855. lineStyle: {
  31856. color: ['#ccc'],
  31857. width: 1,
  31858. type: 'solid'
  31859. }
  31860. },
  31861. splitArea: {
  31862. show: false,
  31863. areaStyle: {
  31864. color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)']
  31865. }
  31866. }
  31867. };
  31868. var axisDefault = {};
  31869. axisDefault.categoryAxis = merge({
  31870. // The gap at both ends of the axis. For categoryAxis, boolean.
  31871. boundaryGap: true,
  31872. // Set false to faster category collection.
  31873. // Only usefull in the case like: category is
  31874. // ['2012-01-01', '2012-01-02', ...], where the input
  31875. // data has been ensured not duplicate and is large data.
  31876. // null means "auto":
  31877. // if axis.data provided, do not deduplication,
  31878. // else do deduplication.
  31879. deduplication: null,
  31880. // splitArea: {
  31881. // show: false
  31882. // },
  31883. splitLine: {
  31884. show: false
  31885. },
  31886. axisTick: {
  31887. // If tick is align with label when boundaryGap is true
  31888. alignWithLabel: false,
  31889. interval: 'auto'
  31890. },
  31891. axisLabel: {
  31892. interval: 'auto'
  31893. }
  31894. }, defaultOption);
  31895. axisDefault.valueAxis = merge({
  31896. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  31897. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  31898. boundaryGap: [0, 0],
  31899. // TODO
  31900. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  31901. // Min value of the axis. can be:
  31902. // + a number
  31903. // + 'dataMin': use the min value in data.
  31904. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  31905. // min: null,
  31906. // Max value of the axis. can be:
  31907. // + a number
  31908. // + 'dataMax': use the max value in data.
  31909. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  31910. // max: null,
  31911. // Readonly prop, specifies start value of the range when using data zoom.
  31912. // rangeStart: null
  31913. // Readonly prop, specifies end value of the range when using data zoom.
  31914. // rangeEnd: null
  31915. // Optional value can be:
  31916. // + `false`: always include value 0.
  31917. // + `true`: the extent do not consider value 0.
  31918. // scale: false,
  31919. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  31920. splitNumber: 5
  31921. // Interval specifies the span of the ticks is mandatorily.
  31922. // interval: null
  31923. // Specify min interval when auto calculate tick interval.
  31924. // minInterval: null
  31925. // Specify max interval when auto calculate tick interval.
  31926. // maxInterval: null
  31927. }, defaultOption);
  31928. axisDefault.timeAxis = defaults({
  31929. scale: true,
  31930. min: 'dataMin',
  31931. max: 'dataMax'
  31932. }, axisDefault.valueAxis);
  31933. axisDefault.logAxis = defaults({
  31934. scale: true,
  31935. logBase: 10
  31936. }, axisDefault.valueAxis);
  31937. /*
  31938. * Licensed to the Apache Software Foundation (ASF) under one
  31939. * or more contributor license agreements. See the NOTICE file
  31940. * distributed with this work for additional information
  31941. * regarding copyright ownership. The ASF licenses this file
  31942. * to you under the Apache License, Version 2.0 (the
  31943. * "License"); you may not use this file except in compliance
  31944. * with the License. You may obtain a copy of the License at
  31945. *
  31946. * http://www.apache.org/licenses/LICENSE-2.0
  31947. *
  31948. * Unless required by applicable law or agreed to in writing,
  31949. * software distributed under the License is distributed on an
  31950. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31951. * KIND, either express or implied. See the License for the
  31952. * specific language governing permissions and limitations
  31953. * under the License.
  31954. */
  31955. // FIXME axisType is fixed ?
  31956. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  31957. /**
  31958. * Generate sub axis model class
  31959. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  31960. * @param {module:echarts/model/Component} BaseAxisModelClass
  31961. * @param {Function} axisTypeDefaulter
  31962. * @param {Object} [extraDefaultOption]
  31963. */
  31964. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  31965. each$1(AXIS_TYPES, function (axisType) {
  31966. BaseAxisModelClass.extend({
  31967. /**
  31968. * @readOnly
  31969. */
  31970. type: axisName + 'Axis.' + axisType,
  31971. mergeDefaultAndTheme: function (option, ecModel) {
  31972. var layoutMode = this.layoutMode;
  31973. var inputPositionParams = layoutMode
  31974. ? getLayoutParams(option) : {};
  31975. var themeModel = ecModel.getTheme();
  31976. merge(option, themeModel.get(axisType + 'Axis'));
  31977. merge(option, this.getDefaultOption());
  31978. option.type = axisTypeDefaulter(axisName, option);
  31979. if (layoutMode) {
  31980. mergeLayoutParam(option, inputPositionParams, layoutMode);
  31981. }
  31982. },
  31983. /**
  31984. * @override
  31985. */
  31986. optionUpdated: function () {
  31987. var thisOption = this.option;
  31988. if (thisOption.type === 'category') {
  31989. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  31990. }
  31991. },
  31992. /**
  31993. * Should not be called before all of 'getInitailData' finished.
  31994. * Because categories are collected during initializing data.
  31995. */
  31996. getCategories: function (rawData) {
  31997. var option = this.option;
  31998. // FIXME
  31999. // warning if called before all of 'getInitailData' finished.
  32000. if (option.type === 'category') {
  32001. if (rawData) {
  32002. return option.data;
  32003. }
  32004. return this.__ordinalMeta.categories;
  32005. }
  32006. },
  32007. getOrdinalMeta: function () {
  32008. return this.__ordinalMeta;
  32009. },
  32010. defaultOption: mergeAll(
  32011. [
  32012. {},
  32013. axisDefault[axisType + 'Axis'],
  32014. extraDefaultOption
  32015. ],
  32016. true
  32017. )
  32018. });
  32019. });
  32020. ComponentModel.registerSubTypeDefaulter(
  32021. axisName + 'Axis',
  32022. curry(axisTypeDefaulter, axisName)
  32023. );
  32024. };
  32025. /*
  32026. * Licensed to the Apache Software Foundation (ASF) under one
  32027. * or more contributor license agreements. See the NOTICE file
  32028. * distributed with this work for additional information
  32029. * regarding copyright ownership. The ASF licenses this file
  32030. * to you under the Apache License, Version 2.0 (the
  32031. * "License"); you may not use this file except in compliance
  32032. * with the License. You may obtain a copy of the License at
  32033. *
  32034. * http://www.apache.org/licenses/LICENSE-2.0
  32035. *
  32036. * Unless required by applicable law or agreed to in writing,
  32037. * software distributed under the License is distributed on an
  32038. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32039. * KIND, either express or implied. See the License for the
  32040. * specific language governing permissions and limitations
  32041. * under the License.
  32042. */
  32043. var AxisModel = ComponentModel.extend({
  32044. type: 'cartesian2dAxis',
  32045. /**
  32046. * @type {module:echarts/coord/cartesian/Axis2D}
  32047. */
  32048. axis: null,
  32049. /**
  32050. * @override
  32051. */
  32052. init: function () {
  32053. AxisModel.superApply(this, 'init', arguments);
  32054. this.resetRange();
  32055. },
  32056. /**
  32057. * @override
  32058. */
  32059. mergeOption: function () {
  32060. AxisModel.superApply(this, 'mergeOption', arguments);
  32061. this.resetRange();
  32062. },
  32063. /**
  32064. * @override
  32065. */
  32066. restoreData: function () {
  32067. AxisModel.superApply(this, 'restoreData', arguments);
  32068. this.resetRange();
  32069. },
  32070. /**
  32071. * @override
  32072. * @return {module:echarts/model/Component}
  32073. */
  32074. getCoordSysModel: function () {
  32075. return this.ecModel.queryComponents({
  32076. mainType: 'grid',
  32077. index: this.option.gridIndex,
  32078. id: this.option.gridId
  32079. })[0];
  32080. }
  32081. });
  32082. function getAxisType(axisDim, option) {
  32083. // Default axis with data is category axis
  32084. return option.type || (option.data ? 'category' : 'value');
  32085. }
  32086. merge(AxisModel.prototype, axisModelCommonMixin);
  32087. var extraOption = {
  32088. // gridIndex: 0,
  32089. // gridId: '',
  32090. // Offset is for multiple axis on the same position
  32091. offset: 0
  32092. };
  32093. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  32094. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  32095. /*
  32096. * Licensed to the Apache Software Foundation (ASF) under one
  32097. * or more contributor license agreements. See the NOTICE file
  32098. * distributed with this work for additional information
  32099. * regarding copyright ownership. The ASF licenses this file
  32100. * to you under the Apache License, Version 2.0 (the
  32101. * "License"); you may not use this file except in compliance
  32102. * with the License. You may obtain a copy of the License at
  32103. *
  32104. * http://www.apache.org/licenses/LICENSE-2.0
  32105. *
  32106. * Unless required by applicable law or agreed to in writing,
  32107. * software distributed under the License is distributed on an
  32108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32109. * KIND, either express or implied. See the License for the
  32110. * specific language governing permissions and limitations
  32111. * under the License.
  32112. */
  32113. // Grid 是在有直角坐标系的时候必须要存在的
  32114. // 所以这里也要被 Cartesian2D 依赖
  32115. ComponentModel.extend({
  32116. type: 'grid',
  32117. dependencies: ['xAxis', 'yAxis'],
  32118. layoutMode: 'box',
  32119. /**
  32120. * @type {module:echarts/coord/cartesian/Grid}
  32121. */
  32122. coordinateSystem: null,
  32123. defaultOption: {
  32124. show: false,
  32125. zlevel: 0,
  32126. z: 0,
  32127. left: '10%',
  32128. top: 60,
  32129. right: '10%',
  32130. bottom: 60,
  32131. // If grid size contain label
  32132. containLabel: false,
  32133. // width: {totalWidth} - left - right,
  32134. // height: {totalHeight} - top - bottom,
  32135. backgroundColor: 'rgba(0,0,0,0)',
  32136. borderWidth: 1,
  32137. borderColor: '#ccc'
  32138. }
  32139. });
  32140. /*
  32141. * Licensed to the Apache Software Foundation (ASF) under one
  32142. * or more contributor license agreements. See the NOTICE file
  32143. * distributed with this work for additional information
  32144. * regarding copyright ownership. The ASF licenses this file
  32145. * to you under the Apache License, Version 2.0 (the
  32146. * "License"); you may not use this file except in compliance
  32147. * with the License. You may obtain a copy of the License at
  32148. *
  32149. * http://www.apache.org/licenses/LICENSE-2.0
  32150. *
  32151. * Unless required by applicable law or agreed to in writing,
  32152. * software distributed under the License is distributed on an
  32153. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32154. * KIND, either express or implied. See the License for the
  32155. * specific language governing permissions and limitations
  32156. * under the License.
  32157. */
  32158. /**
  32159. * Grid is a region which contains at most 4 cartesian systems
  32160. *
  32161. * TODO Default cartesian
  32162. */
  32163. // Depends on GridModel, AxisModel, which performs preprocess.
  32164. /**
  32165. * Check if the axis is used in the specified grid
  32166. * @inner
  32167. */
  32168. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  32169. return axisModel.getCoordSysModel() === gridModel;
  32170. }
  32171. function Grid(gridModel, ecModel, api) {
  32172. /**
  32173. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  32174. * @private
  32175. */
  32176. this._coordsMap = {};
  32177. /**
  32178. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  32179. * @private
  32180. */
  32181. this._coordsList = [];
  32182. /**
  32183. * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>}
  32184. * @private
  32185. */
  32186. this._axesMap = {};
  32187. /**
  32188. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  32189. * @private
  32190. */
  32191. this._axesList = [];
  32192. this._initCartesian(gridModel, ecModel, api);
  32193. this.model = gridModel;
  32194. }
  32195. var gridProto = Grid.prototype;
  32196. gridProto.type = 'grid';
  32197. gridProto.axisPointerEnabled = true;
  32198. gridProto.getRect = function () {
  32199. return this._rect;
  32200. };
  32201. gridProto.update = function (ecModel, api) {
  32202. var axesMap = this._axesMap;
  32203. this._updateScale(ecModel, this.model);
  32204. each$1(axesMap.x, function (xAxis) {
  32205. niceScaleExtent(xAxis.scale, xAxis.model);
  32206. });
  32207. each$1(axesMap.y, function (yAxis) {
  32208. niceScaleExtent(yAxis.scale, yAxis.model);
  32209. });
  32210. each$1(axesMap.x, function (xAxis) {
  32211. fixAxisOnZero(axesMap, 'y', xAxis);
  32212. });
  32213. each$1(axesMap.y, function (yAxis) {
  32214. fixAxisOnZero(axesMap, 'x', yAxis);
  32215. });
  32216. // Resize again if containLabel is enabled
  32217. // FIXME It may cause getting wrong grid size in data processing stage
  32218. this.resize(this.model, api);
  32219. };
  32220. function fixAxisOnZero(axesMap, otherAxisDim, axis) {
  32221. axis.getAxesOnZeroOf = function () {
  32222. // TODO: onZero of multiple axes.
  32223. return otherAxis ? [otherAxis] : [];
  32224. };
  32225. // onZero can not be enabled in these two situations:
  32226. // 1. When any other axis is a category axis.
  32227. // 2. When no axis is cross 0 point.
  32228. var otherAxes = axesMap[otherAxisDim];
  32229. var otherAxis;
  32230. var axisModel = axis.model;
  32231. var onZero = axisModel.get('axisLine.onZero');
  32232. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  32233. if (!onZero) {
  32234. return;
  32235. }
  32236. // If target axis is specified.
  32237. if (onZeroAxisIndex != null) {
  32238. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  32239. otherAxis = otherAxes[onZeroAxisIndex];
  32240. }
  32241. return;
  32242. }
  32243. // Find the first available other axis.
  32244. for (var idx in otherAxes) {
  32245. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx])) {
  32246. otherAxis = otherAxes[idx];
  32247. break;
  32248. }
  32249. }
  32250. }
  32251. function canOnZeroToAxis(axis) {
  32252. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  32253. }
  32254. /**
  32255. * Resize the grid
  32256. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  32257. * @param {module:echarts/ExtensionAPI} api
  32258. */
  32259. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  32260. var gridRect = getLayoutRect(
  32261. gridModel.getBoxLayoutParams(), {
  32262. width: api.getWidth(),
  32263. height: api.getHeight()
  32264. });
  32265. this._rect = gridRect;
  32266. var axesList = this._axesList;
  32267. adjustAxes();
  32268. // Minus label size
  32269. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  32270. each$1(axesList, function (axis) {
  32271. if (!axis.model.get('axisLabel.inside')) {
  32272. var labelUnionRect = estimateLabelUnionRect(axis);
  32273. if (labelUnionRect) {
  32274. var dim = axis.isHorizontal() ? 'height' : 'width';
  32275. var margin = axis.model.get('axisLabel.margin');
  32276. gridRect[dim] -= labelUnionRect[dim] + margin;
  32277. if (axis.position === 'top') {
  32278. gridRect.y += labelUnionRect.height + margin;
  32279. }
  32280. else if (axis.position === 'left') {
  32281. gridRect.x += labelUnionRect.width + margin;
  32282. }
  32283. }
  32284. }
  32285. });
  32286. adjustAxes();
  32287. }
  32288. function adjustAxes() {
  32289. each$1(axesList, function (axis) {
  32290. var isHorizontal = axis.isHorizontal();
  32291. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  32292. var idx = axis.inverse ? 1 : 0;
  32293. axis.setExtent(extent[idx], extent[1 - idx]);
  32294. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  32295. });
  32296. }
  32297. };
  32298. /**
  32299. * @param {string} axisType
  32300. * @param {number} [axisIndex]
  32301. */
  32302. gridProto.getAxis = function (axisType, axisIndex) {
  32303. var axesMapOnDim = this._axesMap[axisType];
  32304. if (axesMapOnDim != null) {
  32305. if (axisIndex == null) {
  32306. // Find first axis
  32307. for (var name in axesMapOnDim) {
  32308. if (axesMapOnDim.hasOwnProperty(name)) {
  32309. return axesMapOnDim[name];
  32310. }
  32311. }
  32312. }
  32313. return axesMapOnDim[axisIndex];
  32314. }
  32315. };
  32316. /**
  32317. * @return {Array.<module:echarts/coord/Axis>}
  32318. */
  32319. gridProto.getAxes = function () {
  32320. return this._axesList.slice();
  32321. };
  32322. /**
  32323. * Usage:
  32324. * grid.getCartesian(xAxisIndex, yAxisIndex);
  32325. * grid.getCartesian(xAxisIndex);
  32326. * grid.getCartesian(null, yAxisIndex);
  32327. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  32328. *
  32329. * @param {number|Object} [xAxisIndex]
  32330. * @param {number} [yAxisIndex]
  32331. */
  32332. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  32333. if (xAxisIndex != null && yAxisIndex != null) {
  32334. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32335. return this._coordsMap[key];
  32336. }
  32337. if (isObject$1(xAxisIndex)) {
  32338. yAxisIndex = xAxisIndex.yAxisIndex;
  32339. xAxisIndex = xAxisIndex.xAxisIndex;
  32340. }
  32341. // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  32342. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  32343. if (coordList[i].getAxis('x').index === xAxisIndex
  32344. || coordList[i].getAxis('y').index === yAxisIndex
  32345. ) {
  32346. return coordList[i];
  32347. }
  32348. }
  32349. };
  32350. gridProto.getCartesians = function () {
  32351. return this._coordsList.slice();
  32352. };
  32353. /**
  32354. * @implements
  32355. * see {module:echarts/CoodinateSystem}
  32356. */
  32357. gridProto.convertToPixel = function (ecModel, finder, value) {
  32358. var target = this._findConvertTarget(ecModel, finder);
  32359. return target.cartesian
  32360. ? target.cartesian.dataToPoint(value)
  32361. : target.axis
  32362. ? target.axis.toGlobalCoord(target.axis.dataToCoord(value))
  32363. : null;
  32364. };
  32365. /**
  32366. * @implements
  32367. * see {module:echarts/CoodinateSystem}
  32368. */
  32369. gridProto.convertFromPixel = function (ecModel, finder, value) {
  32370. var target = this._findConvertTarget(ecModel, finder);
  32371. return target.cartesian
  32372. ? target.cartesian.pointToData(value)
  32373. : target.axis
  32374. ? target.axis.coordToData(target.axis.toLocalCoord(value))
  32375. : null;
  32376. };
  32377. /**
  32378. * @inner
  32379. */
  32380. gridProto._findConvertTarget = function (ecModel, finder) {
  32381. var seriesModel = finder.seriesModel;
  32382. var xAxisModel = finder.xAxisModel
  32383. || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]);
  32384. var yAxisModel = finder.yAxisModel
  32385. || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]);
  32386. var gridModel = finder.gridModel;
  32387. var coordsList = this._coordsList;
  32388. var cartesian;
  32389. var axis;
  32390. if (seriesModel) {
  32391. cartesian = seriesModel.coordinateSystem;
  32392. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  32393. }
  32394. else if (xAxisModel && yAxisModel) {
  32395. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  32396. }
  32397. else if (xAxisModel) {
  32398. axis = this.getAxis('x', xAxisModel.componentIndex);
  32399. }
  32400. else if (yAxisModel) {
  32401. axis = this.getAxis('y', yAxisModel.componentIndex);
  32402. }
  32403. // Lowest priority.
  32404. else if (gridModel) {
  32405. var grid = gridModel.coordinateSystem;
  32406. if (grid === this) {
  32407. cartesian = this._coordsList[0];
  32408. }
  32409. }
  32410. return {cartesian: cartesian, axis: axis};
  32411. };
  32412. /**
  32413. * @implements
  32414. * see {module:echarts/CoodinateSystem}
  32415. */
  32416. gridProto.containPoint = function (point) {
  32417. var coord = this._coordsList[0];
  32418. if (coord) {
  32419. return coord.containPoint(point);
  32420. }
  32421. };
  32422. /**
  32423. * Initialize cartesian coordinate systems
  32424. * @private
  32425. */
  32426. gridProto._initCartesian = function (gridModel, ecModel, api) {
  32427. var axisPositionUsed = {
  32428. left: false,
  32429. right: false,
  32430. top: false,
  32431. bottom: false
  32432. };
  32433. var axesMap = {
  32434. x: {},
  32435. y: {}
  32436. };
  32437. var axesCount = {
  32438. x: 0,
  32439. y: 0
  32440. };
  32441. /// Create axis
  32442. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  32443. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  32444. if (!axesCount.x || !axesCount.y) {
  32445. // Roll back when there no either x or y axis
  32446. this._axesMap = {};
  32447. this._axesList = [];
  32448. return;
  32449. }
  32450. this._axesMap = axesMap;
  32451. /// Create cartesian2d
  32452. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  32453. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  32454. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  32455. var cartesian = new Cartesian2D(key);
  32456. cartesian.grid = this;
  32457. cartesian.model = gridModel;
  32458. this._coordsMap[key] = cartesian;
  32459. this._coordsList.push(cartesian);
  32460. cartesian.addAxis(xAxis);
  32461. cartesian.addAxis(yAxis);
  32462. }, this);
  32463. }, this);
  32464. function createAxisCreator(axisType) {
  32465. return function (axisModel, idx) {
  32466. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  32467. return;
  32468. }
  32469. var axisPosition = axisModel.get('position');
  32470. if (axisType === 'x') {
  32471. // Fix position
  32472. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  32473. // Default bottom of X
  32474. axisPosition = 'bottom';
  32475. if (axisPositionUsed[axisPosition]) {
  32476. axisPosition = axisPosition === 'top' ? 'bottom' : 'top';
  32477. }
  32478. }
  32479. }
  32480. else {
  32481. // Fix position
  32482. if (axisPosition !== 'left' && axisPosition !== 'right') {
  32483. // Default left of Y
  32484. axisPosition = 'left';
  32485. if (axisPositionUsed[axisPosition]) {
  32486. axisPosition = axisPosition === 'left' ? 'right' : 'left';
  32487. }
  32488. }
  32489. }
  32490. axisPositionUsed[axisPosition] = true;
  32491. var axis = new Axis2D(
  32492. axisType, createScaleByModel(axisModel),
  32493. [0, 0],
  32494. axisModel.get('type'),
  32495. axisPosition
  32496. );
  32497. var isCategory = axis.type === 'category';
  32498. axis.onBand = isCategory && axisModel.get('boundaryGap');
  32499. axis.inverse = axisModel.get('inverse');
  32500. // Inject axis into axisModel
  32501. axisModel.axis = axis;
  32502. // Inject axisModel into axis
  32503. axis.model = axisModel;
  32504. // Inject grid info axis
  32505. axis.grid = this;
  32506. // Index of axis, can be used as key
  32507. axis.index = idx;
  32508. this._axesList.push(axis);
  32509. axesMap[axisType][idx] = axis;
  32510. axesCount[axisType]++;
  32511. };
  32512. }
  32513. };
  32514. /**
  32515. * Update cartesian properties from series
  32516. * @param {module:echarts/model/Option} option
  32517. * @private
  32518. */
  32519. gridProto._updateScale = function (ecModel, gridModel) {
  32520. // Reset scale
  32521. each$1(this._axesList, function (axis) {
  32522. axis.scale.setExtent(Infinity, -Infinity);
  32523. });
  32524. ecModel.eachSeries(function (seriesModel) {
  32525. if (isCartesian2D(seriesModel)) {
  32526. var axesModels = findAxesModels(seriesModel, ecModel);
  32527. var xAxisModel = axesModels[0];
  32528. var yAxisModel = axesModels[1];
  32529. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel)
  32530. || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)
  32531. ) {
  32532. return;
  32533. }
  32534. var cartesian = this.getCartesian(
  32535. xAxisModel.componentIndex, yAxisModel.componentIndex
  32536. );
  32537. var data = seriesModel.getData();
  32538. var xAxis = cartesian.getAxis('x');
  32539. var yAxis = cartesian.getAxis('y');
  32540. if (data.type === 'list') {
  32541. unionExtent(data, xAxis, seriesModel);
  32542. unionExtent(data, yAxis, seriesModel);
  32543. }
  32544. }
  32545. }, this);
  32546. function unionExtent(data, axis, seriesModel) {
  32547. each$1(data.mapDimension(axis.dim, true), function (dim) {
  32548. axis.scale.unionExtentFromData(
  32549. // For example, the extent of the orginal dimension
  32550. // is [0.1, 0.5], the extent of the `stackResultDimension`
  32551. // is [7, 9], the final extent should not include [0.1, 0.5].
  32552. data, getStackedDimension(data, dim)
  32553. );
  32554. });
  32555. }
  32556. };
  32557. /**
  32558. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  32559. * @return {Object} {baseAxes: [], otherAxes: []}
  32560. */
  32561. gridProto.getTooltipAxes = function (dim) {
  32562. var baseAxes = [];
  32563. var otherAxes = [];
  32564. each$1(this.getCartesians(), function (cartesian) {
  32565. var baseAxis = (dim != null && dim !== 'auto')
  32566. ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  32567. var otherAxis = cartesian.getOtherAxis(baseAxis);
  32568. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  32569. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  32570. });
  32571. return {baseAxes: baseAxes, otherAxes: otherAxes};
  32572. };
  32573. /**
  32574. * @inner
  32575. */
  32576. function updateAxisTransform(axis, coordBase) {
  32577. var axisExtent = axis.getExtent();
  32578. var axisExtentSum = axisExtent[0] + axisExtent[1];
  32579. // Fast transform
  32580. axis.toGlobalCoord = axis.dim === 'x'
  32581. ? function (coord) {
  32582. return coord + coordBase;
  32583. }
  32584. : function (coord) {
  32585. return axisExtentSum - coord + coordBase;
  32586. };
  32587. axis.toLocalCoord = axis.dim === 'x'
  32588. ? function (coord) {
  32589. return coord - coordBase;
  32590. }
  32591. : function (coord) {
  32592. return axisExtentSum - coord + coordBase;
  32593. };
  32594. }
  32595. var axesTypes = ['xAxis', 'yAxis'];
  32596. /**
  32597. * @inner
  32598. */
  32599. function findAxesModels(seriesModel, ecModel) {
  32600. return map(axesTypes, function (axisType) {
  32601. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  32602. if (__DEV__) {
  32603. if (!axisModel) {
  32604. throw new Error(axisType + ' "' + retrieve(
  32605. seriesModel.get(axisType + 'Index'),
  32606. seriesModel.get(axisType + 'Id'),
  32607. 0
  32608. ) + '" not found');
  32609. }
  32610. }
  32611. return axisModel;
  32612. });
  32613. }
  32614. /**
  32615. * @inner
  32616. */
  32617. function isCartesian2D(seriesModel) {
  32618. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  32619. }
  32620. Grid.create = function (ecModel, api) {
  32621. var grids = [];
  32622. ecModel.eachComponent('grid', function (gridModel, idx) {
  32623. var grid = new Grid(gridModel, ecModel, api);
  32624. grid.name = 'grid_' + idx;
  32625. // dataSampling requires axis extent, so resize
  32626. // should be performed in create stage.
  32627. grid.resize(gridModel, api, true);
  32628. gridModel.coordinateSystem = grid;
  32629. grids.push(grid);
  32630. });
  32631. // Inject the coordinateSystems into seriesModel
  32632. ecModel.eachSeries(function (seriesModel) {
  32633. if (!isCartesian2D(seriesModel)) {
  32634. return;
  32635. }
  32636. var axesModels = findAxesModels(seriesModel, ecModel);
  32637. var xAxisModel = axesModels[0];
  32638. var yAxisModel = axesModels[1];
  32639. var gridModel = xAxisModel.getCoordSysModel();
  32640. if (__DEV__) {
  32641. if (!gridModel) {
  32642. throw new Error(
  32643. 'Grid "' + retrieve(
  32644. xAxisModel.get('gridIndex'),
  32645. xAxisModel.get('gridId'),
  32646. 0
  32647. ) + '" not found'
  32648. );
  32649. }
  32650. if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) {
  32651. throw new Error('xAxis and yAxis must use the same grid');
  32652. }
  32653. }
  32654. var grid = gridModel.coordinateSystem;
  32655. seriesModel.coordinateSystem = grid.getCartesian(
  32656. xAxisModel.componentIndex, yAxisModel.componentIndex
  32657. );
  32658. });
  32659. return grids;
  32660. };
  32661. // For deciding which dimensions to use when creating list data
  32662. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  32663. CoordinateSystemManager.register('cartesian2d', Grid);
  32664. /*
  32665. * Licensed to the Apache Software Foundation (ASF) under one
  32666. * or more contributor license agreements. See the NOTICE file
  32667. * distributed with this work for additional information
  32668. * regarding copyright ownership. The ASF licenses this file
  32669. * to you under the Apache License, Version 2.0 (the
  32670. * "License"); you may not use this file except in compliance
  32671. * with the License. You may obtain a copy of the License at
  32672. *
  32673. * http://www.apache.org/licenses/LICENSE-2.0
  32674. *
  32675. * Unless required by applicable law or agreed to in writing,
  32676. * software distributed under the License is distributed on an
  32677. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32678. * KIND, either express or implied. See the License for the
  32679. * specific language governing permissions and limitations
  32680. * under the License.
  32681. */
  32682. var PI$2 = Math.PI;
  32683. function makeAxisEventDataBase(axisModel) {
  32684. var eventData = {
  32685. componentType: axisModel.mainType
  32686. };
  32687. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  32688. return eventData;
  32689. }
  32690. /**
  32691. * A final axis is translated and rotated from a "standard axis".
  32692. * So opt.position and opt.rotation is required.
  32693. *
  32694. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  32695. * for example: (0, 0) ------------> (0, 50)
  32696. *
  32697. * nameDirection or tickDirection or labelDirection is 1 means tick
  32698. * or label is below the standard axis, whereas is -1 means above
  32699. * the standard axis. labelOffset means offset between label and axis,
  32700. * which is useful when 'onZero', where axisLabel is in the grid and
  32701. * label in outside grid.
  32702. *
  32703. * Tips: like always,
  32704. * positive rotation represents anticlockwise, and negative rotation
  32705. * represents clockwise.
  32706. * The direction of position coordinate is the same as the direction
  32707. * of screen coordinate.
  32708. *
  32709. * Do not need to consider axis 'inverse', which is auto processed by
  32710. * axis extent.
  32711. *
  32712. * @param {module:zrender/container/Group} group
  32713. * @param {Object} axisModel
  32714. * @param {Object} opt Standard axis parameters.
  32715. * @param {Array.<number>} opt.position [x, y]
  32716. * @param {number} opt.rotation by radian
  32717. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  32718. * @param {number} [opt.tickDirection=1] 1 or -1
  32719. * @param {number} [opt.labelDirection=1] 1 or -1
  32720. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  32721. * @param {string} [opt.axisLabelShow] default get from axisModel.
  32722. * @param {string} [opt.axisName] default get from axisModel.
  32723. * @param {number} [opt.axisNameAvailableWidth]
  32724. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  32725. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  32726. * @param {number} [opt.nameTruncateMaxWidth]
  32727. */
  32728. var AxisBuilder = function (axisModel, opt) {
  32729. /**
  32730. * @readOnly
  32731. */
  32732. this.opt = opt;
  32733. /**
  32734. * @readOnly
  32735. */
  32736. this.axisModel = axisModel;
  32737. // Default value
  32738. defaults(
  32739. opt,
  32740. {
  32741. labelOffset: 0,
  32742. nameDirection: 1,
  32743. tickDirection: 1,
  32744. labelDirection: 1,
  32745. silent: true
  32746. }
  32747. );
  32748. /**
  32749. * @readOnly
  32750. */
  32751. this.group = new Group();
  32752. // FIXME Not use a seperate text group?
  32753. var dumbGroup = new Group({
  32754. position: opt.position.slice(),
  32755. rotation: opt.rotation
  32756. });
  32757. // this.group.add(dumbGroup);
  32758. // this._dumbGroup = dumbGroup;
  32759. dumbGroup.updateTransform();
  32760. this._transform = dumbGroup.transform;
  32761. this._dumbGroup = dumbGroup;
  32762. };
  32763. AxisBuilder.prototype = {
  32764. constructor: AxisBuilder,
  32765. hasBuilder: function (name) {
  32766. return !!builders[name];
  32767. },
  32768. add: function (name) {
  32769. builders[name].call(this);
  32770. },
  32771. getGroup: function () {
  32772. return this.group;
  32773. }
  32774. };
  32775. var builders = {
  32776. /**
  32777. * @private
  32778. */
  32779. axisLine: function () {
  32780. var opt = this.opt;
  32781. var axisModel = this.axisModel;
  32782. if (!axisModel.get('axisLine.show')) {
  32783. return;
  32784. }
  32785. var extent = this.axisModel.axis.getExtent();
  32786. var matrix = this._transform;
  32787. var pt1 = [extent[0], 0];
  32788. var pt2 = [extent[1], 0];
  32789. if (matrix) {
  32790. applyTransform(pt1, pt1, matrix);
  32791. applyTransform(pt2, pt2, matrix);
  32792. }
  32793. var lineStyle = extend(
  32794. {
  32795. lineCap: 'round'
  32796. },
  32797. axisModel.getModel('axisLine.lineStyle').getLineStyle()
  32798. );
  32799. this.group.add(new Line(subPixelOptimizeLine({
  32800. // Id for animation
  32801. anid: 'line',
  32802. shape: {
  32803. x1: pt1[0],
  32804. y1: pt1[1],
  32805. x2: pt2[0],
  32806. y2: pt2[1]
  32807. },
  32808. style: lineStyle,
  32809. strokeContainThreshold: opt.strokeContainThreshold || 5,
  32810. silent: true,
  32811. z2: 1
  32812. })));
  32813. var arrows = axisModel.get('axisLine.symbol');
  32814. var arrowSize = axisModel.get('axisLine.symbolSize');
  32815. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  32816. if (typeof arrowOffset === 'number') {
  32817. arrowOffset = [arrowOffset, arrowOffset];
  32818. }
  32819. if (arrows != null) {
  32820. if (typeof arrows === 'string') {
  32821. // Use the same arrow for start and end point
  32822. arrows = [arrows, arrows];
  32823. }
  32824. if (typeof arrowSize === 'string'
  32825. || typeof arrowSize === 'number'
  32826. ) {
  32827. // Use the same size for width and height
  32828. arrowSize = [arrowSize, arrowSize];
  32829. }
  32830. var symbolWidth = arrowSize[0];
  32831. var symbolHeight = arrowSize[1];
  32832. each$1([{
  32833. rotate: opt.rotation + Math.PI / 2,
  32834. offset: arrowOffset[0],
  32835. r: 0
  32836. }, {
  32837. rotate: opt.rotation - Math.PI / 2,
  32838. offset: arrowOffset[1],
  32839. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0])
  32840. + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  32841. }], function (point, index) {
  32842. if (arrows[index] !== 'none' && arrows[index] != null) {
  32843. var symbol = createSymbol(
  32844. arrows[index],
  32845. -symbolWidth / 2,
  32846. -symbolHeight / 2,
  32847. symbolWidth,
  32848. symbolHeight,
  32849. lineStyle.stroke,
  32850. true
  32851. );
  32852. // Calculate arrow position with offset
  32853. var r = point.r + point.offset;
  32854. var pos = [
  32855. pt1[0] + r * Math.cos(opt.rotation),
  32856. pt1[1] - r * Math.sin(opt.rotation)
  32857. ];
  32858. symbol.attr({
  32859. rotation: point.rotate,
  32860. position: pos,
  32861. silent: true
  32862. });
  32863. this.group.add(symbol);
  32864. }
  32865. }, this);
  32866. }
  32867. },
  32868. /**
  32869. * @private
  32870. */
  32871. axisTickLabel: function () {
  32872. var axisModel = this.axisModel;
  32873. var opt = this.opt;
  32874. var tickEls = buildAxisTick(this, axisModel, opt);
  32875. var labelEls = buildAxisLabel(this, axisModel, opt);
  32876. fixMinMaxLabelShow(axisModel, labelEls, tickEls);
  32877. },
  32878. /**
  32879. * @private
  32880. */
  32881. axisName: function () {
  32882. var opt = this.opt;
  32883. var axisModel = this.axisModel;
  32884. var name = retrieve(opt.axisName, axisModel.get('name'));
  32885. if (!name) {
  32886. return;
  32887. }
  32888. var nameLocation = axisModel.get('nameLocation');
  32889. var nameDirection = opt.nameDirection;
  32890. var textStyleModel = axisModel.getModel('nameTextStyle');
  32891. var gap = axisModel.get('nameGap') || 0;
  32892. var extent = this.axisModel.axis.getExtent();
  32893. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  32894. var pos = [
  32895. nameLocation === 'start'
  32896. ? extent[0] - gapSignal * gap
  32897. : nameLocation === 'end'
  32898. ? extent[1] + gapSignal * gap
  32899. : (extent[0] + extent[1]) / 2, // 'middle'
  32900. // Reuse labelOffset.
  32901. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0
  32902. ];
  32903. var labelLayout;
  32904. var nameRotation = axisModel.get('nameRotate');
  32905. if (nameRotation != null) {
  32906. nameRotation = nameRotation * PI$2 / 180; // To radian.
  32907. }
  32908. var axisNameAvailableWidth;
  32909. if (isNameLocationCenter(nameLocation)) {
  32910. labelLayout = innerTextLayout(
  32911. opt.rotation,
  32912. nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  32913. nameDirection
  32914. );
  32915. }
  32916. else {
  32917. labelLayout = endTextLayout(
  32918. opt, nameLocation, nameRotation || 0, extent
  32919. );
  32920. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  32921. if (axisNameAvailableWidth != null) {
  32922. axisNameAvailableWidth = Math.abs(
  32923. axisNameAvailableWidth / Math.sin(labelLayout.rotation)
  32924. );
  32925. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  32926. }
  32927. }
  32928. var textFont = textStyleModel.getFont();
  32929. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  32930. var ellipsis = truncateOpt.ellipsis;
  32931. var maxWidth = retrieve(
  32932. opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth
  32933. );
  32934. // FIXME
  32935. // truncate rich text? (consider performance)
  32936. var truncatedText = (ellipsis != null && maxWidth != null)
  32937. ? truncateText$1(
  32938. name, maxWidth, textFont, ellipsis,
  32939. {minChar: 2, placeholder: truncateOpt.placeholder}
  32940. )
  32941. : name;
  32942. var tooltipOpt = axisModel.get('tooltip', true);
  32943. var mainType = axisModel.mainType;
  32944. var formatterParams = {
  32945. componentType: mainType,
  32946. name: name,
  32947. $vars: ['name']
  32948. };
  32949. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  32950. var textEl = new Text({
  32951. // Id for animation
  32952. anid: 'name',
  32953. __fullText: name,
  32954. __truncatedText: truncatedText,
  32955. position: pos,
  32956. rotation: labelLayout.rotation,
  32957. silent: isSilent(axisModel),
  32958. z2: 1,
  32959. tooltip: (tooltipOpt && tooltipOpt.show)
  32960. ? extend({
  32961. content: name,
  32962. formatter: function () {
  32963. return name;
  32964. },
  32965. formatterParams: formatterParams
  32966. }, tooltipOpt)
  32967. : null
  32968. });
  32969. setTextStyle(textEl.style, textStyleModel, {
  32970. text: truncatedText,
  32971. textFont: textFont,
  32972. textFill: textStyleModel.getTextColor()
  32973. || axisModel.get('axisLine.lineStyle.color'),
  32974. textAlign: labelLayout.textAlign,
  32975. textVerticalAlign: labelLayout.textVerticalAlign
  32976. });
  32977. if (axisModel.get('triggerEvent')) {
  32978. textEl.eventData = makeAxisEventDataBase(axisModel);
  32979. textEl.eventData.targetType = 'axisName';
  32980. textEl.eventData.name = name;
  32981. }
  32982. // FIXME
  32983. this._dumbGroup.add(textEl);
  32984. textEl.updateTransform();
  32985. this.group.add(textEl);
  32986. textEl.decomposeTransform();
  32987. }
  32988. };
  32989. /**
  32990. * @public
  32991. * @static
  32992. * @param {Object} opt
  32993. * @param {number} axisRotation in radian
  32994. * @param {number} textRotation in radian
  32995. * @param {number} direction
  32996. * @return {Object} {
  32997. * rotation, // according to axis
  32998. * textAlign,
  32999. * textVerticalAlign
  33000. * }
  33001. */
  33002. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  33003. var rotationDiff = remRadian(textRotation - axisRotation);
  33004. var textAlign;
  33005. var textVerticalAlign;
  33006. if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line.
  33007. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  33008. textAlign = 'center';
  33009. }
  33010. else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line.
  33011. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  33012. textAlign = 'center';
  33013. }
  33014. else {
  33015. textVerticalAlign = 'middle';
  33016. if (rotationDiff > 0 && rotationDiff < PI$2) {
  33017. textAlign = direction > 0 ? 'right' : 'left';
  33018. }
  33019. else {
  33020. textAlign = direction > 0 ? 'left' : 'right';
  33021. }
  33022. }
  33023. return {
  33024. rotation: rotationDiff,
  33025. textAlign: textAlign,
  33026. textVerticalAlign: textVerticalAlign
  33027. };
  33028. };
  33029. function endTextLayout(opt, textPosition, textRotate, extent) {
  33030. var rotationDiff = remRadian(textRotate - opt.rotation);
  33031. var textAlign;
  33032. var textVerticalAlign;
  33033. var inverse = extent[0] > extent[1];
  33034. var onLeft = (textPosition === 'start' && !inverse)
  33035. || (textPosition !== 'start' && inverse);
  33036. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  33037. textVerticalAlign = onLeft ? 'bottom' : 'top';
  33038. textAlign = 'center';
  33039. }
  33040. else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  33041. textVerticalAlign = onLeft ? 'top' : 'bottom';
  33042. textAlign = 'center';
  33043. }
  33044. else {
  33045. textVerticalAlign = 'middle';
  33046. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  33047. textAlign = onLeft ? 'left' : 'right';
  33048. }
  33049. else {
  33050. textAlign = onLeft ? 'right' : 'left';
  33051. }
  33052. }
  33053. return {
  33054. rotation: rotationDiff,
  33055. textAlign: textAlign,
  33056. textVerticalAlign: textVerticalAlign
  33057. };
  33058. }
  33059. function isSilent(axisModel) {
  33060. var tooltipOpt = axisModel.get('tooltip');
  33061. return axisModel.get('silent')
  33062. // Consider mouse cursor, add these restrictions.
  33063. || !(
  33064. axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show)
  33065. );
  33066. }
  33067. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  33068. // If min or max are user set, we need to check
  33069. // If the tick on min(max) are overlap on their neighbour tick
  33070. // If they are overlapped, we need to hide the min(max) tick label
  33071. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  33072. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel');
  33073. // FIXME
  33074. // Have not consider onBand yet, where tick els is more than label els.
  33075. labelEls = labelEls || [];
  33076. tickEls = tickEls || [];
  33077. var firstLabel = labelEls[0];
  33078. var nextLabel = labelEls[1];
  33079. var lastLabel = labelEls[labelEls.length - 1];
  33080. var prevLabel = labelEls[labelEls.length - 2];
  33081. var firstTick = tickEls[0];
  33082. var nextTick = tickEls[1];
  33083. var lastTick = tickEls[tickEls.length - 1];
  33084. var prevTick = tickEls[tickEls.length - 2];
  33085. if (showMinLabel === false) {
  33086. ignoreEl(firstLabel);
  33087. ignoreEl(firstTick);
  33088. }
  33089. else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  33090. if (showMinLabel) {
  33091. ignoreEl(nextLabel);
  33092. ignoreEl(nextTick);
  33093. }
  33094. else {
  33095. ignoreEl(firstLabel);
  33096. ignoreEl(firstTick);
  33097. }
  33098. }
  33099. if (showMaxLabel === false) {
  33100. ignoreEl(lastLabel);
  33101. ignoreEl(lastTick);
  33102. }
  33103. else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  33104. if (showMaxLabel) {
  33105. ignoreEl(prevLabel);
  33106. ignoreEl(prevTick);
  33107. }
  33108. else {
  33109. ignoreEl(lastLabel);
  33110. ignoreEl(lastTick);
  33111. }
  33112. }
  33113. }
  33114. function ignoreEl(el) {
  33115. el && (el.ignore = true);
  33116. }
  33117. function isTwoLabelOverlapped(current, next, labelLayout) {
  33118. // current and next has the same rotation.
  33119. var firstRect = current && current.getBoundingRect().clone();
  33120. var nextRect = next && next.getBoundingRect().clone();
  33121. if (!firstRect || !nextRect) {
  33122. return;
  33123. }
  33124. // When checking intersect of two rotated labels, we use mRotationBack
  33125. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  33126. var mRotationBack = identity([]);
  33127. rotate(mRotationBack, mRotationBack, -current.rotation);
  33128. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  33129. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  33130. return firstRect.intersect(nextRect);
  33131. }
  33132. function isNameLocationCenter(nameLocation) {
  33133. return nameLocation === 'middle' || nameLocation === 'center';
  33134. }
  33135. function buildAxisTick(axisBuilder, axisModel, opt) {
  33136. var axis = axisModel.axis;
  33137. if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) {
  33138. return;
  33139. }
  33140. var tickModel = axisModel.getModel('axisTick');
  33141. var lineStyleModel = tickModel.getModel('lineStyle');
  33142. var tickLen = tickModel.get('length');
  33143. var ticksCoords = axis.getTicksCoords();
  33144. var pt1 = [];
  33145. var pt2 = [];
  33146. var matrix = axisBuilder._transform;
  33147. var tickEls = [];
  33148. for (var i = 0; i < ticksCoords.length; i++) {
  33149. var tickCoord = ticksCoords[i].coord;
  33150. pt1[0] = tickCoord;
  33151. pt1[1] = 0;
  33152. pt2[0] = tickCoord;
  33153. pt2[1] = opt.tickDirection * tickLen;
  33154. if (matrix) {
  33155. applyTransform(pt1, pt1, matrix);
  33156. applyTransform(pt2, pt2, matrix);
  33157. }
  33158. // Tick line, Not use group transform to have better line draw
  33159. var tickEl = new Line(subPixelOptimizeLine({
  33160. // Id for animation
  33161. anid: 'tick_' + ticksCoords[i].tickValue,
  33162. shape: {
  33163. x1: pt1[0],
  33164. y1: pt1[1],
  33165. x2: pt2[0],
  33166. y2: pt2[1]
  33167. },
  33168. style: defaults(
  33169. lineStyleModel.getLineStyle(),
  33170. {
  33171. stroke: axisModel.get('axisLine.lineStyle.color')
  33172. }
  33173. ),
  33174. z2: 2,
  33175. silent: true
  33176. }));
  33177. axisBuilder.group.add(tickEl);
  33178. tickEls.push(tickEl);
  33179. }
  33180. return tickEls;
  33181. }
  33182. function buildAxisLabel(axisBuilder, axisModel, opt) {
  33183. var axis = axisModel.axis;
  33184. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  33185. if (!show || axis.scale.isBlank()) {
  33186. return;
  33187. }
  33188. var labelModel = axisModel.getModel('axisLabel');
  33189. var labelMargin = labelModel.get('margin');
  33190. var labels = axis.getViewLabels();
  33191. // Special label rotate.
  33192. var labelRotation = (
  33193. retrieve(opt.labelRotate, labelModel.get('rotate')) || 0
  33194. ) * PI$2 / 180;
  33195. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  33196. var rawCategoryData = axisModel.getCategories(true);
  33197. var labelEls = [];
  33198. var silent = isSilent(axisModel);
  33199. var triggerEvent = axisModel.get('triggerEvent');
  33200. each$1(labels, function (labelItem, index) {
  33201. var tickValue = labelItem.tickValue;
  33202. var formattedLabel = labelItem.formattedLabel;
  33203. var rawLabel = labelItem.rawLabel;
  33204. var itemLabelModel = labelModel;
  33205. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  33206. itemLabelModel = new Model(
  33207. rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel
  33208. );
  33209. }
  33210. var textColor = itemLabelModel.getTextColor()
  33211. || axisModel.get('axisLine.lineStyle.color');
  33212. var tickCoord = axis.dataToCoord(tickValue);
  33213. var pos = [
  33214. tickCoord,
  33215. opt.labelOffset + opt.labelDirection * labelMargin
  33216. ];
  33217. var textEl = new Text({
  33218. // Id for animation
  33219. anid: 'label_' + tickValue,
  33220. position: pos,
  33221. rotation: labelLayout.rotation,
  33222. silent: silent,
  33223. z2: 10
  33224. });
  33225. setTextStyle(textEl.style, itemLabelModel, {
  33226. text: formattedLabel,
  33227. textAlign: itemLabelModel.getShallow('align', true)
  33228. || labelLayout.textAlign,
  33229. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true)
  33230. || itemLabelModel.getShallow('baseline', true)
  33231. || labelLayout.textVerticalAlign,
  33232. textFill: typeof textColor === 'function'
  33233. ? textColor(
  33234. // (1) In category axis with data zoom, tick is not the original
  33235. // index of axis.data. So tick should not be exposed to user
  33236. // in category axis.
  33237. // (2) Compatible with previous version, which always use formatted label as
  33238. // input. But in interval scale the formatted label is like '223,445', which
  33239. // maked user repalce ','. So we modify it to return original val but remain
  33240. // it as 'string' to avoid error in replacing.
  33241. axis.type === 'category'
  33242. ? rawLabel
  33243. : axis.type === 'value'
  33244. ? tickValue + ''
  33245. : tickValue,
  33246. index
  33247. )
  33248. : textColor
  33249. });
  33250. // Pack data for mouse event
  33251. if (triggerEvent) {
  33252. textEl.eventData = makeAxisEventDataBase(axisModel);
  33253. textEl.eventData.targetType = 'axisLabel';
  33254. textEl.eventData.value = rawLabel;
  33255. }
  33256. // FIXME
  33257. axisBuilder._dumbGroup.add(textEl);
  33258. textEl.updateTransform();
  33259. labelEls.push(textEl);
  33260. axisBuilder.group.add(textEl);
  33261. textEl.decomposeTransform();
  33262. });
  33263. return labelEls;
  33264. }
  33265. /*
  33266. * Licensed to the Apache Software Foundation (ASF) under one
  33267. * or more contributor license agreements. See the NOTICE file
  33268. * distributed with this work for additional information
  33269. * regarding copyright ownership. The ASF licenses this file
  33270. * to you under the Apache License, Version 2.0 (the
  33271. * "License"); you may not use this file except in compliance
  33272. * with the License. You may obtain a copy of the License at
  33273. *
  33274. * http://www.apache.org/licenses/LICENSE-2.0
  33275. *
  33276. * Unless required by applicable law or agreed to in writing,
  33277. * software distributed under the License is distributed on an
  33278. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33279. * KIND, either express or implied. See the License for the
  33280. * specific language governing permissions and limitations
  33281. * under the License.
  33282. */
  33283. var each$6 = each$1;
  33284. var curry$1 = curry;
  33285. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  33286. // allAxesInfo should be updated when setOption performed.
  33287. function collect(ecModel, api) {
  33288. var result = {
  33289. /**
  33290. * key: makeKey(axis.model)
  33291. * value: {
  33292. * axis,
  33293. * coordSys,
  33294. * axisPointerModel,
  33295. * triggerTooltip,
  33296. * involveSeries,
  33297. * snap,
  33298. * seriesModels,
  33299. * seriesDataCount
  33300. * }
  33301. */
  33302. axesInfo: {},
  33303. seriesInvolved: false,
  33304. /**
  33305. * key: makeKey(coordSys.model)
  33306. * value: Object: key makeKey(axis.model), value: axisInfo
  33307. */
  33308. coordSysAxesInfo: {},
  33309. coordSysMap: {}
  33310. };
  33311. collectAxesInfo(result, ecModel, api);
  33312. // Check seriesInvolved for performance, in case too many series in some chart.
  33313. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  33314. return result;
  33315. }
  33316. function collectAxesInfo(result, ecModel, api) {
  33317. var globalTooltipModel = ecModel.getComponent('tooltip');
  33318. var globalAxisPointerModel = ecModel.getComponent('axisPointer');
  33319. // links can only be set on global.
  33320. var linksOption = globalAxisPointerModel.get('link', true) || [];
  33321. var linkGroups = [];
  33322. // Collect axes info.
  33323. each$6(api.getCoordinateSystems(), function (coordSys) {
  33324. // Some coordinate system do not support axes, like geo.
  33325. if (!coordSys.axisPointerEnabled) {
  33326. return;
  33327. }
  33328. var coordSysKey = makeKey(coordSys.model);
  33329. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  33330. result.coordSysMap[coordSysKey] = coordSys;
  33331. // Set tooltip (like 'cross') is a convienent way to show axisPointer
  33332. // for user. So we enable seting tooltip on coordSys model.
  33333. var coordSysModel = coordSys.model;
  33334. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  33335. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null));
  33336. // If axis tooltip used, choose tooltip axis for each coordSys.
  33337. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  33338. if (coordSys.getTooltipAxes
  33339. && globalTooltipModel
  33340. // If tooltip.showContent is set as false, tooltip will not
  33341. // show but axisPointer will show as normal.
  33342. && baseTooltipModel.get('show')
  33343. ) {
  33344. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  33345. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  33346. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  33347. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  33348. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  33349. if (triggerAxis || cross) {
  33350. each$6(tooltipAxes.baseAxes, curry$1(
  33351. saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis
  33352. ));
  33353. }
  33354. if (cross) {
  33355. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  33356. }
  33357. }
  33358. // fromTooltip: true | false | 'cross'
  33359. // triggerTooltip: true | false | null
  33360. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  33361. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  33362. var axisPointerShow = axisPointerModel.get('show');
  33363. if (!axisPointerShow || (
  33364. axisPointerShow === 'auto'
  33365. && !fromTooltip
  33366. && !isHandleTrigger(axisPointerModel)
  33367. )) {
  33368. return;
  33369. }
  33370. if (triggerTooltip == null) {
  33371. triggerTooltip = axisPointerModel.get('triggerTooltip');
  33372. }
  33373. axisPointerModel = fromTooltip
  33374. ? makeAxisPointerModel(
  33375. axis, baseTooltipModel, globalAxisPointerModel, ecModel,
  33376. fromTooltip, triggerTooltip
  33377. )
  33378. : axisPointerModel;
  33379. var snap = axisPointerModel.get('snap');
  33380. var key = makeKey(axis.model);
  33381. var involveSeries = triggerTooltip || snap || axis.type === 'category';
  33382. // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  33383. var axisInfo = result.axesInfo[key] = {
  33384. key: key,
  33385. axis: axis,
  33386. coordSys: coordSys,
  33387. axisPointerModel: axisPointerModel,
  33388. triggerTooltip: triggerTooltip,
  33389. involveSeries: involveSeries,
  33390. snap: snap,
  33391. useHandle: isHandleTrigger(axisPointerModel),
  33392. seriesModels: []
  33393. };
  33394. axesInfoInCoordSys[key] = axisInfo;
  33395. result.seriesInvolved |= involveSeries;
  33396. var groupIndex = getLinkGroupIndex(linksOption, axis);
  33397. if (groupIndex != null) {
  33398. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {axesInfo: {}});
  33399. linkGroup.axesInfo[key] = axisInfo;
  33400. linkGroup.mapper = linksOption[groupIndex].mapper;
  33401. axisInfo.linkGroup = linkGroup;
  33402. }
  33403. }
  33404. });
  33405. }
  33406. function makeAxisPointerModel(
  33407. axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip
  33408. ) {
  33409. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  33410. var volatileOption = {};
  33411. each$6(
  33412. [
  33413. 'type', 'snap', 'lineStyle', 'shadowStyle', 'label',
  33414. 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'
  33415. ],
  33416. function (field) {
  33417. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  33418. }
  33419. );
  33420. // category axis do not auto snap, otherwise some tick that do not
  33421. // has value can not be hovered. value/time/log axis default snap if
  33422. // triggered from tooltip and trigger tooltip.
  33423. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip;
  33424. // Compatibel with previous behavior, tooltip axis do not show label by default.
  33425. // Only these properties can be overrided from tooltip to axisPointer.
  33426. if (tooltipAxisPointerModel.get('type') === 'cross') {
  33427. volatileOption.type = 'line';
  33428. }
  33429. var labelOption = volatileOption.label || (volatileOption.label = {});
  33430. // Follow the convention, do not show label when triggered by tooltip by default.
  33431. labelOption.show == null && (labelOption.show = false);
  33432. if (fromTooltip === 'cross') {
  33433. // When 'cross', both axes show labels.
  33434. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  33435. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true;
  33436. // If triggerTooltip, this is a base axis, which should better not use cross style
  33437. // (cross style is dashed by default)
  33438. if (!triggerTooltip) {
  33439. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  33440. crossStyle && defaults(labelOption, crossStyle.textStyle);
  33441. }
  33442. }
  33443. return axis.model.getModel(
  33444. 'axisPointer',
  33445. new Model(volatileOption, globalAxisPointerModel, ecModel)
  33446. );
  33447. }
  33448. function collectSeriesInfo(result, ecModel) {
  33449. // Prepare data for axis trigger
  33450. ecModel.eachSeries(function (seriesModel) {
  33451. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  33452. var coordSys = seriesModel.coordinateSystem;
  33453. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  33454. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  33455. if (!coordSys
  33456. || seriesTooltipTrigger === 'none'
  33457. || seriesTooltipTrigger === false
  33458. || seriesTooltipTrigger === 'item'
  33459. || seriesTooltipShow === false
  33460. || seriesModel.get('axisPointer.show', true) === false
  33461. ) {
  33462. return;
  33463. }
  33464. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  33465. var axis = axisInfo.axis;
  33466. if (coordSys.getAxis(axis.dim) === axis) {
  33467. axisInfo.seriesModels.push(seriesModel);
  33468. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  33469. axisInfo.seriesDataCount += seriesModel.getData().count();
  33470. }
  33471. });
  33472. }, this);
  33473. }
  33474. /**
  33475. * For example:
  33476. * {
  33477. * axisPointer: {
  33478. * links: [{
  33479. * xAxisIndex: [2, 4],
  33480. * yAxisIndex: 'all'
  33481. * }, {
  33482. * xAxisId: ['a5', 'a7'],
  33483. * xAxisName: 'xxx'
  33484. * }]
  33485. * }
  33486. * }
  33487. */
  33488. function getLinkGroupIndex(linksOption, axis) {
  33489. var axisModel = axis.model;
  33490. var dim = axis.dim;
  33491. for (var i = 0; i < linksOption.length; i++) {
  33492. var linkOption = linksOption[i] || {};
  33493. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id)
  33494. || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex)
  33495. || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)
  33496. ) {
  33497. return i;
  33498. }
  33499. }
  33500. }
  33501. function checkPropInLink(linkPropValue, axisPropValue) {
  33502. return linkPropValue === 'all'
  33503. || (isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0)
  33504. || linkPropValue === axisPropValue;
  33505. }
  33506. function fixValue(axisModel) {
  33507. var axisInfo = getAxisInfo(axisModel);
  33508. if (!axisInfo) {
  33509. return;
  33510. }
  33511. var axisPointerModel = axisInfo.axisPointerModel;
  33512. var scale = axisInfo.axis.scale;
  33513. var option = axisPointerModel.option;
  33514. var status = axisPointerModel.get('status');
  33515. var value = axisPointerModel.get('value');
  33516. // Parse init value for category and time axis.
  33517. if (value != null) {
  33518. value = scale.parse(value);
  33519. }
  33520. var useHandle = isHandleTrigger(axisPointerModel);
  33521. // If `handle` used, `axisPointer` will always be displayed, so value
  33522. // and status should be initialized.
  33523. if (status == null) {
  33524. option.status = useHandle ? 'show' : 'hide';
  33525. }
  33526. var extent = scale.getExtent().slice();
  33527. extent[0] > extent[1] && extent.reverse();
  33528. if (// Pick a value on axis when initializing.
  33529. value == null
  33530. // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  33531. // where we should re-pick a value to keep `handle` displaying normally.
  33532. || value > extent[1]
  33533. ) {
  33534. // Make handle displayed on the end of the axis when init, which looks better.
  33535. value = extent[1];
  33536. }
  33537. if (value < extent[0]) {
  33538. value = extent[0];
  33539. }
  33540. option.value = value;
  33541. if (useHandle) {
  33542. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  33543. }
  33544. }
  33545. function getAxisInfo(axisModel) {
  33546. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  33547. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  33548. }
  33549. function getAxisPointerModel(axisModel) {
  33550. var axisInfo = getAxisInfo(axisModel);
  33551. return axisInfo && axisInfo.axisPointerModel;
  33552. }
  33553. function isHandleTrigger(axisPointerModel) {
  33554. return !!axisPointerModel.get('handle.show');
  33555. }
  33556. /**
  33557. * @param {module:echarts/model/Model} model
  33558. * @return {string} unique key
  33559. */
  33560. function makeKey(model) {
  33561. return model.type + '||' + model.id;
  33562. }
  33563. /*
  33564. * Licensed to the Apache Software Foundation (ASF) under one
  33565. * or more contributor license agreements. See the NOTICE file
  33566. * distributed with this work for additional information
  33567. * regarding copyright ownership. The ASF licenses this file
  33568. * to you under the Apache License, Version 2.0 (the
  33569. * "License"); you may not use this file except in compliance
  33570. * with the License. You may obtain a copy of the License at
  33571. *
  33572. * http://www.apache.org/licenses/LICENSE-2.0
  33573. *
  33574. * Unless required by applicable law or agreed to in writing,
  33575. * software distributed under the License is distributed on an
  33576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33577. * KIND, either express or implied. See the License for the
  33578. * specific language governing permissions and limitations
  33579. * under the License.
  33580. */
  33581. /**
  33582. * Base class of AxisView.
  33583. */
  33584. var AxisView = extendComponentView({
  33585. type: 'axis',
  33586. /**
  33587. * @private
  33588. */
  33589. _axisPointer: null,
  33590. /**
  33591. * @protected
  33592. * @type {string}
  33593. */
  33594. axisPointerClass: null,
  33595. /**
  33596. * @override
  33597. */
  33598. render: function (axisModel, ecModel, api, payload) {
  33599. // FIXME
  33600. // This process should proformed after coordinate systems updated
  33601. // (axis scale updated), and should be performed each time update.
  33602. // So put it here temporarily, although it is not appropriate to
  33603. // put a model-writing procedure in `view`.
  33604. this.axisPointerClass && fixValue(axisModel);
  33605. AxisView.superApply(this, 'render', arguments);
  33606. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  33607. },
  33608. /**
  33609. * Action handler.
  33610. * @public
  33611. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33612. * @param {module:echarts/model/Global} ecModel
  33613. * @param {module:echarts/ExtensionAPI} api
  33614. * @param {Object} payload
  33615. */
  33616. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  33617. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  33618. },
  33619. /**
  33620. * @override
  33621. */
  33622. remove: function (ecModel, api) {
  33623. var axisPointer = this._axisPointer;
  33624. axisPointer && axisPointer.remove(api);
  33625. AxisView.superApply(this, 'remove', arguments);
  33626. },
  33627. /**
  33628. * @override
  33629. */
  33630. dispose: function (ecModel, api) {
  33631. disposeAxisPointer(this, api);
  33632. AxisView.superApply(this, 'dispose', arguments);
  33633. }
  33634. });
  33635. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  33636. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  33637. if (!Clazz) {
  33638. return;
  33639. }
  33640. var axisPointerModel = getAxisPointerModel(axisModel);
  33641. axisPointerModel
  33642. ? (axisView._axisPointer || (axisView._axisPointer = new Clazz()))
  33643. .render(axisModel, axisPointerModel, api, forceRender)
  33644. : disposeAxisPointer(axisView, api);
  33645. }
  33646. function disposeAxisPointer(axisView, ecModel, api) {
  33647. var axisPointer = axisView._axisPointer;
  33648. axisPointer && axisPointer.dispose(ecModel, api);
  33649. axisView._axisPointer = null;
  33650. }
  33651. var axisPointerClazz = [];
  33652. AxisView.registerAxisPointerClass = function (type, clazz) {
  33653. if (__DEV__) {
  33654. if (axisPointerClazz[type]) {
  33655. throw new Error('axisPointer ' + type + ' exists');
  33656. }
  33657. }
  33658. axisPointerClazz[type] = clazz;
  33659. };
  33660. AxisView.getAxisPointerClass = function (type) {
  33661. return type && axisPointerClazz[type];
  33662. };
  33663. /*
  33664. * Licensed to the Apache Software Foundation (ASF) under one
  33665. * or more contributor license agreements. See the NOTICE file
  33666. * distributed with this work for additional information
  33667. * regarding copyright ownership. The ASF licenses this file
  33668. * to you under the Apache License, Version 2.0 (the
  33669. * "License"); you may not use this file except in compliance
  33670. * with the License. You may obtain a copy of the License at
  33671. *
  33672. * http://www.apache.org/licenses/LICENSE-2.0
  33673. *
  33674. * Unless required by applicable law or agreed to in writing,
  33675. * software distributed under the License is distributed on an
  33676. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33677. * KIND, either express or implied. See the License for the
  33678. * specific language governing permissions and limitations
  33679. * under the License.
  33680. */
  33681. /**
  33682. * Can only be called after coordinate system creation stage.
  33683. * (Can be called before coordinate system update stage).
  33684. *
  33685. * @param {Object} opt {labelInside}
  33686. * @return {Object} {
  33687. * position, rotation, labelDirection, labelOffset,
  33688. * tickDirection, labelRotate, z2
  33689. * }
  33690. */
  33691. function layout$1(gridModel, axisModel, opt) {
  33692. opt = opt || {};
  33693. var grid = gridModel.coordinateSystem;
  33694. var axis = axisModel.axis;
  33695. var layout = {};
  33696. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  33697. var rawAxisPosition = axis.position;
  33698. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  33699. var axisDim = axis.dim;
  33700. var rect = grid.getRect();
  33701. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  33702. var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2};
  33703. var axisOffset = axisModel.get('offset') || 0;
  33704. var posBound = axisDim === 'x'
  33705. ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset]
  33706. : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  33707. if (otherAxisOnZeroOf) {
  33708. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  33709. posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  33710. }
  33711. // Axis position
  33712. layout.position = [
  33713. axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0],
  33714. axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]
  33715. ];
  33716. // Axis rotation
  33717. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1);
  33718. // Tick and label direction, x y is axisDim
  33719. var dirMap = {top: -1, bottom: 1, left: -1, right: 1};
  33720. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  33721. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0;
  33722. if (axisModel.get('axisTick.inside')) {
  33723. layout.tickDirection = -layout.tickDirection;
  33724. }
  33725. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  33726. layout.labelDirection = -layout.labelDirection;
  33727. }
  33728. // Special label rotation
  33729. var labelRotate = axisModel.get('axisLabel.rotate');
  33730. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate;
  33731. // Over splitLine and splitArea
  33732. layout.z2 = 1;
  33733. return layout;
  33734. }
  33735. /*
  33736. * Licensed to the Apache Software Foundation (ASF) under one
  33737. * or more contributor license agreements. See the NOTICE file
  33738. * distributed with this work for additional information
  33739. * regarding copyright ownership. The ASF licenses this file
  33740. * to you under the Apache License, Version 2.0 (the
  33741. * "License"); you may not use this file except in compliance
  33742. * with the License. You may obtain a copy of the License at
  33743. *
  33744. * http://www.apache.org/licenses/LICENSE-2.0
  33745. *
  33746. * Unless required by applicable law or agreed to in writing,
  33747. * software distributed under the License is distributed on an
  33748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33749. * KIND, either express or implied. See the License for the
  33750. * specific language governing permissions and limitations
  33751. * under the License.
  33752. */
  33753. var axisBuilderAttrs = [
  33754. 'axisLine', 'axisTickLabel', 'axisName'
  33755. ];
  33756. var selfBuilderAttrs = [
  33757. 'splitArea', 'splitLine'
  33758. ];
  33759. // function getAlignWithLabel(model, axisModel) {
  33760. // var alignWithLabel = model.get('alignWithLabel');
  33761. // if (alignWithLabel === 'auto') {
  33762. // alignWithLabel = axisModel.get('axisTick.alignWithLabel');
  33763. // }
  33764. // return alignWithLabel;
  33765. // }
  33766. var CartesianAxisView = AxisView.extend({
  33767. type: 'cartesianAxis',
  33768. axisPointerClass: 'CartesianAxisPointer',
  33769. /**
  33770. * @override
  33771. */
  33772. render: function (axisModel, ecModel, api, payload) {
  33773. this.group.removeAll();
  33774. var oldAxisGroup = this._axisGroup;
  33775. this._axisGroup = new Group();
  33776. this.group.add(this._axisGroup);
  33777. if (!axisModel.get('show')) {
  33778. return;
  33779. }
  33780. var gridModel = axisModel.getCoordSysModel();
  33781. var layout = layout$1(gridModel, axisModel);
  33782. var axisBuilder = new AxisBuilder(axisModel, layout);
  33783. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  33784. this._axisGroup.add(axisBuilder.getGroup());
  33785. each$1(selfBuilderAttrs, function (name) {
  33786. if (axisModel.get(name + '.show')) {
  33787. this['_' + name](axisModel, gridModel);
  33788. }
  33789. }, this);
  33790. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  33791. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  33792. },
  33793. remove: function () {
  33794. this._splitAreaColors = null;
  33795. },
  33796. /**
  33797. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33798. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33799. * @private
  33800. */
  33801. _splitLine: function (axisModel, gridModel) {
  33802. var axis = axisModel.axis;
  33803. if (axis.scale.isBlank()) {
  33804. return;
  33805. }
  33806. var splitLineModel = axisModel.getModel('splitLine');
  33807. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33808. var lineColors = lineStyleModel.get('color');
  33809. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  33810. var gridRect = gridModel.coordinateSystem.getRect();
  33811. var isHorizontal = axis.isHorizontal();
  33812. var lineCount = 0;
  33813. var ticksCoords = axis.getTicksCoords({
  33814. tickModel: splitLineModel
  33815. });
  33816. var p1 = [];
  33817. var p2 = [];
  33818. // Simple optimization
  33819. // Batching the lines if color are the same
  33820. var lineStyle = lineStyleModel.getLineStyle();
  33821. for (var i = 0; i < ticksCoords.length; i++) {
  33822. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33823. if (isHorizontal) {
  33824. p1[0] = tickCoord;
  33825. p1[1] = gridRect.y;
  33826. p2[0] = tickCoord;
  33827. p2[1] = gridRect.y + gridRect.height;
  33828. }
  33829. else {
  33830. p1[0] = gridRect.x;
  33831. p1[1] = tickCoord;
  33832. p2[0] = gridRect.x + gridRect.width;
  33833. p2[1] = tickCoord;
  33834. }
  33835. var colorIndex = (lineCount++) % lineColors.length;
  33836. var tickValue = ticksCoords[i].tickValue;
  33837. this._axisGroup.add(new Line(subPixelOptimizeLine({
  33838. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  33839. shape: {
  33840. x1: p1[0],
  33841. y1: p1[1],
  33842. x2: p2[0],
  33843. y2: p2[1]
  33844. },
  33845. style: defaults({
  33846. stroke: lineColors[colorIndex]
  33847. }, lineStyle),
  33848. silent: true
  33849. })));
  33850. }
  33851. },
  33852. /**
  33853. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33854. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33855. * @private
  33856. */
  33857. _splitArea: function (axisModel, gridModel) {
  33858. var axis = axisModel.axis;
  33859. if (axis.scale.isBlank()) {
  33860. return;
  33861. }
  33862. var splitAreaModel = axisModel.getModel('splitArea');
  33863. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  33864. var areaColors = areaStyleModel.get('color');
  33865. var gridRect = gridModel.coordinateSystem.getRect();
  33866. var ticksCoords = axis.getTicksCoords({
  33867. tickModel: splitAreaModel,
  33868. clamp: true
  33869. });
  33870. if (!ticksCoords.length) {
  33871. return;
  33872. }
  33873. // For Making appropriate splitArea animation, the color and anid
  33874. // should be corresponding to previous one if possible.
  33875. var areaColorsLen = areaColors.length;
  33876. var lastSplitAreaColors = this._splitAreaColors;
  33877. var newSplitAreaColors = createHashMap();
  33878. var colorIndex = 0;
  33879. if (lastSplitAreaColors) {
  33880. for (var i = 0; i < ticksCoords.length; i++) {
  33881. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  33882. if (cIndex != null) {
  33883. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  33884. break;
  33885. }
  33886. }
  33887. }
  33888. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  33889. var areaStyle = areaStyleModel.getAreaStyle();
  33890. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  33891. for (var i = 1; i < ticksCoords.length; i++) {
  33892. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33893. var x;
  33894. var y;
  33895. var width;
  33896. var height;
  33897. if (axis.isHorizontal()) {
  33898. x = prev;
  33899. y = gridRect.y;
  33900. width = tickCoord - x;
  33901. height = gridRect.height;
  33902. prev = x + width;
  33903. }
  33904. else {
  33905. x = gridRect.x;
  33906. y = prev;
  33907. width = gridRect.width;
  33908. height = tickCoord - y;
  33909. prev = y + height;
  33910. }
  33911. var tickValue = ticksCoords[i - 1].tickValue;
  33912. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  33913. this._axisGroup.add(new Rect({
  33914. anid: tickValue != null ? 'area_' + tickValue : null,
  33915. shape: {
  33916. x: x,
  33917. y: y,
  33918. width: width,
  33919. height: height
  33920. },
  33921. style: defaults({
  33922. fill: areaColors[colorIndex]
  33923. }, areaStyle),
  33924. silent: true
  33925. }));
  33926. colorIndex = (colorIndex + 1) % areaColorsLen;
  33927. }
  33928. this._splitAreaColors = newSplitAreaColors;
  33929. }
  33930. });
  33931. CartesianAxisView.extend({
  33932. type: 'xAxis'
  33933. });
  33934. CartesianAxisView.extend({
  33935. type: 'yAxis'
  33936. });
  33937. /*
  33938. * Licensed to the Apache Software Foundation (ASF) under one
  33939. * or more contributor license agreements. See the NOTICE file
  33940. * distributed with this work for additional information
  33941. * regarding copyright ownership. The ASF licenses this file
  33942. * to you under the Apache License, Version 2.0 (the
  33943. * "License"); you may not use this file except in compliance
  33944. * with the License. You may obtain a copy of the License at
  33945. *
  33946. * http://www.apache.org/licenses/LICENSE-2.0
  33947. *
  33948. * Unless required by applicable law or agreed to in writing,
  33949. * software distributed under the License is distributed on an
  33950. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33951. * KIND, either express or implied. See the License for the
  33952. * specific language governing permissions and limitations
  33953. * under the License.
  33954. */
  33955. /*
  33956. * Licensed to the Apache Software Foundation (ASF) under one
  33957. * or more contributor license agreements. See the NOTICE file
  33958. * distributed with this work for additional information
  33959. * regarding copyright ownership. The ASF licenses this file
  33960. * to you under the Apache License, Version 2.0 (the
  33961. * "License"); you may not use this file except in compliance
  33962. * with the License. You may obtain a copy of the License at
  33963. *
  33964. * http://www.apache.org/licenses/LICENSE-2.0
  33965. *
  33966. * Unless required by applicable law or agreed to in writing,
  33967. * software distributed under the License is distributed on an
  33968. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33969. * KIND, either express or implied. See the License for the
  33970. * specific language governing permissions and limitations
  33971. * under the License.
  33972. */
  33973. // Grid view
  33974. extendComponentView({
  33975. type: 'grid',
  33976. render: function (gridModel, ecModel) {
  33977. this.group.removeAll();
  33978. if (gridModel.get('show')) {
  33979. this.group.add(new Rect({
  33980. shape: gridModel.coordinateSystem.getRect(),
  33981. style: defaults({
  33982. fill: gridModel.get('backgroundColor')
  33983. }, gridModel.getItemStyle()),
  33984. silent: true,
  33985. z2: -1
  33986. }));
  33987. }
  33988. }
  33989. });
  33990. registerPreprocessor(function (option) {
  33991. // Only create grid when need
  33992. if (option.xAxis && option.yAxis && !option.grid) {
  33993. option.grid = {};
  33994. }
  33995. });
  33996. /*
  33997. * Licensed to the Apache Software Foundation (ASF) under one
  33998. * or more contributor license agreements. See the NOTICE file
  33999. * distributed with this work for additional information
  34000. * regarding copyright ownership. The ASF licenses this file
  34001. * to you under the Apache License, Version 2.0 (the
  34002. * "License"); you may not use this file except in compliance
  34003. * with the License. You may obtain a copy of the License at
  34004. *
  34005. * http://www.apache.org/licenses/LICENSE-2.0
  34006. *
  34007. * Unless required by applicable law or agreed to in writing,
  34008. * software distributed under the License is distributed on an
  34009. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34010. * KIND, either express or implied. See the License for the
  34011. * specific language governing permissions and limitations
  34012. * under the License.
  34013. */
  34014. // In case developer forget to include grid component
  34015. registerVisual(visualSymbol('line', 'circle', 'line'));
  34016. registerLayout(pointsLayout('line'));
  34017. // Down sample after filter
  34018. registerProcessor(
  34019. PRIORITY.PROCESSOR.STATISTIC,
  34020. dataSample('line')
  34021. );
  34022. /*
  34023. * Licensed to the Apache Software Foundation (ASF) under one
  34024. * or more contributor license agreements. See the NOTICE file
  34025. * distributed with this work for additional information
  34026. * regarding copyright ownership. The ASF licenses this file
  34027. * to you under the Apache License, Version 2.0 (the
  34028. * "License"); you may not use this file except in compliance
  34029. * with the License. You may obtain a copy of the License at
  34030. *
  34031. * http://www.apache.org/licenses/LICENSE-2.0
  34032. *
  34033. * Unless required by applicable law or agreed to in writing,
  34034. * software distributed under the License is distributed on an
  34035. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34036. * KIND, either express or implied. See the License for the
  34037. * specific language governing permissions and limitations
  34038. * under the License.
  34039. */
  34040. var BaseBarSeries = SeriesModel.extend({
  34041. type: 'series.__base_bar__',
  34042. getInitialData: function (option, ecModel) {
  34043. return createListFromArray(this.getSource(), this);
  34044. },
  34045. getMarkerPosition: function (value) {
  34046. var coordSys = this.coordinateSystem;
  34047. if (coordSys) {
  34048. // PENDING if clamp ?
  34049. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  34050. var data = this.getData();
  34051. var offset = data.getLayout('offset');
  34052. var size = data.getLayout('size');
  34053. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  34054. pt[offsetIndex] += offset + size / 2;
  34055. return pt;
  34056. }
  34057. return [NaN, NaN];
  34058. },
  34059. defaultOption: {
  34060. zlevel: 0, // 一级层叠
  34061. z: 2, // 二级层叠
  34062. coordinateSystem: 'cartesian2d',
  34063. legendHoverLink: true,
  34064. // stack: null
  34065. // Cartesian coordinate system
  34066. // xAxisIndex: 0,
  34067. // yAxisIndex: 0,
  34068. // 最小高度改为0
  34069. barMinHeight: 0,
  34070. // 最小角度为0,仅对极坐标系下的柱状图有效
  34071. barMinAngle: 0,
  34072. // cursor: null,
  34073. large: false,
  34074. largeThreshold: 400,
  34075. progressive: 3e3,
  34076. progressiveChunkMode: 'mod',
  34077. // barMaxWidth: null,
  34078. // 默认自适应
  34079. // barWidth: null,
  34080. // 柱间距离,默认为柱形宽度的30%,可设固定值
  34081. // barGap: '30%',
  34082. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  34083. // barCategoryGap: '20%',
  34084. label: {
  34085. show: true,
  34086. formatter:'{c}',
  34087. },
  34088. // label: {
  34089. // show: false
  34090. // },
  34091. itemStyle: {},
  34092. emphasis: {}
  34093. }
  34094. });
  34095. /*
  34096. * Licensed to the Apache Software Foundation (ASF) under one
  34097. * or more contributor license agreements. See the NOTICE file
  34098. * distributed with this work for additional information
  34099. * regarding copyright ownership. The ASF licenses this file
  34100. * to you under the Apache License, Version 2.0 (the
  34101. * "License"); you may not use this file except in compliance
  34102. * with the License. You may obtain a copy of the License at
  34103. *
  34104. * http://www.apache.org/licenses/LICENSE-2.0
  34105. *
  34106. * Unless required by applicable law or agreed to in writing,
  34107. * software distributed under the License is distributed on an
  34108. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34109. * KIND, either express or implied. See the License for the
  34110. * specific language governing permissions and limitations
  34111. * under the License.
  34112. */
  34113. BaseBarSeries.extend({
  34114. type: 'series.bar',
  34115. dependencies: ['grid', 'polar'],
  34116. brushSelector: 'rect',
  34117. /**
  34118. * @override
  34119. */
  34120. getProgressive: function () {
  34121. // Do not support progressive in normal mode.
  34122. return this.get('large')
  34123. ? this.get('progressive')
  34124. : false;
  34125. },
  34126. /**
  34127. * @override
  34128. */
  34129. getProgressiveThreshold: function () {
  34130. // Do not support progressive in normal mode.
  34131. var progressiveThreshold = this.get('progressiveThreshold');
  34132. var largeThreshold = this.get('largeThreshold');
  34133. if (largeThreshold > progressiveThreshold) {
  34134. progressiveThreshold = largeThreshold;
  34135. }
  34136. return progressiveThreshold;
  34137. }
  34138. });
  34139. /*
  34140. * Licensed to the Apache Software Foundation (ASF) under one
  34141. * or more contributor license agreements. See the NOTICE file
  34142. * distributed with this work for additional information
  34143. * regarding copyright ownership. The ASF licenses this file
  34144. * to you under the Apache License, Version 2.0 (the
  34145. * "License"); you may not use this file except in compliance
  34146. * with the License. You may obtain a copy of the License at
  34147. *
  34148. * http://www.apache.org/licenses/LICENSE-2.0
  34149. *
  34150. * Unless required by applicable law or agreed to in writing,
  34151. * software distributed under the License is distributed on an
  34152. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34153. * KIND, either express or implied. See the License for the
  34154. * specific language governing permissions and limitations
  34155. * under the License.
  34156. */
  34157. function setLabel(
  34158. normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside
  34159. ) {
  34160. var labelModel = itemModel.getModel('label');
  34161. var hoverLabelModel = itemModel.getModel('emphasis.label');
  34162. setLabelStyle(
  34163. normalStyle, hoverStyle, labelModel, hoverLabelModel,
  34164. {
  34165. labelFetcher: seriesModel,
  34166. labelDataIndex: dataIndex,
  34167. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  34168. isRectText: true,
  34169. autoColor: color
  34170. }
  34171. );
  34172. fixPosition(normalStyle);
  34173. fixPosition(hoverStyle);
  34174. }
  34175. function fixPosition(style, labelPositionOutside) {
  34176. if (style.textPosition === 'outside') {
  34177. style.textPosition = labelPositionOutside;
  34178. }
  34179. }
  34180. /*
  34181. * Licensed to the Apache Software Foundation (ASF) under one
  34182. * or more contributor license agreements. See the NOTICE file
  34183. * distributed with this work for additional information
  34184. * regarding copyright ownership. The ASF licenses this file
  34185. * to you under the Apache License, Version 2.0 (the
  34186. * "License"); you may not use this file except in compliance
  34187. * with the License. You may obtain a copy of the License at
  34188. *
  34189. * http://www.apache.org/licenses/LICENSE-2.0
  34190. *
  34191. * Unless required by applicable law or agreed to in writing,
  34192. * software distributed under the License is distributed on an
  34193. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34194. * KIND, either express or implied. See the License for the
  34195. * specific language governing permissions and limitations
  34196. * under the License.
  34197. */
  34198. var getBarItemStyle = makeStyleMapper(
  34199. [
  34200. ['fill', 'color'],
  34201. ['stroke', 'borderColor'],
  34202. ['lineWidth', 'borderWidth'],
  34203. // Compatitable with 2
  34204. ['stroke', 'barBorderColor'],
  34205. ['lineWidth', 'barBorderWidth'],
  34206. ['opacity'],
  34207. ['shadowBlur'],
  34208. ['shadowOffsetX'],
  34209. ['shadowOffsetY'],
  34210. ['shadowColor']
  34211. ]
  34212. );
  34213. var barItemStyle = {
  34214. getBarItemStyle: function (excludes) {
  34215. var style = getBarItemStyle(this, excludes);
  34216. if (this.getBorderLineDash) {
  34217. var lineDash = this.getBorderLineDash();
  34218. lineDash && (style.lineDash = lineDash);
  34219. }
  34220. return style;
  34221. }
  34222. };
  34223. /*
  34224. * Licensed to the Apache Software Foundation (ASF) under one
  34225. * or more contributor license agreements. See the NOTICE file
  34226. * distributed with this work for additional information
  34227. * regarding copyright ownership. The ASF licenses this file
  34228. * to you under the Apache License, Version 2.0 (the
  34229. * "License"); you may not use this file except in compliance
  34230. * with the License. You may obtain a copy of the License at
  34231. *
  34232. * http://www.apache.org/licenses/LICENSE-2.0
  34233. *
  34234. * Unless required by applicable law or agreed to in writing,
  34235. * software distributed under the License is distributed on an
  34236. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34237. * KIND, either express or implied. See the License for the
  34238. * specific language governing permissions and limitations
  34239. * under the License.
  34240. */
  34241. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  34242. // FIXME
  34243. // Just for compatible with ec2.
  34244. extend(Model.prototype, barItemStyle);
  34245. extendChartView({
  34246. type: 'bar',
  34247. render: function (seriesModel, ecModel, api) {
  34248. this._updateDrawMode(seriesModel);
  34249. var coordinateSystemType = seriesModel.get('coordinateSystem');
  34250. if (coordinateSystemType === 'cartesian2d'
  34251. || coordinateSystemType === 'polar'
  34252. ) {
  34253. this._isLargeDraw
  34254. ? this._renderLarge(seriesModel, ecModel, api)
  34255. : this._renderNormal(seriesModel, ecModel, api);
  34256. }
  34257. else if (__DEV__) {
  34258. console.warn('Only cartesian2d and polar supported for bar.');
  34259. }
  34260. return this.group;
  34261. },
  34262. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  34263. this._clear();
  34264. this._updateDrawMode(seriesModel);
  34265. },
  34266. incrementalRender: function (params, seriesModel, ecModel, api) {
  34267. // Do not support progressive in normal mode.
  34268. this._incrementalRenderLarge(params, seriesModel);
  34269. },
  34270. _updateDrawMode: function (seriesModel) {
  34271. var isLargeDraw = seriesModel.pipelineContext.large;
  34272. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  34273. this._isLargeDraw = isLargeDraw;
  34274. this._clear();
  34275. }
  34276. },
  34277. _renderNormal: function (seriesModel, ecModel, api) {
  34278. var group = this.group;
  34279. var data = seriesModel.getData();
  34280. var oldData = this._data;
  34281. var coord = seriesModel.coordinateSystem;
  34282. var baseAxis = coord.getBaseAxis();
  34283. var isHorizontalOrRadial;
  34284. if (coord.type === 'cartesian2d') {
  34285. isHorizontalOrRadial = baseAxis.isHorizontal();
  34286. }
  34287. else if (coord.type === 'polar') {
  34288. isHorizontalOrRadial = baseAxis.dim === 'angle';
  34289. }
  34290. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  34291. data.diff(oldData)
  34292. .add(function (dataIndex) {
  34293. if (!data.hasValue(dataIndex)) {
  34294. return;
  34295. }
  34296. var itemModel = data.getItemModel(dataIndex);
  34297. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  34298. var el = elementCreator[coord.type](
  34299. data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel
  34300. );
  34301. data.setItemGraphicEl(dataIndex, el);
  34302. group.add(el);
  34303. updateStyle(
  34304. el, data, dataIndex, itemModel, layout,
  34305. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34306. );
  34307. })
  34308. .update(function (newIndex, oldIndex) {
  34309. var el = oldData.getItemGraphicEl(oldIndex);
  34310. if (!data.hasValue(newIndex)) {
  34311. group.remove(el);
  34312. return;
  34313. }
  34314. var itemModel = data.getItemModel(newIndex);
  34315. var layout = getLayout[coord.type](data, newIndex, itemModel);
  34316. if (el) {
  34317. updateProps(el, {shape: layout}, animationModel, newIndex);
  34318. }
  34319. else {
  34320. el = elementCreator[coord.type](
  34321. data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true
  34322. );
  34323. }
  34324. data.setItemGraphicEl(newIndex, el);
  34325. // Add back
  34326. group.add(el);
  34327. updateStyle(
  34328. el, data, newIndex, itemModel, layout,
  34329. seriesModel, isHorizontalOrRadial, coord.type === 'polar'
  34330. );
  34331. })
  34332. .remove(function (dataIndex) {
  34333. var el = oldData.getItemGraphicEl(dataIndex);
  34334. if (coord.type === 'cartesian2d') {
  34335. el && removeRect(dataIndex, animationModel, el);
  34336. }
  34337. else {
  34338. el && removeSector(dataIndex, animationModel, el);
  34339. }
  34340. })
  34341. .execute();
  34342. this._data = data;
  34343. },
  34344. _renderLarge: function (seriesModel, ecModel, api) {
  34345. this._clear();
  34346. createLarge(seriesModel, this.group);
  34347. },
  34348. _incrementalRenderLarge: function (params, seriesModel) {
  34349. createLarge(seriesModel, this.group, true);
  34350. },
  34351. dispose: noop,
  34352. remove: function (ecModel) {
  34353. this._clear(ecModel);
  34354. },
  34355. _clear: function (ecModel) {
  34356. var group = this.group;
  34357. var data = this._data;
  34358. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  34359. data.eachItemGraphicEl(function (el) {
  34360. if (el.type === 'sector') {
  34361. removeSector(el.dataIndex, ecModel, el);
  34362. }
  34363. else {
  34364. removeRect(el.dataIndex, ecModel, el);
  34365. }
  34366. });
  34367. }
  34368. else {
  34369. group.removeAll();
  34370. }
  34371. this._data = null;
  34372. }
  34373. });
  34374. var elementCreator = {
  34375. cartesian2d: function (
  34376. data, dataIndex, itemModel, layout, isHorizontal,
  34377. animationModel, isUpdate
  34378. ) {
  34379. var rect = new Rect({shape: extend({}, layout)});
  34380. // Animation
  34381. if (animationModel) {
  34382. var rectShape = rect.shape;
  34383. var animateProperty = isHorizontal ? 'height' : 'width';
  34384. var animateTarget = {};
  34385. rectShape[animateProperty] = 0;
  34386. animateTarget[animateProperty] = layout[animateProperty];
  34387. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  34388. shape: animateTarget
  34389. }, animationModel, dataIndex);
  34390. }
  34391. return rect;
  34392. },
  34393. polar: function (
  34394. data, dataIndex, itemModel, layout, isRadial,
  34395. animationModel, isUpdate
  34396. ) {
  34397. // Keep the same logic with bar in catesion: use end value to control
  34398. // direction. Notice that if clockwise is true (by default), the sector
  34399. // will always draw clockwisely, no matter whether endAngle is greater
  34400. // or less than startAngle.
  34401. var clockwise = layout.startAngle < layout.endAngle;
  34402. var sector = new Sector({
  34403. shape: defaults({clockwise: clockwise}, layout)
  34404. });
  34405. // Animation
  34406. if (animationModel) {
  34407. var sectorShape = sector.shape;
  34408. var animateProperty = isRadial ? 'r' : 'endAngle';
  34409. var animateTarget = {};
  34410. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  34411. animateTarget[animateProperty] = layout[animateProperty];
  34412. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  34413. shape: animateTarget
  34414. }, animationModel, dataIndex);
  34415. }
  34416. return sector;
  34417. }
  34418. };
  34419. function removeRect(dataIndex, animationModel, el) {
  34420. // Not show text when animating
  34421. el.style.text = null;
  34422. updateProps(el, {
  34423. shape: {
  34424. width: 0
  34425. }
  34426. }, animationModel, dataIndex, function () {
  34427. el.parent && el.parent.remove(el);
  34428. });
  34429. }
  34430. function removeSector(dataIndex, animationModel, el) {
  34431. // Not show text when animating
  34432. el.style.text = null;
  34433. updateProps(el, {
  34434. shape: {
  34435. r: el.shape.r0
  34436. }
  34437. }, animationModel, dataIndex, function () {
  34438. el.parent && el.parent.remove(el);
  34439. });
  34440. }
  34441. var getLayout = {
  34442. cartesian2d: function (data, dataIndex, itemModel) {
  34443. var layout = data.getItemLayout(dataIndex);
  34444. var fixedLineWidth = getLineWidth(itemModel, layout);
  34445. // fix layout with lineWidth
  34446. var signX = layout.width > 0 ? 1 : -1;
  34447. var signY = layout.height > 0 ? 1 : -1;
  34448. return {
  34449. x: layout.x + signX * fixedLineWidth / 2,
  34450. y: layout.y + signY * fixedLineWidth / 2,
  34451. width: layout.width - signX * fixedLineWidth,
  34452. height: layout.height - signY * fixedLineWidth
  34453. };
  34454. },
  34455. polar: function (data, dataIndex, itemModel) {
  34456. var layout = data.getItemLayout(dataIndex);
  34457. return {
  34458. cx: layout.cx,
  34459. cy: layout.cy,
  34460. r0: layout.r0,
  34461. r: layout.r,
  34462. startAngle: layout.startAngle,
  34463. endAngle: layout.endAngle
  34464. };
  34465. }
  34466. };
  34467. function updateStyle(
  34468. el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar
  34469. ) {
  34470. var color = data.getItemVisual(dataIndex, 'color');
  34471. var opacity = data.getItemVisual(dataIndex, 'opacity');
  34472. var itemStyleModel = itemModel.getModel('itemStyle');
  34473. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  34474. if (!isPolar) {
  34475. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  34476. }
  34477. el.useStyle(defaults(
  34478. {
  34479. fill: color,
  34480. opacity: opacity
  34481. },
  34482. itemStyleModel.getBarItemStyle()
  34483. ));
  34484. var cursorStyle = itemModel.getShallow('cursor');
  34485. cursorStyle && el.attr('cursor', cursorStyle);
  34486. var labelPositionOutside = isHorizontal
  34487. ? (layout.height > 0 ? 'bottom' : 'top')
  34488. : (layout.width > 0 ? 'left' : 'right');
  34489. if (!isPolar) {
  34490. setLabel(
  34491. el.style, hoverStyle, itemModel, color,
  34492. seriesModel, dataIndex, labelPositionOutside
  34493. );
  34494. }
  34495. setHoverStyle(el, hoverStyle);
  34496. }
  34497. // In case width or height are too small.
  34498. function getLineWidth(itemModel, rawLayout) {
  34499. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0;
  34500. return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height));
  34501. }
  34502. var LargePath = Path.extend({
  34503. type: 'largeBar',
  34504. shape: {points: []},
  34505. buildPath: function (ctx, shape) {
  34506. // Drawing lines is more efficient than drawing
  34507. // a whole line or drawing rects.
  34508. var points = shape.points;
  34509. var startPoint = this.__startPoint;
  34510. var valueIdx = this.__valueIdx;
  34511. for (var i = 0; i < points.length; i += 2) {
  34512. startPoint[this.__valueIdx] = points[i + valueIdx];
  34513. ctx.moveTo(startPoint[0], startPoint[1]);
  34514. ctx.lineTo(points[i], points[i + 1]);
  34515. }
  34516. }
  34517. });
  34518. function createLarge(seriesModel, group, incremental) {
  34519. // TODO support polar
  34520. var data = seriesModel.getData();
  34521. var startPoint = [];
  34522. var valueIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  34523. startPoint[1 - valueIdx] = data.getLayout('valueAxisStart');
  34524. var el = new LargePath({
  34525. shape: {points: data.getLayout('largePoints')},
  34526. incremental: !!incremental,
  34527. __startPoint: startPoint,
  34528. __valueIdx: valueIdx
  34529. });
  34530. group.add(el);
  34531. setLargeStyle(el, seriesModel, data);
  34532. }
  34533. function setLargeStyle(el, seriesModel, data) {
  34534. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  34535. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  34536. el.useStyle(itemStyle);
  34537. el.style.fill = null;
  34538. el.style.stroke = borderColor;
  34539. el.style.lineWidth = data.getLayout('barWidth');
  34540. }
  34541. /*
  34542. * Licensed to the Apache Software Foundation (ASF) under one
  34543. * or more contributor license agreements. See the NOTICE file
  34544. * distributed with this work for additional information
  34545. * regarding copyright ownership. The ASF licenses this file
  34546. * to you under the Apache License, Version 2.0 (the
  34547. * "License"); you may not use this file except in compliance
  34548. * with the License. You may obtain a copy of the License at
  34549. *
  34550. * http://www.apache.org/licenses/LICENSE-2.0
  34551. *
  34552. * Unless required by applicable law or agreed to in writing,
  34553. * software distributed under the License is distributed on an
  34554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34555. * KIND, either express or implied. See the License for the
  34556. * specific language governing permissions and limitations
  34557. * under the License.
  34558. */
  34559. // In case developer forget to include grid component
  34560. registerLayout(curry(layout, 'bar'));
  34561. // Should after normal bar layout, otherwise it is blocked by normal bar layout.
  34562. registerLayout(largeLayout);
  34563. registerVisual({
  34564. seriesType: 'bar',
  34565. reset: function (seriesModel) {
  34566. // Visual coding for legend
  34567. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  34568. }
  34569. });
  34570. /*
  34571. * Licensed to the Apache Software Foundation (ASF) under one
  34572. * or more contributor license agreements. See the NOTICE file
  34573. * distributed with this work for additional information
  34574. * regarding copyright ownership. The ASF licenses this file
  34575. * to you under the Apache License, Version 2.0 (the
  34576. * "License"); you may not use this file except in compliance
  34577. * with the License. You may obtain a copy of the License at
  34578. *
  34579. * http://www.apache.org/licenses/LICENSE-2.0
  34580. *
  34581. * Unless required by applicable law or agreed to in writing,
  34582. * software distributed under the License is distributed on an
  34583. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34584. * KIND, either express or implied. See the License for the
  34585. * specific language governing permissions and limitations
  34586. * under the License.
  34587. */
  34588. /**
  34589. * [Usage]:
  34590. * (1)
  34591. * createListSimply(seriesModel, ['value']);
  34592. * (2)
  34593. * createListSimply(seriesModel, {
  34594. * coordDimensions: ['value'],
  34595. * dimensionsCount: 5
  34596. * });
  34597. *
  34598. * @param {module:echarts/model/Series} seriesModel
  34599. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  34600. * The options in opt, see `echarts/data/helper/createDimensions`
  34601. * @param {Array.<string>} [nameList]
  34602. * @return {module:echarts/data/List}
  34603. */
  34604. var createListSimply = function (seriesModel, opt, nameList) {
  34605. opt = isArray(opt) && {coordDimensions: opt} || extend({}, opt);
  34606. var source = seriesModel.getSource();
  34607. var dimensionsInfo = createDimensions(source, opt);
  34608. var list = new List(dimensionsInfo, seriesModel);
  34609. list.initData(source, nameList);
  34610. return list;
  34611. };
  34612. /*
  34613. * Licensed to the Apache Software Foundation (ASF) under one
  34614. * or more contributor license agreements. See the NOTICE file
  34615. * distributed with this work for additional information
  34616. * regarding copyright ownership. The ASF licenses this file
  34617. * to you under the Apache License, Version 2.0 (the
  34618. * "License"); you may not use this file except in compliance
  34619. * with the License. You may obtain a copy of the License at
  34620. *
  34621. * http://www.apache.org/licenses/LICENSE-2.0
  34622. *
  34623. * Unless required by applicable law or agreed to in writing,
  34624. * software distributed under the License is distributed on an
  34625. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34626. * KIND, either express or implied. See the License for the
  34627. * specific language governing permissions and limitations
  34628. * under the License.
  34629. */
  34630. /**
  34631. * Data selectable mixin for chart series.
  34632. * To eanble data select, option of series must have `selectedMode`.
  34633. * And each data item will use `selected` to toggle itself selected status
  34634. */
  34635. var selectableMixin = {
  34636. /**
  34637. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  34638. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  34639. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  34640. */
  34641. updateSelectedMap: function (targetList) {
  34642. this._targetList = isArray(targetList) ? targetList.slice() : [];
  34643. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  34644. targetMap.set(target.name, target);
  34645. return targetMap;
  34646. }, createHashMap());
  34647. },
  34648. /**
  34649. * Either name or id should be passed as input here.
  34650. * If both of them are defined, id is used.
  34651. *
  34652. * @param {string|undefined} name name of data
  34653. * @param {number|undefined} id dataIndex of data
  34654. */
  34655. // PENGING If selectedMode is null ?
  34656. select: function (name, id) {
  34657. var target = id != null
  34658. ? this._targetList[id]
  34659. : this._selectTargetMap.get(name);
  34660. var selectedMode = this.get('selectedMode');
  34661. if (selectedMode === 'single') {
  34662. this._selectTargetMap.each(function (target) {
  34663. target.selected = false;
  34664. });
  34665. }
  34666. target && (target.selected = true);
  34667. },
  34668. /**
  34669. * Either name or id should be passed as input here.
  34670. * If both of them are defined, id is used.
  34671. *
  34672. * @param {string|undefined} name name of data
  34673. * @param {number|undefined} id dataIndex of data
  34674. */
  34675. unSelect: function (name, id) {
  34676. var target = id != null
  34677. ? this._targetList[id]
  34678. : this._selectTargetMap.get(name);
  34679. // var selectedMode = this.get('selectedMode');
  34680. // selectedMode !== 'single' && target && (target.selected = false);
  34681. target && (target.selected = false);
  34682. },
  34683. /**
  34684. * Either name or id should be passed as input here.
  34685. * If both of them are defined, id is used.
  34686. *
  34687. * @param {string|undefined} name name of data
  34688. * @param {number|undefined} id dataIndex of data
  34689. */
  34690. toggleSelected: function (name, id) {
  34691. var target = id != null
  34692. ? this._targetList[id]
  34693. : this._selectTargetMap.get(name);
  34694. if (target != null) {
  34695. this[target.selected ? 'unSelect' : 'select'](name, id);
  34696. return target.selected;
  34697. }
  34698. },
  34699. /**
  34700. * Either name or id should be passed as input here.
  34701. * If both of them are defined, id is used.
  34702. *
  34703. * @param {string|undefined} name name of data
  34704. * @param {number|undefined} id dataIndex of data
  34705. */
  34706. isSelected: function (name, id) {
  34707. var target = id != null
  34708. ? this._targetList[id]
  34709. : this._selectTargetMap.get(name);
  34710. return target && target.selected;
  34711. }
  34712. };
  34713. /*
  34714. * Licensed to the Apache Software Foundation (ASF) under one
  34715. * or more contributor license agreements. See the NOTICE file
  34716. * distributed with this work for additional information
  34717. * regarding copyright ownership. The ASF licenses this file
  34718. * to you under the Apache License, Version 2.0 (the
  34719. * "License"); you may not use this file except in compliance
  34720. * with the License. You may obtain a copy of the License at
  34721. *
  34722. * http://www.apache.org/licenses/LICENSE-2.0
  34723. *
  34724. * Unless required by applicable law or agreed to in writing,
  34725. * software distributed under the License is distributed on an
  34726. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34727. * KIND, either express or implied. See the License for the
  34728. * specific language governing permissions and limitations
  34729. * under the License.
  34730. */
  34731. var PieSeries = extendSeriesModel({
  34732. type: 'series.pie',
  34733. // Overwrite
  34734. init: function (option) {
  34735. PieSeries.superApply(this, 'init', arguments);
  34736. // Enable legend selection for each data item
  34737. // Use a function instead of direct access because data reference may changed
  34738. this.legendDataProvider = function () {
  34739. return this.getRawData();
  34740. };
  34741. this.updateSelectedMap(this._createSelectableList());
  34742. this._defaultLabelLine(option);
  34743. },
  34744. // Overwrite
  34745. mergeOption: function (newOption) {
  34746. PieSeries.superCall(this, 'mergeOption', newOption);
  34747. this.updateSelectedMap(this._createSelectableList());
  34748. },
  34749. getInitialData: function (option, ecModel) {
  34750. return createListSimply(this, ['value']);
  34751. },
  34752. _createSelectableList: function () {
  34753. var data = this.getRawData();
  34754. var valueDim = data.mapDimension('value');
  34755. var targetList = [];
  34756. for (var i = 0, len = data.count(); i < len; i++) {
  34757. targetList.push({
  34758. name: data.getName(i),
  34759. value: data.get(valueDim, i),
  34760. selected: retrieveRawAttr(data, i, 'selected')
  34761. });
  34762. }
  34763. return targetList;
  34764. },
  34765. // Overwrite
  34766. getDataParams: function (dataIndex) {
  34767. var data = this.getData();
  34768. var params = PieSeries.superCall(this, 'getDataParams', dataIndex);
  34769. // FIXME toFixed?
  34770. var valueList = [];
  34771. data.each(data.mapDimension('value'), function (value) {
  34772. valueList.push(value);
  34773. });
  34774. params.percent = getPercentWithPrecision(
  34775. valueList,
  34776. dataIndex,
  34777. data.hostModel.get('percentPrecision')
  34778. );
  34779. params.$vars.push('percent');
  34780. return params;
  34781. },
  34782. _defaultLabelLine: function (option) {
  34783. // Extend labelLine emphasis
  34784. defaultEmphasis(option, 'labelLine', ['show']);
  34785. var labelLineNormalOpt = option.labelLine;
  34786. var labelLineEmphasisOpt = option.emphasis.labelLine;
  34787. // Not show label line if `label.normal.show = false`
  34788. labelLineNormalOpt.show = labelLineNormalOpt.show
  34789. && option.label.show;
  34790. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  34791. && option.emphasis.label.show;
  34792. },
  34793. defaultOption: {
  34794. zlevel: 0,
  34795. z: 2,
  34796. legendHoverLink: true,
  34797. hoverAnimation: true,
  34798. // 默认全局居中
  34799. center: ['50%', '60%'],
  34800. radius: [0, '50%'],
  34801. // 默认顺时针
  34802. clockwise: true,
  34803. startAngle: 90,
  34804. // 最小角度改为0
  34805. minAngle: 0,
  34806. // 选中时扇区偏移量
  34807. selectedOffset: 10,
  34808. // 高亮扇区偏移量
  34809. hoverOffset: 10,
  34810. // If use strategy to avoid label overlapping
  34811. avoidLabelOverlap: true,
  34812. // 选择模式,默认关闭,可选single,multiple
  34813. // selectedMode: false,
  34814. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  34815. // roseType: null,
  34816. percentPrecision: 2,
  34817. // If still show when all data zero.
  34818. stillShowZeroSum: true,
  34819. // cursor: null,
  34820. label: {
  34821. // If rotate around circle
  34822. rotate: false,
  34823. show: true,
  34824. // 'outer', 'inside', 'center'
  34825. position: 'outer',
  34826. formatter: '{b} : {c}({d}%)'
  34827. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  34828. // 默认使用全局文本样式,详见TEXTSTYLE
  34829. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  34830. },
  34831. // Enabled when label.normal.position is 'outer'
  34832. labelLine: {
  34833. show: true,
  34834. // 引导线两段中的第一段长度
  34835. length: 15,
  34836. // 引导线两段中的第二段长度
  34837. length2: 15,
  34838. smooth: false,
  34839. lineStyle: {
  34840. // color: 各异,
  34841. width: 1,
  34842. type: 'solid'
  34843. }
  34844. },
  34845. itemStyle: {
  34846. borderWidth: 1
  34847. },
  34848. // Animation type canbe expansion, scale
  34849. animationType: 'expansion',
  34850. animationEasing: 'cubicOut'
  34851. }
  34852. });
  34853. mixin(PieSeries, selectableMixin);
  34854. /*
  34855. * Licensed to the Apache Software Foundation (ASF) under one
  34856. * or more contributor license agreements. See the NOTICE file
  34857. * distributed with this work for additional information
  34858. * regarding copyright ownership. The ASF licenses this file
  34859. * to you under the Apache License, Version 2.0 (the
  34860. * "License"); you may not use this file except in compliance
  34861. * with the License. You may obtain a copy of the License at
  34862. *
  34863. * http://www.apache.org/licenses/LICENSE-2.0
  34864. *
  34865. * Unless required by applicable law or agreed to in writing,
  34866. * software distributed under the License is distributed on an
  34867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34868. * KIND, either express or implied. See the License for the
  34869. * specific language governing permissions and limitations
  34870. * under the License.
  34871. */
  34872. /**
  34873. * @param {module:echarts/model/Series} seriesModel
  34874. * @param {boolean} hasAnimation
  34875. * @inner
  34876. */
  34877. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  34878. var data = seriesModel.getData();
  34879. var dataIndex = this.dataIndex;
  34880. var name = data.getName(dataIndex);
  34881. var selectedOffset = seriesModel.get('selectedOffset');
  34882. api.dispatchAction({
  34883. type: 'pieToggleSelect',
  34884. from: uid,
  34885. name: name,
  34886. seriesId: seriesModel.id
  34887. });
  34888. data.each(function (idx) {
  34889. toggleItemSelected(
  34890. data.getItemGraphicEl(idx),
  34891. data.getItemLayout(idx),
  34892. seriesModel.isSelected(data.getName(idx)),
  34893. selectedOffset,
  34894. hasAnimation
  34895. );
  34896. });
  34897. }
  34898. /**
  34899. * @param {module:zrender/graphic/Sector} el
  34900. * @param {Object} layout
  34901. * @param {boolean} isSelected
  34902. * @param {number} selectedOffset
  34903. * @param {boolean} hasAnimation
  34904. * @inner
  34905. */
  34906. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  34907. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  34908. var dx = Math.cos(midAngle);
  34909. var dy = Math.sin(midAngle);
  34910. var offset = isSelected ? selectedOffset : 0;
  34911. var position = [dx * offset, dy * offset];
  34912. hasAnimation
  34913. // animateTo will stop revious animation like update transition
  34914. ? el.animate()
  34915. .when(200, {
  34916. position: position
  34917. })
  34918. .start('bounceOut')
  34919. : el.attr('position', position);
  34920. }
  34921. /**
  34922. * Piece of pie including Sector, Label, LabelLine
  34923. * @constructor
  34924. * @extends {module:zrender/graphic/Group}
  34925. */
  34926. function PiePiece(data, idx) {
  34927. Group.call(this);
  34928. var sector = new Sector({
  34929. z2: 2
  34930. });
  34931. var polyline = new Polyline();
  34932. var text = new Text();
  34933. this.add(sector);
  34934. this.add(polyline);
  34935. this.add(text);
  34936. this.updateData(data, idx, true);
  34937. // Hover to change label and labelLine
  34938. function onEmphasis() {
  34939. polyline.ignore = polyline.hoverIgnore;
  34940. text.ignore = text.hoverIgnore;
  34941. }
  34942. function onNormal() {
  34943. polyline.ignore = polyline.normalIgnore;
  34944. text.ignore = text.normalIgnore;
  34945. }
  34946. this.on('emphasis', onEmphasis)
  34947. .on('normal', onNormal)
  34948. .on('mouseover', onEmphasis)
  34949. .on('mouseout', onNormal);
  34950. }
  34951. var piePieceProto = PiePiece.prototype;
  34952. piePieceProto.updateData = function (data, idx, firstCreate) {
  34953. var sector = this.childAt(0);
  34954. var seriesModel = data.hostModel;
  34955. var itemModel = data.getItemModel(idx);
  34956. var layout = data.getItemLayout(idx);
  34957. var sectorShape = extend({}, layout);
  34958. sectorShape.label = null;
  34959. if (firstCreate) {
  34960. sector.setShape(sectorShape);
  34961. var animationType = seriesModel.getShallow('animationType');
  34962. if (animationType === 'scale') {
  34963. sector.shape.r = layout.r0;
  34964. initProps(sector, {
  34965. shape: {
  34966. r: layout.r
  34967. }
  34968. }, seriesModel, idx);
  34969. }
  34970. // Expansion
  34971. else {
  34972. sector.shape.endAngle = layout.startAngle;
  34973. updateProps(sector, {
  34974. shape: {
  34975. endAngle: layout.endAngle
  34976. }
  34977. }, seriesModel, idx);
  34978. }
  34979. }
  34980. else {
  34981. updateProps(sector, {
  34982. shape: sectorShape
  34983. }, seriesModel, idx);
  34984. }
  34985. // Update common style
  34986. var visualColor = data.getItemVisual(idx, 'color');
  34987. sector.useStyle(
  34988. defaults(
  34989. {
  34990. lineJoin: 'bevel',
  34991. fill: visualColor
  34992. },
  34993. itemModel.getModel('itemStyle').getItemStyle()
  34994. )
  34995. );
  34996. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  34997. var cursorStyle = itemModel.getShallow('cursor');
  34998. cursorStyle && sector.attr('cursor', cursorStyle);
  34999. // Toggle selected
  35000. toggleItemSelected(
  35001. this,
  35002. data.getItemLayout(idx),
  35003. seriesModel.isSelected(null, idx),
  35004. seriesModel.get('selectedOffset'),
  35005. seriesModel.get('animation')
  35006. );
  35007. function onEmphasis() {
  35008. // Sector may has animation of updating data. Force to move to the last frame
  35009. // Or it may stopped on the wrong shape
  35010. sector.stopAnimation(true);
  35011. sector.animateTo({
  35012. shape: {
  35013. r: layout.r + seriesModel.get('hoverOffset')
  35014. }
  35015. }, 300, 'elasticOut');
  35016. }
  35017. function onNormal() {
  35018. sector.stopAnimation(true);
  35019. sector.animateTo({
  35020. shape: {
  35021. r: layout.r
  35022. }
  35023. }, 300, 'elasticOut');
  35024. }
  35025. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  35026. if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) {
  35027. sector
  35028. .on('mouseover', onEmphasis)
  35029. .on('mouseout', onNormal)
  35030. .on('emphasis', onEmphasis)
  35031. .on('normal', onNormal);
  35032. }
  35033. this._updateLabel(data, idx);
  35034. setHoverStyle(this);
  35035. };
  35036. piePieceProto._updateLabel = function (data, idx) {
  35037. var labelLine = this.childAt(1);
  35038. var labelText = this.childAt(2);
  35039. var seriesModel = data.hostModel;
  35040. var itemModel = data.getItemModel(idx);
  35041. var layout = data.getItemLayout(idx);
  35042. var labelLayout = layout.label;
  35043. var visualColor = data.getItemVisual(idx, 'color');
  35044. updateProps(labelLine, {
  35045. shape: {
  35046. points: labelLayout.linePoints || [
  35047. [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]
  35048. ]
  35049. }
  35050. }, seriesModel, idx);
  35051. updateProps(labelText, {
  35052. style: {
  35053. x: labelLayout.x,
  35054. y: labelLayout.y
  35055. }
  35056. }, seriesModel, idx);
  35057. labelText.attr({
  35058. rotation: labelLayout.rotation,
  35059. origin: [labelLayout.x, labelLayout.y],
  35060. z2: 10
  35061. });
  35062. var labelModel = itemModel.getModel('label');
  35063. var labelHoverModel = itemModel.getModel('emphasis.label');
  35064. var labelLineModel = itemModel.getModel('labelLine');
  35065. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  35066. var visualColor = data.getItemVisual(idx, 'color');
  35067. setLabelStyle(
  35068. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  35069. {
  35070. labelFetcher: data.hostModel,
  35071. labelDataIndex: idx,
  35072. defaultText: data.getName(idx),
  35073. autoColor: visualColor,
  35074. useInsideStyle: !!labelLayout.inside
  35075. },
  35076. {
  35077. textAlign: labelLayout.textAlign,
  35078. textVerticalAlign: labelLayout.verticalAlign,
  35079. opacity: data.getItemVisual(idx, 'opacity')
  35080. }
  35081. );
  35082. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35083. labelText.hoverIgnore = !labelHoverModel.get('show');
  35084. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35085. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  35086. // Default use item visual color
  35087. labelLine.setStyle({
  35088. stroke: visualColor,
  35089. opacity: data.getItemVisual(idx, 'opacity')
  35090. });
  35091. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35092. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35093. var smooth = labelLineModel.get('smooth');
  35094. if (smooth && smooth === true) {
  35095. smooth = 0.4;
  35096. }
  35097. labelLine.setShape({
  35098. smooth: smooth
  35099. });
  35100. };
  35101. inherits(PiePiece, Group);
  35102. // Pie view
  35103. var PieView = Chart.extend({
  35104. type: 'pie',
  35105. init: function () {
  35106. var sectorGroup = new Group();
  35107. this._sectorGroup = sectorGroup;
  35108. },
  35109. render: function (seriesModel, ecModel, api, payload) {
  35110. if (payload && (payload.from === this.uid)) {
  35111. return;
  35112. }
  35113. var data = seriesModel.getData();
  35114. var oldData = this._data;
  35115. var group = this.group;
  35116. var hasAnimation = ecModel.get('animation');
  35117. var isFirstRender = !oldData;
  35118. var animationType = seriesModel.get('animationType');
  35119. var onSectorClick = curry(
  35120. updateDataSelected, this.uid, seriesModel, hasAnimation, api
  35121. );
  35122. var selectedMode = seriesModel.get('selectedMode');
  35123. data.diff(oldData)
  35124. .add(function (idx) {
  35125. var piePiece = new PiePiece(data, idx);
  35126. // Default expansion animation
  35127. if (isFirstRender && animationType !== 'scale') {
  35128. piePiece.eachChild(function (child) {
  35129. child.stopAnimation(true);
  35130. });
  35131. }
  35132. selectedMode && piePiece.on('click', onSectorClick);
  35133. data.setItemGraphicEl(idx, piePiece);
  35134. group.add(piePiece);
  35135. })
  35136. .update(function (newIdx, oldIdx) {
  35137. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35138. piePiece.updateData(data, newIdx);
  35139. piePiece.off('click');
  35140. selectedMode && piePiece.on('click', onSectorClick);
  35141. group.add(piePiece);
  35142. data.setItemGraphicEl(newIdx, piePiece);
  35143. })
  35144. .remove(function (idx) {
  35145. var piePiece = oldData.getItemGraphicEl(idx);
  35146. group.remove(piePiece);
  35147. })
  35148. .execute();
  35149. if (
  35150. hasAnimation && isFirstRender && data.count() > 0
  35151. // Default expansion animation
  35152. && animationType !== 'scale'
  35153. ) {
  35154. var shape = data.getItemLayout(0);
  35155. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35156. var removeClipPath = bind(group.removeClipPath, group);
  35157. group.setClipPath(this._createClipPath(
  35158. shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel
  35159. ));
  35160. }
  35161. this._data = data;
  35162. },
  35163. dispose: function () {},
  35164. _createClipPath: function (
  35165. cx, cy, r, startAngle, clockwise, cb, seriesModel
  35166. ) {
  35167. var clipPath = new Sector({
  35168. shape: {
  35169. cx: cx,
  35170. cy: cy,
  35171. r0: 0,
  35172. r: r,
  35173. startAngle: startAngle,
  35174. endAngle: startAngle,
  35175. clockwise: clockwise
  35176. }
  35177. });
  35178. initProps(clipPath, {
  35179. shape: {
  35180. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35181. }
  35182. }, seriesModel, cb);
  35183. return clipPath;
  35184. },
  35185. /**
  35186. * @implement
  35187. */
  35188. containPoint: function (point, seriesModel) {
  35189. var data = seriesModel.getData();
  35190. var itemLayout = data.getItemLayout(0);
  35191. if (itemLayout) {
  35192. var dx = point[0] - itemLayout.cx;
  35193. var dy = point[1] - itemLayout.cy;
  35194. var radius = Math.sqrt(dx * dx + dy * dy);
  35195. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35196. }
  35197. }
  35198. });
  35199. /*
  35200. * Licensed to the Apache Software Foundation (ASF) under one
  35201. * or more contributor license agreements. See the NOTICE file
  35202. * distributed with this work for additional information
  35203. * regarding copyright ownership. The ASF licenses this file
  35204. * to you under the Apache License, Version 2.0 (the
  35205. * "License"); you may not use this file except in compliance
  35206. * with the License. You may obtain a copy of the License at
  35207. *
  35208. * http://www.apache.org/licenses/LICENSE-2.0
  35209. *
  35210. * Unless required by applicable law or agreed to in writing,
  35211. * software distributed under the License is distributed on an
  35212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35213. * KIND, either express or implied. See the License for the
  35214. * specific language governing permissions and limitations
  35215. * under the License.
  35216. */
  35217. var createDataSelectAction = function (seriesType, actionInfos) {
  35218. each$1(actionInfos, function (actionInfo) {
  35219. actionInfo.update = 'updateView';
  35220. /**
  35221. * @payload
  35222. * @property {string} seriesName
  35223. * @property {string} name
  35224. */
  35225. registerAction(actionInfo, function (payload, ecModel) {
  35226. var selected = {};
  35227. ecModel.eachComponent(
  35228. {mainType: 'series', subType: seriesType, query: payload},
  35229. function (seriesModel) {
  35230. if (seriesModel[actionInfo.method]) {
  35231. seriesModel[actionInfo.method](
  35232. payload.name,
  35233. payload.dataIndex
  35234. );
  35235. }
  35236. var data = seriesModel.getData();
  35237. // Create selected map
  35238. data.each(function (idx) {
  35239. var name = data.getName(idx);
  35240. selected[name] = seriesModel.isSelected(name)
  35241. || false;
  35242. });
  35243. }
  35244. );
  35245. return {
  35246. name: payload.name,
  35247. selected: selected
  35248. };
  35249. });
  35250. });
  35251. };
  35252. /*
  35253. * Licensed to the Apache Software Foundation (ASF) under one
  35254. * or more contributor license agreements. See the NOTICE file
  35255. * distributed with this work for additional information
  35256. * regarding copyright ownership. The ASF licenses this file
  35257. * to you under the Apache License, Version 2.0 (the
  35258. * "License"); you may not use this file except in compliance
  35259. * with the License. You may obtain a copy of the License at
  35260. *
  35261. * http://www.apache.org/licenses/LICENSE-2.0
  35262. *
  35263. * Unless required by applicable law or agreed to in writing,
  35264. * software distributed under the License is distributed on an
  35265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35266. * KIND, either express or implied. See the License for the
  35267. * specific language governing permissions and limitations
  35268. * under the License.
  35269. */
  35270. // Pick color from palette for each data item.
  35271. // Applicable for charts that require applying color palette
  35272. // in data level (like pie, funnel, chord).
  35273. var dataColor = function (seriesType) {
  35274. return {
  35275. getTargetSeries: function (ecModel) {
  35276. // Pie and funnel may use diferrent scope
  35277. var paletteScope = {};
  35278. var seiresModelMap = createHashMap();
  35279. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35280. seriesModel.__paletteScope = paletteScope;
  35281. seiresModelMap.set(seriesModel.uid, seriesModel);
  35282. });
  35283. return seiresModelMap;
  35284. },
  35285. reset: function (seriesModel, ecModel) {
  35286. var dataAll = seriesModel.getRawData();
  35287. var idxMap = {};
  35288. var data = seriesModel.getData();
  35289. data.each(function (idx) {
  35290. var rawIdx = data.getRawIndex(idx);
  35291. idxMap[rawIdx] = idx;
  35292. });
  35293. dataAll.each(function (rawIdx) {
  35294. var filteredIdx = idxMap[rawIdx];
  35295. // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  35296. var singleDataColor = filteredIdx != null
  35297. && data.getItemVisual(filteredIdx, 'color', true);
  35298. if (!singleDataColor) {
  35299. // FIXME Performance
  35300. var itemModel = dataAll.getItemModel(rawIdx);
  35301. var color = itemModel.get('itemStyle.color')
  35302. || seriesModel.getColorFromPalette(
  35303. dataAll.getName(rawIdx) || (rawIdx + ''), seriesModel.__paletteScope,
  35304. dataAll.count()
  35305. );
  35306. // Legend may use the visual info in data before processed
  35307. dataAll.setItemVisual(rawIdx, 'color', color);
  35308. // Data is not filtered
  35309. if (filteredIdx != null) {
  35310. data.setItemVisual(filteredIdx, 'color', color);
  35311. }
  35312. }
  35313. else {
  35314. // Set data all color for legend
  35315. dataAll.setItemVisual(rawIdx, 'color', singleDataColor);
  35316. }
  35317. });
  35318. }
  35319. };
  35320. };
  35321. /*
  35322. * Licensed to the Apache Software Foundation (ASF) under one
  35323. * or more contributor license agreements. See the NOTICE file
  35324. * distributed with this work for additional information
  35325. * regarding copyright ownership. The ASF licenses this file
  35326. * to you under the Apache License, Version 2.0 (the
  35327. * "License"); you may not use this file except in compliance
  35328. * with the License. You may obtain a copy of the License at
  35329. *
  35330. * http://www.apache.org/licenses/LICENSE-2.0
  35331. *
  35332. * Unless required by applicable law or agreed to in writing,
  35333. * software distributed under the License is distributed on an
  35334. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35335. * KIND, either express or implied. See the License for the
  35336. * specific language governing permissions and limitations
  35337. * under the License.
  35338. */
  35339. // FIXME emphasis label position is not same with normal label position
  35340. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) {
  35341. list.sort(function (a, b) {
  35342. return a.y - b.y;
  35343. });
  35344. // 压
  35345. function shiftDown(start, end, delta, dir) {
  35346. for (var j = start; j < end; j++) {
  35347. list[j].y += delta;
  35348. if (j > start
  35349. && j + 1 < end
  35350. && list[j + 1].y > list[j].y + list[j].height
  35351. ) {
  35352. shiftUp(j, delta / 2);
  35353. return;
  35354. }
  35355. }
  35356. shiftUp(end - 1, delta / 2);
  35357. }
  35358. // 弹
  35359. function shiftUp(end, delta) {
  35360. for (var j = end; j >= 0; j--) {
  35361. list[j].y -= delta;
  35362. if (j > 0
  35363. && list[j].y > list[j - 1].y + list[j - 1].height
  35364. ) {
  35365. break;
  35366. }
  35367. }
  35368. }
  35369. function changeX(list, isDownList, cx, cy, r, dir) {
  35370. var lastDeltaX = dir > 0
  35371. ? isDownList // 右侧
  35372. ? Number.MAX_VALUE // 下
  35373. : 0 // 上
  35374. : isDownList // 左侧
  35375. ? Number.MAX_VALUE // 下
  35376. : 0; // 上
  35377. for (var i = 0, l = list.length; i < l; i++) {
  35378. // Not change x for center label
  35379. if (list[i].position === 'center') {
  35380. continue;
  35381. }
  35382. var deltaY = Math.abs(list[i].y - cy);
  35383. var length = list[i].len;
  35384. var length2 = list[i].len2;
  35385. var deltaX = (deltaY < r + length)
  35386. ? Math.sqrt(
  35387. (r + length + length2) * (r + length + length2)
  35388. - deltaY * deltaY
  35389. )
  35390. : Math.abs(list[i].x - cx);
  35391. if (isDownList && deltaX >= lastDeltaX) {
  35392. // 右下,左下
  35393. deltaX = lastDeltaX - 10;
  35394. }
  35395. if (!isDownList && deltaX <= lastDeltaX) {
  35396. // 右上,左上
  35397. deltaX = lastDeltaX + 10;
  35398. }
  35399. list[i].x = cx + deltaX * dir;
  35400. lastDeltaX = deltaX;
  35401. }
  35402. }
  35403. var lastY = 0;
  35404. var delta;
  35405. var len = list.length;
  35406. var upList = [];
  35407. var downList = [];
  35408. for (var i = 0; i < len; i++) {
  35409. delta = list[i].y - lastY;
  35410. if (delta < 0) {
  35411. shiftDown(i, len, -delta, dir);
  35412. }
  35413. lastY = list[i].y + list[i].height;
  35414. }
  35415. if (viewHeight - lastY < 0) {
  35416. shiftUp(len - 1, lastY - viewHeight);
  35417. }
  35418. for (var i = 0; i < len; i++) {
  35419. if (list[i].y >= cy) {
  35420. downList.push(list[i]);
  35421. }
  35422. else {
  35423. upList.push(list[i]);
  35424. }
  35425. }
  35426. changeX(upList, false, cx, cy, r, dir);
  35427. changeX(downList, true, cx, cy, r, dir);
  35428. }
  35429. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) {
  35430. var leftList = [];
  35431. var rightList = [];
  35432. for (var i = 0; i < labelLayoutList.length; i++) {
  35433. if (labelLayoutList[i].x < cx) {
  35434. leftList.push(labelLayoutList[i]);
  35435. }
  35436. else {
  35437. rightList.push(labelLayoutList[i]);
  35438. }
  35439. }
  35440. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight);
  35441. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight);
  35442. for (var i = 0; i < labelLayoutList.length; i++) {
  35443. var linePoints = labelLayoutList[i].linePoints;
  35444. if (linePoints) {
  35445. var dist = linePoints[1][0] - linePoints[2][0];
  35446. if (labelLayoutList[i].x < cx) {
  35447. linePoints[2][0] = labelLayoutList[i].x + 3;
  35448. }
  35449. else {
  35450. linePoints[2][0] = labelLayoutList[i].x - 3;
  35451. }
  35452. linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y;
  35453. linePoints[1][0] = linePoints[2][0] + dist;
  35454. }
  35455. }
  35456. }
  35457. var labelLayout = function (seriesModel, r, viewWidth, viewHeight) {
  35458. var data = seriesModel.getData();
  35459. var labelLayoutList = [];
  35460. var cx;
  35461. var cy;
  35462. var hasLabelRotate = false;
  35463. data.each(function (idx) {
  35464. var layout = data.getItemLayout(idx);
  35465. var itemModel = data.getItemModel(idx);
  35466. var labelModel = itemModel.getModel('label');
  35467. // Use position in normal or emphasis
  35468. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  35469. var labelLineModel = itemModel.getModel('labelLine');
  35470. var labelLineLen = labelLineModel.get('length');
  35471. var labelLineLen2 = labelLineModel.get('length2');
  35472. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35473. var dx = Math.cos(midAngle);
  35474. var dy = Math.sin(midAngle);
  35475. var textX;
  35476. var textY;
  35477. var linePoints;
  35478. var textAlign;
  35479. cx = layout.cx;
  35480. cy = layout.cy;
  35481. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  35482. if (labelPosition === 'center') {
  35483. textX = layout.cx;
  35484. textY = layout.cy;
  35485. textAlign = 'center';
  35486. }
  35487. else {
  35488. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  35489. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  35490. textX = x1 + dx * 3;
  35491. textY = y1 + dy * 3;
  35492. if (!isLabelInside) {
  35493. // For roseType
  35494. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  35495. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  35496. var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2);
  35497. var y3 = y2;
  35498. textX = x3 + (dx < 0 ? -5 : 5);
  35499. textY = y3;
  35500. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  35501. }
  35502. textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right');
  35503. }
  35504. var font = labelModel.getFont();
  35505. var labelRotate = labelModel.get('rotate')
  35506. ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0;
  35507. var text = seriesModel.getFormattedLabel(idx, 'normal')
  35508. || data.getName(idx);
  35509. var textRect = getBoundingRect(
  35510. text, font, textAlign, 'top'
  35511. );
  35512. hasLabelRotate = !!labelRotate;
  35513. layout.label = {
  35514. x: textX,
  35515. y: textY,
  35516. position: labelPosition,
  35517. height: textRect.height,
  35518. len: labelLineLen,
  35519. len2: labelLineLen2,
  35520. linePoints: linePoints,
  35521. textAlign: textAlign,
  35522. verticalAlign: 'middle',
  35523. rotation: labelRotate,
  35524. inside: isLabelInside
  35525. };
  35526. // Not layout the inside label
  35527. if (!isLabelInside) {
  35528. labelLayoutList.push(layout.label);
  35529. }
  35530. });
  35531. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  35532. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight);
  35533. }
  35534. };
  35535. /*
  35536. * Licensed to the Apache Software Foundation (ASF) under one
  35537. * or more contributor license agreements. See the NOTICE file
  35538. * distributed with this work for additional information
  35539. * regarding copyright ownership. The ASF licenses this file
  35540. * to you under the Apache License, Version 2.0 (the
  35541. * "License"); you may not use this file except in compliance
  35542. * with the License. You may obtain a copy of the License at
  35543. *
  35544. * http://www.apache.org/licenses/LICENSE-2.0
  35545. *
  35546. * Unless required by applicable law or agreed to in writing,
  35547. * software distributed under the License is distributed on an
  35548. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35549. * KIND, either express or implied. See the License for the
  35550. * specific language governing permissions and limitations
  35551. * under the License.
  35552. */
  35553. var PI2$4 = Math.PI * 2;
  35554. var RADIAN = Math.PI / 180;
  35555. var pieLayout = function (seriesType, ecModel, api, payload) {
  35556. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  35557. var data = seriesModel.getData();
  35558. var valueDim = data.mapDimension('value');
  35559. var center = seriesModel.get('center');
  35560. var radius = seriesModel.get('radius');
  35561. if (!isArray(radius)) {
  35562. radius = [0, radius];
  35563. }
  35564. if (!isArray(center)) {
  35565. center = [center, center];
  35566. }
  35567. var width = api.getWidth();
  35568. var height = api.getHeight();
  35569. var size = Math.min(width, height);
  35570. var cx = parsePercent$1(center[0], width);
  35571. var cy = parsePercent$1(center[1], height);
  35572. var r0 = parsePercent$1(radius[0], size / 2);
  35573. var r = parsePercent$1(radius[1], size / 2);
  35574. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  35575. var minAngle = seriesModel.get('minAngle') * RADIAN;
  35576. var validDataCount = 0;
  35577. data.each(valueDim, function (value) {
  35578. !isNaN(value) && validDataCount++;
  35579. });
  35580. var sum = data.getSum(valueDim);
  35581. // Sum may be 0
  35582. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  35583. var clockwise = seriesModel.get('clockwise');
  35584. var roseType = seriesModel.get('roseType');
  35585. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  35586. // [0...max]
  35587. var extent = data.getDataExtent(valueDim);
  35588. extent[0] = 0;
  35589. // In the case some sector angle is smaller than minAngle
  35590. var restAngle = PI2$4;
  35591. var valueSumLargerThanMinAngle = 0;
  35592. var currentAngle = startAngle;
  35593. var dir = clockwise ? 1 : -1;
  35594. data.each(valueDim, function (value, idx) {
  35595. var angle;
  35596. if (isNaN(value)) {
  35597. data.setItemLayout(idx, {
  35598. angle: NaN,
  35599. startAngle: NaN,
  35600. endAngle: NaN,
  35601. clockwise: clockwise,
  35602. cx: cx,
  35603. cy: cy,
  35604. r0: r0,
  35605. r: roseType
  35606. ? NaN
  35607. : r
  35608. });
  35609. return;
  35610. }
  35611. // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  35612. if (roseType !== 'area') {
  35613. angle = (sum === 0 && stillShowZeroSum)
  35614. ? unitRadian : (value * unitRadian);
  35615. }
  35616. else {
  35617. angle = PI2$4 / validDataCount;
  35618. }
  35619. if (angle < minAngle) {
  35620. angle = minAngle;
  35621. restAngle -= minAngle;
  35622. }
  35623. else {
  35624. valueSumLargerThanMinAngle += value;
  35625. }
  35626. var endAngle = currentAngle + dir * angle;
  35627. data.setItemLayout(idx, {
  35628. angle: angle,
  35629. startAngle: currentAngle,
  35630. endAngle: endAngle,
  35631. clockwise: clockwise,
  35632. cx: cx,
  35633. cy: cy,
  35634. r0: r0,
  35635. r: roseType
  35636. ? linearMap(value, extent, [r0, r])
  35637. : r
  35638. });
  35639. currentAngle = endAngle;
  35640. });
  35641. // Some sector is constrained by minAngle
  35642. // Rest sectors needs recalculate angle
  35643. if (restAngle < PI2$4 && validDataCount) {
  35644. // Average the angle if rest angle is not enough after all angles is
  35645. // Constrained by minAngle
  35646. if (restAngle <= 1e-3) {
  35647. var angle = PI2$4 / validDataCount;
  35648. data.each(valueDim, function (value, idx) {
  35649. if (!isNaN(value)) {
  35650. var layout = data.getItemLayout(idx);
  35651. layout.angle = angle;
  35652. layout.startAngle = startAngle + dir * idx * angle;
  35653. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  35654. }
  35655. });
  35656. }
  35657. else {
  35658. unitRadian = restAngle / valueSumLargerThanMinAngle;
  35659. currentAngle = startAngle;
  35660. data.each(valueDim, function (value, idx) {
  35661. if (!isNaN(value)) {
  35662. var layout = data.getItemLayout(idx);
  35663. var angle = layout.angle === minAngle
  35664. ? minAngle : value * unitRadian;
  35665. layout.startAngle = currentAngle;
  35666. layout.endAngle = currentAngle + dir * angle;
  35667. currentAngle += dir * angle;
  35668. }
  35669. });
  35670. }
  35671. }
  35672. labelLayout(seriesModel, r, width, height);
  35673. });
  35674. };
  35675. /*
  35676. * Licensed to the Apache Software Foundation (ASF) under one
  35677. * or more contributor license agreements. See the NOTICE file
  35678. * distributed with this work for additional information
  35679. * regarding copyright ownership. The ASF licenses this file
  35680. * to you under the Apache License, Version 2.0 (the
  35681. * "License"); you may not use this file except in compliance
  35682. * with the License. You may obtain a copy of the License at
  35683. *
  35684. * http://www.apache.org/licenses/LICENSE-2.0
  35685. *
  35686. * Unless required by applicable law or agreed to in writing,
  35687. * software distributed under the License is distributed on an
  35688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35689. * KIND, either express or implied. See the License for the
  35690. * specific language governing permissions and limitations
  35691. * under the License.
  35692. */
  35693. var dataFilter = function (seriesType) {
  35694. return {
  35695. seriesType: seriesType,
  35696. reset: function (seriesModel, ecModel) {
  35697. var legendModels = ecModel.findComponents({
  35698. mainType: 'legend'
  35699. });
  35700. if (!legendModels || !legendModels.length) {
  35701. return;
  35702. }
  35703. var data = seriesModel.getData();
  35704. data.filterSelf(function (idx) {
  35705. var name = data.getName(idx);
  35706. // If in any legend component the status is not selected.
  35707. for (var i = 0; i < legendModels.length; i++) {
  35708. if (!legendModels[i].isSelected(name)) {
  35709. return false;
  35710. }
  35711. }
  35712. return true;
  35713. });
  35714. }
  35715. };
  35716. };
  35717. /*
  35718. * Licensed to the Apache Software Foundation (ASF) under one
  35719. * or more contributor license agreements. See the NOTICE file
  35720. * distributed with this work for additional information
  35721. * regarding copyright ownership. The ASF licenses this file
  35722. * to you under the Apache License, Version 2.0 (the
  35723. * "License"); you may not use this file except in compliance
  35724. * with the License. You may obtain a copy of the License at
  35725. *
  35726. * http://www.apache.org/licenses/LICENSE-2.0
  35727. *
  35728. * Unless required by applicable law or agreed to in writing,
  35729. * software distributed under the License is distributed on an
  35730. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35731. * KIND, either express or implied. See the License for the
  35732. * specific language governing permissions and limitations
  35733. * under the License.
  35734. */
  35735. createDataSelectAction('pie', [{
  35736. type: 'pieToggleSelect',
  35737. event: 'pieselectchanged',
  35738. method: 'toggleSelected'
  35739. }, {
  35740. type: 'pieSelect',
  35741. event: 'pieselected',
  35742. method: 'select'
  35743. }, {
  35744. type: 'pieUnSelect',
  35745. event: 'pieunselected',
  35746. method: 'unSelect'
  35747. }]);
  35748. registerVisual(dataColor('pie'));
  35749. registerLayout(curry(pieLayout, 'pie'));
  35750. registerProcessor(dataFilter('pie'));
  35751. /*
  35752. * Licensed to the Apache Software Foundation (ASF) under one
  35753. * or more contributor license agreements. See the NOTICE file
  35754. * distributed with this work for additional information
  35755. * regarding copyright ownership. The ASF licenses this file
  35756. * to you under the Apache License, Version 2.0 (the
  35757. * "License"); you may not use this file except in compliance
  35758. * with the License. You may obtain a copy of the License at
  35759. *
  35760. * http://www.apache.org/licenses/LICENSE-2.0
  35761. *
  35762. * Unless required by applicable law or agreed to in writing,
  35763. * software distributed under the License is distributed on an
  35764. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35765. * KIND, either express or implied. See the License for the
  35766. * specific language governing permissions and limitations
  35767. * under the License.
  35768. */
  35769. SeriesModel.extend({
  35770. type: 'series.scatter',
  35771. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  35772. getInitialData: function (option, ecModel) {
  35773. return createListFromArray(this.getSource(), this);
  35774. },
  35775. brushSelector: 'point',
  35776. getProgressive: function () {
  35777. var progressive = this.option.progressive;
  35778. if (progressive == null) {
  35779. // PENDING
  35780. return this.option.large ? 5e3 : this.get('progressive');
  35781. }
  35782. return progressive;
  35783. },
  35784. getProgressiveThreshold: function () {
  35785. var progressiveThreshold = this.option.progressiveThreshold;
  35786. if (progressiveThreshold == null) {
  35787. // PENDING
  35788. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  35789. }
  35790. return progressiveThreshold;
  35791. },
  35792. defaultOption: {
  35793. coordinateSystem: 'cartesian2d',
  35794. zlevel: 0,
  35795. z: 2,
  35796. legendHoverLink: true,
  35797. hoverAnimation: true,
  35798. // Cartesian coordinate system
  35799. // xAxisIndex: 0,
  35800. // yAxisIndex: 0,
  35801. // Polar coordinate system
  35802. // polarIndex: 0,
  35803. // Geo coordinate system
  35804. // geoIndex: 0,
  35805. // symbol: null, // 图形类型
  35806. symbolSize: 10, // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  35807. // symbolRotate: null, // 图形旋转控制
  35808. large: false,
  35809. // Available when large is true
  35810. largeThreshold: 2000,
  35811. // cursor: null,
  35812. // label: {
  35813. // show: false
  35814. // distance: 5,
  35815. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35816. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  35817. // 'inside'|'left'|'right'|'top'|'bottom'
  35818. // 默认使用全局文本样式,详见TEXTSTYLE
  35819. // },
  35820. itemStyle: {
  35821. opacity: 0.8
  35822. // color: 各异
  35823. }
  35824. // progressive: null
  35825. }
  35826. });
  35827. /*
  35828. * Licensed to the Apache Software Foundation (ASF) under one
  35829. * or more contributor license agreements. See the NOTICE file
  35830. * distributed with this work for additional information
  35831. * regarding copyright ownership. The ASF licenses this file
  35832. * to you under the Apache License, Version 2.0 (the
  35833. * "License"); you may not use this file except in compliance
  35834. * with the License. You may obtain a copy of the License at
  35835. *
  35836. * http://www.apache.org/licenses/LICENSE-2.0
  35837. *
  35838. * Unless required by applicable law or agreed to in writing,
  35839. * software distributed under the License is distributed on an
  35840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35841. * KIND, either express or implied. See the License for the
  35842. * specific language governing permissions and limitations
  35843. * under the License.
  35844. */
  35845. // TODO Batch by color
  35846. var BOOST_SIZE_THRESHOLD = 4;
  35847. var LargeSymbolPath = extendShape({
  35848. shape: {
  35849. points: null
  35850. },
  35851. symbolProxy: null,
  35852. buildPath: function (path, shape) {
  35853. var points = shape.points;
  35854. var size = shape.size;
  35855. var symbolProxy = this.symbolProxy;
  35856. var symbolProxyShape = symbolProxy.shape;
  35857. var ctx = path.getContext ? path.getContext() : path;
  35858. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD;
  35859. // Do draw in afterBrush.
  35860. if (canBoost) {
  35861. return;
  35862. }
  35863. for (var i = 0; i < points.length;) {
  35864. var x = points[i++];
  35865. var y = points[i++];
  35866. if (isNaN(x) || isNaN(y)) {
  35867. continue;
  35868. }
  35869. symbolProxyShape.x = x - size[0] / 2;
  35870. symbolProxyShape.y = y - size[1] / 2;
  35871. symbolProxyShape.width = size[0];
  35872. symbolProxyShape.height = size[1];
  35873. symbolProxy.buildPath(path, symbolProxyShape, true);
  35874. }
  35875. },
  35876. afterBrush: function (ctx) {
  35877. var shape = this.shape;
  35878. var points = shape.points;
  35879. var size = shape.size;
  35880. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  35881. if (!canBoost) {
  35882. return;
  35883. }
  35884. this.setTransform(ctx);
  35885. // PENDING If style or other canvas status changed?
  35886. for (var i = 0; i < points.length;) {
  35887. var x = points[i++];
  35888. var y = points[i++];
  35889. if (isNaN(x) || isNaN(y)) {
  35890. continue;
  35891. }
  35892. // fillRect is faster than building a rect path and draw.
  35893. // And it support light globalCompositeOperation.
  35894. ctx.fillRect(
  35895. x - size[0] / 2, y - size[1] / 2,
  35896. size[0], size[1]
  35897. );
  35898. }
  35899. this.restoreTransform(ctx);
  35900. },
  35901. findDataIndex: function (x, y) {
  35902. // TODO ???
  35903. // Consider transform
  35904. var shape = this.shape;
  35905. var points = shape.points;
  35906. var size = shape.size;
  35907. var w = Math.max(size[0], 4);
  35908. var h = Math.max(size[1], 4);
  35909. // Not consider transform
  35910. // Treat each element as a rect
  35911. // top down traverse
  35912. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  35913. var i = idx * 2;
  35914. var x0 = points[i] - w / 2;
  35915. var y0 = points[i + 1] - h / 2;
  35916. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  35917. return idx;
  35918. }
  35919. }
  35920. return -1;
  35921. }
  35922. });
  35923. function LargeSymbolDraw() {
  35924. this.group = new Group();
  35925. }
  35926. var largeSymbolProto = LargeSymbolDraw.prototype;
  35927. largeSymbolProto.isPersistent = function () {
  35928. return !this._incremental;
  35929. };
  35930. /**
  35931. * Update symbols draw by new data
  35932. * @param {module:echarts/data/List} data
  35933. */
  35934. largeSymbolProto.updateData = function (data) {
  35935. this.group.removeAll();
  35936. var symbolEl = new LargeSymbolPath({
  35937. rectHover: true,
  35938. cursor: 'default'
  35939. });
  35940. symbolEl.setShape({
  35941. points: data.getLayout('symbolPoints')
  35942. });
  35943. this._setCommon(symbolEl, data);
  35944. this.group.add(symbolEl);
  35945. this._incremental = null;
  35946. };
  35947. largeSymbolProto.updateLayout = function (data) {
  35948. if (this._incremental) {
  35949. return;
  35950. }
  35951. var points = data.getLayout('symbolPoints');
  35952. this.group.eachChild(function (child) {
  35953. if (child.startIndex != null) {
  35954. var len = (child.endIndex - child.startIndex) * 2;
  35955. var byteOffset = child.startIndex * 4 * 2;
  35956. points = new Float32Array(points.buffer, byteOffset, len);
  35957. }
  35958. child.setShape('points', points);
  35959. });
  35960. };
  35961. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  35962. this.group.removeAll();
  35963. this._clearIncremental();
  35964. // Only use incremental displayables when data amount is larger than 2 million.
  35965. // PENDING Incremental data?
  35966. if (data.count() > 2e6) {
  35967. if (!this._incremental) {
  35968. this._incremental = new IncrementalDisplayble({
  35969. silent: true
  35970. });
  35971. }
  35972. this.group.add(this._incremental);
  35973. }
  35974. else {
  35975. this._incremental = null;
  35976. }
  35977. };
  35978. largeSymbolProto.incrementalUpdate = function (taskParams, data) {
  35979. var symbolEl;
  35980. if (this._incremental) {
  35981. symbolEl = new LargeSymbolPath();
  35982. this._incremental.addDisplayable(symbolEl, true);
  35983. }
  35984. else {
  35985. symbolEl = new LargeSymbolPath({
  35986. rectHover: true,
  35987. cursor: 'default',
  35988. startIndex: taskParams.start,
  35989. endIndex: taskParams.end
  35990. });
  35991. symbolEl.incremental = true;
  35992. this.group.add(symbolEl);
  35993. }
  35994. symbolEl.setShape({
  35995. points: data.getLayout('symbolPoints')
  35996. });
  35997. this._setCommon(symbolEl, data, !!this._incremental);
  35998. };
  35999. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental) {
  36000. var hostModel = data.hostModel;
  36001. // TODO
  36002. // if (data.hasItemVisual.symbolSize) {
  36003. // // TODO typed array?
  36004. // symbolEl.setShape('sizes', data.mapArray(
  36005. // function (idx) {
  36006. // var size = data.getItemVisual(idx, 'symbolSize');
  36007. // return (size instanceof Array) ? size : [size, size];
  36008. // }
  36009. // ));
  36010. // }
  36011. // else {
  36012. var size = data.getVisual('symbolSize');
  36013. symbolEl.setShape('size', (size instanceof Array) ? size : [size, size]);
  36014. // }
  36015. // Create symbolProxy to build path for each data
  36016. symbolEl.symbolProxy = createSymbol(
  36017. data.getVisual('symbol'), 0, 0, 0, 0
  36018. );
  36019. // Use symbolProxy setColor method
  36020. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  36021. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  36022. symbolEl.useStyle(
  36023. // Draw shadow when doing fillRect is extremely slow.
  36024. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color'])
  36025. );
  36026. var visualColor = data.getVisual('color');
  36027. if (visualColor) {
  36028. symbolEl.setColor(visualColor);
  36029. }
  36030. if (!isIncremental) {
  36031. // Enable tooltip
  36032. // PENDING May have performance issue when path is extremely large
  36033. symbolEl.seriesIndex = hostModel.seriesIndex;
  36034. symbolEl.on('mousemove', function (e) {
  36035. symbolEl.dataIndex = null;
  36036. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  36037. if (dataIndex >= 0) {
  36038. // Provide dataIndex for tooltip
  36039. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  36040. }
  36041. });
  36042. }
  36043. };
  36044. largeSymbolProto.remove = function () {
  36045. this._clearIncremental();
  36046. this._incremental = null;
  36047. this.group.removeAll();
  36048. };
  36049. largeSymbolProto._clearIncremental = function () {
  36050. var incremental = this._incremental;
  36051. if (incremental) {
  36052. incremental.clearDisplaybles();
  36053. }
  36054. };
  36055. /*
  36056. * Licensed to the Apache Software Foundation (ASF) under one
  36057. * or more contributor license agreements. See the NOTICE file
  36058. * distributed with this work for additional information
  36059. * regarding copyright ownership. The ASF licenses this file
  36060. * to you under the Apache License, Version 2.0 (the
  36061. * "License"); you may not use this file except in compliance
  36062. * with the License. You may obtain a copy of the License at
  36063. *
  36064. * http://www.apache.org/licenses/LICENSE-2.0
  36065. *
  36066. * Unless required by applicable law or agreed to in writing,
  36067. * software distributed under the License is distributed on an
  36068. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36069. * KIND, either express or implied. See the License for the
  36070. * specific language governing permissions and limitations
  36071. * under the License.
  36072. */
  36073. extendChartView({
  36074. type: 'scatter',
  36075. render: function (seriesModel, ecModel, api) {
  36076. var data = seriesModel.getData();
  36077. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36078. symbolDraw.updateData(data);
  36079. this._finished = true;
  36080. },
  36081. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36082. var data = seriesModel.getData();
  36083. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36084. symbolDraw.incrementalPrepareUpdate(data);
  36085. this._finished = false;
  36086. },
  36087. incrementalRender: function (taskParams, seriesModel, ecModel) {
  36088. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData());
  36089. this._finished = taskParams.end === seriesModel.getData().count();
  36090. },
  36091. updateTransform: function (seriesModel, ecModel, api) {
  36092. var data = seriesModel.getData();
  36093. // Must mark group dirty and make sure the incremental layer will be cleared
  36094. // PENDING
  36095. this.group.dirty();
  36096. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  36097. return {
  36098. update: true
  36099. };
  36100. }
  36101. else {
  36102. var res = pointsLayout().reset(seriesModel);
  36103. if (res.progress) {
  36104. res.progress({ start: 0, end: data.count() }, data);
  36105. }
  36106. this._symbolDraw.updateLayout(data);
  36107. }
  36108. },
  36109. _updateSymbolDraw: function (data, seriesModel) {
  36110. var symbolDraw = this._symbolDraw;
  36111. var pipelineContext = seriesModel.pipelineContext;
  36112. var isLargeDraw = pipelineContext.large;
  36113. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  36114. symbolDraw && symbolDraw.remove();
  36115. symbolDraw = this._symbolDraw = isLargeDraw
  36116. ? new LargeSymbolDraw()
  36117. : new SymbolDraw();
  36118. this._isLargeDraw = isLargeDraw;
  36119. this.group.removeAll();
  36120. }
  36121. this.group.add(symbolDraw.group);
  36122. return symbolDraw;
  36123. },
  36124. remove: function (ecModel, api) {
  36125. this._symbolDraw && this._symbolDraw.remove(true);
  36126. this._symbolDraw = null;
  36127. },
  36128. dispose: function () {}
  36129. });
  36130. /*
  36131. * Licensed to the Apache Software Foundation (ASF) under one
  36132. * or more contributor license agreements. See the NOTICE file
  36133. * distributed with this work for additional information
  36134. * regarding copyright ownership. The ASF licenses this file
  36135. * to you under the Apache License, Version 2.0 (the
  36136. * "License"); you may not use this file except in compliance
  36137. * with the License. You may obtain a copy of the License at
  36138. *
  36139. * http://www.apache.org/licenses/LICENSE-2.0
  36140. *
  36141. * Unless required by applicable law or agreed to in writing,
  36142. * software distributed under the License is distributed on an
  36143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36144. * KIND, either express or implied. See the License for the
  36145. * specific language governing permissions and limitations
  36146. * under the License.
  36147. */
  36148. // import * as zrUtil from 'zrender/src/core/util';
  36149. // In case developer forget to include grid component
  36150. registerVisual(visualSymbol('scatter', 'circle'));
  36151. registerLayout(pointsLayout('scatter'));
  36152. // echarts.registerProcessor(function (ecModel, api) {
  36153. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  36154. // var data = seriesModel.getData();
  36155. // var coordSys = seriesModel.coordinateSystem;
  36156. // if (coordSys.type !== 'geo') {
  36157. // return;
  36158. // }
  36159. // var startPt = coordSys.pointToData([0, 0]);
  36160. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  36161. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  36162. // return data.mapDimension(dim);
  36163. // });
  36164. // var range = {};
  36165. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  36166. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  36167. // data.selectRange(range);
  36168. // });
  36169. // });
  36170. /*
  36171. * Licensed to the Apache Software Foundation (ASF) under one
  36172. * or more contributor license agreements. See the NOTICE file
  36173. * distributed with this work for additional information
  36174. * regarding copyright ownership. The ASF licenses this file
  36175. * to you under the Apache License, Version 2.0 (the
  36176. * "License"); you may not use this file except in compliance
  36177. * with the License. You may obtain a copy of the License at
  36178. *
  36179. * http://www.apache.org/licenses/LICENSE-2.0
  36180. *
  36181. * Unless required by applicable law or agreed to in writing,
  36182. * software distributed under the License is distributed on an
  36183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36184. * KIND, either express or implied. See the License for the
  36185. * specific language governing permissions and limitations
  36186. * under the License.
  36187. */
  36188. function IndicatorAxis(dim, scale, radiusExtent) {
  36189. Axis.call(this, dim, scale, radiusExtent);
  36190. /**
  36191. * Axis type
  36192. * - 'category'
  36193. * - 'value'
  36194. * - 'time'
  36195. * - 'log'
  36196. * @type {string}
  36197. */
  36198. this.type = 'value';
  36199. this.angle = 0;
  36200. /**
  36201. * Indicator name
  36202. * @type {string}
  36203. */
  36204. this.name = '';
  36205. /**
  36206. * @type {module:echarts/model/Model}
  36207. */
  36208. this.model;
  36209. }
  36210. inherits(IndicatorAxis, Axis);
  36211. /*
  36212. * Licensed to the Apache Software Foundation (ASF) under one
  36213. * or more contributor license agreements. See the NOTICE file
  36214. * distributed with this work for additional information
  36215. * regarding copyright ownership. The ASF licenses this file
  36216. * to you under the Apache License, Version 2.0 (the
  36217. * "License"); you may not use this file except in compliance
  36218. * with the License. You may obtain a copy of the License at
  36219. *
  36220. * http://www.apache.org/licenses/LICENSE-2.0
  36221. *
  36222. * Unless required by applicable law or agreed to in writing,
  36223. * software distributed under the License is distributed on an
  36224. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36225. * KIND, either express or implied. See the License for the
  36226. * specific language governing permissions and limitations
  36227. * under the License.
  36228. */
  36229. // TODO clockwise
  36230. function Radar(radarModel, ecModel, api) {
  36231. this._model = radarModel;
  36232. /**
  36233. * Radar dimensions
  36234. * @type {Array.<string>}
  36235. */
  36236. this.dimensions = [];
  36237. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  36238. var dim = 'indicator_' + idx;
  36239. var indicatorAxis = new IndicatorAxis(dim, new IntervalScale());
  36240. indicatorAxis.name = indicatorModel.get('name');
  36241. // Inject model and axis
  36242. indicatorAxis.model = indicatorModel;
  36243. indicatorModel.axis = indicatorAxis;
  36244. this.dimensions.push(dim);
  36245. return indicatorAxis;
  36246. }, this);
  36247. this.resize(radarModel, api);
  36248. /**
  36249. * @type {number}
  36250. * @readOnly
  36251. */
  36252. this.cx;
  36253. /**
  36254. * @type {number}
  36255. * @readOnly
  36256. */
  36257. this.cy;
  36258. /**
  36259. * @type {number}
  36260. * @readOnly
  36261. */
  36262. this.r;
  36263. /**
  36264. * @type {number}
  36265. * @readOnly
  36266. */
  36267. this.startAngle;
  36268. }
  36269. Radar.prototype.getIndicatorAxes = function () {
  36270. return this._indicatorAxes;
  36271. };
  36272. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  36273. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  36274. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  36275. };
  36276. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  36277. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  36278. var angle = indicatorAxis.angle;
  36279. var x = this.cx + coord * Math.cos(angle);
  36280. var y = this.cy - coord * Math.sin(angle);
  36281. return [x, y];
  36282. };
  36283. Radar.prototype.pointToData = function (pt) {
  36284. var dx = pt[0] - this.cx;
  36285. var dy = pt[1] - this.cy;
  36286. var radius = Math.sqrt(dx * dx + dy * dy);
  36287. dx /= radius;
  36288. dy /= radius;
  36289. var radian = Math.atan2(-dy, dx);
  36290. // Find the closest angle
  36291. // FIXME index can calculated directly
  36292. var minRadianDiff = Infinity;
  36293. var closestAxis;
  36294. var closestAxisIdx = -1;
  36295. for (var i = 0; i < this._indicatorAxes.length; i++) {
  36296. var indicatorAxis = this._indicatorAxes[i];
  36297. var diff = Math.abs(radian - indicatorAxis.angle);
  36298. if (diff < minRadianDiff) {
  36299. closestAxis = indicatorAxis;
  36300. closestAxisIdx = i;
  36301. minRadianDiff = diff;
  36302. }
  36303. }
  36304. return [closestAxisIdx, +(closestAxis && closestAxis.coodToData(radius))];
  36305. };
  36306. Radar.prototype.resize = function (radarModel, api) {
  36307. var center = radarModel.get('center');
  36308. var viewWidth = api.getWidth();
  36309. var viewHeight = api.getHeight();
  36310. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  36311. this.cx = parsePercent$1(center[0], viewWidth);
  36312. this.cy = parsePercent$1(center[1], viewHeight);
  36313. this.startAngle = radarModel.get('startAngle') * Math.PI / 180;
  36314. this.r = parsePercent$1(radarModel.get('radius'), viewSize);
  36315. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  36316. indicatorAxis.setExtent(0, this.r);
  36317. var angle = (this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length);
  36318. // Normalize to [-PI, PI]
  36319. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  36320. indicatorAxis.angle = angle;
  36321. }, this);
  36322. };
  36323. Radar.prototype.update = function (ecModel, api) {
  36324. var indicatorAxes = this._indicatorAxes;
  36325. var radarModel = this._model;
  36326. each$1(indicatorAxes, function (indicatorAxis) {
  36327. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  36328. });
  36329. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  36330. if (radarSeries.get('coordinateSystem') !== 'radar'
  36331. || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel
  36332. ) {
  36333. return;
  36334. }
  36335. var data = radarSeries.getData();
  36336. each$1(indicatorAxes, function (indicatorAxis) {
  36337. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  36338. });
  36339. }, this);
  36340. var splitNumber = radarModel.get('splitNumber');
  36341. function increaseInterval(interval) {
  36342. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10));
  36343. // Increase interval
  36344. var f = interval / exp10;
  36345. if (f === 2) {
  36346. f = 5;
  36347. }
  36348. else { // f is 2 or 5
  36349. f *= 2;
  36350. }
  36351. return f * exp10;
  36352. }
  36353. // Force all the axis fixing the maxSplitNumber.
  36354. each$1(indicatorAxes, function (indicatorAxis, idx) {
  36355. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  36356. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  36357. var axisModel = indicatorAxis.model;
  36358. var scale = indicatorAxis.scale;
  36359. var fixedMin = axisModel.getMin();
  36360. var fixedMax = axisModel.getMax();
  36361. var interval = scale.getInterval();
  36362. if (fixedMin != null && fixedMax != null) {
  36363. // User set min, max, divide to get new interval
  36364. scale.setExtent(+fixedMin, +fixedMax);
  36365. scale.setInterval(
  36366. (fixedMax - fixedMin) / splitNumber
  36367. );
  36368. }
  36369. else if (fixedMin != null) {
  36370. var max;
  36371. // User set min, expand extent on the other side
  36372. do {
  36373. max = fixedMin + interval * splitNumber;
  36374. scale.setExtent(+fixedMin, max);
  36375. // Interval must been set after extent
  36376. // FIXME
  36377. scale.setInterval(interval);
  36378. interval = increaseInterval(interval);
  36379. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  36380. }
  36381. else if (fixedMax != null) {
  36382. var min;
  36383. // User set min, expand extent on the other side
  36384. do {
  36385. min = fixedMax - interval * splitNumber;
  36386. scale.setExtent(min, +fixedMax);
  36387. scale.setInterval(interval);
  36388. interval = increaseInterval(interval);
  36389. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  36390. }
  36391. else {
  36392. var nicedSplitNumber = scale.getTicks().length - 1;
  36393. if (nicedSplitNumber > splitNumber) {
  36394. interval = increaseInterval(interval);
  36395. }
  36396. // PENDING
  36397. var center = Math.round((rawExtent[0] + rawExtent[1]) / 2 / interval) * interval;
  36398. var halfSplitNumber = Math.round(splitNumber / 2);
  36399. scale.setExtent(
  36400. round$1(center - halfSplitNumber * interval),
  36401. round$1(center + (splitNumber - halfSplitNumber) * interval)
  36402. );
  36403. scale.setInterval(interval);
  36404. }
  36405. });
  36406. };
  36407. /**
  36408. * Radar dimensions is based on the data
  36409. * @type {Array}
  36410. */
  36411. Radar.dimensions = [];
  36412. Radar.create = function (ecModel, api) {
  36413. var radarList = [];
  36414. ecModel.eachComponent('radar', function (radarModel) {
  36415. var radar = new Radar(radarModel, ecModel, api);
  36416. radarList.push(radar);
  36417. radarModel.coordinateSystem = radar;
  36418. });
  36419. ecModel.eachSeriesByType('radar', function (radarSeries) {
  36420. if (radarSeries.get('coordinateSystem') === 'radar') {
  36421. // Inject coordinate system
  36422. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  36423. }
  36424. });
  36425. return radarList;
  36426. };
  36427. CoordinateSystemManager.register('radar', Radar);
  36428. /*
  36429. * Licensed to the Apache Software Foundation (ASF) under one
  36430. * or more contributor license agreements. See the NOTICE file
  36431. * distributed with this work for additional information
  36432. * regarding copyright ownership. The ASF licenses this file
  36433. * to you under the Apache License, Version 2.0 (the
  36434. * "License"); you may not use this file except in compliance
  36435. * with the License. You may obtain a copy of the License at
  36436. *
  36437. * http://www.apache.org/licenses/LICENSE-2.0
  36438. *
  36439. * Unless required by applicable law or agreed to in writing,
  36440. * software distributed under the License is distributed on an
  36441. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36442. * KIND, either express or implied. See the License for the
  36443. * specific language governing permissions and limitations
  36444. * under the License.
  36445. */
  36446. var valueAxisDefault = axisDefault.valueAxis;
  36447. function defaultsShow(opt, show) {
  36448. return defaults({
  36449. show: show
  36450. }, opt);
  36451. }
  36452. var RadarModel = extendComponentModel({
  36453. type: 'radar',
  36454. optionUpdated: function () {
  36455. var boundaryGap = this.get('boundaryGap');
  36456. var splitNumber = this.get('splitNumber');
  36457. var scale = this.get('scale');
  36458. var axisLine = this.get('axisLine');
  36459. var axisTick = this.get('axisTick');
  36460. var axisLabel = this.get('axisLabel');
  36461. var nameTextStyle = this.get('name');
  36462. var showName = this.get('name.show');
  36463. var nameFormatter = this.get('name.formatter');
  36464. var nameGap = this.get('nameGap');
  36465. var triggerEvent = this.get('triggerEvent');
  36466. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  36467. // PENDING
  36468. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  36469. indicatorOpt.min = 0;
  36470. }
  36471. else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  36472. indicatorOpt.max = 0;
  36473. }
  36474. var iNameTextStyle = nameTextStyle;
  36475. if(indicatorOpt.color != null) {
  36476. iNameTextStyle = defaults({color: indicatorOpt.color}, nameTextStyle);
  36477. }
  36478. // Use same configuration
  36479. indicatorOpt = merge(clone(indicatorOpt), {
  36480. boundaryGap: boundaryGap,
  36481. splitNumber: splitNumber,
  36482. scale: scale,
  36483. axisLine: axisLine,
  36484. axisTick: axisTick,
  36485. axisLabel: axisLabel,
  36486. // Competitable with 2 and use text
  36487. name: indicatorOpt.text,
  36488. nameLocation: 'end',
  36489. nameGap: nameGap,
  36490. // min: 0,
  36491. nameTextStyle: iNameTextStyle,
  36492. triggerEvent: triggerEvent
  36493. }, false);
  36494. if (!showName) {
  36495. indicatorOpt.name = '';
  36496. }
  36497. if (typeof nameFormatter === 'string') {
  36498. var indName = indicatorOpt.name;
  36499. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  36500. }
  36501. else if (typeof nameFormatter === 'function') {
  36502. indicatorOpt.name = nameFormatter(
  36503. indicatorOpt.name, indicatorOpt
  36504. );
  36505. }
  36506. var model = extend(
  36507. new Model(indicatorOpt, null, this.ecModel),
  36508. axisModelCommonMixin
  36509. );
  36510. // For triggerEvent.
  36511. model.mainType = 'radar';
  36512. model.componentIndex = this.componentIndex;
  36513. return model;
  36514. }, this);
  36515. this.getIndicatorModels = function () {
  36516. return indicatorModels;
  36517. };
  36518. },
  36519. defaultOption: {
  36520. zlevel: 0,
  36521. z: 0,
  36522. center: ['50%', '50%'],
  36523. radius: '75%',
  36524. startAngle: 90,
  36525. name: {
  36526. show: true
  36527. // formatter: null
  36528. // textStyle: {}
  36529. },
  36530. boundaryGap: [0, 0],
  36531. splitNumber: 5,
  36532. nameGap: 15,
  36533. scale: false,
  36534. // Polygon or circle
  36535. shape: 'polygon',
  36536. axisLine: merge(
  36537. {
  36538. lineStyle: {
  36539. color: '#bbb'
  36540. }
  36541. },
  36542. valueAxisDefault.axisLine
  36543. ),
  36544. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  36545. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  36546. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  36547. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  36548. // {text, min, max}
  36549. indicator: []
  36550. }
  36551. });
  36552. /*
  36553. * Licensed to the Apache Software Foundation (ASF) under one
  36554. * or more contributor license agreements. See the NOTICE file
  36555. * distributed with this work for additional information
  36556. * regarding copyright ownership. The ASF licenses this file
  36557. * to you under the Apache License, Version 2.0 (the
  36558. * "License"); you may not use this file except in compliance
  36559. * with the License. You may obtain a copy of the License at
  36560. *
  36561. * http://www.apache.org/licenses/LICENSE-2.0
  36562. *
  36563. * Unless required by applicable law or agreed to in writing,
  36564. * software distributed under the License is distributed on an
  36565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36566. * KIND, either express or implied. See the License for the
  36567. * specific language governing permissions and limitations
  36568. * under the License.
  36569. */
  36570. var axisBuilderAttrs$1 = [
  36571. 'axisLine', 'axisTickLabel', 'axisName'
  36572. ];
  36573. extendComponentView({
  36574. type: 'radar',
  36575. render: function (radarModel, ecModel, api) {
  36576. var group = this.group;
  36577. group.removeAll();
  36578. this._buildAxes(radarModel);
  36579. this._buildSplitLineAndArea(radarModel);
  36580. },
  36581. _buildAxes: function (radarModel) {
  36582. var radar = radarModel.coordinateSystem;
  36583. var indicatorAxes = radar.getIndicatorAxes();
  36584. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  36585. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  36586. position: [radar.cx, radar.cy],
  36587. rotation: indicatorAxis.angle,
  36588. labelDirection: -1,
  36589. tickDirection: -1,
  36590. nameDirection: 1
  36591. });
  36592. return axisBuilder;
  36593. });
  36594. each$1(axisBuilders, function (axisBuilder) {
  36595. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  36596. this.group.add(axisBuilder.getGroup());
  36597. }, this);
  36598. },
  36599. _buildSplitLineAndArea: function (radarModel) {
  36600. var radar = radarModel.coordinateSystem;
  36601. var indicatorAxes = radar.getIndicatorAxes();
  36602. if (!indicatorAxes.length) {
  36603. return;
  36604. }
  36605. var shape = radarModel.get('shape');
  36606. var splitLineModel = radarModel.getModel('splitLine');
  36607. var splitAreaModel = radarModel.getModel('splitArea');
  36608. var lineStyleModel = splitLineModel.getModel('lineStyle');
  36609. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  36610. var showSplitLine = splitLineModel.get('show');
  36611. var showSplitArea = splitAreaModel.get('show');
  36612. var splitLineColors = lineStyleModel.get('color');
  36613. var splitAreaColors = areaStyleModel.get('color');
  36614. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  36615. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  36616. var splitLines = [];
  36617. var splitAreas = [];
  36618. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  36619. var colorIndex = idx % areaOrLineColorList.length;
  36620. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  36621. return colorIndex;
  36622. }
  36623. if (shape === 'circle') {
  36624. var ticksRadius = indicatorAxes[0].getTicksCoords();
  36625. var cx = radar.cx;
  36626. var cy = radar.cy;
  36627. for (var i = 0; i < ticksRadius.length; i++) {
  36628. if (showSplitLine) {
  36629. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  36630. splitLines[colorIndex].push(new Circle({
  36631. shape: {
  36632. cx: cx,
  36633. cy: cy,
  36634. r: ticksRadius[i].coord
  36635. }
  36636. }));
  36637. }
  36638. if (showSplitArea && i < ticksRadius.length - 1) {
  36639. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  36640. splitAreas[colorIndex].push(new Ring({
  36641. shape: {
  36642. cx: cx,
  36643. cy: cy,
  36644. r0: ticksRadius[i].coord,
  36645. r: ticksRadius[i + 1].coord
  36646. }
  36647. }));
  36648. }
  36649. }
  36650. }
  36651. // Polyyon
  36652. else {
  36653. var realSplitNumber;
  36654. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  36655. var ticksCoords = indicatorAxis.getTicksCoords();
  36656. realSplitNumber = realSplitNumber == null
  36657. ? ticksCoords.length - 1
  36658. : Math.min(ticksCoords.length - 1, realSplitNumber);
  36659. return map(ticksCoords, function (tickCoord) {
  36660. return radar.coordToPoint(tickCoord.coord, idx);
  36661. });
  36662. });
  36663. var prevPoints = [];
  36664. for (var i = 0; i <= realSplitNumber; i++) {
  36665. var points = [];
  36666. for (var j = 0; j < indicatorAxes.length; j++) {
  36667. points.push(axesTicksPoints[j][i]);
  36668. }
  36669. // Close
  36670. if (points[0]) {
  36671. points.push(points[0].slice());
  36672. }
  36673. else {
  36674. if (__DEV__) {
  36675. console.error('Can\'t draw value axis ' + i);
  36676. }
  36677. }
  36678. if (showSplitLine) {
  36679. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  36680. splitLines[colorIndex].push(new Polyline({
  36681. shape: {
  36682. points: points
  36683. }
  36684. }));
  36685. }
  36686. if (showSplitArea && prevPoints) {
  36687. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  36688. splitAreas[colorIndex].push(new Polygon({
  36689. shape: {
  36690. points: points.concat(prevPoints)
  36691. }
  36692. }));
  36693. }
  36694. prevPoints = points.slice().reverse();
  36695. }
  36696. }
  36697. var lineStyle = lineStyleModel.getLineStyle();
  36698. var areaStyle = areaStyleModel.getAreaStyle();
  36699. // Add splitArea before splitLine
  36700. each$1(splitAreas, function (splitAreas, idx) {
  36701. this.group.add(mergePath(
  36702. splitAreas, {
  36703. style: defaults({
  36704. stroke: 'none',
  36705. fill: splitAreaColors[idx % splitAreaColors.length]
  36706. }, areaStyle),
  36707. silent: true
  36708. }
  36709. ));
  36710. }, this);
  36711. each$1(splitLines, function (splitLines, idx) {
  36712. this.group.add(mergePath(
  36713. splitLines, {
  36714. style: defaults({
  36715. fill: 'none',
  36716. stroke: splitLineColors[idx % splitLineColors.length]
  36717. }, lineStyle),
  36718. silent: true
  36719. }
  36720. ));
  36721. }, this);
  36722. }
  36723. });
  36724. /*
  36725. * Licensed to the Apache Software Foundation (ASF) under one
  36726. * or more contributor license agreements. See the NOTICE file
  36727. * distributed with this work for additional information
  36728. * regarding copyright ownership. The ASF licenses this file
  36729. * to you under the Apache License, Version 2.0 (the
  36730. * "License"); you may not use this file except in compliance
  36731. * with the License. You may obtain a copy of the License at
  36732. *
  36733. * http://www.apache.org/licenses/LICENSE-2.0
  36734. *
  36735. * Unless required by applicable law or agreed to in writing,
  36736. * software distributed under the License is distributed on an
  36737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36738. * KIND, either express or implied. See the License for the
  36739. * specific language governing permissions and limitations
  36740. * under the License.
  36741. */
  36742. /*
  36743. * Licensed to the Apache Software Foundation (ASF) under one
  36744. * or more contributor license agreements. See the NOTICE file
  36745. * distributed with this work for additional information
  36746. * regarding copyright ownership. The ASF licenses this file
  36747. * to you under the Apache License, Version 2.0 (the
  36748. * "License"); you may not use this file except in compliance
  36749. * with the License. You may obtain a copy of the License at
  36750. *
  36751. * http://www.apache.org/licenses/LICENSE-2.0
  36752. *
  36753. * Unless required by applicable law or agreed to in writing,
  36754. * software distributed under the License is distributed on an
  36755. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36756. * KIND, either express or implied. See the License for the
  36757. * specific language governing permissions and limitations
  36758. * under the License.
  36759. */
  36760. var RadarSeries = SeriesModel.extend({
  36761. type: 'series.radar',
  36762. dependencies: ['radar'],
  36763. // Overwrite
  36764. init: function (option) {
  36765. RadarSeries.superApply(this, 'init', arguments);
  36766. // Enable legend selection for each data item
  36767. // Use a function instead of direct access because data reference may changed
  36768. this.legendDataProvider = function () {
  36769. return this.getRawData();
  36770. };
  36771. },
  36772. getInitialData: function (option, ecModel) {
  36773. return createListSimply(this, {
  36774. generateCoord: 'indicator_',
  36775. generateCoordCount: Infinity
  36776. });
  36777. },
  36778. formatTooltip: function (dataIndex) {
  36779. var data = this.getData();
  36780. var coordSys = this.coordinateSystem;
  36781. var indicatorAxes = coordSys.getIndicatorAxes();
  36782. var name = this.getData().getName(dataIndex);
  36783. return encodeHTML(name === '' ? this.name : name) + '<br/>'
  36784. + map(indicatorAxes, function (axis, idx) {
  36785. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  36786. return encodeHTML(axis.name + ' : ' + val);
  36787. }).join('<br />');
  36788. },
  36789. defaultOption: {
  36790. zlevel: 0,
  36791. z: 2,
  36792. coordinateSystem: 'radar',
  36793. legendHoverLink: true,
  36794. radarIndex: 0,
  36795. lineStyle: {
  36796. width: 2,
  36797. type: 'solid'
  36798. },
  36799. label: {
  36800. position: 'top'
  36801. },
  36802. // areaStyle: {
  36803. // },
  36804. // itemStyle: {}
  36805. symbol: 'emptyCircle',
  36806. symbolSize: 4
  36807. // symbolRotate: null
  36808. }
  36809. });
  36810. /*
  36811. * Licensed to the Apache Software Foundation (ASF) under one
  36812. * or more contributor license agreements. See the NOTICE file
  36813. * distributed with this work for additional information
  36814. * regarding copyright ownership. The ASF licenses this file
  36815. * to you under the Apache License, Version 2.0 (the
  36816. * "License"); you may not use this file except in compliance
  36817. * with the License. You may obtain a copy of the License at
  36818. *
  36819. * http://www.apache.org/licenses/LICENSE-2.0
  36820. *
  36821. * Unless required by applicable law or agreed to in writing,
  36822. * software distributed under the License is distributed on an
  36823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36824. * KIND, either express or implied. See the License for the
  36825. * specific language governing permissions and limitations
  36826. * under the License.
  36827. */
  36828. function normalizeSymbolSize(symbolSize) {
  36829. if (!isArray(symbolSize)) {
  36830. symbolSize = [+symbolSize, +symbolSize];
  36831. }
  36832. return symbolSize;
  36833. }
  36834. extendChartView({
  36835. type: 'radar',
  36836. render: function (seriesModel, ecModel, api) {
  36837. var polar = seriesModel.coordinateSystem;
  36838. var group = this.group;
  36839. var data = seriesModel.getData();
  36840. var oldData = this._data;
  36841. function createSymbol$$1(data, idx) {
  36842. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  36843. var color = data.getItemVisual(idx, 'color');
  36844. if (symbolType === 'none') {
  36845. return;
  36846. }
  36847. var symbolSize = normalizeSymbolSize(
  36848. data.getItemVisual(idx, 'symbolSize')
  36849. );
  36850. var symbolPath = createSymbol(
  36851. symbolType, -1, -1, 2, 2, color
  36852. );
  36853. symbolPath.attr({
  36854. style: {
  36855. strokeNoScale: true
  36856. },
  36857. z2: 100,
  36858. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  36859. });
  36860. return symbolPath;
  36861. }
  36862. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  36863. // Simply rerender all
  36864. symbolGroup.removeAll();
  36865. for (var i = 0; i < newPoints.length - 1; i++) {
  36866. var symbolPath = createSymbol$$1(data, idx);
  36867. if (symbolPath) {
  36868. symbolPath.__dimIdx = i;
  36869. if (oldPoints[i]) {
  36870. symbolPath.attr('position', oldPoints[i]);
  36871. graphic[isInit ? 'initProps' : 'updateProps'](
  36872. symbolPath, {
  36873. position: newPoints[i]
  36874. }, seriesModel, idx
  36875. );
  36876. }
  36877. else {
  36878. symbolPath.attr('position', newPoints[i]);
  36879. }
  36880. symbolGroup.add(symbolPath);
  36881. }
  36882. }
  36883. }
  36884. function getInitialPoints(points) {
  36885. return map(points, function (pt) {
  36886. return [polar.cx, polar.cy];
  36887. });
  36888. }
  36889. data.diff(oldData)
  36890. .add(function (idx) {
  36891. var points = data.getItemLayout(idx);
  36892. if (!points) {
  36893. return;
  36894. }
  36895. var polygon = new Polygon();
  36896. var polyline = new Polyline();
  36897. var target = {
  36898. shape: {
  36899. points: points
  36900. }
  36901. };
  36902. polygon.shape.points = getInitialPoints(points);
  36903. polyline.shape.points = getInitialPoints(points);
  36904. initProps(polygon, target, seriesModel, idx);
  36905. initProps(polyline, target, seriesModel, idx);
  36906. var itemGroup = new Group();
  36907. var symbolGroup = new Group();
  36908. itemGroup.add(polyline);
  36909. itemGroup.add(polygon);
  36910. itemGroup.add(symbolGroup);
  36911. updateSymbols(
  36912. polyline.shape.points, points, symbolGroup, data, idx, true
  36913. );
  36914. data.setItemGraphicEl(idx, itemGroup);
  36915. })
  36916. .update(function (newIdx, oldIdx) {
  36917. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  36918. var polyline = itemGroup.childAt(0);
  36919. var polygon = itemGroup.childAt(1);
  36920. var symbolGroup = itemGroup.childAt(2);
  36921. var target = {
  36922. shape: {
  36923. points: data.getItemLayout(newIdx)
  36924. }
  36925. };
  36926. if (!target.shape.points) {
  36927. return;
  36928. }
  36929. updateSymbols(
  36930. polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false
  36931. );
  36932. updateProps(polyline, target, seriesModel);
  36933. updateProps(polygon, target, seriesModel);
  36934. data.setItemGraphicEl(newIdx, itemGroup);
  36935. })
  36936. .remove(function (idx) {
  36937. group.remove(oldData.getItemGraphicEl(idx));
  36938. })
  36939. .execute();
  36940. data.eachItemGraphicEl(function (itemGroup, idx) {
  36941. var itemModel = data.getItemModel(idx);
  36942. var polyline = itemGroup.childAt(0);
  36943. var polygon = itemGroup.childAt(1);
  36944. var symbolGroup = itemGroup.childAt(2);
  36945. var color = data.getItemVisual(idx, 'color');
  36946. group.add(itemGroup);
  36947. polyline.useStyle(
  36948. defaults(
  36949. itemModel.getModel('lineStyle').getLineStyle(),
  36950. {
  36951. fill: 'none',
  36952. stroke: color
  36953. }
  36954. )
  36955. );
  36956. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  36957. var areaStyleModel = itemModel.getModel('areaStyle');
  36958. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  36959. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  36960. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  36961. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  36962. polygon.ignore = polygonIgnore;
  36963. polygon.useStyle(
  36964. defaults(
  36965. areaStyleModel.getAreaStyle(),
  36966. {
  36967. fill: color,
  36968. opacity: 0.7
  36969. }
  36970. )
  36971. );
  36972. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  36973. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  36974. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  36975. var labelModel = itemModel.getModel('label');
  36976. var labelHoverModel = itemModel.getModel('emphasis.label');
  36977. symbolGroup.eachChild(function (symbolPath) {
  36978. symbolPath.setStyle(itemStyle);
  36979. symbolPath.hoverStyle = clone(itemHoverStyle);
  36980. setLabelStyle(
  36981. symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel,
  36982. {
  36983. labelFetcher: data.hostModel,
  36984. labelDataIndex: idx,
  36985. labelDimIndex: symbolPath.__dimIdx,
  36986. defaultText: data.get(data.dimensions[symbolPath.__dimIdx], idx),
  36987. autoColor: color,
  36988. isRectText: true
  36989. }
  36990. );
  36991. });
  36992. function onEmphasis() {
  36993. polygon.attr('ignore', hoverPolygonIgnore);
  36994. }
  36995. function onNormal() {
  36996. polygon.attr('ignore', polygonIgnore);
  36997. }
  36998. itemGroup.off('mouseover').off('mouseout').off('normal').off('emphasis');
  36999. itemGroup.on('emphasis', onEmphasis)
  37000. .on('mouseover', onEmphasis)
  37001. .on('normal', onNormal)
  37002. .on('mouseout', onNormal);
  37003. setHoverStyle(itemGroup);
  37004. });
  37005. this._data = data;
  37006. },
  37007. remove: function () {
  37008. this.group.removeAll();
  37009. this._data = null;
  37010. },
  37011. dispose: function () {}
  37012. });
  37013. /*
  37014. * Licensed to the Apache Software Foundation (ASF) under one
  37015. * or more contributor license agreements. See the NOTICE file
  37016. * distributed with this work for additional information
  37017. * regarding copyright ownership. The ASF licenses this file
  37018. * to you under the Apache License, Version 2.0 (the
  37019. * "License"); you may not use this file except in compliance
  37020. * with the License. You may obtain a copy of the License at
  37021. *
  37022. * http://www.apache.org/licenses/LICENSE-2.0
  37023. *
  37024. * Unless required by applicable law or agreed to in writing,
  37025. * software distributed under the License is distributed on an
  37026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37027. * KIND, either express or implied. See the License for the
  37028. * specific language governing permissions and limitations
  37029. * under the License.
  37030. */
  37031. var radarLayout = function (ecModel) {
  37032. ecModel.eachSeriesByType('radar', function (seriesModel) {
  37033. var data = seriesModel.getData();
  37034. var points = [];
  37035. var coordSys = seriesModel.coordinateSystem;
  37036. if (!coordSys) {
  37037. return;
  37038. }
  37039. function pointsConverter(val, idx) {
  37040. points[idx] = points[idx] || [];
  37041. points[idx][i] = coordSys.dataToPoint(val, i);
  37042. }
  37043. var axes = coordSys.getIndicatorAxes();
  37044. for (var i = 0; i < axes.length; i++) {
  37045. data.each(data.mapDimension(axes[i].dim), pointsConverter);
  37046. }
  37047. data.each(function (idx) {
  37048. // Close polygon
  37049. points[idx][0] && points[idx].push(points[idx][0].slice());
  37050. data.setItemLayout(idx, points[idx]);
  37051. });
  37052. });
  37053. };
  37054. /*
  37055. * Licensed to the Apache Software Foundation (ASF) under one
  37056. * or more contributor license agreements. See the NOTICE file
  37057. * distributed with this work for additional information
  37058. * regarding copyright ownership. The ASF licenses this file
  37059. * to you under the Apache License, Version 2.0 (the
  37060. * "License"); you may not use this file except in compliance
  37061. * with the License. You may obtain a copy of the License at
  37062. *
  37063. * http://www.apache.org/licenses/LICENSE-2.0
  37064. *
  37065. * Unless required by applicable law or agreed to in writing,
  37066. * software distributed under the License is distributed on an
  37067. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37068. * KIND, either express or implied. See the License for the
  37069. * specific language governing permissions and limitations
  37070. * under the License.
  37071. */
  37072. // Backward compat for radar chart in 2
  37073. var backwardCompat$1 = function (option) {
  37074. var polarOptArr = option.polar;
  37075. if (polarOptArr) {
  37076. if (!isArray(polarOptArr)) {
  37077. polarOptArr = [polarOptArr];
  37078. }
  37079. var polarNotRadar = [];
  37080. each$1(polarOptArr, function (polarOpt, idx) {
  37081. if (polarOpt.indicator) {
  37082. if (polarOpt.type && !polarOpt.shape) {
  37083. polarOpt.shape = polarOpt.type;
  37084. }
  37085. option.radar = option.radar || [];
  37086. if (!isArray(option.radar)) {
  37087. option.radar = [option.radar];
  37088. }
  37089. option.radar.push(polarOpt);
  37090. }
  37091. else {
  37092. polarNotRadar.push(polarOpt);
  37093. }
  37094. });
  37095. option.polar = polarNotRadar;
  37096. }
  37097. each$1(option.series, function (seriesOpt) {
  37098. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  37099. seriesOpt.radarIndex = seriesOpt.polarIndex;
  37100. }
  37101. });
  37102. };
  37103. /*
  37104. * Licensed to the Apache Software Foundation (ASF) under one
  37105. * or more contributor license agreements. See the NOTICE file
  37106. * distributed with this work for additional information
  37107. * regarding copyright ownership. The ASF licenses this file
  37108. * to you under the Apache License, Version 2.0 (the
  37109. * "License"); you may not use this file except in compliance
  37110. * with the License. You may obtain a copy of the License at
  37111. *
  37112. * http://www.apache.org/licenses/LICENSE-2.0
  37113. *
  37114. * Unless required by applicable law or agreed to in writing,
  37115. * software distributed under the License is distributed on an
  37116. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37117. * KIND, either express or implied. See the License for the
  37118. * specific language governing permissions and limitations
  37119. * under the License.
  37120. */
  37121. // Must use radar component
  37122. registerVisual(dataColor('radar'));
  37123. registerVisual(visualSymbol('radar', 'circle'));
  37124. registerLayout(radarLayout);
  37125. registerProcessor(dataFilter('radar'));
  37126. registerPreprocessor(backwardCompat$1);
  37127. /*
  37128. * Licensed to the Apache Software Foundation (ASF) under one
  37129. * or more contributor license agreements. See the NOTICE file
  37130. * distributed with this work for additional information
  37131. * regarding copyright ownership. The ASF licenses this file
  37132. * to you under the Apache License, Version 2.0 (the
  37133. * "License"); you may not use this file except in compliance
  37134. * with the License. You may obtain a copy of the License at
  37135. *
  37136. * http://www.apache.org/licenses/LICENSE-2.0
  37137. *
  37138. * Unless required by applicable law or agreed to in writing,
  37139. * software distributed under the License is distributed on an
  37140. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37141. * KIND, either express or implied. See the License for the
  37142. * specific language governing permissions and limitations
  37143. * under the License.
  37144. */
  37145. /**
  37146. * Simple view coordinate system
  37147. * Mapping given x, y to transformd view x, y
  37148. */
  37149. var v2ApplyTransform$1 = applyTransform;
  37150. // Dummy transform node
  37151. function TransformDummy() {
  37152. Transformable.call(this);
  37153. }
  37154. mixin(TransformDummy, Transformable);
  37155. function View(name) {
  37156. /**
  37157. * @type {string}
  37158. */
  37159. this.name = name;
  37160. /**
  37161. * @type {Object}
  37162. */
  37163. this.zoomLimit;
  37164. Transformable.call(this);
  37165. this._roamTransformable = new TransformDummy();
  37166. this._rawTransformable = new TransformDummy();
  37167. this._center;
  37168. this._zoom;
  37169. }
  37170. View.prototype = {
  37171. constructor: View,
  37172. type: 'view',
  37173. /**
  37174. * @param {Array.<string>}
  37175. * @readOnly
  37176. */
  37177. dimensions: ['x', 'y'],
  37178. /**
  37179. * Set bounding rect
  37180. * @param {number} x
  37181. * @param {number} y
  37182. * @param {number} width
  37183. * @param {number} height
  37184. */
  37185. // PENDING to getRect
  37186. setBoundingRect: function (x, y, width, height) {
  37187. this._rect = new BoundingRect(x, y, width, height);
  37188. return this._rect;
  37189. },
  37190. /**
  37191. * @return {module:zrender/core/BoundingRect}
  37192. */
  37193. // PENDING to getRect
  37194. getBoundingRect: function () {
  37195. return this._rect;
  37196. },
  37197. /**
  37198. * @param {number} x
  37199. * @param {number} y
  37200. * @param {number} width
  37201. * @param {number} height
  37202. */
  37203. setViewRect: function (x, y, width, height) {
  37204. this.transformTo(x, y, width, height);
  37205. this._viewRect = new BoundingRect(x, y, width, height);
  37206. },
  37207. /**
  37208. * Transformed to particular position and size
  37209. * @param {number} x
  37210. * @param {number} y
  37211. * @param {number} width
  37212. * @param {number} height
  37213. */
  37214. transformTo: function (x, y, width, height) {
  37215. var rect = this.getBoundingRect();
  37216. var rawTransform = this._rawTransformable;
  37217. rawTransform.transform = rect.calculateTransform(
  37218. new BoundingRect(x, y, width, height)
  37219. );
  37220. rawTransform.decomposeTransform();
  37221. this._updateTransform();
  37222. },
  37223. /**
  37224. * Set center of view
  37225. * @param {Array.<number>} [centerCoord]
  37226. */
  37227. setCenter: function (centerCoord) {
  37228. if (!centerCoord) {
  37229. return;
  37230. }
  37231. this._center = centerCoord;
  37232. this._updateCenterAndZoom();
  37233. },
  37234. /**
  37235. * @param {number} zoom
  37236. */
  37237. setZoom: function (zoom) {
  37238. zoom = zoom || 1;
  37239. var zoomLimit = this.zoomLimit;
  37240. if (zoomLimit) {
  37241. if (zoomLimit.max != null) {
  37242. zoom = Math.min(zoomLimit.max, zoom);
  37243. }
  37244. if (zoomLimit.min != null) {
  37245. zoom = Math.max(zoomLimit.min, zoom);
  37246. }
  37247. }
  37248. this._zoom = zoom;
  37249. this._updateCenterAndZoom();
  37250. },
  37251. /**
  37252. * Get default center without roam
  37253. */
  37254. getDefaultCenter: function () {
  37255. // Rect before any transform
  37256. var rawRect = this.getBoundingRect();
  37257. var cx = rawRect.x + rawRect.width / 2;
  37258. var cy = rawRect.y + rawRect.height / 2;
  37259. return [cx, cy];
  37260. },
  37261. getCenter: function () {
  37262. return this._center || this.getDefaultCenter();
  37263. },
  37264. getZoom: function () {
  37265. return this._zoom || 1;
  37266. },
  37267. /**
  37268. * @return {Array.<number}
  37269. */
  37270. getRoamTransform: function () {
  37271. return this._roamTransformable.getLocalTransform();
  37272. },
  37273. /**
  37274. * Remove roam
  37275. */
  37276. _updateCenterAndZoom: function () {
  37277. // Must update after view transform updated
  37278. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  37279. var roamTransform = this._roamTransformable;
  37280. var defaultCenter = this.getDefaultCenter();
  37281. var center = this.getCenter();
  37282. var zoom = this.getZoom();
  37283. center = applyTransform([], center, rawTransformMatrix);
  37284. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  37285. roamTransform.origin = center;
  37286. roamTransform.position = [
  37287. defaultCenter[0] - center[0],
  37288. defaultCenter[1] - center[1]
  37289. ];
  37290. roamTransform.scale = [zoom, zoom];
  37291. this._updateTransform();
  37292. },
  37293. /**
  37294. * Update transform from roam and mapLocation
  37295. * @private
  37296. */
  37297. _updateTransform: function () {
  37298. var roamTransformable = this._roamTransformable;
  37299. var rawTransformable = this._rawTransformable;
  37300. rawTransformable.parent = roamTransformable;
  37301. roamTransformable.updateTransform();
  37302. rawTransformable.updateTransform();
  37303. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  37304. this._rawTransform = rawTransformable.getLocalTransform();
  37305. this.invTransform = this.invTransform || [];
  37306. invert(this.invTransform, this.transform);
  37307. this.decomposeTransform();
  37308. },
  37309. /**
  37310. * @return {module:zrender/core/BoundingRect}
  37311. */
  37312. getViewRect: function () {
  37313. return this._viewRect;
  37314. },
  37315. /**
  37316. * Get view rect after roam transform
  37317. * @return {module:zrender/core/BoundingRect}
  37318. */
  37319. getViewRectAfterRoam: function () {
  37320. var rect = this.getBoundingRect().clone();
  37321. rect.applyTransform(this.transform);
  37322. return rect;
  37323. },
  37324. /**
  37325. * Convert a single (lon, lat) data item to (x, y) point.
  37326. * @param {Array.<number>} data
  37327. * @param {boolean} noRoam
  37328. * @param {Array.<number>} [out]
  37329. * @return {Array.<number>}
  37330. */
  37331. dataToPoint: function (data, noRoam, out) {
  37332. var transform = noRoam ? this._rawTransform : this.transform;
  37333. out = out || [];
  37334. return transform
  37335. ? v2ApplyTransform$1(out, data, transform)
  37336. : copy(out, data);
  37337. },
  37338. /**
  37339. * Convert a (x, y) point to (lon, lat) data
  37340. * @param {Array.<number>} point
  37341. * @return {Array.<number>}
  37342. */
  37343. pointToData: function (point) {
  37344. var invTransform = this.invTransform;
  37345. return invTransform
  37346. ? v2ApplyTransform$1([], point, invTransform)
  37347. : [point[0], point[1]];
  37348. },
  37349. /**
  37350. * @implements
  37351. * see {module:echarts/CoodinateSystem}
  37352. */
  37353. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  37354. /**
  37355. * @implements
  37356. * see {module:echarts/CoodinateSystem}
  37357. */
  37358. convertFromPixel: curry(doConvert$1, 'pointToData'),
  37359. /**
  37360. * @implements
  37361. * see {module:echarts/CoodinateSystem}
  37362. */
  37363. containPoint: function (point) {
  37364. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  37365. }
  37366. /**
  37367. * @return {number}
  37368. */
  37369. // getScalarScale: function () {
  37370. // // Use determinant square root of transform to mutiply scalar
  37371. // var m = this.transform;
  37372. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  37373. // return det;
  37374. // }
  37375. };
  37376. mixin(View, Transformable);
  37377. function doConvert$1(methodName, ecModel, finder, value) {
  37378. var seriesModel = finder.seriesModel;
  37379. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  37380. return coordSys === this ? coordSys[methodName](value) : null;
  37381. }
  37382. /*
  37383. * Licensed to the Apache Software Foundation (ASF) under one
  37384. * or more contributor license agreements. See the NOTICE file
  37385. * distributed with this work for additional information
  37386. * regarding copyright ownership. The ASF licenses this file
  37387. * to you under the Apache License, Version 2.0 (the
  37388. * "License"); you may not use this file except in compliance
  37389. * with the License. You may obtain a copy of the License at
  37390. *
  37391. * http://www.apache.org/licenses/LICENSE-2.0
  37392. *
  37393. * Unless required by applicable law or agreed to in writing,
  37394. * software distributed under the License is distributed on an
  37395. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37396. * KIND, either express or implied. See the License for the
  37397. * specific language governing permissions and limitations
  37398. * under the License.
  37399. */
  37400. // Fix for 南海诸岛
  37401. var geoCoord = [126, 25];
  37402. var points$1 = [
  37403. [[0,3.5],[7,11.2],[15,11.9],[30,7],[42,0.7],[52,0.7],
  37404. [56,7.7],[59,0.7],[64,0.7],[64,0],[5,0],[0,3.5]],
  37405. [[13,16.1],[19,14.7],[16,21.7],[11,23.1],[13,16.1]],
  37406. [[12,32.2],[14,38.5],[15,38.5],[13,32.2],[12,32.2]],
  37407. [[16,47.6],[12,53.2],[13,53.2],[18,47.6],[16,47.6]],
  37408. [[6,64.4],[8,70],[9,70],[8,64.4],[6,64.4]],
  37409. [[23,82.6],[29,79.8],[30,79.8],[25,82.6],[23,82.6]],
  37410. [[37,70.7],[43,62.3],[44,62.3],[39,70.7],[37,70.7]],
  37411. [[48,51.1],[51,45.5],[53,45.5],[50,51.1],[48,51.1]],
  37412. [[51,35],[51,28.7],[53,28.7],[53,35],[51,35]],
  37413. [[52,22.4],[55,17.5],[56,17.5],[53,22.4],[52,22.4]],
  37414. [[58,12.6],[62,7],[63,7],[60,12.6],[58,12.6]],
  37415. [[0,3.5],[0,93.1],[64,93.1],[64,0],[63,0],[63,92.4],
  37416. [1,92.4],[1,3.5],[0,3.5]]
  37417. ];
  37418. for (var i$1 = 0; i$1 < points$1.length; i$1++) {
  37419. for (var k = 0; k < points$1[i$1].length; k++) {
  37420. points$1[i$1][k][0] /= 10.5;
  37421. points$1[i$1][k][1] /= -10.5 / 0.75;
  37422. points$1[i$1][k][0] += geoCoord[0];
  37423. points$1[i$1][k][1] += geoCoord[1];
  37424. }
  37425. }
  37426. var fixNanhai = function (geo) {
  37427. if (geo.map === 'china') {
  37428. geo.regions.push(new Region(
  37429. '南海诸岛',
  37430. map(points$1, function (exterior) {
  37431. return {
  37432. type: 'polygon',
  37433. exterior: exterior
  37434. };
  37435. }), geoCoord
  37436. ));
  37437. }
  37438. };
  37439. /*
  37440. * Licensed to the Apache Software Foundation (ASF) under one
  37441. * or more contributor license agreements. See the NOTICE file
  37442. * distributed with this work for additional information
  37443. * regarding copyright ownership. The ASF licenses this file
  37444. * to you under the Apache License, Version 2.0 (the
  37445. * "License"); you may not use this file except in compliance
  37446. * with the License. You may obtain a copy of the License at
  37447. *
  37448. * http://www.apache.org/licenses/LICENSE-2.0
  37449. *
  37450. * Unless required by applicable law or agreed to in writing,
  37451. * software distributed under the License is distributed on an
  37452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37453. * KIND, either express or implied. See the License for the
  37454. * specific language governing permissions and limitations
  37455. * under the License.
  37456. */
  37457. var coordsOffsetMap = {
  37458. '南海诸岛' : [32, 80],
  37459. // 全国
  37460. '广东': [0, -10],
  37461. '香港': [10, 5],
  37462. '澳门': [-10, 10],
  37463. //'北京': [-10, 0],
  37464. '天津': [5, 5]
  37465. };
  37466. var fixTextCoord = function (geo) {
  37467. each$1(geo.regions, function (region) {
  37468. var coordFix = coordsOffsetMap[region.name];
  37469. if (coordFix) {
  37470. var cp = region.center;
  37471. cp[0] += coordFix[0] / 10.5;
  37472. cp[1] += -coordFix[1] / (10.5 / 0.75);
  37473. }
  37474. });
  37475. };
  37476. /*
  37477. * Licensed to the Apache Software Foundation (ASF) under one
  37478. * or more contributor license agreements. See the NOTICE file
  37479. * distributed with this work for additional information
  37480. * regarding copyright ownership. The ASF licenses this file
  37481. * to you under the Apache License, Version 2.0 (the
  37482. * "License"); you may not use this file except in compliance
  37483. * with the License. You may obtain a copy of the License at
  37484. *
  37485. * http://www.apache.org/licenses/LICENSE-2.0
  37486. *
  37487. * Unless required by applicable law or agreed to in writing,
  37488. * software distributed under the License is distributed on an
  37489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37490. * KIND, either express or implied. See the License for the
  37491. * specific language governing permissions and limitations
  37492. * under the License.
  37493. */
  37494. var geoCoordMap = {
  37495. 'Russia': [100, 60],
  37496. 'United States': [-99, 38],
  37497. 'United States of America': [-99, 38]
  37498. };
  37499. var fixGeoCoord = function (geo) {
  37500. each$1(geo.regions, function (region) {
  37501. var geoCoord = geoCoordMap[region.name];
  37502. if (geoCoord) {
  37503. var cp = region.center;
  37504. cp[0] = geoCoord[0];
  37505. cp[1] = geoCoord[1];
  37506. }
  37507. });
  37508. };
  37509. /*
  37510. * Licensed to the Apache Software Foundation (ASF) under one
  37511. * or more contributor license agreements. See the NOTICE file
  37512. * distributed with this work for additional information
  37513. * regarding copyright ownership. The ASF licenses this file
  37514. * to you under the Apache License, Version 2.0 (the
  37515. * "License"); you may not use this file except in compliance
  37516. * with the License. You may obtain a copy of the License at
  37517. *
  37518. * http://www.apache.org/licenses/LICENSE-2.0
  37519. *
  37520. * Unless required by applicable law or agreed to in writing,
  37521. * software distributed under the License is distributed on an
  37522. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37523. * KIND, either express or implied. See the License for the
  37524. * specific language governing permissions and limitations
  37525. * under the License.
  37526. */
  37527. // Fix for 钓鱼岛
  37528. // var Region = require('../Region');
  37529. // var zrUtil = require('zrender/src/core/util');
  37530. // var geoCoord = [126, 25];
  37531. var points$2 = [
  37532. [
  37533. [123.45165252685547, 25.73527164402261],
  37534. [123.49731445312499, 25.73527164402261],
  37535. [123.49731445312499, 25.750734064600884],
  37536. [123.45165252685547, 25.750734064600884],
  37537. [123.45165252685547, 25.73527164402261]
  37538. ]
  37539. ];
  37540. var fixDiaoyuIsland = function (geo) {
  37541. if (geo.map === 'china') {
  37542. for (var i = 0, len = geo.regions.length; i < len; ++i) {
  37543. if (geo.regions[i].name === '台湾') {
  37544. geo.regions[i].geometries.push({
  37545. type: 'polygon',
  37546. exterior: points$2[0]
  37547. });
  37548. }
  37549. }
  37550. }
  37551. };
  37552. /*
  37553. * Licensed to the Apache Software Foundation (ASF) under one
  37554. * or more contributor license agreements. See the NOTICE file
  37555. * distributed with this work for additional information
  37556. * regarding copyright ownership. The ASF licenses this file
  37557. * to you under the Apache License, Version 2.0 (the
  37558. * "License"); you may not use this file except in compliance
  37559. * with the License. You may obtain a copy of the License at
  37560. *
  37561. * http://www.apache.org/licenses/LICENSE-2.0
  37562. *
  37563. * Unless required by applicable law or agreed to in writing,
  37564. * software distributed under the License is distributed on an
  37565. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37566. * KIND, either express or implied. See the License for the
  37567. * specific language governing permissions and limitations
  37568. * under the License.
  37569. */
  37570. // Geo fix functions
  37571. var geoFixFuncs = [
  37572. fixNanhai,
  37573. fixTextCoord,
  37574. fixGeoCoord,
  37575. fixDiaoyuIsland
  37576. ];
  37577. /**
  37578. * [Geo description]
  37579. * @param {string} name Geo name
  37580. * @param {string} map Map type
  37581. * @param {Object} geoJson
  37582. * @param {Object} [specialAreas]
  37583. * Specify the positioned areas by left, top, width, height
  37584. * @param {Object.<string, string>} [nameMap]
  37585. * Specify name alias
  37586. */
  37587. function Geo(name, map$$1, geoJson, specialAreas, nameMap) {
  37588. View.call(this, name);
  37589. /**
  37590. * Map type
  37591. * @type {string}
  37592. */
  37593. this.map = map$$1;
  37594. this._nameCoordMap = createHashMap();
  37595. this.loadGeoJson(geoJson, specialAreas, nameMap);
  37596. }
  37597. Geo.prototype = {
  37598. constructor: Geo,
  37599. type: 'geo',
  37600. /**
  37601. * @param {Array.<string>}
  37602. * @readOnly
  37603. */
  37604. dimensions: ['lng', 'lat'],
  37605. /**
  37606. * If contain given lng,lat coord
  37607. * @param {Array.<number>}
  37608. * @readOnly
  37609. */
  37610. containCoord: function (coord) {
  37611. var regions = this.regions;
  37612. for (var i = 0; i < regions.length; i++) {
  37613. if (regions[i].contain(coord)) {
  37614. return true;
  37615. }
  37616. }
  37617. return false;
  37618. },
  37619. /**
  37620. * @param {Object} geoJson
  37621. * @param {Object} [specialAreas]
  37622. * Specify the positioned areas by left, top, width, height
  37623. * @param {Object.<string, string>} [nameMap]
  37624. * Specify name alias
  37625. */
  37626. loadGeoJson: function (geoJson, specialAreas, nameMap) {
  37627. // https://jsperf.com/try-catch-performance-overhead
  37628. try {
  37629. this.regions = geoJson ? parseGeoJson$1(geoJson) : [];
  37630. }
  37631. catch (e) {
  37632. throw 'Invalid geoJson format\n' + e.message;
  37633. }
  37634. specialAreas = specialAreas || {};
  37635. nameMap = nameMap || {};
  37636. var regions = this.regions;
  37637. var regionsMap = createHashMap();
  37638. for (var i = 0; i < regions.length; i++) {
  37639. var regionName = regions[i].name;
  37640. // Try use the alias in nameMap
  37641. regionName = nameMap.hasOwnProperty(regionName) ? nameMap[regionName] : regionName;
  37642. regions[i].name = regionName;
  37643. regionsMap.set(regionName, regions[i]);
  37644. // Add geoJson
  37645. this.addGeoCoord(regionName, regions[i].center);
  37646. // Some area like Alaska in USA map needs to be tansformed
  37647. // to look better
  37648. var specialArea = specialAreas[regionName];
  37649. if (specialArea) {
  37650. regions[i].transformTo(
  37651. specialArea.left, specialArea.top, specialArea.width, specialArea.height
  37652. );
  37653. }
  37654. }
  37655. this._regionsMap = regionsMap;
  37656. this._rect = null;
  37657. each$1(geoFixFuncs, function (fixFunc) {
  37658. fixFunc(this);
  37659. }, this);
  37660. },
  37661. // Overwrite
  37662. transformTo: function (x, y, width, height) {
  37663. var rect = this.getBoundingRect();
  37664. rect = rect.clone();
  37665. // Longitute is inverted
  37666. rect.y = -rect.y - rect.height;
  37667. var rawTransformable = this._rawTransformable;
  37668. rawTransformable.transform = rect.calculateTransform(
  37669. new BoundingRect(x, y, width, height)
  37670. );
  37671. rawTransformable.decomposeTransform();
  37672. var scale = rawTransformable.scale;
  37673. scale[1] = -scale[1];
  37674. rawTransformable.updateTransform();
  37675. this._updateTransform();
  37676. },
  37677. /**
  37678. * @param {string} name
  37679. * @return {module:echarts/coord/geo/Region}
  37680. */
  37681. getRegion: function (name) {
  37682. return this._regionsMap.get(name);
  37683. },
  37684. getRegionByCoord: function (coord) {
  37685. var regions = this.regions;
  37686. for (var i = 0; i < regions.length; i++) {
  37687. if (regions[i].contain(coord)) {
  37688. return regions[i];
  37689. }
  37690. }
  37691. },
  37692. /**
  37693. * Add geoCoord for indexing by name
  37694. * @param {string} name
  37695. * @param {Array.<number>} geoCoord
  37696. */
  37697. addGeoCoord: function (name, geoCoord) {
  37698. this._nameCoordMap.set(name, geoCoord);
  37699. },
  37700. /**
  37701. * Get geoCoord by name
  37702. * @param {string} name
  37703. * @return {Array.<number>}
  37704. */
  37705. getGeoCoord: function (name) {
  37706. return this._nameCoordMap.get(name);
  37707. },
  37708. // Overwrite
  37709. getBoundingRect: function () {
  37710. if (this._rect) {
  37711. return this._rect;
  37712. }
  37713. var rect;
  37714. var regions = this.regions;
  37715. for (var i = 0; i < regions.length; i++) {
  37716. var regionRect = regions[i].getBoundingRect();
  37717. rect = rect || regionRect.clone();
  37718. rect.union(regionRect);
  37719. }
  37720. // FIXME Always return new ?
  37721. return (this._rect = rect || new BoundingRect(0, 0, 0, 0));
  37722. },
  37723. /**
  37724. * @param {string|Array.<number>} data
  37725. * @param {boolean} noRoam
  37726. * @param {Array.<number>} [out]
  37727. * @return {Array.<number>}
  37728. */
  37729. dataToPoint: function (data, noRoam, out) {
  37730. if (typeof data === 'string') {
  37731. // Map area name to geoCoord
  37732. data = this.getGeoCoord(data);
  37733. }
  37734. if (data) {
  37735. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  37736. }
  37737. },
  37738. /**
  37739. * @inheritDoc
  37740. */
  37741. convertToPixel: curry(doConvert, 'dataToPoint'),
  37742. /**
  37743. * @inheritDoc
  37744. */
  37745. convertFromPixel: curry(doConvert, 'pointToData')
  37746. };
  37747. mixin(Geo, View);
  37748. function doConvert(methodName, ecModel, finder, value) {
  37749. var geoModel = finder.geoModel;
  37750. var seriesModel = finder.seriesModel;
  37751. var coordSys = geoModel
  37752. ? geoModel.coordinateSystem
  37753. : seriesModel
  37754. ? (
  37755. seriesModel.coordinateSystem // For map.
  37756. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem
  37757. )
  37758. : null;
  37759. return coordSys === this ? coordSys[methodName](value) : null;
  37760. }
  37761. /*
  37762. * Licensed to the Apache Software Foundation (ASF) under one
  37763. * or more contributor license agreements. See the NOTICE file
  37764. * distributed with this work for additional information
  37765. * regarding copyright ownership. The ASF licenses this file
  37766. * to you under the Apache License, Version 2.0 (the
  37767. * "License"); you may not use this file except in compliance
  37768. * with the License. You may obtain a copy of the License at
  37769. *
  37770. * http://www.apache.org/licenses/LICENSE-2.0
  37771. *
  37772. * Unless required by applicable law or agreed to in writing,
  37773. * software distributed under the License is distributed on an
  37774. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37775. * KIND, either express or implied. See the License for the
  37776. * specific language governing permissions and limitations
  37777. * under the License.
  37778. */
  37779. /**
  37780. * Resize method bound to the geo
  37781. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  37782. * @param {module:echarts/ExtensionAPI} api
  37783. */
  37784. function resizeGeo(geoModel, api) {
  37785. var boundingCoords = geoModel.get('boundingCoords');
  37786. if (boundingCoords != null) {
  37787. var leftTop = boundingCoords[0];
  37788. var rightBottom = boundingCoords[1];
  37789. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {
  37790. if (__DEV__) {
  37791. console.error('Invalid boundingCoords');
  37792. }
  37793. }
  37794. else {
  37795. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  37796. }
  37797. }
  37798. var rect = this.getBoundingRect();
  37799. var boxLayoutOption;
  37800. var center = geoModel.get('layoutCenter');
  37801. var size = geoModel.get('layoutSize');
  37802. var viewWidth = api.getWidth();
  37803. var viewHeight = api.getHeight();
  37804. var aspectScale = geoModel.get('aspectScale') || 0.75;
  37805. var aspect = rect.width / rect.height * aspectScale;
  37806. var useCenterAndSize = false;
  37807. if (center && size) {
  37808. center = [
  37809. parsePercent$1(center[0], viewWidth),
  37810. parsePercent$1(center[1], viewHeight)
  37811. ];
  37812. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  37813. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  37814. useCenterAndSize = true;
  37815. }
  37816. else {
  37817. if (__DEV__) {
  37818. console.warn('Given layoutCenter or layoutSize data are invalid. Use left/top/width/height instead.');
  37819. }
  37820. }
  37821. }
  37822. var viewRect;
  37823. if (useCenterAndSize) {
  37824. var viewRect = {};
  37825. if (aspect > 1) {
  37826. // Width is same with size
  37827. viewRect.width = size;
  37828. viewRect.height = size / aspect;
  37829. }
  37830. else {
  37831. viewRect.height = size;
  37832. viewRect.width = size * aspect;
  37833. }
  37834. viewRect.y = center[1] - viewRect.height / 2;
  37835. viewRect.x = center[0] - viewRect.width / 2;
  37836. }
  37837. else {
  37838. // Use left/top/width/height
  37839. boxLayoutOption = geoModel.getBoxLayoutParams();
  37840. // 0.75 rate
  37841. boxLayoutOption.aspect = aspect;
  37842. viewRect = getLayoutRect(boxLayoutOption, {
  37843. width: viewWidth,
  37844. height: viewHeight
  37845. });
  37846. }
  37847. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  37848. this.setCenter(geoModel.get('center'));
  37849. this.setZoom(geoModel.get('zoom'));
  37850. }
  37851. /**
  37852. * @param {module:echarts/coord/Geo} geo
  37853. * @param {module:echarts/model/Model} model
  37854. * @inner
  37855. */
  37856. function setGeoCoords(geo, model) {
  37857. each$1(model.get('geoCoord'), function (geoCoord, name) {
  37858. geo.addGeoCoord(name, geoCoord);
  37859. });
  37860. }
  37861. if (__DEV__) {
  37862. var mapNotExistsError = function (name) {
  37863. console.error('Map ' + name + ' not exists. You can download map file on http://echarts.baidu.com/download-map.html');
  37864. };
  37865. }
  37866. var geoCreator = {
  37867. // For deciding which dimensions to use when creating list data
  37868. dimensions: Geo.prototype.dimensions,
  37869. create: function (ecModel, api) {
  37870. var geoList = [];
  37871. // FIXME Create each time may be slow
  37872. ecModel.eachComponent('geo', function (geoModel, idx) {
  37873. var name = geoModel.get('map');
  37874. var mapData = getMap(name);
  37875. if (__DEV__) {
  37876. if (!mapData) {
  37877. mapNotExistsError(name);
  37878. }
  37879. }
  37880. var geo = new Geo(
  37881. name + idx, name,
  37882. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  37883. geoModel.get('nameMap')
  37884. );
  37885. geo.zoomLimit = geoModel.get('scaleLimit');
  37886. geoList.push(geo);
  37887. setGeoCoords(geo, geoModel);
  37888. geoModel.coordinateSystem = geo;
  37889. geo.model = geoModel;
  37890. // Inject resize method
  37891. geo.resize = resizeGeo;
  37892. geo.resize(geoModel, api);
  37893. });
  37894. ecModel.eachSeries(function (seriesModel) {
  37895. var coordSys = seriesModel.get('coordinateSystem');
  37896. if (coordSys === 'geo') {
  37897. var geoIndex = seriesModel.get('geoIndex') || 0;
  37898. seriesModel.coordinateSystem = geoList[geoIndex];
  37899. }
  37900. });
  37901. // If has map series
  37902. var mapModelGroupBySeries = {};
  37903. ecModel.eachSeriesByType('map', function (seriesModel) {
  37904. if (!seriesModel.getHostGeoModel()) {
  37905. var mapType = seriesModel.getMapType();
  37906. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  37907. mapModelGroupBySeries[mapType].push(seriesModel);
  37908. }
  37909. });
  37910. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  37911. var mapData = getMap(mapType);
  37912. if (__DEV__) {
  37913. if (!mapData) {
  37914. mapNotExistsError(mapSeries[0].get('map'));
  37915. }
  37916. }
  37917. var nameMapList = map(mapSeries, function (singleMapSeries) {
  37918. return singleMapSeries.get('nameMap');
  37919. });
  37920. var geo = new Geo(
  37921. mapType, mapType,
  37922. mapData && mapData.geoJson, mapData && mapData.specialAreas,
  37923. mergeAll(nameMapList)
  37924. );
  37925. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  37926. return singleMapSeries.get('scaleLimit');
  37927. }));
  37928. geoList.push(geo);
  37929. // Inject resize method
  37930. geo.resize = resizeGeo;
  37931. geo.resize(mapSeries[0], api);
  37932. each$1(mapSeries, function (singleMapSeries) {
  37933. singleMapSeries.coordinateSystem = geo;
  37934. setGeoCoords(geo, singleMapSeries);
  37935. });
  37936. });
  37937. return geoList;
  37938. },
  37939. /**
  37940. * Fill given regions array
  37941. * @param {Array.<Object>} originRegionArr
  37942. * @param {string} mapName
  37943. * @param {Object} [nameMap]
  37944. * @return {Array}
  37945. */
  37946. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  37947. // Not use the original
  37948. var regionsArr = (originRegionArr || []).slice();
  37949. nameMap = nameMap || {};
  37950. var map$$1 = getMap(mapName);
  37951. var geoJson = map$$1 && map$$1.geoJson;
  37952. if (!geoJson) {
  37953. if (__DEV__) {
  37954. mapNotExistsError(mapName);
  37955. }
  37956. return originRegionArr;
  37957. }
  37958. var dataNameMap = createHashMap();
  37959. var features = geoJson.features;
  37960. for (var i = 0; i < regionsArr.length; i++) {
  37961. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  37962. }
  37963. for (var i = 0; i < features.length; i++) {
  37964. var name = features[i].properties.name;
  37965. if (!dataNameMap.get(name)) {
  37966. if (nameMap.hasOwnProperty(name)) {
  37967. name = nameMap[name];
  37968. }
  37969. regionsArr.push({
  37970. name: name
  37971. });
  37972. }
  37973. }
  37974. return regionsArr;
  37975. }
  37976. };
  37977. registerCoordinateSystem('geo', geoCreator);
  37978. /*
  37979. * Licensed to the Apache Software Foundation (ASF) under one
  37980. * or more contributor license agreements. See the NOTICE file
  37981. * distributed with this work for additional information
  37982. * regarding copyright ownership. The ASF licenses this file
  37983. * to you under the Apache License, Version 2.0 (the
  37984. * "License"); you may not use this file except in compliance
  37985. * with the License. You may obtain a copy of the License at
  37986. *
  37987. * http://www.apache.org/licenses/LICENSE-2.0
  37988. *
  37989. * Unless required by applicable law or agreed to in writing,
  37990. * software distributed under the License is distributed on an
  37991. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37992. * KIND, either express or implied. See the License for the
  37993. * specific language governing permissions and limitations
  37994. * under the License.
  37995. */
  37996. var MapSeries = SeriesModel.extend({
  37997. type: 'series.map',
  37998. dependencies: ['geo'],
  37999. layoutMode: 'box',
  38000. /**
  38001. * Only first map series of same mapType will drawMap
  38002. * @type {boolean}
  38003. */
  38004. needsDrawMap: false,
  38005. /**
  38006. * Group of all map series with same mapType
  38007. * @type {boolean}
  38008. */
  38009. seriesGroup: [],
  38010. init: function (option) {
  38011. // this._fillOption(option, this.getMapType());
  38012. // this.option = option;
  38013. MapSeries.superApply(this, 'init', arguments);
  38014. this.updateSelectedMap(this._createSelectableList());
  38015. },
  38016. getInitialData: function (option) {
  38017. return createListSimply(this, ['value']);
  38018. },
  38019. mergeOption: function (newOption) {
  38020. // this._fillOption(newOption, this.getMapType());
  38021. MapSeries.superApply(this, 'mergeOption', arguments);
  38022. this.updateSelectedMap(this._createSelectableList());
  38023. },
  38024. _createSelectableList: function () {
  38025. var data = this.getRawData();
  38026. var valueDim = data.mapDimension('value');
  38027. var targetList = [];
  38028. for (var i = 0, len = data.count(); i < len; i++) {
  38029. targetList.push({
  38030. name: data.getName(i),
  38031. value: data.get(valueDim, i),
  38032. selected: retrieveRawAttr(data, i, 'selected')
  38033. });
  38034. }
  38035. targetList = geoCreator.getFilledRegions(targetList, this.getMapType(), this.option.nameMap);
  38036. return targetList;
  38037. },
  38038. /**
  38039. * If no host geo model, return null, which means using a
  38040. * inner exclusive geo model.
  38041. */
  38042. getHostGeoModel: function () {
  38043. var geoIndex = this.option.geoIndex;
  38044. return geoIndex != null
  38045. ? this.dependentModels.geo[geoIndex]
  38046. : null;
  38047. },
  38048. getMapType: function () {
  38049. return (this.getHostGeoModel() || this).option.map;
  38050. },
  38051. _fillOption: function (option, mapName) {
  38052. // Shallow clone
  38053. // option = zrUtil.extend({}, option);
  38054. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  38055. // return option;
  38056. },
  38057. getRawValue: function (dataIndex) {
  38058. // Use value stored in data instead because it is calculated from multiple series
  38059. // FIXME Provide all value of multiple series ?
  38060. var data = this.getData();
  38061. return data.get(data.mapDimension('value'), dataIndex);
  38062. },
  38063. /**
  38064. * Get model of region
  38065. * @param {string} name
  38066. * @return {module:echarts/model/Model}
  38067. */
  38068. getRegionModel: function (regionName) {
  38069. var data = this.getData();
  38070. return data.getItemModel(data.indexOfName(regionName));
  38071. },
  38072. /**
  38073. * Map tooltip formatter
  38074. *
  38075. * @param {number} dataIndex
  38076. */
  38077. formatTooltip: function (dataIndex) {
  38078. // FIXME orignalData and data is a bit confusing
  38079. var data = this.getData();
  38080. var formattedValue = addCommas(this.getRawValue(dataIndex));
  38081. var name = data.getName(dataIndex);
  38082. var seriesGroup = this.seriesGroup;
  38083. var seriesNames = [];
  38084. for (var i = 0; i < seriesGroup.length; i++) {
  38085. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  38086. var valueDim = data.mapDimension('value');
  38087. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  38088. seriesNames.push(
  38089. encodeHTML(seriesGroup[i].name)
  38090. );
  38091. }
  38092. }
  38093. return seriesNames.join(', ') + '<br />'
  38094. + encodeHTML(name + ' : ' + formattedValue);
  38095. },
  38096. /**
  38097. * @implement
  38098. */
  38099. getTooltipPosition: function (dataIndex) {
  38100. if (dataIndex != null) {
  38101. var name = this.getData().getName(dataIndex);
  38102. var geo = this.coordinateSystem;
  38103. var region = geo.getRegion(name);
  38104. return region && geo.dataToPoint(region.center);
  38105. }
  38106. },
  38107. setZoom: function (zoom) {
  38108. this.option.zoom = zoom;
  38109. },
  38110. setCenter: function (center) {
  38111. this.option.center = center;
  38112. },
  38113. defaultOption: {
  38114. // 一级层叠
  38115. zlevel: 0,
  38116. // 二级层叠
  38117. z: 2,
  38118. coordinateSystem: 'geo',
  38119. // map should be explicitly specified since ec3.
  38120. map: '',
  38121. // If `geoIndex` is not specified, a exclusive geo will be
  38122. // created. Otherwise use the specified geo component, and
  38123. // `map` and `mapType` are ignored.
  38124. // geoIndex: 0,
  38125. // 'center' | 'left' | 'right' | 'x%' | {number}
  38126. left: 'center',
  38127. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  38128. top: 'center',
  38129. // right
  38130. // bottom
  38131. // width:
  38132. // height
  38133. // Aspect is width / height. Inited to be geoJson bbox aspect
  38134. // This parameter is used for scale this aspect
  38135. aspectScale: 0.75,
  38136. ///// Layout with center and size
  38137. // If you wan't to put map in a fixed size box with right aspect ratio
  38138. // This two properties may more conveninet
  38139. // layoutCenter: [50%, 50%]
  38140. // layoutSize: 100
  38141. // 数值合并方式,默认加和,可选为:
  38142. // 'sum' | 'average' | 'max' | 'min'
  38143. // mapValueCalculation: 'sum',
  38144. // 地图数值计算结果小数精度
  38145. // mapValuePrecision: 0,
  38146. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  38147. showLegendSymbol: true,
  38148. // 选择模式,默认关闭,可选single,multiple
  38149. // selectedMode: false,
  38150. dataRangeHoverLink: true,
  38151. // 是否开启缩放及漫游模式
  38152. // roam: false,
  38153. // Define left-top, right-bottom coords to control view
  38154. // For example, [ [180, 90], [-180, -90] ],
  38155. // higher priority than center and zoom
  38156. boundingCoords: null,
  38157. // Default on center of map
  38158. center: null,
  38159. zoom: 1,
  38160. scaleLimit: null,
  38161. label: {
  38162. show: false,
  38163. color: '#000'
  38164. },
  38165. // scaleLimit: null,
  38166. itemStyle: {
  38167. borderWidth: 0.5,
  38168. borderColor: '#444',
  38169. areaColor: '#eee'
  38170. },
  38171. emphasis: {
  38172. label: {
  38173. show: true,
  38174. color: 'rgb(100,0,0)'
  38175. },
  38176. itemStyle: {
  38177. areaColor: 'rgba(255,215,0,0.8)'
  38178. }
  38179. }
  38180. }
  38181. });
  38182. mixin(MapSeries, selectableMixin);
  38183. /*
  38184. * Licensed to the Apache Software Foundation (ASF) under one
  38185. * or more contributor license agreements. See the NOTICE file
  38186. * distributed with this work for additional information
  38187. * regarding copyright ownership. The ASF licenses this file
  38188. * to you under the Apache License, Version 2.0 (the
  38189. * "License"); you may not use this file except in compliance
  38190. * with the License. You may obtain a copy of the License at
  38191. *
  38192. * http://www.apache.org/licenses/LICENSE-2.0
  38193. *
  38194. * Unless required by applicable law or agreed to in writing,
  38195. * software distributed under the License is distributed on an
  38196. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38197. * KIND, either express or implied. See the License for the
  38198. * specific language governing permissions and limitations
  38199. * under the License.
  38200. */
  38201. var ATTR = '\0_ec_interaction_mutex';
  38202. function take(zr, resourceKey, userKey) {
  38203. var store = getStore(zr);
  38204. store[resourceKey] = userKey;
  38205. }
  38206. function release(zr, resourceKey, userKey) {
  38207. var store = getStore(zr);
  38208. var uKey = store[resourceKey];
  38209. if (uKey === userKey) {
  38210. store[resourceKey] = null;
  38211. }
  38212. }
  38213. function isTaken(zr, resourceKey) {
  38214. return !!getStore(zr)[resourceKey];
  38215. }
  38216. function getStore(zr) {
  38217. return zr[ATTR] || (zr[ATTR] = {});
  38218. }
  38219. /**
  38220. * payload: {
  38221. * type: 'takeGlobalCursor',
  38222. * key: 'dataZoomSelect', or 'brush', or ...,
  38223. * If no userKey, release global cursor.
  38224. * }
  38225. */
  38226. registerAction(
  38227. {type: 'takeGlobalCursor', event: 'globalCursorTaken', update: 'update'},
  38228. function () {}
  38229. );
  38230. /*
  38231. * Licensed to the Apache Software Foundation (ASF) under one
  38232. * or more contributor license agreements. See the NOTICE file
  38233. * distributed with this work for additional information
  38234. * regarding copyright ownership. The ASF licenses this file
  38235. * to you under the Apache License, Version 2.0 (the
  38236. * "License"); you may not use this file except in compliance
  38237. * with the License. You may obtain a copy of the License at
  38238. *
  38239. * http://www.apache.org/licenses/LICENSE-2.0
  38240. *
  38241. * Unless required by applicable law or agreed to in writing,
  38242. * software distributed under the License is distributed on an
  38243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38244. * KIND, either express or implied. See the License for the
  38245. * specific language governing permissions and limitations
  38246. * under the License.
  38247. */
  38248. /**
  38249. * @alias module:echarts/component/helper/RoamController
  38250. * @constructor
  38251. * @mixin {module:zrender/mixin/Eventful}
  38252. *
  38253. * @param {module:zrender/zrender~ZRender} zr
  38254. */
  38255. function RoamController(zr) {
  38256. /**
  38257. * @type {Function}
  38258. */
  38259. this.pointerChecker;
  38260. /**
  38261. * @type {module:zrender}
  38262. */
  38263. this._zr = zr;
  38264. /**
  38265. * @type {Object}
  38266. */
  38267. this._opt = {};
  38268. // Avoid two roamController bind the same handler
  38269. var bind$$1 = bind;
  38270. var mousedownHandler = bind$$1(mousedown, this);
  38271. var mousemoveHandler = bind$$1(mousemove, this);
  38272. var mouseupHandler = bind$$1(mouseup, this);
  38273. var mousewheelHandler = bind$$1(mousewheel, this);
  38274. var pinchHandler = bind$$1(pinch, this);
  38275. Eventful.call(this);
  38276. /**
  38277. * @param {Function} pointerChecker
  38278. * input: x, y
  38279. * output: boolean
  38280. */
  38281. this.setPointerChecker = function (pointerChecker) {
  38282. this.pointerChecker = pointerChecker;
  38283. };
  38284. /**
  38285. * Notice: only enable needed types. For example, if 'zoom'
  38286. * is not needed, 'zoom' should not be enabled, otherwise
  38287. * default mousewheel behaviour (scroll page) will be disabled.
  38288. *
  38289. * @param {boolean|string} [controlType=true] Specify the control type,
  38290. * which can be null/undefined or true/false
  38291. * or 'pan/move' or 'zoom'/'scale'
  38292. * @param {Object} [opt]
  38293. * @param {Object} [opt.zoomOnMouseWheel=true]
  38294. * @param {Object} [opt.moveOnMouseMove=true]
  38295. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  38296. */
  38297. this.enable = function (controlType, opt) {
  38298. // Disable previous first
  38299. this.disable();
  38300. this._opt = defaults(clone(opt) || {}, {
  38301. zoomOnMouseWheel: true,
  38302. moveOnMouseMove: true,
  38303. preventDefaultMouseMove: true
  38304. });
  38305. if (controlType == null) {
  38306. controlType = true;
  38307. }
  38308. if (controlType === true || (controlType === 'move' || controlType === 'pan')) {
  38309. zr.on('mousedown', mousedownHandler);
  38310. zr.on('mousemove', mousemoveHandler);
  38311. zr.on('mouseup', mouseupHandler);
  38312. }
  38313. if (controlType === true || (controlType === 'scale' || controlType === 'zoom')) {
  38314. zr.on('mousewheel', mousewheelHandler);
  38315. zr.on('pinch', pinchHandler);
  38316. }
  38317. };
  38318. this.disable = function () {
  38319. zr.off('mousedown', mousedownHandler);
  38320. zr.off('mousemove', mousemoveHandler);
  38321. zr.off('mouseup', mouseupHandler);
  38322. zr.off('mousewheel', mousewheelHandler);
  38323. zr.off('pinch', pinchHandler);
  38324. };
  38325. this.dispose = this.disable;
  38326. this.isDragging = function () {
  38327. return this._dragging;
  38328. };
  38329. this.isPinching = function () {
  38330. return this._pinching;
  38331. };
  38332. }
  38333. mixin(RoamController, Eventful);
  38334. function mousedown(e) {
  38335. if (notLeftMouse(e)
  38336. || (e.target && e.target.draggable)
  38337. ) {
  38338. return;
  38339. }
  38340. var x = e.offsetX;
  38341. var y = e.offsetY;
  38342. // Only check on mosedown, but not mousemove.
  38343. // Mouse can be out of target when mouse moving.
  38344. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  38345. this._x = x;
  38346. this._y = y;
  38347. this._dragging = true;
  38348. }
  38349. }
  38350. function mousemove(e) {
  38351. if (notLeftMouse(e)
  38352. || !checkKeyBinding(this, 'moveOnMouseMove', e)
  38353. || !this._dragging
  38354. || e.gestureEvent === 'pinch'
  38355. || isTaken(this._zr, 'globalPan')
  38356. ) {
  38357. return;
  38358. }
  38359. var x = e.offsetX;
  38360. var y = e.offsetY;
  38361. var oldX = this._x;
  38362. var oldY = this._y;
  38363. var dx = x - oldX;
  38364. var dy = y - oldY;
  38365. this._x = x;
  38366. this._y = y;
  38367. this._opt.preventDefaultMouseMove && stop(e.event);
  38368. this.trigger('pan', dx, dy, oldX, oldY, x, y);
  38369. }
  38370. function mouseup(e) {
  38371. if (!notLeftMouse(e)) {
  38372. this._dragging = false;
  38373. }
  38374. }
  38375. function mousewheel(e) {
  38376. // wheelDelta maybe -0 in chrome mac.
  38377. if (!checkKeyBinding(this, 'zoomOnMouseWheel', e) || e.wheelDelta === 0) {
  38378. return;
  38379. }
  38380. // Convenience:
  38381. // Mac and VM Windows on Mac: scroll up: zoom out.
  38382. // Windows: scroll up: zoom in.
  38383. var zoomDelta = e.wheelDelta > 0 ? 1.1 : 1 / 1.1;
  38384. zoom.call(this, e, zoomDelta, e.offsetX, e.offsetY);
  38385. }
  38386. function pinch(e) {
  38387. if (isTaken(this._zr, 'globalPan')) {
  38388. return;
  38389. }
  38390. var zoomDelta = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  38391. zoom.call(this, e, zoomDelta, e.pinchX, e.pinchY);
  38392. }
  38393. function zoom(e, zoomDelta, zoomX, zoomY) {
  38394. if (this.pointerChecker && this.pointerChecker(e, zoomX, zoomY)) {
  38395. // When mouse is out of roamController rect,
  38396. // default befavoius should not be be disabled, otherwise
  38397. // page sliding is disabled, contrary to expectation.
  38398. stop(e.event);
  38399. this.trigger('zoom', zoomDelta, zoomX, zoomY);
  38400. }
  38401. }
  38402. function checkKeyBinding(roamController, prop, e) {
  38403. var setting = roamController._opt[prop];
  38404. return setting
  38405. && (!isString(setting) || e.event[setting + 'Key']);
  38406. }
  38407. /*
  38408. * Licensed to the Apache Software Foundation (ASF) under one
  38409. * or more contributor license agreements. See the NOTICE file
  38410. * distributed with this work for additional information
  38411. * regarding copyright ownership. The ASF licenses this file
  38412. * to you under the Apache License, Version 2.0 (the
  38413. * "License"); you may not use this file except in compliance
  38414. * with the License. You may obtain a copy of the License at
  38415. *
  38416. * http://www.apache.org/licenses/LICENSE-2.0
  38417. *
  38418. * Unless required by applicable law or agreed to in writing,
  38419. * software distributed under the License is distributed on an
  38420. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38421. * KIND, either express or implied. See the License for the
  38422. * specific language governing permissions and limitations
  38423. * under the License.
  38424. */
  38425. /**
  38426. * For geo and graph.
  38427. *
  38428. * @param {Object} controllerHost
  38429. * @param {module:zrender/Element} controllerHost.target
  38430. */
  38431. function updateViewOnPan(controllerHost, dx, dy) {
  38432. var target = controllerHost.target;
  38433. var pos = target.position;
  38434. pos[0] += dx;
  38435. pos[1] += dy;
  38436. target.dirty();
  38437. }
  38438. /**
  38439. * For geo and graph.
  38440. *
  38441. * @param {Object} controllerHost
  38442. * @param {module:zrender/Element} controllerHost.target
  38443. * @param {number} controllerHost.zoom
  38444. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  38445. */
  38446. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  38447. var target = controllerHost.target;
  38448. var zoomLimit = controllerHost.zoomLimit;
  38449. var pos = target.position;
  38450. var scale = target.scale;
  38451. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  38452. newZoom *= zoomDelta;
  38453. if (zoomLimit) {
  38454. var zoomMin = zoomLimit.min || 0;
  38455. var zoomMax = zoomLimit.max || Infinity;
  38456. newZoom = Math.max(
  38457. Math.min(zoomMax, newZoom),
  38458. zoomMin
  38459. );
  38460. }
  38461. var zoomScale = newZoom / controllerHost.zoom;
  38462. controllerHost.zoom = newZoom;
  38463. // Keep the mouse center when scaling
  38464. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  38465. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  38466. scale[0] *= zoomScale;
  38467. scale[1] *= zoomScale;
  38468. target.dirty();
  38469. }
  38470. /*
  38471. * Licensed to the Apache Software Foundation (ASF) under one
  38472. * or more contributor license agreements. See the NOTICE file
  38473. * distributed with this work for additional information
  38474. * regarding copyright ownership. The ASF licenses this file
  38475. * to you under the Apache License, Version 2.0 (the
  38476. * "License"); you may not use this file except in compliance
  38477. * with the License. You may obtain a copy of the License at
  38478. *
  38479. * http://www.apache.org/licenses/LICENSE-2.0
  38480. *
  38481. * Unless required by applicable law or agreed to in writing,
  38482. * software distributed under the License is distributed on an
  38483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38484. * KIND, either express or implied. See the License for the
  38485. * specific language governing permissions and limitations
  38486. * under the License.
  38487. */
  38488. var IRRELEVANT_EXCLUDES = {'axisPointer': 1, 'tooltip': 1, 'brush': 1};
  38489. /**
  38490. * Avoid that: mouse click on a elements that is over geo or graph,
  38491. * but roam is triggered.
  38492. */
  38493. function onIrrelevantElement(e, api, targetCoordSysModel) {
  38494. var model = api.getComponentByElement(e.topTarget);
  38495. // If model is axisModel, it works only if it is injected with coordinateSystem.
  38496. var coordSys = model && model.coordinateSystem;
  38497. return model
  38498. && model !== targetCoordSysModel
  38499. && !IRRELEVANT_EXCLUDES[model.mainType]
  38500. && (coordSys && coordSys.model !== targetCoordSysModel);
  38501. }
  38502. /*
  38503. * Licensed to the Apache Software Foundation (ASF) under one
  38504. * or more contributor license agreements. See the NOTICE file
  38505. * distributed with this work for additional information
  38506. * regarding copyright ownership. The ASF licenses this file
  38507. * to you under the Apache License, Version 2.0 (the
  38508. * "License"); you may not use this file except in compliance
  38509. * with the License. You may obtain a copy of the License at
  38510. *
  38511. * http://www.apache.org/licenses/LICENSE-2.0
  38512. *
  38513. * Unless required by applicable law or agreed to in writing,
  38514. * software distributed under the License is distributed on an
  38515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38516. * KIND, either express or implied. See the License for the
  38517. * specific language governing permissions and limitations
  38518. * under the License.
  38519. */
  38520. function getFixedItemStyle(model, scale) {
  38521. var itemStyle = model.getItemStyle();
  38522. var areaColor = model.get('areaColor');
  38523. // If user want the color not to be changed when hover,
  38524. // they should both set areaColor and color to be null.
  38525. if (areaColor != null) {
  38526. itemStyle.fill = areaColor;
  38527. }
  38528. return itemStyle;
  38529. }
  38530. function updateMapSelectHandler(mapDraw, mapOrGeoModel, group, api, fromView) {
  38531. group.off('click');
  38532. group.off('mousedown');
  38533. if (mapOrGeoModel.get('selectedMode')) {
  38534. group.on('mousedown', function () {
  38535. mapDraw._mouseDownFlag = true;
  38536. });
  38537. group.on('click', function (e) {
  38538. if (!mapDraw._mouseDownFlag) {
  38539. return;
  38540. }
  38541. mapDraw._mouseDownFlag = false;
  38542. var el = e.target;
  38543. while (!el.__regions) {
  38544. el = el.parent;
  38545. }
  38546. if (!el) {
  38547. return;
  38548. }
  38549. var action = {
  38550. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  38551. batch: map(el.__regions, function (region) {
  38552. return {
  38553. name: region.name,
  38554. from: fromView.uid
  38555. };
  38556. })
  38557. };
  38558. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  38559. api.dispatchAction(action);
  38560. updateMapSelected(mapOrGeoModel, group);
  38561. });
  38562. }
  38563. }
  38564. function updateMapSelected(mapOrGeoModel, group) {
  38565. // FIXME
  38566. group.eachChild(function (otherRegionEl) {
  38567. each$1(otherRegionEl.__regions, function (region) {
  38568. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  38569. });
  38570. });
  38571. }
  38572. /**
  38573. * @alias module:echarts/component/helper/MapDraw
  38574. * @param {module:echarts/ExtensionAPI} api
  38575. * @param {boolean} updateGroup
  38576. */
  38577. function MapDraw(api, updateGroup) {
  38578. var group = new Group();
  38579. /**
  38580. * @type {module:echarts/component/helper/RoamController}
  38581. * @private
  38582. */
  38583. this._controller = new RoamController(api.getZr());
  38584. /**
  38585. * @type {Object} {target, zoom, zoomLimit}
  38586. * @private
  38587. */
  38588. this._controllerHost = {target: updateGroup ? group : null};
  38589. /**
  38590. * @type {module:zrender/container/Group}
  38591. * @readOnly
  38592. */
  38593. this.group = group;
  38594. /**
  38595. * @type {boolean}
  38596. * @private
  38597. */
  38598. this._updateGroup = updateGroup;
  38599. /**
  38600. * This flag is used to make sure that only one among
  38601. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  38602. * action may be triggered when `pan`, which is unexpected.
  38603. * @type {booelan}
  38604. */
  38605. this._mouseDownFlag;
  38606. }
  38607. MapDraw.prototype = {
  38608. constructor: MapDraw,
  38609. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  38610. var isGeo = mapOrGeoModel.mainType === 'geo';
  38611. // Map series has data. GEO model that controlled by map series
  38612. // will be assigned with map data. Other GEO model has no data.
  38613. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  38614. isGeo && ecModel.eachComponent({mainType: 'series', subType: 'map'}, function (mapSeries) {
  38615. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  38616. data = mapSeries.getData();
  38617. }
  38618. });
  38619. var geo = mapOrGeoModel.coordinateSystem;
  38620. var group = this.group;
  38621. var scale = geo.scale;
  38622. var groupNewProp = {
  38623. position: geo.position,
  38624. scale: scale
  38625. };
  38626. // No animation when first draw or in action
  38627. if (!group.childAt(0) || payload) {
  38628. group.attr(groupNewProp);
  38629. }
  38630. else {
  38631. updateProps(group, groupNewProp, mapOrGeoModel);
  38632. }
  38633. group.removeAll();
  38634. var itemStyleAccessPath = ['itemStyle'];
  38635. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  38636. var labelAccessPath = ['label'];
  38637. var hoverLabelAccessPath = ['emphasis', 'label'];
  38638. var nameMap = createHashMap();
  38639. each$1(geo.regions, function (region) {
  38640. // Consider in GeoJson properties.name may be duplicated, for example,
  38641. // there is multiple region named "United Kindom" or "France" (so many
  38642. // colonies). And it is not appropriate to merge them in geo, which
  38643. // will make them share the same label and bring trouble in label
  38644. // location calculation.
  38645. var regionGroup = nameMap.get(region.name)
  38646. || nameMap.set(region.name, new Group());
  38647. var compoundPath = new CompoundPath({
  38648. shape: {
  38649. paths: []
  38650. }
  38651. });
  38652. regionGroup.add(compoundPath);
  38653. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  38654. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  38655. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  38656. var itemStyle = getFixedItemStyle(itemStyleModel, scale);
  38657. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel, scale);
  38658. var labelModel = regionModel.getModel(labelAccessPath);
  38659. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  38660. var dataIdx;
  38661. // Use the itemStyle in data if has data
  38662. if (data) {
  38663. dataIdx = data.indexOfName(region.name);
  38664. // Only visual color of each item will be used. It can be encoded by dataRange
  38665. // But visual color of series is used in symbol drawing
  38666. //
  38667. // Visual color for each series is for the symbol draw
  38668. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  38669. if (visualColor) {
  38670. itemStyle.fill = visualColor;
  38671. }
  38672. }
  38673. each$1(region.geometries, function (geometry) {
  38674. if (geometry.type !== 'polygon') {
  38675. return;
  38676. }
  38677. compoundPath.shape.paths.push(new Polygon({
  38678. shape: {
  38679. points: geometry.exterior
  38680. }
  38681. }));
  38682. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); i++) {
  38683. compoundPath.shape.paths.push(new Polygon({
  38684. shape: {
  38685. points: geometry.interiors[i]
  38686. }
  38687. }));
  38688. }
  38689. });
  38690. compoundPath.setStyle(itemStyle);
  38691. compoundPath.style.strokeNoScale = true;
  38692. compoundPath.culling = true;
  38693. // Label
  38694. var showLabel = labelModel.get('show');
  38695. var hoverShowLabel = hoverLabelModel.get('show');
  38696. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  38697. var itemLayout = data && data.getItemLayout(dataIdx);
  38698. // In the following cases label will be drawn
  38699. // 1. In map series and data value is NaN
  38700. // 2. In geo component
  38701. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  38702. if (
  38703. (isGeo || isDataNaN && (showLabel || hoverShowLabel))
  38704. || (itemLayout && itemLayout.showLabel)
  38705. ) {
  38706. var query = !isGeo ? dataIdx : region.name;
  38707. var labelFetcher;
  38708. // Consider dataIdx not found.
  38709. if (!data || dataIdx >= 0) {
  38710. labelFetcher = mapOrGeoModel;
  38711. }
  38712. var textEl = new Text({
  38713. position: region.center.slice(),
  38714. scale: [1 / scale[0], 1 / scale[1]],
  38715. z2: 10,
  38716. silent: true
  38717. });
  38718. setLabelStyle(
  38719. textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel,
  38720. {
  38721. labelFetcher: labelFetcher,
  38722. labelDataIndex: query,
  38723. defaultText: region.name,
  38724. useInsideStyle: false
  38725. },
  38726. {
  38727. textAlign: 'center',
  38728. textVerticalAlign: 'middle'
  38729. }
  38730. );
  38731. regionGroup.add(textEl);
  38732. }
  38733. // setItemGraphicEl, setHoverStyle after all polygons and labels
  38734. // are added to the rigionGroup
  38735. if (data) {
  38736. data.setItemGraphicEl(dataIdx, regionGroup);
  38737. }
  38738. else {
  38739. var regionModel = mapOrGeoModel.getRegionModel(region.name);
  38740. // Package custom mouse event for geo component
  38741. compoundPath.eventData = {
  38742. componentType: 'geo',
  38743. geoIndex: mapOrGeoModel.componentIndex,
  38744. name: region.name,
  38745. region: (regionModel && regionModel.option) || {}
  38746. };
  38747. }
  38748. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  38749. groupRegions.push(region);
  38750. setHoverStyle(
  38751. regionGroup,
  38752. hoverItemStyle,
  38753. {hoverSilentOnTouch: !!mapOrGeoModel.get('selectedMode')}
  38754. );
  38755. group.add(regionGroup);
  38756. });
  38757. this._updateController(mapOrGeoModel, ecModel, api);
  38758. updateMapSelectHandler(this, mapOrGeoModel, group, api, fromView);
  38759. updateMapSelected(mapOrGeoModel, group);
  38760. },
  38761. remove: function () {
  38762. this.group.removeAll();
  38763. this._controller.dispose();
  38764. this._controllerHost = {};
  38765. },
  38766. _updateController: function (mapOrGeoModel, ecModel, api) {
  38767. var geo = mapOrGeoModel.coordinateSystem;
  38768. var controller = this._controller;
  38769. var controllerHost = this._controllerHost;
  38770. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  38771. controllerHost.zoom = geo.getZoom();
  38772. // roamType is will be set default true if it is null
  38773. controller.enable(mapOrGeoModel.get('roam') || false);
  38774. var mainType = mapOrGeoModel.mainType;
  38775. function makeActionBase() {
  38776. var action = {
  38777. type: 'geoRoam',
  38778. componentType: mainType
  38779. };
  38780. action[mainType + 'Id'] = mapOrGeoModel.id;
  38781. return action;
  38782. }
  38783. controller.off('pan').on('pan', function (dx, dy) {
  38784. this._mouseDownFlag = false;
  38785. updateViewOnPan(controllerHost, dx, dy);
  38786. api.dispatchAction(extend(makeActionBase(), {
  38787. dx: dx,
  38788. dy: dy
  38789. }));
  38790. }, this);
  38791. controller.off('zoom').on('zoom', function (zoom, mouseX, mouseY) {
  38792. this._mouseDownFlag = false;
  38793. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  38794. api.dispatchAction(extend(makeActionBase(), {
  38795. zoom: zoom,
  38796. originX: mouseX,
  38797. originY: mouseY
  38798. }));
  38799. if (this._updateGroup) {
  38800. var group = this.group;
  38801. var scale = group.scale;
  38802. group.traverse(function (el) {
  38803. if (el.type === 'text') {
  38804. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  38805. }
  38806. });
  38807. }
  38808. }, this);
  38809. controller.setPointerChecker(function (e, x, y) {
  38810. return geo.getViewRectAfterRoam().contain(x, y)
  38811. && !onIrrelevantElement(e, api, mapOrGeoModel);
  38812. });
  38813. }
  38814. };
  38815. /*
  38816. * Licensed to the Apache Software Foundation (ASF) under one
  38817. * or more contributor license agreements. See the NOTICE file
  38818. * distributed with this work for additional information
  38819. * regarding copyright ownership. The ASF licenses this file
  38820. * to you under the Apache License, Version 2.0 (the
  38821. * "License"); you may not use this file except in compliance
  38822. * with the License. You may obtain a copy of the License at
  38823. *
  38824. * http://www.apache.org/licenses/LICENSE-2.0
  38825. *
  38826. * Unless required by applicable law or agreed to in writing,
  38827. * software distributed under the License is distributed on an
  38828. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38829. * KIND, either express or implied. See the License for the
  38830. * specific language governing permissions and limitations
  38831. * under the License.
  38832. */
  38833. extendChartView({
  38834. type: 'map',
  38835. render: function (mapModel, ecModel, api, payload) {
  38836. // Not render if it is an toggleSelect action from self
  38837. if (payload && payload.type === 'mapToggleSelect'
  38838. && payload.from === this.uid
  38839. ) {
  38840. return;
  38841. }
  38842. var group = this.group;
  38843. group.removeAll();
  38844. if (mapModel.getHostGeoModel()) {
  38845. return;
  38846. }
  38847. // Not update map if it is an roam action from self
  38848. if (!(payload && payload.type === 'geoRoam'
  38849. && payload.componentType === 'series'
  38850. && payload.seriesId === mapModel.id
  38851. )
  38852. ) {
  38853. if (mapModel.needsDrawMap) {
  38854. var mapDraw = this._mapDraw || new MapDraw(api, true);
  38855. group.add(mapDraw.group);
  38856. mapDraw.draw(mapModel, ecModel, api, this, payload);
  38857. this._mapDraw = mapDraw;
  38858. }
  38859. else {
  38860. // Remove drawed map
  38861. this._mapDraw && this._mapDraw.remove();
  38862. this._mapDraw = null;
  38863. }
  38864. }
  38865. else {
  38866. var mapDraw = this._mapDraw;
  38867. mapDraw && group.add(mapDraw.group);
  38868. }
  38869. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend')
  38870. && this._renderSymbols(mapModel, ecModel, api);
  38871. },
  38872. remove: function () {
  38873. this._mapDraw && this._mapDraw.remove();
  38874. this._mapDraw = null;
  38875. this.group.removeAll();
  38876. },
  38877. dispose: function () {
  38878. this._mapDraw && this._mapDraw.remove();
  38879. this._mapDraw = null;
  38880. },
  38881. _renderSymbols: function (mapModel, ecModel, api) {
  38882. var originalData = mapModel.originalData;
  38883. var group = this.group;
  38884. originalData.each(originalData.mapDimension('value'), function (value, idx) {
  38885. if (isNaN(value)) {
  38886. return;
  38887. }
  38888. var layout = originalData.getItemLayout(idx);
  38889. if (!layout || !layout.point) {
  38890. // Not exists in map
  38891. return;
  38892. }
  38893. var point = layout.point;
  38894. var offset = layout.offset;
  38895. var circle = new Circle({
  38896. style: {
  38897. // Because the special of map draw.
  38898. // Which needs statistic of multiple series and draw on one map.
  38899. // And each series also need a symbol with legend color
  38900. //
  38901. // Layout and visual are put one the different data
  38902. fill: mapModel.getData().getVisual('color')
  38903. },
  38904. shape: {
  38905. cx: point[0] + offset * 9,
  38906. cy: point[1],
  38907. r: 3
  38908. },
  38909. silent: true,
  38910. // Do not overlap the first series, on which labels are displayed.
  38911. z2: !offset ? 10 : 8
  38912. });
  38913. // First data on the same region
  38914. if (!offset) {
  38915. var fullData = mapModel.mainSeries.getData();
  38916. var name = originalData.getName(idx);
  38917. var fullIndex = fullData.indexOfName(name);
  38918. var itemModel = originalData.getItemModel(idx);
  38919. var labelModel = itemModel.getModel('label');
  38920. var hoverLabelModel = itemModel.getModel('emphasis.label');
  38921. var polygonGroups = fullData.getItemGraphicEl(fullIndex);
  38922. var normalText = retrieve2(
  38923. mapModel.getFormattedLabel(idx, 'normal'),
  38924. name
  38925. );
  38926. var emphasisText = retrieve2(
  38927. mapModel.getFormattedLabel(idx, 'emphasis'),
  38928. normalText
  38929. );
  38930. var onEmphasis = function () {
  38931. var hoverStyle = setTextStyle({}, hoverLabelModel, {
  38932. text: hoverLabelModel.get('show') ? emphasisText : null
  38933. }, {isRectText: true, useInsideStyle: false}, true);
  38934. circle.style.extendFrom(hoverStyle);
  38935. // Make label upper than others if overlaps.
  38936. circle.__mapOriginalZ2 = circle.z2;
  38937. circle.z2 += 1;
  38938. };
  38939. var onNormal = function () {
  38940. setTextStyle(circle.style, labelModel, {
  38941. text: labelModel.get('show') ? normalText : null,
  38942. textPosition: labelModel.getShallow('position') || 'bottom'
  38943. }, {isRectText: true, useInsideStyle: false});
  38944. if (circle.__mapOriginalZ2 != null) {
  38945. circle.z2 = circle.__mapOriginalZ2;
  38946. circle.__mapOriginalZ2 = null;
  38947. }
  38948. };
  38949. polygonGroups.on('mouseover', onEmphasis)
  38950. .on('mouseout', onNormal)
  38951. .on('emphasis', onEmphasis)
  38952. .on('normal', onNormal);
  38953. onNormal();
  38954. }
  38955. group.add(circle);
  38956. });
  38957. }
  38958. });
  38959. /*
  38960. * Licensed to the Apache Software Foundation (ASF) under one
  38961. * or more contributor license agreements. See the NOTICE file
  38962. * distributed with this work for additional information
  38963. * regarding copyright ownership. The ASF licenses this file
  38964. * to you under the Apache License, Version 2.0 (the
  38965. * "License"); you may not use this file except in compliance
  38966. * with the License. You may obtain a copy of the License at
  38967. *
  38968. * http://www.apache.org/licenses/LICENSE-2.0
  38969. *
  38970. * Unless required by applicable law or agreed to in writing,
  38971. * software distributed under the License is distributed on an
  38972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38973. * KIND, either express or implied. See the License for the
  38974. * specific language governing permissions and limitations
  38975. * under the License.
  38976. */
  38977. /**
  38978. * @param {module:echarts/coord/View} view
  38979. * @param {Object} payload
  38980. * @param {Object} [zoomLimit]
  38981. */
  38982. function updateCenterAndZoom(
  38983. view, payload, zoomLimit
  38984. ) {
  38985. var previousZoom = view.getZoom();
  38986. var center = view.getCenter();
  38987. var zoom = payload.zoom;
  38988. var point = view.dataToPoint(center);
  38989. if (payload.dx != null && payload.dy != null) {
  38990. point[0] -= payload.dx;
  38991. point[1] -= payload.dy;
  38992. var center = view.pointToData(point);
  38993. view.setCenter(center);
  38994. }
  38995. if (zoom != null) {
  38996. if (zoomLimit) {
  38997. var zoomMin = zoomLimit.min || 0;
  38998. var zoomMax = zoomLimit.max || Infinity;
  38999. zoom = Math.max(
  39000. Math.min(previousZoom * zoom, zoomMax),
  39001. zoomMin
  39002. ) / previousZoom;
  39003. }
  39004. // Zoom on given point(originX, originY)
  39005. view.scale[0] *= zoom;
  39006. view.scale[1] *= zoom;
  39007. var position = view.position;
  39008. var fixX = (payload.originX - position[0]) * (zoom - 1);
  39009. var fixY = (payload.originY - position[1]) * (zoom - 1);
  39010. position[0] -= fixX;
  39011. position[1] -= fixY;
  39012. view.updateTransform();
  39013. // Get the new center
  39014. var center = view.pointToData(point);
  39015. view.setCenter(center);
  39016. view.setZoom(zoom * previousZoom);
  39017. }
  39018. return {
  39019. center: view.getCenter(),
  39020. zoom: view.getZoom()
  39021. };
  39022. }
  39023. /*
  39024. * Licensed to the Apache Software Foundation (ASF) under one
  39025. * or more contributor license agreements. See the NOTICE file
  39026. * distributed with this work for additional information
  39027. * regarding copyright ownership. The ASF licenses this file
  39028. * to you under the Apache License, Version 2.0 (the
  39029. * "License"); you may not use this file except in compliance
  39030. * with the License. You may obtain a copy of the License at
  39031. *
  39032. * http://www.apache.org/licenses/LICENSE-2.0
  39033. *
  39034. * Unless required by applicable law or agreed to in writing,
  39035. * software distributed under the License is distributed on an
  39036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39037. * KIND, either express or implied. See the License for the
  39038. * specific language governing permissions and limitations
  39039. * under the License.
  39040. */
  39041. /**
  39042. * @payload
  39043. * @property {string} [componentType=series]
  39044. * @property {number} [dx]
  39045. * @property {number} [dy]
  39046. * @property {number} [zoom]
  39047. * @property {number} [originX]
  39048. * @property {number} [originY]
  39049. */
  39050. registerAction({
  39051. type: 'geoRoam',
  39052. event: 'geoRoam',
  39053. update: 'updateTransform'
  39054. }, function (payload, ecModel) {
  39055. var componentType = payload.componentType || 'series';
  39056. ecModel.eachComponent(
  39057. { mainType: componentType, query: payload },
  39058. function (componentModel) {
  39059. var geo = componentModel.coordinateSystem;
  39060. if (geo.type !== 'geo') {
  39061. return;
  39062. }
  39063. var res = updateCenterAndZoom(
  39064. geo, payload, componentModel.get('scaleLimit')
  39065. );
  39066. componentModel.setCenter
  39067. && componentModel.setCenter(res.center);
  39068. componentModel.setZoom
  39069. && componentModel.setZoom(res.zoom);
  39070. // All map series with same `map` use the same geo coordinate system
  39071. // So the center and zoom must be in sync. Include the series not selected by legend
  39072. if (componentType === 'series') {
  39073. each$1(componentModel.seriesGroup, function (seriesModel) {
  39074. seriesModel.setCenter(res.center);
  39075. seriesModel.setZoom(res.zoom);
  39076. });
  39077. }
  39078. }
  39079. );
  39080. });
  39081. /*
  39082. * Licensed to the Apache Software Foundation (ASF) under one
  39083. * or more contributor license agreements. See the NOTICE file
  39084. * distributed with this work for additional information
  39085. * regarding copyright ownership. The ASF licenses this file
  39086. * to you under the Apache License, Version 2.0 (the
  39087. * "License"); you may not use this file except in compliance
  39088. * with the License. You may obtain a copy of the License at
  39089. *
  39090. * http://www.apache.org/licenses/LICENSE-2.0
  39091. *
  39092. * Unless required by applicable law or agreed to in writing,
  39093. * software distributed under the License is distributed on an
  39094. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39095. * KIND, either express or implied. See the License for the
  39096. * specific language governing permissions and limitations
  39097. * under the License.
  39098. */
  39099. var mapSymbolLayout = function (ecModel) {
  39100. var processedMapType = {};
  39101. ecModel.eachSeriesByType('map', function (mapSeries) {
  39102. var mapType = mapSeries.getMapType();
  39103. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  39104. return;
  39105. }
  39106. var mapSymbolOffsets = {};
  39107. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  39108. var geo = subMapSeries.coordinateSystem;
  39109. var data = subMapSeries.originalData;
  39110. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  39111. data.each(data.mapDimension('value'), function (value, idx) {
  39112. var name = data.getName(idx);
  39113. var region = geo.getRegion(name);
  39114. // If input series.data is [11, 22, '-'/null/undefined, 44],
  39115. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  39116. // not be drawn. So here must validate if value is NaN.
  39117. if (!region || isNaN(value)) {
  39118. return;
  39119. }
  39120. var offset = mapSymbolOffsets[name] || 0;
  39121. var point = geo.dataToPoint(region.center);
  39122. mapSymbolOffsets[name] = offset + 1;
  39123. data.setItemLayout(idx, {
  39124. point: point,
  39125. offset: offset
  39126. });
  39127. });
  39128. }
  39129. });
  39130. // Show label of those region not has legendSymbol(which is offset 0)
  39131. var data = mapSeries.getData();
  39132. data.each(function (idx) {
  39133. var name = data.getName(idx);
  39134. var layout = data.getItemLayout(idx) || {};
  39135. layout.showLabel = !mapSymbolOffsets[name];
  39136. data.setItemLayout(idx, layout);
  39137. });
  39138. processedMapType[mapType] = true;
  39139. });
  39140. };
  39141. /*
  39142. * Licensed to the Apache Software Foundation (ASF) under one
  39143. * or more contributor license agreements. See the NOTICE file
  39144. * distributed with this work for additional information
  39145. * regarding copyright ownership. The ASF licenses this file
  39146. * to you under the Apache License, Version 2.0 (the
  39147. * "License"); you may not use this file except in compliance
  39148. * with the License. You may obtain a copy of the License at
  39149. *
  39150. * http://www.apache.org/licenses/LICENSE-2.0
  39151. *
  39152. * Unless required by applicable law or agreed to in writing,
  39153. * software distributed under the License is distributed on an
  39154. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39155. * KIND, either express or implied. See the License for the
  39156. * specific language governing permissions and limitations
  39157. * under the License.
  39158. */
  39159. var mapVisual = function (ecModel) {
  39160. ecModel.eachSeriesByType('map', function (seriesModel) {
  39161. var colorList = seriesModel.get('color');
  39162. var itemStyleModel = seriesModel.getModel('itemStyle');
  39163. var areaColor = itemStyleModel.get('areaColor');
  39164. var color = itemStyleModel.get('color')
  39165. || colorList[seriesModel.seriesIndex % colorList.length];
  39166. seriesModel.getData().setVisual({
  39167. 'areaColor': areaColor,
  39168. 'color': color
  39169. });
  39170. });
  39171. };
  39172. /*
  39173. * Licensed to the Apache Software Foundation (ASF) under one
  39174. * or more contributor license agreements. See the NOTICE file
  39175. * distributed with this work for additional information
  39176. * regarding copyright ownership. The ASF licenses this file
  39177. * to you under the Apache License, Version 2.0 (the
  39178. * "License"); you may not use this file except in compliance
  39179. * with the License. You may obtain a copy of the License at
  39180. *
  39181. * http://www.apache.org/licenses/LICENSE-2.0
  39182. *
  39183. * Unless required by applicable law or agreed to in writing,
  39184. * software distributed under the License is distributed on an
  39185. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39186. * KIND, either express or implied. See the License for the
  39187. * specific language governing permissions and limitations
  39188. * under the License.
  39189. */
  39190. // FIXME 公用?
  39191. /**
  39192. * @param {Array.<module:echarts/data/List>} datas
  39193. * @param {string} statisticType 'average' 'sum'
  39194. * @inner
  39195. */
  39196. function dataStatistics(datas, statisticType) {
  39197. var dataNameMap = {};
  39198. each$1(datas, function (data) {
  39199. data.each(data.mapDimension('value'), function (value, idx) {
  39200. // Add prefix to avoid conflict with Object.prototype.
  39201. var mapKey = 'ec-' + data.getName(idx);
  39202. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  39203. if (!isNaN(value)) {
  39204. dataNameMap[mapKey].push(value);
  39205. }
  39206. });
  39207. });
  39208. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  39209. var mapKey = 'ec-' + datas[0].getName(idx);
  39210. var sum = 0;
  39211. var min = Infinity;
  39212. var max = -Infinity;
  39213. var len = dataNameMap[mapKey].length;
  39214. for (var i = 0; i < len; i++) {
  39215. min = Math.min(min, dataNameMap[mapKey][i]);
  39216. max = Math.max(max, dataNameMap[mapKey][i]);
  39217. sum += dataNameMap[mapKey][i];
  39218. }
  39219. var result;
  39220. if (statisticType === 'min') {
  39221. result = min;
  39222. }
  39223. else if (statisticType === 'max') {
  39224. result = max;
  39225. }
  39226. else if (statisticType === 'average') {
  39227. result = sum / len;
  39228. }
  39229. else {
  39230. result = sum;
  39231. }
  39232. return len === 0 ? NaN : result;
  39233. });
  39234. }
  39235. var mapDataStatistic = function (ecModel) {
  39236. var seriesGroups = {};
  39237. ecModel.eachSeriesByType('map', function (seriesModel) {
  39238. var hostGeoModel = seriesModel.getHostGeoModel();
  39239. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  39240. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  39241. });
  39242. each$1(seriesGroups, function (seriesList, key) {
  39243. var data = dataStatistics(
  39244. map(seriesList, function (seriesModel) {
  39245. return seriesModel.getData();
  39246. }),
  39247. seriesList[0].get('mapValueCalculation')
  39248. );
  39249. for (var i = 0; i < seriesList.length; i++) {
  39250. seriesList[i].originalData = seriesList[i].getData();
  39251. }
  39252. // FIXME Put where?
  39253. for (var i = 0; i < seriesList.length; i++) {
  39254. seriesList[i].seriesGroup = seriesList;
  39255. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  39256. seriesList[i].setData(data.cloneShallow());
  39257. seriesList[i].mainSeries = seriesList[0];
  39258. }
  39259. });
  39260. };
  39261. /*
  39262. * Licensed to the Apache Software Foundation (ASF) under one
  39263. * or more contributor license agreements. See the NOTICE file
  39264. * distributed with this work for additional information
  39265. * regarding copyright ownership. The ASF licenses this file
  39266. * to you under the Apache License, Version 2.0 (the
  39267. * "License"); you may not use this file except in compliance
  39268. * with the License. You may obtain a copy of the License at
  39269. *
  39270. * http://www.apache.org/licenses/LICENSE-2.0
  39271. *
  39272. * Unless required by applicable law or agreed to in writing,
  39273. * software distributed under the License is distributed on an
  39274. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39275. * KIND, either express or implied. See the License for the
  39276. * specific language governing permissions and limitations
  39277. * under the License.
  39278. */
  39279. var backwardCompat$2 = function (option) {
  39280. // Save geoCoord
  39281. var mapSeries = [];
  39282. each$1(option.series, function (seriesOpt) {
  39283. if (seriesOpt && seriesOpt.type === 'map') {
  39284. mapSeries.push(seriesOpt);
  39285. seriesOpt.map = seriesOpt.map || seriesOpt.mapType;
  39286. // Put x, y, width, height, x2, y2 in the top level
  39287. defaults(seriesOpt, seriesOpt.mapLocation);
  39288. }
  39289. });
  39290. };
  39291. /*
  39292. * Licensed to the Apache Software Foundation (ASF) under one
  39293. * or more contributor license agreements. See the NOTICE file
  39294. * distributed with this work for additional information
  39295. * regarding copyright ownership. The ASF licenses this file
  39296. * to you under the Apache License, Version 2.0 (the
  39297. * "License"); you may not use this file except in compliance
  39298. * with the License. You may obtain a copy of the License at
  39299. *
  39300. * http://www.apache.org/licenses/LICENSE-2.0
  39301. *
  39302. * Unless required by applicable law or agreed to in writing,
  39303. * software distributed under the License is distributed on an
  39304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39305. * KIND, either express or implied. See the License for the
  39306. * specific language governing permissions and limitations
  39307. * under the License.
  39308. */
  39309. registerLayout(mapSymbolLayout);
  39310. registerVisual(mapVisual);
  39311. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  39312. registerPreprocessor(backwardCompat$2);
  39313. createDataSelectAction('map', [{
  39314. type: 'mapToggleSelect',
  39315. event: 'mapselectchanged',
  39316. method: 'toggleSelected'
  39317. }, {
  39318. type: 'mapSelect',
  39319. event: 'mapselected',
  39320. method: 'select'
  39321. }, {
  39322. type: 'mapUnSelect',
  39323. event: 'mapunselected',
  39324. method: 'unSelect'
  39325. }]);
  39326. /*
  39327. * Licensed to the Apache Software Foundation (ASF) under one
  39328. * or more contributor license agreements. See the NOTICE file
  39329. * distributed with this work for additional information
  39330. * regarding copyright ownership. The ASF licenses this file
  39331. * to you under the Apache License, Version 2.0 (the
  39332. * "License"); you may not use this file except in compliance
  39333. * with the License. You may obtain a copy of the License at
  39334. *
  39335. * http://www.apache.org/licenses/LICENSE-2.0
  39336. *
  39337. * Unless required by applicable law or agreed to in writing,
  39338. * software distributed under the License is distributed on an
  39339. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39340. * KIND, either express or implied. See the License for the
  39341. * specific language governing permissions and limitations
  39342. * under the License.
  39343. */
  39344. /**
  39345. * Link lists and struct (graph or tree)
  39346. */
  39347. var each$7 = each$1;
  39348. var DATAS = '\0__link_datas';
  39349. var MAIN_DATA = '\0__link_mainData';
  39350. // Caution:
  39351. // In most case, either list or its shallow clones (see list.cloneShallow)
  39352. // is active in echarts process. So considering heap memory consumption,
  39353. // we do not clone tree or graph, but share them among list and its shallow clones.
  39354. // But in some rare case, we have to keep old list (like do animation in chart). So
  39355. // please take care that both the old list and the new list share the same tree/graph.
  39356. /**
  39357. * @param {Object} opt
  39358. * @param {module:echarts/data/List} opt.mainData
  39359. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  39360. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  39361. * @param {Object} [opt.datas] {dataType: data},
  39362. * like: {node: nodeList, edge: edgeList}.
  39363. * Should contain mainData.
  39364. * @param {Object} [opt.datasAttr] {dataType: attr},
  39365. * designation: struct[datasAttr[dataType]] = list;
  39366. */
  39367. function linkList(opt) {
  39368. var mainData = opt.mainData;
  39369. var datas = opt.datas;
  39370. if (!datas) {
  39371. datas = {main: mainData};
  39372. opt.datasAttr = {main: 'data'};
  39373. }
  39374. opt.datas = opt.mainData = null;
  39375. linkAll(mainData, datas, opt);
  39376. // Porxy data original methods.
  39377. each$7(datas, function (data) {
  39378. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  39379. data.wrapMethod(methodName, curry(transferInjection, opt));
  39380. });
  39381. });
  39382. // Beyond transfer, additional features should be added to `cloneShallow`.
  39383. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt));
  39384. // Only mainData trigger change, because struct.update may trigger
  39385. // another changable methods, which may bring about dead lock.
  39386. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  39387. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  39388. });
  39389. // Make sure datas contains mainData.
  39390. assert$1(datas[mainData.dataType] === mainData);
  39391. }
  39392. function transferInjection(opt, res) {
  39393. if (isMainData(this)) {
  39394. // Transfer datas to new main data.
  39395. var datas = extend({}, this[DATAS]);
  39396. datas[this.dataType] = res;
  39397. linkAll(res, datas, opt);
  39398. }
  39399. else {
  39400. // Modify the reference in main data to point newData.
  39401. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  39402. }
  39403. return res;
  39404. }
  39405. function changeInjection(opt, res) {
  39406. opt.struct && opt.struct.update(this);
  39407. return res;
  39408. }
  39409. function cloneShallowInjection(opt, res) {
  39410. // cloneShallow, which brings about some fragilities, may be inappropriate
  39411. // to be exposed as an API. So for implementation simplicity we can make
  39412. // the restriction that cloneShallow of not-mainData should not be invoked
  39413. // outside, but only be invoked here.
  39414. each$7(res[DATAS], function (data, dataType) {
  39415. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  39416. });
  39417. return res;
  39418. }
  39419. /**
  39420. * Supplement method to List.
  39421. *
  39422. * @public
  39423. * @param {string} [dataType] If not specified, return mainData.
  39424. * @return {module:echarts/data/List}
  39425. */
  39426. function getLinkedData(dataType) {
  39427. var mainData = this[MAIN_DATA];
  39428. return (dataType == null || mainData == null)
  39429. ? mainData
  39430. : mainData[DATAS][dataType];
  39431. }
  39432. function isMainData(data) {
  39433. return data[MAIN_DATA] === data;
  39434. }
  39435. function linkAll(mainData, datas, opt) {
  39436. mainData[DATAS] = {};
  39437. each$7(datas, function (data, dataType) {
  39438. linkSingle(data, dataType, mainData, opt);
  39439. });
  39440. }
  39441. function linkSingle(data, dataType, mainData, opt) {
  39442. mainData[DATAS][dataType] = data;
  39443. data[MAIN_DATA] = mainData;
  39444. data.dataType = dataType;
  39445. if (opt.struct) {
  39446. data[opt.structAttr] = opt.struct;
  39447. opt.struct[opt.datasAttr[dataType]] = data;
  39448. }
  39449. // Supplement method.
  39450. data.getLinkedData = getLinkedData;
  39451. }
  39452. /*
  39453. * Licensed to the Apache Software Foundation (ASF) under one
  39454. * or more contributor license agreements. See the NOTICE file
  39455. * distributed with this work for additional information
  39456. * regarding copyright ownership. The ASF licenses this file
  39457. * to you under the Apache License, Version 2.0 (the
  39458. * "License"); you may not use this file except in compliance
  39459. * with the License. You may obtain a copy of the License at
  39460. *
  39461. * http://www.apache.org/licenses/LICENSE-2.0
  39462. *
  39463. * Unless required by applicable law or agreed to in writing,
  39464. * software distributed under the License is distributed on an
  39465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39466. * KIND, either express or implied. See the License for the
  39467. * specific language governing permissions and limitations
  39468. * under the License.
  39469. */
  39470. /**
  39471. * Tree data structure
  39472. *
  39473. * @module echarts/data/Tree
  39474. */
  39475. /**
  39476. * @constructor module:echarts/data/Tree~TreeNode
  39477. * @param {string} name
  39478. * @param {module:echarts/data/Tree} hostTree
  39479. */
  39480. var TreeNode = function (name, hostTree) {
  39481. /**
  39482. * @type {string}
  39483. */
  39484. this.name = name || '';
  39485. /**
  39486. * Depth of node
  39487. *
  39488. * @type {number}
  39489. * @readOnly
  39490. */
  39491. this.depth = 0;
  39492. /**
  39493. * Height of the subtree rooted at this node.
  39494. * @type {number}
  39495. * @readOnly
  39496. */
  39497. this.height = 0;
  39498. /**
  39499. * @type {module:echarts/data/Tree~TreeNode}
  39500. * @readOnly
  39501. */
  39502. this.parentNode = null;
  39503. /**
  39504. * Reference to list item.
  39505. * Do not persistent dataIndex outside,
  39506. * besause it may be changed by list.
  39507. * If dataIndex -1,
  39508. * this node is logical deleted (filtered) in list.
  39509. *
  39510. * @type {Object}
  39511. * @readOnly
  39512. */
  39513. this.dataIndex = -1;
  39514. /**
  39515. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39516. * @readOnly
  39517. */
  39518. this.children = [];
  39519. /**
  39520. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39521. * @pubilc
  39522. */
  39523. this.viewChildren = [];
  39524. /**
  39525. * @type {moduel:echarts/data/Tree}
  39526. * @readOnly
  39527. */
  39528. this.hostTree = hostTree;
  39529. };
  39530. TreeNode.prototype = {
  39531. constructor: TreeNode,
  39532. /**
  39533. * The node is removed.
  39534. * @return {boolean} is removed.
  39535. */
  39536. isRemoved: function () {
  39537. return this.dataIndex < 0;
  39538. },
  39539. /**
  39540. * Travel this subtree (include this node).
  39541. * Usage:
  39542. * node.eachNode(function () { ... }); // preorder
  39543. * node.eachNode('preorder', function () { ... }); // preorder
  39544. * node.eachNode('postorder', function () { ... }); // postorder
  39545. * node.eachNode(
  39546. * {order: 'postorder', attr: 'viewChildren'},
  39547. * function () { ... }
  39548. * ); // postorder
  39549. *
  39550. * @param {(Object|string)} options If string, means order.
  39551. * @param {string=} options.order 'preorder' or 'postorder'
  39552. * @param {string=} options.attr 'children' or 'viewChildren'
  39553. * @param {Function} cb If in preorder and return false,
  39554. * its subtree will not be visited.
  39555. * @param {Object} [context]
  39556. */
  39557. eachNode: function (options, cb, context) {
  39558. if (typeof options === 'function') {
  39559. context = cb;
  39560. cb = options;
  39561. options = null;
  39562. }
  39563. options = options || {};
  39564. if (isString(options)) {
  39565. options = {order: options};
  39566. }
  39567. var order = options.order || 'preorder';
  39568. var children = this[options.attr || 'children'];
  39569. var suppressVisitSub;
  39570. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  39571. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  39572. children[i].eachNode(options, cb, context);
  39573. }
  39574. order === 'postorder' && cb.call(context, this);
  39575. },
  39576. /**
  39577. * Update depth and height of this subtree.
  39578. *
  39579. * @param {number} depth
  39580. */
  39581. updateDepthAndHeight: function (depth) {
  39582. var height = 0;
  39583. this.depth = depth;
  39584. for (var i = 0; i < this.children.length; i++) {
  39585. var child = this.children[i];
  39586. child.updateDepthAndHeight(depth + 1);
  39587. if (child.height > height) {
  39588. height = child.height;
  39589. }
  39590. }
  39591. this.height = height + 1;
  39592. },
  39593. /**
  39594. * @param {string} id
  39595. * @return {module:echarts/data/Tree~TreeNode}
  39596. */
  39597. getNodeById: function (id) {
  39598. if (this.getId() === id) {
  39599. return this;
  39600. }
  39601. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39602. var res = children[i].getNodeById(id);
  39603. if (res) {
  39604. return res;
  39605. }
  39606. }
  39607. },
  39608. /**
  39609. * @param {module:echarts/data/Tree~TreeNode} node
  39610. * @return {boolean}
  39611. */
  39612. contains: function (node) {
  39613. if (node === this) {
  39614. return true;
  39615. }
  39616. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39617. var res = children[i].contains(node);
  39618. if (res) {
  39619. return res;
  39620. }
  39621. }
  39622. },
  39623. /**
  39624. * @param {boolean} includeSelf Default false.
  39625. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  39626. */
  39627. getAncestors: function (includeSelf) {
  39628. var ancestors = [];
  39629. var node = includeSelf ? this : this.parentNode;
  39630. while (node) {
  39631. ancestors.push(node);
  39632. node = node.parentNode;
  39633. }
  39634. ancestors.reverse();
  39635. return ancestors;
  39636. },
  39637. /**
  39638. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  39639. * @return {number} Value.
  39640. */
  39641. getValue: function (dimension) {
  39642. var data = this.hostTree.data;
  39643. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  39644. },
  39645. /**
  39646. * @param {Object} layout
  39647. * @param {boolean=} [merge=false]
  39648. */
  39649. setLayout: function (layout, merge$$1) {
  39650. this.dataIndex >= 0
  39651. && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  39652. },
  39653. /**
  39654. * @return {Object} layout
  39655. */
  39656. getLayout: function () {
  39657. return this.hostTree.data.getItemLayout(this.dataIndex);
  39658. },
  39659. /**
  39660. * @param {string} [path]
  39661. * @return {module:echarts/model/Model}
  39662. */
  39663. getModel: function (path) {
  39664. if (this.dataIndex < 0) {
  39665. return;
  39666. }
  39667. var hostTree = this.hostTree;
  39668. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  39669. var levelModel = this.getLevelModel();
  39670. var leavesModel;
  39671. if (!levelModel && (this.children.length === 0 || (this.children.length !== 0 && this.isExpand === false))) {
  39672. leavesModel = this.getLeavesModel();
  39673. }
  39674. return itemModel.getModel(path, (levelModel || leavesModel || hostTree.hostModel).getModel(path));
  39675. },
  39676. /**
  39677. * @return {module:echarts/model/Model}
  39678. */
  39679. getLevelModel: function () {
  39680. return (this.hostTree.levelModels || [])[this.depth];
  39681. },
  39682. /**
  39683. * @return {module:echarts/model/Model}
  39684. */
  39685. getLeavesModel: function () {
  39686. return this.hostTree.leavesModel;
  39687. },
  39688. /**
  39689. * @example
  39690. * setItemVisual('color', color);
  39691. * setItemVisual({
  39692. * 'color': color
  39693. * });
  39694. */
  39695. setVisual: function (key, value) {
  39696. this.dataIndex >= 0
  39697. && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  39698. },
  39699. /**
  39700. * Get item visual
  39701. */
  39702. getVisual: function (key, ignoreParent) {
  39703. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  39704. },
  39705. /**
  39706. * @public
  39707. * @return {number}
  39708. */
  39709. getRawIndex: function () {
  39710. return this.hostTree.data.getRawIndex(this.dataIndex);
  39711. },
  39712. /**
  39713. * @public
  39714. * @return {string}
  39715. */
  39716. getId: function () {
  39717. return this.hostTree.data.getId(this.dataIndex);
  39718. },
  39719. /**
  39720. * if this is an ancestor of another node
  39721. *
  39722. * @public
  39723. * @param {TreeNode} node another node
  39724. * @return {boolean} if is ancestor
  39725. */
  39726. isAncestorOf: function (node) {
  39727. var parent = node.parentNode;
  39728. while (parent) {
  39729. if (parent === this) {
  39730. return true;
  39731. }
  39732. parent = parent.parentNode;
  39733. }
  39734. return false;
  39735. },
  39736. /**
  39737. * if this is an descendant of another node
  39738. *
  39739. * @public
  39740. * @param {TreeNode} node another node
  39741. * @return {boolean} if is descendant
  39742. */
  39743. isDescendantOf: function (node) {
  39744. return node !== this && node.isAncestorOf(this);
  39745. }
  39746. };
  39747. /**
  39748. * @constructor
  39749. * @alias module:echarts/data/Tree
  39750. * @param {module:echarts/model/Model} hostModel
  39751. * @param {Array.<Object>} levelOptions
  39752. * @param {Object} leavesOption
  39753. */
  39754. function Tree(hostModel, levelOptions, leavesOption) {
  39755. /**
  39756. * @type {module:echarts/data/Tree~TreeNode}
  39757. * @readOnly
  39758. */
  39759. this.root;
  39760. /**
  39761. * @type {module:echarts/data/List}
  39762. * @readOnly
  39763. */
  39764. this.data;
  39765. /**
  39766. * Index of each item is the same as the raw index of coresponding list item.
  39767. * @private
  39768. * @type {Array.<module:echarts/data/Tree~TreeNode}
  39769. */
  39770. this._nodes = [];
  39771. /**
  39772. * @private
  39773. * @readOnly
  39774. * @type {module:echarts/model/Model}
  39775. */
  39776. this.hostModel = hostModel;
  39777. /**
  39778. * @private
  39779. * @readOnly
  39780. * @type {Array.<module:echarts/model/Model}
  39781. */
  39782. this.levelModels = map(levelOptions || [], function (levelDefine) {
  39783. return new Model(levelDefine, hostModel, hostModel.ecModel);
  39784. });
  39785. this.leavesModel = new Model(leavesOption || {}, hostModel, hostModel.ecModel);
  39786. }
  39787. Tree.prototype = {
  39788. constructor: Tree,
  39789. type: 'tree',
  39790. /**
  39791. * Travel this subtree (include this node).
  39792. * Usage:
  39793. * node.eachNode(function () { ... }); // preorder
  39794. * node.eachNode('preorder', function () { ... }); // preorder
  39795. * node.eachNode('postorder', function () { ... }); // postorder
  39796. * node.eachNode(
  39797. * {order: 'postorder', attr: 'viewChildren'},
  39798. * function () { ... }
  39799. * ); // postorder
  39800. *
  39801. * @param {(Object|string)} options If string, means order.
  39802. * @param {string=} options.order 'preorder' or 'postorder'
  39803. * @param {string=} options.attr 'children' or 'viewChildren'
  39804. * @param {Function} cb
  39805. * @param {Object} [context]
  39806. */
  39807. eachNode: function(options, cb, context) {
  39808. this.root.eachNode(options, cb, context);
  39809. },
  39810. /**
  39811. * @param {number} dataIndex
  39812. * @return {module:echarts/data/Tree~TreeNode}
  39813. */
  39814. getNodeByDataIndex: function (dataIndex) {
  39815. var rawIndex = this.data.getRawIndex(dataIndex);
  39816. return this._nodes[rawIndex];
  39817. },
  39818. /**
  39819. * @param {string} name
  39820. * @return {module:echarts/data/Tree~TreeNode}
  39821. */
  39822. getNodeByName: function (name) {
  39823. return this.root.getNodeByName(name);
  39824. },
  39825. /**
  39826. * Update item available by list,
  39827. * when list has been performed options like 'filterSelf' or 'map'.
  39828. */
  39829. update: function () {
  39830. var data = this.data;
  39831. var nodes = this._nodes;
  39832. for (var i = 0, len = nodes.length; i < len; i++) {
  39833. nodes[i].dataIndex = -1;
  39834. }
  39835. for (var i = 0, len = data.count(); i < len; i++) {
  39836. nodes[data.getRawIndex(i)].dataIndex = i;
  39837. }
  39838. },
  39839. /**
  39840. * Clear all layouts
  39841. */
  39842. clearLayouts: function () {
  39843. this.data.clearItemLayouts();
  39844. }
  39845. };
  39846. /**
  39847. * data node format:
  39848. * {
  39849. * name: ...
  39850. * value: ...
  39851. * children: [
  39852. * {
  39853. * name: ...
  39854. * value: ...
  39855. * children: ...
  39856. * },
  39857. * ...
  39858. * ]
  39859. * }
  39860. *
  39861. * @static
  39862. * @param {Object} dataRoot Root node.
  39863. * @param {module:echarts/model/Model} hostModel
  39864. * @param {Object} treeOptions
  39865. * @param {Array.<Object>} treeOptions.levels
  39866. * @param {Array.<Object>} treeOptions.leaves
  39867. * @return module:echarts/data/Tree
  39868. */
  39869. Tree.createTree = function (dataRoot, hostModel, treeOptions) {
  39870. var tree = new Tree(hostModel, treeOptions.levels, treeOptions.leaves);
  39871. var listData = [];
  39872. var dimMax = 1;
  39873. buildHierarchy(dataRoot);
  39874. function buildHierarchy(dataNode, parentNode) {
  39875. var value = dataNode.value;
  39876. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  39877. listData.push(dataNode);
  39878. var node = new TreeNode(dataNode.name, tree);
  39879. parentNode
  39880. ? addChild(node, parentNode)
  39881. : (tree.root = node);
  39882. tree._nodes.push(node);
  39883. var children = dataNode.children;
  39884. if (children) {
  39885. for (var i = 0; i < children.length; i++) {
  39886. buildHierarchy(children[i], node);
  39887. }
  39888. }
  39889. }
  39890. tree.root.updateDepthAndHeight(0);
  39891. var dimensionsInfo = createDimensions(listData, {
  39892. coordDimensions: ['value'],
  39893. dimensionsCount: dimMax
  39894. });
  39895. var list = new List(dimensionsInfo, hostModel);
  39896. list.initData(listData);
  39897. linkList({
  39898. mainData: list,
  39899. struct: tree,
  39900. structAttr: 'tree'
  39901. });
  39902. tree.update();
  39903. return tree;
  39904. };
  39905. /**
  39906. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  39907. * so this function is not ready and not necessary to be public.
  39908. *
  39909. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  39910. */
  39911. function addChild(child, node) {
  39912. var children = node.children;
  39913. if (child.parentNode === node) {
  39914. return;
  39915. }
  39916. children.push(child);
  39917. child.parentNode = node;
  39918. }
  39919. /*
  39920. * Licensed to the Apache Software Foundation (ASF) under one
  39921. * or more contributor license agreements. See the NOTICE file
  39922. * distributed with this work for additional information
  39923. * regarding copyright ownership. The ASF licenses this file
  39924. * to you under the Apache License, Version 2.0 (the
  39925. * "License"); you may not use this file except in compliance
  39926. * with the License. You may obtain a copy of the License at
  39927. *
  39928. * http://www.apache.org/licenses/LICENSE-2.0
  39929. *
  39930. * Unless required by applicable law or agreed to in writing,
  39931. * software distributed under the License is distributed on an
  39932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39933. * KIND, either express or implied. See the License for the
  39934. * specific language governing permissions and limitations
  39935. * under the License.
  39936. */
  39937. /**
  39938. * @file Create data struct and define tree view's series model
  39939. */
  39940. SeriesModel.extend({
  39941. type: 'series.tree',
  39942. layoutInfo: null,
  39943. // can support the position parameters 'left', 'top','right','bottom', 'width',
  39944. // 'height' in the setOption() with 'merge' mode normal.
  39945. layoutMode: 'box',
  39946. /**
  39947. * Init a tree data structure from data in option series
  39948. * @param {Object} option the object used to config echarts view
  39949. * @return {module:echarts/data/List} storage initial data
  39950. */
  39951. getInitialData: function (option) {
  39952. //create an virtual root
  39953. var root = {name: option.name, children: option.data};
  39954. var leaves = option.leaves || {};
  39955. var treeOption = {};
  39956. treeOption.leaves = leaves;
  39957. var tree = Tree.createTree(root, this, treeOption);
  39958. var treeDepth = 0;
  39959. tree.eachNode('preorder', function (node) {
  39960. if (node.depth > treeDepth) {
  39961. treeDepth = node.depth;
  39962. }
  39963. });
  39964. var expandAndCollapse = option.expandAndCollapse;
  39965. var expandTreeDepth = (expandAndCollapse && option.initialTreeDepth >= 0)
  39966. ? option.initialTreeDepth : treeDepth;
  39967. tree.root.eachNode('preorder', function (node) {
  39968. var item = node.hostTree.data.getRawDataItem(node.dataIndex);
  39969. // add item.collapsed != null, because users can collapse node original in the series.data.
  39970. node.isExpand = (item && item.collapsed != null)
  39971. ? !item.collapsed
  39972. : node.depth <= expandTreeDepth;
  39973. });
  39974. return tree.data;
  39975. },
  39976. /**
  39977. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  39978. * @returns {string} orient
  39979. */
  39980. getOrient: function () {
  39981. var orient = this.get('orient');
  39982. if (orient === 'horizontal') {
  39983. orient = 'LR';
  39984. }
  39985. else if (orient === 'vertical') {
  39986. orient = 'TB';
  39987. }
  39988. return orient;
  39989. },
  39990. /**
  39991. * @override
  39992. * @param {number} dataIndex
  39993. */
  39994. formatTooltip: function (dataIndex) {
  39995. var tree = this.getData().tree;
  39996. var realRoot = tree.root.children[0];
  39997. var node = tree.getNodeByDataIndex(dataIndex);
  39998. var value = node.getValue();
  39999. var name = node.name;
  40000. while (node && (node !== realRoot)) {
  40001. name = node.parentNode.name + '.' + name;
  40002. node = node.parentNode;
  40003. }
  40004. return encodeHTML(name + (
  40005. (isNaN(value) || value == null) ? '' : ' : ' + value
  40006. ));
  40007. },
  40008. defaultOption: {
  40009. zlevel: 0,
  40010. z: 2,
  40011. // the position of the whole view
  40012. left: '12%',
  40013. top: '12%',
  40014. right: '12%',
  40015. bottom: '12%',
  40016. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  40017. layout: 'orthogonal',
  40018. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  40019. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  40020. orient: 'LR',
  40021. symbol: 'emptyCircle',
  40022. symbolSize: 7,
  40023. expandAndCollapse: true,
  40024. initialTreeDepth: 2,
  40025. lineStyle: {
  40026. color: '#ccc',
  40027. width: 1.5,
  40028. curveness: 0.5
  40029. },
  40030. itemStyle: {
  40031. color: 'lightsteelblue',
  40032. borderColor: '#c23531',
  40033. borderWidth: 1.5
  40034. },
  40035. label: {
  40036. show: true,
  40037. color: '#555'
  40038. },
  40039. leaves: {
  40040. label: {
  40041. show: true
  40042. }
  40043. },
  40044. animationEasing: 'linear',
  40045. animationDuration: 700,
  40046. animationDurationUpdate: 1000
  40047. }
  40048. });
  40049. /*
  40050. * Licensed to the Apache Software Foundation (ASF) under one
  40051. * or more contributor license agreements. See the NOTICE file
  40052. * distributed with this work for additional information
  40053. * regarding copyright ownership. The ASF licenses this file
  40054. * to you under the Apache License, Version 2.0 (the
  40055. * "License"); you may not use this file except in compliance
  40056. * with the License. You may obtain a copy of the License at
  40057. *
  40058. * http://www.apache.org/licenses/LICENSE-2.0
  40059. *
  40060. * Unless required by applicable law or agreed to in writing,
  40061. * software distributed under the License is distributed on an
  40062. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40063. * KIND, either express or implied. See the License for the
  40064. * specific language governing permissions and limitations
  40065. * under the License.
  40066. */
  40067. /*
  40068. * The tree layout implementation references to d3.js
  40069. * (https://github.com/d3/d3-hierarchy). The use of the source
  40070. * code of this file is also subject to the terms and consitions
  40071. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  40072. */
  40073. /**
  40074. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  40075. * the tree.
  40076. * @see https://github.com/d3/d3-hierarchy
  40077. */
  40078. /**
  40079. * Initialize all computational message for following algorithm
  40080. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree
  40081. */
  40082. function init$2(root) {
  40083. root.hierNode = {
  40084. defaultAncestor: null,
  40085. ancestor: root,
  40086. prelim: 0,
  40087. modifier: 0,
  40088. change: 0,
  40089. shift: 0,
  40090. i: 0,
  40091. thread: null
  40092. };
  40093. var nodes = [root];
  40094. var node;
  40095. var children;
  40096. while (node = nodes.pop()) { // jshint ignore:line
  40097. children = node.children;
  40098. if (node.isExpand && children.length) {
  40099. var n = children.length;
  40100. for (var i = n - 1; i >= 0; i--) {
  40101. var child = children[i];
  40102. child.hierNode = {
  40103. defaultAncestor: null,
  40104. ancestor: child,
  40105. prelim: 0,
  40106. modifier: 0,
  40107. change: 0,
  40108. shift: 0,
  40109. i: i,
  40110. thread: null
  40111. };
  40112. nodes.push(child);
  40113. }
  40114. }
  40115. }
  40116. }
  40117. /**
  40118. * Computes a preliminary x coordinate for node. Before that, this function is
  40119. * applied recursively to the children of node, as well as the function
  40120. * apportion(). After spacing out the children by calling executeShifts(), the
  40121. * node is placed to the midpoint of its outermost children.
  40122. * @param {module:echarts/data/Tree~TreeNode} node
  40123. * @param {Function} separation
  40124. */
  40125. function firstWalk(node, separation) {
  40126. var children = node.isExpand ? node.children : [];
  40127. var siblings = node.parentNode.children;
  40128. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i -1] : null;
  40129. if (children.length) {
  40130. executeShifts(node);
  40131. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  40132. if (subtreeW) {
  40133. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40134. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  40135. }
  40136. else {
  40137. node.hierNode.prelim = midPoint;
  40138. }
  40139. }
  40140. else if (subtreeW) {
  40141. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40142. }
  40143. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  40144. }
  40145. /**
  40146. * Computes all real x-coordinates by summing up the modifiers recursively.
  40147. * @param {module:echarts/data/Tree~TreeNode} node
  40148. */
  40149. function secondWalk(node) {
  40150. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  40151. node.setLayout({x: nodeX}, true);
  40152. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  40153. }
  40154. function separation(cb) {
  40155. return arguments.length ? cb : defaultSeparation;
  40156. }
  40157. /**
  40158. * Transform the common coordinate to radial coordinate
  40159. * @param {number} x
  40160. * @param {number} y
  40161. * @return {Object}
  40162. */
  40163. function radialCoordinate(x, y) {
  40164. var radialCoor = {};
  40165. x -= Math.PI / 2;
  40166. radialCoor.x = y * Math.cos(x);
  40167. radialCoor.y = y * Math.sin(x);
  40168. return radialCoor;
  40169. }
  40170. /**
  40171. * Get the layout position of the whole view
  40172. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  40173. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  40174. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  40175. */
  40176. function getViewRect(seriesModel, api) {
  40177. return getLayoutRect(
  40178. seriesModel.getBoxLayoutParams(), {
  40179. width: api.getWidth(),
  40180. height: api.getHeight()
  40181. }
  40182. );
  40183. }
  40184. /**
  40185. * All other shifts, applied to the smaller subtrees between w- and w+, are
  40186. * performed by this function.
  40187. * @param {module:echarts/data/Tree~TreeNode} node
  40188. */
  40189. function executeShifts(node) {
  40190. var children = node.children;
  40191. var n = children.length;
  40192. var shift = 0;
  40193. var change = 0;
  40194. while (--n >= 0) {
  40195. var child = children[n];
  40196. child.hierNode.prelim += shift;
  40197. child.hierNode.modifier += shift;
  40198. change += child.hierNode.change;
  40199. shift += child.hierNode.shift + change;
  40200. }
  40201. }
  40202. /**
  40203. * The core of the algorithm. Here, a new subtree is combined with the
  40204. * previous subtrees. Threads are used to traverse the inside and outside
  40205. * contours of the left and right subtree up to the highest common level.
  40206. * Whenever two nodes of the inside contours conflict, we compute the left
  40207. * one of the greatest uncommon ancestors using the function nextAncestor()
  40208. * and call moveSubtree() to shift the subtree and prepare the shifts of
  40209. * smaller subtrees. Finally, we add a new thread (if necessary).
  40210. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  40211. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  40212. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40213. * @param {Function} separation
  40214. * @return {module:echarts/data/Tree~TreeNode}
  40215. */
  40216. function apportion(subtreeV, subtreeW, ancestor, separation) {
  40217. if (subtreeW) {
  40218. var nodeOutRight = subtreeV;
  40219. var nodeInRight = subtreeV;
  40220. var nodeOutLeft = nodeInRight.parentNode.children[0];
  40221. var nodeInLeft = subtreeW;
  40222. var sumOutRight = nodeOutRight.hierNode.modifier;
  40223. var sumInRight = nodeInRight.hierNode.modifier;
  40224. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  40225. var sumInLeft = nodeInLeft.hierNode.modifier;
  40226. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  40227. nodeOutRight = nextRight(nodeOutRight);
  40228. nodeOutLeft = nextLeft(nodeOutLeft);
  40229. nodeOutRight.hierNode.ancestor = subtreeV;
  40230. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim
  40231. - sumInRight + separation(nodeInLeft, nodeInRight);
  40232. if (shift > 0) {
  40233. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  40234. sumInRight += shift;
  40235. sumOutRight += shift;
  40236. }
  40237. sumInLeft += nodeInLeft.hierNode.modifier;
  40238. sumInRight += nodeInRight.hierNode.modifier;
  40239. sumOutRight += nodeOutRight.hierNode.modifier;
  40240. sumOutLeft += nodeOutLeft.hierNode.modifier;
  40241. }
  40242. if (nodeInLeft && !nextRight(nodeOutRight)) {
  40243. nodeOutRight.hierNode.thread = nodeInLeft;
  40244. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  40245. }
  40246. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  40247. nodeOutLeft.hierNode.thread = nodeInRight;
  40248. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  40249. ancestor = subtreeV;
  40250. }
  40251. }
  40252. return ancestor;
  40253. }
  40254. /**
  40255. * This function is used to traverse the right contour of a subtree.
  40256. * It returns the rightmost child of node or the thread of node. The function
  40257. * returns null if and only if node is on the highest depth of its subtree.
  40258. * @param {module:echarts/data/Tree~TreeNode} node
  40259. * @return {module:echarts/data/Tree~TreeNode}
  40260. */
  40261. function nextRight(node) {
  40262. var children = node.children;
  40263. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  40264. }
  40265. /**
  40266. * This function is used to traverse the left contour of a subtree (or a subforest).
  40267. * It returns the leftmost child of node or the thread of node. The function
  40268. * returns null if and only if node is on the highest depth of its subtree.
  40269. * @param {module:echarts/data/Tree~TreeNode} node
  40270. * @return {module:echarts/data/Tree~TreeNode}
  40271. */
  40272. function nextLeft(node) {
  40273. var children = node.children;
  40274. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  40275. }
  40276. /**
  40277. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  40278. * Otherwise, returns the specified ancestor.
  40279. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  40280. * @param {module:echarts/data/Tree~TreeNode} node
  40281. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40282. * @return {module:echarts/data/Tree~TreeNode}
  40283. */
  40284. function nextAncestor(nodeInLeft, node, ancestor) {
  40285. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode
  40286. ? nodeInLeft.hierNode.ancestor : ancestor;
  40287. }
  40288. /**
  40289. * Shifts the current subtree rooted at wr. This is done by increasing prelim(w+) and modifier(w+) by shift.
  40290. * @param {module:echarts/data/Tree~TreeNode} wl
  40291. * @param {module:echarts/data/Tree~TreeNode} wr
  40292. * @param {number} shift [description]
  40293. */
  40294. function moveSubtree(wl, wr,shift) {
  40295. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  40296. wr.hierNode.change -= change;
  40297. wr.hierNode.shift += shift;
  40298. wr.hierNode.modifier += shift;
  40299. wr.hierNode.prelim += shift;
  40300. wl.hierNode.change += change;
  40301. }
  40302. function defaultSeparation(node1, node2) {
  40303. return node1.parentNode === node2.parentNode ? 1 : 2;
  40304. }
  40305. /*
  40306. * Licensed to the Apache Software Foundation (ASF) under one
  40307. * or more contributor license agreements. See the NOTICE file
  40308. * distributed with this work for additional information
  40309. * regarding copyright ownership. The ASF licenses this file
  40310. * to you under the Apache License, Version 2.0 (the
  40311. * "License"); you may not use this file except in compliance
  40312. * with the License. You may obtain a copy of the License at
  40313. *
  40314. * http://www.apache.org/licenses/LICENSE-2.0
  40315. *
  40316. * Unless required by applicable law or agreed to in writing,
  40317. * software distributed under the License is distributed on an
  40318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40319. * KIND, either express or implied. See the License for the
  40320. * specific language governing permissions and limitations
  40321. * under the License.
  40322. */
  40323. /**
  40324. * @file This file used to draw tree view
  40325. */
  40326. extendChartView({
  40327. type: 'tree',
  40328. /**
  40329. * Init the chart
  40330. * @override
  40331. * @param {module:echarts/model/Global} ecModel
  40332. * @param {module:echarts/ExtensionAPI} api
  40333. */
  40334. init: function (ecModel, api) {
  40335. /**
  40336. * @private
  40337. * @type {module:echarts/data/Tree}
  40338. */
  40339. this._oldTree;
  40340. /**
  40341. * @private
  40342. * @type {module:zrender/container/Group}
  40343. */
  40344. this._mainGroup = new Group();
  40345. this.group.add(this._mainGroup);
  40346. },
  40347. render: function (seriesModel, ecModel, api, payload) {
  40348. var data = seriesModel.getData();
  40349. var layoutInfo = seriesModel.layoutInfo;
  40350. var group = this._mainGroup;
  40351. var layout = seriesModel.get('layout');
  40352. if (layout === 'radial') {
  40353. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  40354. }
  40355. else {
  40356. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  40357. }
  40358. var oldData = this._data;
  40359. var seriesScope = {
  40360. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  40361. layout: layout,
  40362. orient: seriesModel.getOrient(),
  40363. curvature: seriesModel.get('lineStyle.curveness'),
  40364. symbolRotate: seriesModel.get('symbolRotate'),
  40365. symbolOffset: seriesModel.get('symbolOffset'),
  40366. hoverAnimation: seriesModel.get('hoverAnimation'),
  40367. useNameLabel: true,
  40368. fadeIn: true
  40369. };
  40370. data.diff(oldData)
  40371. .add(function (newIdx) {
  40372. if (symbolNeedsDraw$1(data, newIdx)) {
  40373. // create node and edge
  40374. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  40375. }
  40376. })
  40377. .update(function (newIdx, oldIdx) {
  40378. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  40379. if (!symbolNeedsDraw$1(data, newIdx)) {
  40380. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  40381. return;
  40382. }
  40383. // update node and edge
  40384. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  40385. })
  40386. .remove(function (oldIdx) {
  40387. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  40388. // When remove a collapsed node of subtree, since the collapsed
  40389. // node haven't been initialized with a symbol element,
  40390. // you can't found it's symbol element through index.
  40391. // so if we want to remove the symbol element we should insure
  40392. // that the symbol element is not null.
  40393. if (symbolEl) {
  40394. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  40395. }
  40396. })
  40397. .execute();
  40398. if (seriesScope.expandAndCollapse === true) {
  40399. data.eachItemGraphicEl(function (el, dataIndex) {
  40400. el.off('click').on('click', function () {
  40401. api.dispatchAction({
  40402. type: 'treeExpandAndCollapse',
  40403. seriesId: seriesModel.id,
  40404. dataIndex: dataIndex
  40405. });
  40406. });
  40407. });
  40408. }
  40409. this._data = data;
  40410. },
  40411. dispose: function () {},
  40412. remove: function () {
  40413. this._mainGroup.removeAll();
  40414. this._data = null;
  40415. }
  40416. });
  40417. function symbolNeedsDraw$1(data, dataIndex) {
  40418. var layout = data.getItemLayout(dataIndex);
  40419. return layout
  40420. && !isNaN(layout.x) && !isNaN(layout.y)
  40421. && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  40422. }
  40423. function getTreeNodeStyle(node, itemModel, seriesScope) {
  40424. seriesScope.itemModel = itemModel;
  40425. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  40426. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  40427. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  40428. seriesScope.labelModel = itemModel.getModel('label');
  40429. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  40430. if (node.isExpand === false && node.children.length !== 0) {
  40431. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  40432. }
  40433. else {
  40434. seriesScope.symbolInnerColor = '#fff';
  40435. }
  40436. return seriesScope;
  40437. }
  40438. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  40439. var isInit = !symbolEl;
  40440. var node = data.tree.getNodeByDataIndex(dataIndex);
  40441. var itemModel = node.getModel();
  40442. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  40443. var virtualRoot = data.tree.root;
  40444. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  40445. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  40446. var sourceLayout = source.getLayout();
  40447. var sourceOldLayout = sourceSymbolEl
  40448. ? {
  40449. x: sourceSymbolEl.position[0],
  40450. y: sourceSymbolEl.position[1],
  40451. rawX: sourceSymbolEl.__radialOldRawX,
  40452. rawY: sourceSymbolEl.__radialOldRawY
  40453. }
  40454. : sourceLayout;
  40455. var targetLayout = node.getLayout();
  40456. if (isInit) {
  40457. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  40458. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  40459. }
  40460. else {
  40461. symbolEl.updateData(data, dataIndex, seriesScope);
  40462. }
  40463. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  40464. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  40465. symbolEl.__radialRawX = targetLayout.rawX;
  40466. symbolEl.__radialRawY = targetLayout.rawY;
  40467. group.add(symbolEl);
  40468. data.setItemGraphicEl(dataIndex, symbolEl);
  40469. updateProps(symbolEl, {
  40470. position: [targetLayout.x, targetLayout.y]
  40471. }, seriesModel);
  40472. var symbolPath = symbolEl.getSymbolPath();
  40473. if (seriesScope.layout === 'radial') {
  40474. var realRoot = virtualRoot.children[0];
  40475. var rootLayout = realRoot.getLayout();
  40476. var length = realRoot.children.length;
  40477. var rad;
  40478. var isLeft;
  40479. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  40480. var center = {};
  40481. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  40482. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  40483. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  40484. if (rad < 0) {
  40485. rad = Math.PI * 2 + rad;
  40486. }
  40487. isLeft = center.x < rootLayout.x;
  40488. if (isLeft) {
  40489. rad = rad - Math.PI;
  40490. }
  40491. }
  40492. else {
  40493. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  40494. if (rad < 0) {
  40495. rad = Math.PI * 2 + rad;
  40496. }
  40497. if (node.children.length === 0 || (node.children.length !== 0 && node.isExpand === false)) {
  40498. isLeft = targetLayout.x < rootLayout.x;
  40499. if (isLeft) {
  40500. rad = rad - Math.PI;
  40501. }
  40502. }
  40503. else {
  40504. isLeft = targetLayout.x > rootLayout.x;
  40505. if (!isLeft) {
  40506. rad = rad - Math.PI;
  40507. }
  40508. }
  40509. }
  40510. var textPosition = isLeft ? 'left' : 'right';
  40511. symbolPath.setStyle({
  40512. textPosition: textPosition,
  40513. textRotation: -rad,
  40514. textOrigin: 'center',
  40515. verticalAlign: 'middle'
  40516. });
  40517. }
  40518. if (node.parentNode && node.parentNode !== virtualRoot) {
  40519. var edge = symbolEl.__edge;
  40520. if (!edge) {
  40521. edge = symbolEl.__edge = new BezierCurve({
  40522. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  40523. style: defaults({opacity: 0}, seriesScope.lineStyle)
  40524. });
  40525. }
  40526. updateProps(edge, {
  40527. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  40528. style: {opacity: 1}
  40529. }, seriesModel);
  40530. group.add(edge);
  40531. }
  40532. }
  40533. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  40534. var node = data.tree.getNodeByDataIndex(dataIndex);
  40535. var virtualRoot = data.tree.root;
  40536. var itemModel = node.getModel();
  40537. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  40538. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  40539. var sourceLayout;
  40540. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  40541. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  40542. }
  40543. updateProps(symbolEl, {
  40544. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  40545. }, seriesModel, function () {
  40546. group.remove(symbolEl);
  40547. data.setItemGraphicEl(dataIndex, null);
  40548. });
  40549. symbolEl.fadeOut(null, {keepLabel: true});
  40550. var edge = symbolEl.__edge;
  40551. if (edge) {
  40552. updateProps(edge, {
  40553. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  40554. style: {
  40555. opacity: 0
  40556. }
  40557. }, seriesModel, function () {
  40558. group.remove(edge);
  40559. });
  40560. }
  40561. }
  40562. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  40563. var cpx1;
  40564. var cpy1;
  40565. var cpx2;
  40566. var cpy2;
  40567. var orient = seriesScope.orient;
  40568. if (seriesScope.layout === 'radial') {
  40569. var x1 = sourceLayout.rawX;
  40570. var y1 = sourceLayout.rawY;
  40571. var x2 = targetLayout.rawX;
  40572. var y2 = targetLayout.rawY;
  40573. var radialCoor1 = radialCoordinate(x1, y1);
  40574. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  40575. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  40576. var radialCoor4 = radialCoordinate(x2, y2);
  40577. return {
  40578. x1: radialCoor1.x,
  40579. y1: radialCoor1.y,
  40580. x2: radialCoor4.x,
  40581. y2: radialCoor4.y,
  40582. cpx1: radialCoor2.x,
  40583. cpy1: radialCoor2.y,
  40584. cpx2: radialCoor3.x,
  40585. cpy2: radialCoor3.y
  40586. };
  40587. }
  40588. else {
  40589. var x1 = sourceLayout.x;
  40590. var y1 = sourceLayout.y;
  40591. var x2 = targetLayout.x;
  40592. var y2 = targetLayout.y;
  40593. if (orient === 'LR' || orient === 'RL') {
  40594. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  40595. cpy1 = y1;
  40596. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  40597. cpy2 = y2;
  40598. }
  40599. if (orient === 'TB' || orient === 'BT') {
  40600. cpx1 = x1;
  40601. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  40602. cpx2 = x2;
  40603. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  40604. }
  40605. return {
  40606. x1: x1,
  40607. y1: y1,
  40608. x2: x2,
  40609. y2: y2,
  40610. cpx1: cpx1,
  40611. cpy1: cpy1,
  40612. cpx2: cpx2,
  40613. cpy2: cpy2
  40614. };
  40615. }
  40616. }
  40617. /*
  40618. * Licensed to the Apache Software Foundation (ASF) under one
  40619. * or more contributor license agreements. See the NOTICE file
  40620. * distributed with this work for additional information
  40621. * regarding copyright ownership. The ASF licenses this file
  40622. * to you under the Apache License, Version 2.0 (the
  40623. * "License"); you may not use this file except in compliance
  40624. * with the License. You may obtain a copy of the License at
  40625. *
  40626. * http://www.apache.org/licenses/LICENSE-2.0
  40627. *
  40628. * Unless required by applicable law or agreed to in writing,
  40629. * software distributed under the License is distributed on an
  40630. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40631. * KIND, either express or implied. See the License for the
  40632. * specific language governing permissions and limitations
  40633. * under the License.
  40634. */
  40635. registerAction({
  40636. type: 'treeExpandAndCollapse',
  40637. event: 'treeExpandAndCollapse',
  40638. update: 'update'
  40639. }, function (payload, ecModel) {
  40640. ecModel.eachComponent({mainType: 'series', subType: 'tree', query: payload}, function (seriesModel) {
  40641. var dataIndex = payload.dataIndex;
  40642. var tree = seriesModel.getData().tree;
  40643. var node = tree.getNodeByDataIndex(dataIndex);
  40644. node.isExpand = !node.isExpand;
  40645. });
  40646. });
  40647. /*
  40648. * Licensed to the Apache Software Foundation (ASF) under one
  40649. * or more contributor license agreements. See the NOTICE file
  40650. * distributed with this work for additional information
  40651. * regarding copyright ownership. The ASF licenses this file
  40652. * to you under the Apache License, Version 2.0 (the
  40653. * "License"); you may not use this file except in compliance
  40654. * with the License. You may obtain a copy of the License at
  40655. *
  40656. * http://www.apache.org/licenses/LICENSE-2.0
  40657. *
  40658. * Unless required by applicable law or agreed to in writing,
  40659. * software distributed under the License is distributed on an
  40660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40661. * KIND, either express or implied. See the License for the
  40662. * specific language governing permissions and limitations
  40663. * under the License.
  40664. */
  40665. /**
  40666. * Traverse the tree from bottom to top and do something
  40667. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  40668. * @param {Function} callback
  40669. */
  40670. function eachAfter (root, callback, separation) {
  40671. var nodes = [root];
  40672. var next = [];
  40673. var node;
  40674. while (node = nodes.pop()) { // jshint ignore:line
  40675. next.push(node);
  40676. if (node.isExpand) {
  40677. var children = node.children;
  40678. if (children.length) {
  40679. for (var i = 0; i < children.length; i++) {
  40680. nodes.push(children[i]);
  40681. }
  40682. }
  40683. }
  40684. }
  40685. while (node = next.pop()) { // jshint ignore:line
  40686. callback(node, separation);
  40687. }
  40688. }
  40689. /**
  40690. * Traverse the tree from top to bottom and do something
  40691. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  40692. * @param {Function} callback
  40693. */
  40694. function eachBefore (root, callback) {
  40695. var nodes = [root];
  40696. var node;
  40697. while (node = nodes.pop()) { // jshint ignore:line
  40698. callback(node);
  40699. if (node.isExpand) {
  40700. var children = node.children;
  40701. if (children.length) {
  40702. for (var i = children.length - 1; i >= 0; i--) {
  40703. nodes.push(children[i]);
  40704. }
  40705. }
  40706. }
  40707. }
  40708. }
  40709. /*
  40710. * Licensed to the Apache Software Foundation (ASF) under one
  40711. * or more contributor license agreements. See the NOTICE file
  40712. * distributed with this work for additional information
  40713. * regarding copyright ownership. The ASF licenses this file
  40714. * to you under the Apache License, Version 2.0 (the
  40715. * "License"); you may not use this file except in compliance
  40716. * with the License. You may obtain a copy of the License at
  40717. *
  40718. * http://www.apache.org/licenses/LICENSE-2.0
  40719. *
  40720. * Unless required by applicable law or agreed to in writing,
  40721. * software distributed under the License is distributed on an
  40722. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40723. * KIND, either express or implied. See the License for the
  40724. * specific language governing permissions and limitations
  40725. * under the License.
  40726. */
  40727. var treeLayout = function (ecModel, api) {
  40728. ecModel.eachSeriesByType('tree', function (seriesModel) {
  40729. commonLayout(seriesModel, api);
  40730. });
  40731. };
  40732. function commonLayout(seriesModel, api) {
  40733. var layoutInfo = getViewRect(seriesModel, api);
  40734. seriesModel.layoutInfo = layoutInfo;
  40735. var layout = seriesModel.get('layout');
  40736. var width = 0;
  40737. var height = 0;
  40738. var separation$$1 = null;
  40739. if (layout === 'radial') {
  40740. width = 2 * Math.PI;
  40741. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  40742. separation$$1 = separation(function (node1, node2) {
  40743. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  40744. });
  40745. }
  40746. else {
  40747. width = layoutInfo.width;
  40748. height = layoutInfo.height;
  40749. separation$$1 = separation();
  40750. }
  40751. var virtualRoot = seriesModel.getData().tree.root;
  40752. var realRoot = virtualRoot.children[0];
  40753. if (realRoot) {
  40754. init$2(virtualRoot);
  40755. eachAfter(realRoot, firstWalk, separation$$1);
  40756. virtualRoot.hierNode.modifier = - realRoot.hierNode.prelim;
  40757. eachBefore(realRoot, secondWalk);
  40758. var left = realRoot;
  40759. var right = realRoot;
  40760. var bottom = realRoot;
  40761. eachBefore(realRoot, function (node) {
  40762. var x = node.getLayout().x;
  40763. if (x < left.getLayout().x) {
  40764. left = node;
  40765. }
  40766. if (x > right.getLayout().x) {
  40767. right = node;
  40768. }
  40769. if (node.depth > bottom.depth) {
  40770. bottom = node;
  40771. }
  40772. });
  40773. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  40774. var tx = delta - left.getLayout().x;
  40775. var kx = 0;
  40776. var ky = 0;
  40777. var coorX = 0;
  40778. var coorY = 0;
  40779. if (layout === 'radial') {
  40780. kx = width / (right.getLayout().x + delta + tx);
  40781. // here we use (node.depth - 1), bucause the real root's depth is 1
  40782. ky = height / ((bottom.depth - 1) || 1);
  40783. eachBefore(realRoot, function (node) {
  40784. coorX = (node.getLayout().x + tx) * kx;
  40785. coorY = (node.depth - 1) * ky;
  40786. var finalCoor = radialCoordinate(coorX, coorY);
  40787. node.setLayout({x: finalCoor.x, y: finalCoor.y, rawX: coorX, rawY: coorY}, true);
  40788. });
  40789. }
  40790. else {
  40791. var orient = seriesModel.getOrient();
  40792. if (orient === 'RL' || orient === 'LR') {
  40793. ky = height / (right.getLayout().x + delta + tx);
  40794. kx = width / ((bottom.depth - 1) || 1);
  40795. eachBefore(realRoot, function (node) {
  40796. coorY = (node.getLayout().x + tx) * ky;
  40797. coorX = orient === 'LR'
  40798. ? (node.depth - 1) * kx
  40799. : width - (node.depth - 1) * kx;
  40800. node.setLayout({x: coorX, y: coorY}, true);
  40801. });
  40802. }
  40803. else if (orient === 'TB' || orient === 'BT') {
  40804. kx = width / (right.getLayout().x + delta + tx);
  40805. ky = height / ((bottom.depth - 1) || 1);
  40806. eachBefore(realRoot, function (node) {
  40807. coorX = (node.getLayout().x + tx) * kx;
  40808. coorY = orient === 'TB'
  40809. ? (node.depth - 1) * ky
  40810. : height - (node.depth - 1) * ky;
  40811. node.setLayout({x: coorX, y: coorY}, true);
  40812. });
  40813. }
  40814. }
  40815. }
  40816. }
  40817. /*
  40818. * Licensed to the Apache Software Foundation (ASF) under one
  40819. * or more contributor license agreements. See the NOTICE file
  40820. * distributed with this work for additional information
  40821. * regarding copyright ownership. The ASF licenses this file
  40822. * to you under the Apache License, Version 2.0 (the
  40823. * "License"); you may not use this file except in compliance
  40824. * with the License. You may obtain a copy of the License at
  40825. *
  40826. * http://www.apache.org/licenses/LICENSE-2.0
  40827. *
  40828. * Unless required by applicable law or agreed to in writing,
  40829. * software distributed under the License is distributed on an
  40830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40831. * KIND, either express or implied. See the License for the
  40832. * specific language governing permissions and limitations
  40833. * under the License.
  40834. */
  40835. registerVisual(visualSymbol('tree', 'circle'));
  40836. registerLayout(treeLayout);
  40837. /*
  40838. * Licensed to the Apache Software Foundation (ASF) under one
  40839. * or more contributor license agreements. See the NOTICE file
  40840. * distributed with this work for additional information
  40841. * regarding copyright ownership. The ASF licenses this file
  40842. * to you under the Apache License, Version 2.0 (the
  40843. * "License"); you may not use this file except in compliance
  40844. * with the License. You may obtain a copy of the License at
  40845. *
  40846. * http://www.apache.org/licenses/LICENSE-2.0
  40847. *
  40848. * Unless required by applicable law or agreed to in writing,
  40849. * software distributed under the License is distributed on an
  40850. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40851. * KIND, either express or implied. See the License for the
  40852. * specific language governing permissions and limitations
  40853. * under the License.
  40854. */
  40855. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  40856. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  40857. var root = seriesModel.getData().tree.root;
  40858. var targetNode = payload.targetNode;
  40859. if (targetNode && root.contains(targetNode)) {
  40860. return {node: targetNode};
  40861. }
  40862. var targetNodeId = payload.targetNodeId;
  40863. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  40864. return {node: targetNode};
  40865. }
  40866. }
  40867. }
  40868. // Not includes the given node at the last item.
  40869. function getPathToRoot(node) {
  40870. var path = [];
  40871. while (node) {
  40872. node = node.parentNode;
  40873. node && path.push(node);
  40874. }
  40875. return path.reverse();
  40876. }
  40877. function aboveViewRoot(viewRoot, node) {
  40878. var viewPath = getPathToRoot(viewRoot);
  40879. return indexOf(viewPath, node) >= 0;
  40880. }
  40881. // From root to the input node (the input node will be included).
  40882. function wrapTreePathInfo(node, seriesModel) {
  40883. var treePathInfo = [];
  40884. while (node) {
  40885. var nodeDataIndex = node.dataIndex;
  40886. treePathInfo.push({
  40887. name: node.name,
  40888. dataIndex: nodeDataIndex,
  40889. value: seriesModel.getRawValue(nodeDataIndex)
  40890. });
  40891. node = node.parentNode;
  40892. }
  40893. treePathInfo.reverse();
  40894. return treePathInfo;
  40895. }
  40896. /*
  40897. * Licensed to the Apache Software Foundation (ASF) under one
  40898. * or more contributor license agreements. See the NOTICE file
  40899. * distributed with this work for additional information
  40900. * regarding copyright ownership. The ASF licenses this file
  40901. * to you under the Apache License, Version 2.0 (the
  40902. * "License"); you may not use this file except in compliance
  40903. * with the License. You may obtain a copy of the License at
  40904. *
  40905. * http://www.apache.org/licenses/LICENSE-2.0
  40906. *
  40907. * Unless required by applicable law or agreed to in writing,
  40908. * software distributed under the License is distributed on an
  40909. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40910. * KIND, either express or implied. See the License for the
  40911. * specific language governing permissions and limitations
  40912. * under the License.
  40913. */
  40914. SeriesModel.extend({
  40915. type: 'series.treemap',
  40916. layoutMode: 'box',
  40917. dependencies: ['grid', 'polar'],
  40918. /**
  40919. * @type {module:echarts/data/Tree~Node}
  40920. */
  40921. _viewRoot: null,
  40922. defaultOption: {
  40923. // Disable progressive rendering
  40924. progressive: 0,
  40925. hoverLayerThreshold: Infinity,
  40926. // center: ['50%', '50%'], // not supported in ec3.
  40927. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  40928. left: 'center',
  40929. top: 'middle',
  40930. right: null,
  40931. bottom: null,
  40932. width: '80%',
  40933. height: '80%',
  40934. sort: true, // Can be null or false or true
  40935. // (order by desc default, asc not supported yet (strange effect))
  40936. clipWindow: 'origin', // Size of clipped window when zooming. 'origin' or 'fullscreen'
  40937. squareRatio: 0.5 * (1 + Math.sqrt(5)), // golden ratio
  40938. leafDepth: null, // Nodes on depth from root are regarded as leaves.
  40939. // Count from zero (zero represents only view root).
  40940. drillDownIcon: '▶', // Use html character temporarily because it is complicated
  40941. // to align specialized icon. ▷▶❒❐▼✚
  40942. zoomToNodeRatio: 0.32 * 0.32, // Be effective when using zoomToNode. Specify the proportion of the
  40943. // target node area in the view area.
  40944. roam: true, // true, false, 'scale' or 'zoom', 'move'.
  40945. nodeClick: 'zoomToNode', // Leaf node click behaviour: 'zoomToNode', 'link', false.
  40946. // If leafDepth is set and clicking a node which has children but
  40947. // be on left depth, the behaviour would be changing root. Otherwise
  40948. // use behavious defined above.
  40949. animation: true,
  40950. animationDurationUpdate: 900,
  40951. animationEasing: 'quinticInOut',
  40952. breadcrumb: {
  40953. show: true,
  40954. height: 22,
  40955. left: 'center',
  40956. top: 'bottom',
  40957. // right
  40958. // bottom
  40959. emptyItemWidth: 25, // Width of empty node.
  40960. itemStyle: {
  40961. color: 'rgba(0,0,0,0.7)', //'#5793f3',
  40962. borderColor: 'rgba(255,255,255,0.7)',
  40963. borderWidth: 1,
  40964. shadowColor: 'rgba(150,150,150,1)',
  40965. shadowBlur: 3,
  40966. shadowOffsetX: 0,
  40967. shadowOffsetY: 0,
  40968. textStyle: {
  40969. color: '#fff'
  40970. }
  40971. },
  40972. emphasis: {
  40973. textStyle: {}
  40974. }
  40975. },
  40976. label: {
  40977. show: true,
  40978. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  40979. distance: 0,
  40980. padding: 5,
  40981. position: 'inside', // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  40982. // formatter: null,
  40983. color: '#fff',
  40984. ellipsis: true
  40985. // align
  40986. // verticalAlign
  40987. },
  40988. upperLabel: { // Label when node is parent.
  40989. show: false,
  40990. position: [0, '50%'],
  40991. height: 20,
  40992. // formatter: null,
  40993. color: '#fff',
  40994. ellipsis: true,
  40995. // align: null,
  40996. verticalAlign: 'middle'
  40997. },
  40998. itemStyle: {
  40999. color: null, // Can be 'none' if not necessary.
  41000. colorAlpha: null, // Can be 'none' if not necessary.
  41001. colorSaturation: null, // Can be 'none' if not necessary.
  41002. borderWidth: 0,
  41003. gapWidth: 0,
  41004. borderColor: '#fff',
  41005. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  41006. // border color is evaluated by color of current node and
  41007. // borderColorSaturation.
  41008. },
  41009. emphasis: {
  41010. upperLabel: {
  41011. show: true,
  41012. position: [0, '50%'],
  41013. color: '#fff',
  41014. ellipsis: true,
  41015. verticalAlign: 'middle'
  41016. }
  41017. },
  41018. visualDimension: 0, // Can be 0, 1, 2, 3.
  41019. visualMin: null,
  41020. visualMax: null,
  41021. color: [], // + treemapSeries.color should not be modified. Please only modified
  41022. // level[n].color (if necessary).
  41023. // + Specify color list of each level. level[0].color would be global
  41024. // color list if not specified. (see method `setDefault`).
  41025. // + But set as a empty array to forbid fetch color from global palette
  41026. // when using nodeModel.get('color'), otherwise nodes on deep level
  41027. // will always has color palette set and are not able to inherit color
  41028. // from parent node.
  41029. // + TreemapSeries.color can not be set as 'none', otherwise effect
  41030. // legend color fetching (see seriesColor.js).
  41031. colorAlpha: null, // Array. Specify color alpha range of each level, like [0.2, 0.8]
  41032. colorSaturation: null, // Array. Specify color saturation of each level, like [0.2, 0.5]
  41033. colorMappingBy: 'index', // 'value' or 'index' or 'id'.
  41034. visibleMin: 10, // If area less than this threshold (unit: pixel^2), node will not
  41035. // be rendered. Only works when sort is 'asc' or 'desc'.
  41036. childrenVisibleMin: null, // If area of a node less than this threshold (unit: pixel^2),
  41037. // grandchildren will not show.
  41038. // Why grandchildren? If not grandchildren but children,
  41039. // some siblings show children and some not,
  41040. // the appearance may be mess and not consistent,
  41041. levels: [] // Each item: {
  41042. // visibleMin, itemStyle, visualDimension, label
  41043. // }
  41044. // data: {
  41045. // value: [],
  41046. // children: [],
  41047. // link: 'http://xxx.xxx.xxx',
  41048. // target: 'blank' or 'self'
  41049. // }
  41050. },
  41051. /**
  41052. * @override
  41053. */
  41054. getInitialData: function (option, ecModel) {
  41055. // Create a virtual root.
  41056. var root = {name: option.name, children: option.data};
  41057. completeTreeValue(root);
  41058. var levels = option.levels || [];
  41059. levels = option.levels = setDefault(levels, ecModel);
  41060. var treeOption = {};
  41061. treeOption.levels = levels;
  41062. // Make sure always a new tree is created when setOption,
  41063. // in TreemapView, we check whether oldTree === newTree
  41064. // to choose mappings approach among old shapes and new shapes.
  41065. return Tree.createTree(root, this, treeOption).data;
  41066. },
  41067. optionUpdated: function () {
  41068. this.resetViewRoot();
  41069. },
  41070. /**
  41071. * @override
  41072. * @param {number} dataIndex
  41073. * @param {boolean} [mutipleSeries=false]
  41074. */
  41075. formatTooltip: function (dataIndex) {
  41076. var data = this.getData();
  41077. var value = this.getRawValue(dataIndex);
  41078. var formattedValue = isArray(value)
  41079. ? addCommas(value[0]) : addCommas(value);
  41080. var name = data.getName(dataIndex);
  41081. return encodeHTML(name + ': ' + formattedValue);
  41082. },
  41083. /**
  41084. * Add tree path to tooltip param
  41085. *
  41086. * @override
  41087. * @param {number} dataIndex
  41088. * @return {Object}
  41089. */
  41090. getDataParams: function (dataIndex) {
  41091. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  41092. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  41093. params.treePathInfo = wrapTreePathInfo(node, this);
  41094. return params;
  41095. },
  41096. /**
  41097. * @public
  41098. * @param {Object} layoutInfo {
  41099. * x: containerGroup x
  41100. * y: containerGroup y
  41101. * width: containerGroup width
  41102. * height: containerGroup height
  41103. * }
  41104. */
  41105. setLayoutInfo: function (layoutInfo) {
  41106. /**
  41107. * @readOnly
  41108. * @type {Object}
  41109. */
  41110. this.layoutInfo = this.layoutInfo || {};
  41111. extend(this.layoutInfo, layoutInfo);
  41112. },
  41113. /**
  41114. * @param {string} id
  41115. * @return {number} index
  41116. */
  41117. mapIdToIndex: function (id) {
  41118. // A feature is implemented:
  41119. // index is monotone increasing with the sequence of
  41120. // input id at the first time.
  41121. // This feature can make sure that each data item and its
  41122. // mapped color have the same index between data list and
  41123. // color list at the beginning, which is useful for user
  41124. // to adjust data-color mapping.
  41125. /**
  41126. * @private
  41127. * @type {Object}
  41128. */
  41129. var idIndexMap = this._idIndexMap;
  41130. if (!idIndexMap) {
  41131. idIndexMap = this._idIndexMap = createHashMap();
  41132. /**
  41133. * @private
  41134. * @type {number}
  41135. */
  41136. this._idIndexMapCount = 0;
  41137. }
  41138. var index = idIndexMap.get(id);
  41139. if (index == null) {
  41140. idIndexMap.set(id, index = this._idIndexMapCount++);
  41141. }
  41142. return index;
  41143. },
  41144. getViewRoot: function () {
  41145. return this._viewRoot;
  41146. },
  41147. /**
  41148. * @param {module:echarts/data/Tree~Node} [viewRoot]
  41149. */
  41150. resetViewRoot: function (viewRoot) {
  41151. viewRoot
  41152. ? (this._viewRoot = viewRoot)
  41153. : (viewRoot = this._viewRoot);
  41154. var root = this.getRawData().tree.root;
  41155. if (!viewRoot
  41156. || (viewRoot !== root && !root.contains(viewRoot))
  41157. ) {
  41158. this._viewRoot = root;
  41159. }
  41160. }
  41161. });
  41162. /**
  41163. * @param {Object} dataNode
  41164. */
  41165. function completeTreeValue(dataNode) {
  41166. // Postorder travel tree.
  41167. // If value of none-leaf node is not set,
  41168. // calculate it by suming up the value of all children.
  41169. var sum = 0;
  41170. each$1(dataNode.children, function (child) {
  41171. completeTreeValue(child);
  41172. var childValue = child.value;
  41173. isArray(childValue) && (childValue = childValue[0]);
  41174. sum += childValue;
  41175. });
  41176. var thisValue = dataNode.value;
  41177. if (isArray(thisValue)) {
  41178. thisValue = thisValue[0];
  41179. }
  41180. if (thisValue == null || isNaN(thisValue)) {
  41181. thisValue = sum;
  41182. }
  41183. // Value should not less than 0.
  41184. if (thisValue < 0) {
  41185. thisValue = 0;
  41186. }
  41187. isArray(dataNode.value)
  41188. ? (dataNode.value[0] = thisValue)
  41189. : (dataNode.value = thisValue);
  41190. }
  41191. /**
  41192. * set default to level configuration
  41193. */
  41194. function setDefault(levels, ecModel) {
  41195. var globalColorList = ecModel.get('color');
  41196. if (!globalColorList) {
  41197. return;
  41198. }
  41199. levels = levels || [];
  41200. var hasColorDefine;
  41201. each$1(levels, function (levelDefine) {
  41202. var model = new Model(levelDefine);
  41203. var modelColor = model.get('color');
  41204. if (model.get('itemStyle.color')
  41205. || (modelColor && modelColor !== 'none')
  41206. ) {
  41207. hasColorDefine = true;
  41208. }
  41209. });
  41210. if (!hasColorDefine) {
  41211. var level0 = levels[0] || (levels[0] = {});
  41212. level0.color = globalColorList.slice();
  41213. }
  41214. return levels;
  41215. }
  41216. /*
  41217. * Licensed to the Apache Software Foundation (ASF) under one
  41218. * or more contributor license agreements. See the NOTICE file
  41219. * distributed with this work for additional information
  41220. * regarding copyright ownership. The ASF licenses this file
  41221. * to you under the Apache License, Version 2.0 (the
  41222. * "License"); you may not use this file except in compliance
  41223. * with the License. You may obtain a copy of the License at
  41224. *
  41225. * http://www.apache.org/licenses/LICENSE-2.0
  41226. *
  41227. * Unless required by applicable law or agreed to in writing,
  41228. * software distributed under the License is distributed on an
  41229. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41230. * KIND, either express or implied. See the License for the
  41231. * specific language governing permissions and limitations
  41232. * under the License.
  41233. */
  41234. var TEXT_PADDING = 8;
  41235. var ITEM_GAP = 8;
  41236. var ARRAY_LENGTH = 5;
  41237. function Breadcrumb(containerGroup) {
  41238. /**
  41239. * @private
  41240. * @type {module:zrender/container/Group}
  41241. */
  41242. this.group = new Group();
  41243. containerGroup.add(this.group);
  41244. }
  41245. Breadcrumb.prototype = {
  41246. constructor: Breadcrumb,
  41247. render: function (seriesModel, api, targetNode, onSelect) {
  41248. var model = seriesModel.getModel('breadcrumb');
  41249. var thisGroup = this.group;
  41250. thisGroup.removeAll();
  41251. if (!model.get('show') || !targetNode) {
  41252. return;
  41253. }
  41254. var normalStyleModel = model.getModel('itemStyle');
  41255. // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  41256. var textStyleModel = normalStyleModel.getModel('textStyle');
  41257. var layoutParam = {
  41258. pos: {
  41259. left: model.get('left'),
  41260. right: model.get('right'),
  41261. top: model.get('top'),
  41262. bottom: model.get('bottom')
  41263. },
  41264. box: {
  41265. width: api.getWidth(),
  41266. height: api.getHeight()
  41267. },
  41268. emptyItemWidth: model.get('emptyItemWidth'),
  41269. totalWidth: 0,
  41270. renderList: []
  41271. };
  41272. this._prepare(targetNode, layoutParam, textStyleModel);
  41273. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  41274. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  41275. },
  41276. /**
  41277. * Prepare render list and total width
  41278. * @private
  41279. */
  41280. _prepare: function (targetNode, layoutParam, textStyleModel) {
  41281. for (var node = targetNode; node; node = node.parentNode) {
  41282. var text = node.getModel().get('name');
  41283. var textRect = textStyleModel.getTextRect(text);
  41284. var itemWidth = Math.max(
  41285. textRect.width + TEXT_PADDING * 2,
  41286. layoutParam.emptyItemWidth
  41287. );
  41288. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  41289. layoutParam.renderList.push({node: node, text: text, width: itemWidth});
  41290. }
  41291. },
  41292. /**
  41293. * @private
  41294. */
  41295. _renderContent: function (
  41296. seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect
  41297. ) {
  41298. // Start rendering.
  41299. var lastX = 0;
  41300. var emptyItemWidth = layoutParam.emptyItemWidth;
  41301. var height = seriesModel.get('breadcrumb.height');
  41302. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  41303. var totalWidth = layoutParam.totalWidth;
  41304. var renderList = layoutParam.renderList;
  41305. for (var i = renderList.length - 1; i >= 0; i--) {
  41306. var item = renderList[i];
  41307. var itemNode = item.node;
  41308. var itemWidth = item.width;
  41309. var text = item.text;
  41310. // Hdie text and shorten width if necessary.
  41311. if (totalWidth > availableSize.width) {
  41312. totalWidth -= itemWidth - emptyItemWidth;
  41313. itemWidth = emptyItemWidth;
  41314. text = null;
  41315. }
  41316. var el = new Polygon({
  41317. shape: {
  41318. points: makeItemPoints(
  41319. lastX, 0, itemWidth, height,
  41320. i === renderList.length - 1, i === 0
  41321. )
  41322. },
  41323. style: defaults(
  41324. normalStyleModel.getItemStyle(),
  41325. {
  41326. lineJoin: 'bevel',
  41327. text: text,
  41328. textFill: textStyleModel.getTextColor(),
  41329. textFont: textStyleModel.getFont()
  41330. }
  41331. ),
  41332. z: 10,
  41333. onclick: curry(onSelect, itemNode)
  41334. });
  41335. this.group.add(el);
  41336. packEventData(el, seriesModel, itemNode);
  41337. lastX += itemWidth + ITEM_GAP;
  41338. }
  41339. },
  41340. /**
  41341. * @override
  41342. */
  41343. remove: function () {
  41344. this.group.removeAll();
  41345. }
  41346. };
  41347. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  41348. var points = [
  41349. [head ? x : x - ARRAY_LENGTH, y],
  41350. [x + itemWidth, y],
  41351. [x + itemWidth, y + itemHeight],
  41352. [head ? x : x - ARRAY_LENGTH, y + itemHeight]
  41353. ];
  41354. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  41355. !head && points.push([x, y + itemHeight / 2]);
  41356. return points;
  41357. }
  41358. // Package custom mouse event.
  41359. function packEventData(el, seriesModel, itemNode) {
  41360. el.eventData = {
  41361. componentType: 'series',
  41362. componentSubType: 'treemap',
  41363. seriesIndex: seriesModel.componentIndex,
  41364. seriesName: seriesModel.name,
  41365. seriesType: 'treemap',
  41366. selfType: 'breadcrumb', // Distinguish with click event on treemap node.
  41367. nodeData: {
  41368. dataIndex: itemNode && itemNode.dataIndex,
  41369. name: itemNode && itemNode.name
  41370. },
  41371. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  41372. };
  41373. }
  41374. /*
  41375. * Licensed to the Apache Software Foundation (ASF) under one
  41376. * or more contributor license agreements. See the NOTICE file
  41377. * distributed with this work for additional information
  41378. * regarding copyright ownership. The ASF licenses this file
  41379. * to you under the Apache License, Version 2.0 (the
  41380. * "License"); you may not use this file except in compliance
  41381. * with the License. You may obtain a copy of the License at
  41382. *
  41383. * http://www.apache.org/licenses/LICENSE-2.0
  41384. *
  41385. * Unless required by applicable law or agreed to in writing,
  41386. * software distributed under the License is distributed on an
  41387. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41388. * KIND, either express or implied. See the License for the
  41389. * specific language governing permissions and limitations
  41390. * under the License.
  41391. */
  41392. /**
  41393. * @param {number} [time=500] Time in ms
  41394. * @param {string} [easing='linear']
  41395. * @param {number} [delay=0]
  41396. * @param {Function} [callback]
  41397. *
  41398. * @example
  41399. * // Animate position
  41400. * animation
  41401. * .createWrap()
  41402. * .add(el1, {position: [10, 10]})
  41403. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  41404. * .done(function () { // done })
  41405. * .start('cubicOut');
  41406. */
  41407. function createWrap() {
  41408. var storage = [];
  41409. var elExistsMap = {};
  41410. var doneCallback;
  41411. return {
  41412. /**
  41413. * Caution: a el can only be added once, otherwise 'done'
  41414. * might not be called. This method checks this (by el.id),
  41415. * suppresses adding and returns false when existing el found.
  41416. *
  41417. * @param {modele:zrender/Element} el
  41418. * @param {Object} target
  41419. * @param {number} [time=500]
  41420. * @param {number} [delay=0]
  41421. * @param {string} [easing='linear']
  41422. * @return {boolean} Whether adding succeeded.
  41423. *
  41424. * @example
  41425. * add(el, target, time, delay, easing);
  41426. * add(el, target, time, easing);
  41427. * add(el, target, time);
  41428. * add(el, target);
  41429. */
  41430. add: function (el, target, time, delay, easing) {
  41431. if (isString(delay)) {
  41432. easing = delay;
  41433. delay = 0;
  41434. }
  41435. if (elExistsMap[el.id]) {
  41436. return false;
  41437. }
  41438. elExistsMap[el.id] = 1;
  41439. storage.push(
  41440. {el: el, target: target, time: time, delay: delay, easing: easing}
  41441. );
  41442. return true;
  41443. },
  41444. /**
  41445. * Only execute when animation finished. Will not execute when any
  41446. * of 'stop' or 'stopAnimation' called.
  41447. *
  41448. * @param {Function} callback
  41449. */
  41450. done: function (callback) {
  41451. doneCallback = callback;
  41452. return this;
  41453. },
  41454. /**
  41455. * Will stop exist animation firstly.
  41456. */
  41457. start: function () {
  41458. var count = storage.length;
  41459. for (var i = 0, len = storage.length; i < len; i++) {
  41460. var item = storage[i];
  41461. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  41462. }
  41463. return this;
  41464. function done() {
  41465. count--;
  41466. if (!count) {
  41467. storage.length = 0;
  41468. elExistsMap = {};
  41469. doneCallback && doneCallback();
  41470. }
  41471. }
  41472. }
  41473. };
  41474. }
  41475. /*
  41476. * Licensed to the Apache Software Foundation (ASF) under one
  41477. * or more contributor license agreements. See the NOTICE file
  41478. * distributed with this work for additional information
  41479. * regarding copyright ownership. The ASF licenses this file
  41480. * to you under the Apache License, Version 2.0 (the
  41481. * "License"); you may not use this file except in compliance
  41482. * with the License. You may obtain a copy of the License at
  41483. *
  41484. * http://www.apache.org/licenses/LICENSE-2.0
  41485. *
  41486. * Unless required by applicable law or agreed to in writing,
  41487. * software distributed under the License is distributed on an
  41488. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41489. * KIND, either express or implied. See the License for the
  41490. * specific language governing permissions and limitations
  41491. * under the License.
  41492. */
  41493. var bind$1 = bind;
  41494. var Group$2 = Group;
  41495. var Rect$1 = Rect;
  41496. var each$8 = each$1;
  41497. var DRAG_THRESHOLD = 3;
  41498. var PATH_LABEL_NOAMAL = ['label'];
  41499. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  41500. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  41501. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  41502. var Z_BASE = 10; // Should bigger than every z.
  41503. var Z_BG = 1;
  41504. var Z_CONTENT = 2;
  41505. var getItemStyleEmphasis = makeStyleMapper([
  41506. ['fill', 'color'],
  41507. // `borderColor` and `borderWidth` has been occupied,
  41508. // so use `stroke` to indicate the stroke of the rect.
  41509. ['stroke', 'strokeColor'],
  41510. ['lineWidth', 'strokeWidth'],
  41511. ['shadowBlur'],
  41512. ['shadowOffsetX'],
  41513. ['shadowOffsetY'],
  41514. ['shadowColor']
  41515. ]);
  41516. var getItemStyleNormal = function (model) {
  41517. // Normal style props should include emphasis style props.
  41518. var itemStyle = getItemStyleEmphasis(model);
  41519. // Clear styles set by emphasis.
  41520. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  41521. return itemStyle;
  41522. };
  41523. extendChartView({
  41524. type: 'treemap',
  41525. /**
  41526. * @override
  41527. */
  41528. init: function (o, api) {
  41529. /**
  41530. * @private
  41531. * @type {module:zrender/container/Group}
  41532. */
  41533. this._containerGroup;
  41534. /**
  41535. * @private
  41536. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  41537. */
  41538. this._storage = createStorage();
  41539. /**
  41540. * @private
  41541. * @type {module:echarts/data/Tree}
  41542. */
  41543. this._oldTree;
  41544. /**
  41545. * @private
  41546. * @type {module:echarts/chart/treemap/Breadcrumb}
  41547. */
  41548. this._breadcrumb;
  41549. /**
  41550. * @private
  41551. * @type {module:echarts/component/helper/RoamController}
  41552. */
  41553. this._controller;
  41554. /**
  41555. * 'ready', 'animating'
  41556. * @private
  41557. */
  41558. this._state = 'ready';
  41559. },
  41560. /**
  41561. * @override
  41562. */
  41563. render: function (seriesModel, ecModel, api, payload) {
  41564. var models = ecModel.findComponents({
  41565. mainType: 'series', subType: 'treemap', query: payload
  41566. });
  41567. if (indexOf(models, seriesModel) < 0) {
  41568. return;
  41569. }
  41570. this.seriesModel = seriesModel;
  41571. this.api = api;
  41572. this.ecModel = ecModel;
  41573. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  41574. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  41575. var payloadType = payload && payload.type;
  41576. var layoutInfo = seriesModel.layoutInfo;
  41577. var isInit = !this._oldTree;
  41578. var thisStorage = this._storage;
  41579. // Mark new root when action is treemapRootToNode.
  41580. var reRoot = (payloadType === 'treemapRootToNode' && targetInfo && thisStorage)
  41581. ? {
  41582. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  41583. direction: payload.direction
  41584. }
  41585. : null;
  41586. var containerGroup = this._giveContainerGroup(layoutInfo);
  41587. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  41588. (
  41589. !isInit && (
  41590. !payloadType
  41591. || payloadType === 'treemapZoomToNode'
  41592. || payloadType === 'treemapRootToNode'
  41593. )
  41594. )
  41595. ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot)
  41596. : renderResult.renderFinally();
  41597. this._resetController(api);
  41598. this._renderBreadcrumb(seriesModel, api, targetInfo);
  41599. },
  41600. /**
  41601. * @private
  41602. */
  41603. _giveContainerGroup: function (layoutInfo) {
  41604. var containerGroup = this._containerGroup;
  41605. if (!containerGroup) {
  41606. // FIXME
  41607. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  41608. containerGroup = this._containerGroup = new Group$2();
  41609. this._initEvents(containerGroup);
  41610. this.group.add(containerGroup);
  41611. }
  41612. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  41613. return containerGroup;
  41614. },
  41615. /**
  41616. * @private
  41617. */
  41618. _doRender: function (containerGroup, seriesModel, reRoot) {
  41619. var thisTree = seriesModel.getData().tree;
  41620. var oldTree = this._oldTree;
  41621. // Clear last shape records.
  41622. var lastsForAnimation = createStorage();
  41623. var thisStorage = createStorage();
  41624. var oldStorage = this._storage;
  41625. var willInvisibleEls = [];
  41626. var doRenderNode = curry(
  41627. renderNode, seriesModel,
  41628. thisStorage, oldStorage, reRoot,
  41629. lastsForAnimation, willInvisibleEls
  41630. );
  41631. // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  41632. // the oldTree is actually losted, so we can not find all of the old graphic
  41633. // elements from tree. So we use this stragegy: make element storage, move
  41634. // from old storage to new storage, clear old storage.
  41635. dualTravel(
  41636. thisTree.root ? [thisTree.root] : [],
  41637. (oldTree && oldTree.root) ? [oldTree.root] : [],
  41638. containerGroup,
  41639. thisTree === oldTree || !oldTree,
  41640. 0
  41641. );
  41642. // Process all removing.
  41643. var willDeleteEls = clearStorage(oldStorage);
  41644. this._oldTree = thisTree;
  41645. this._storage = thisStorage;
  41646. return {
  41647. lastsForAnimation: lastsForAnimation,
  41648. willDeleteEls: willDeleteEls,
  41649. renderFinally: renderFinally
  41650. };
  41651. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  41652. // When 'render' is triggered by action,
  41653. // 'this' and 'old' may be the same tree,
  41654. // we use rawIndex in that case.
  41655. if (sameTree) {
  41656. oldViewChildren = thisViewChildren;
  41657. each$8(thisViewChildren, function (child, index) {
  41658. !child.isRemoved() && processNode(index, index);
  41659. });
  41660. }
  41661. // Diff hierarchically (diff only in each subtree, but not whole).
  41662. // because, consistency of view is important.
  41663. else {
  41664. (new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey))
  41665. .add(processNode)
  41666. .update(processNode)
  41667. .remove(curry(processNode, null))
  41668. .execute();
  41669. }
  41670. function getKey(node) {
  41671. // Identify by name or raw index.
  41672. return node.getId();
  41673. }
  41674. function processNode(newIndex, oldIndex) {
  41675. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  41676. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  41677. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  41678. group && dualTravel(
  41679. thisNode && thisNode.viewChildren || [],
  41680. oldNode && oldNode.viewChildren || [],
  41681. group,
  41682. sameTree,
  41683. depth + 1
  41684. );
  41685. }
  41686. }
  41687. function clearStorage(storage) {
  41688. var willDeleteEls = createStorage();
  41689. storage && each$8(storage, function (store, storageName) {
  41690. var delEls = willDeleteEls[storageName];
  41691. each$8(store, function (el) {
  41692. el && (delEls.push(el), el.__tmWillDelete = 1);
  41693. });
  41694. });
  41695. return willDeleteEls;
  41696. }
  41697. function renderFinally() {
  41698. each$8(willDeleteEls, function (els) {
  41699. each$8(els, function (el) {
  41700. el.parent && el.parent.remove(el);
  41701. });
  41702. });
  41703. each$8(willInvisibleEls, function (el) {
  41704. el.invisible = true;
  41705. // Setting invisible is for optimizing, so no need to set dirty,
  41706. // just mark as invisible.
  41707. el.dirty();
  41708. });
  41709. }
  41710. },
  41711. /**
  41712. * @private
  41713. */
  41714. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  41715. if (!seriesModel.get('animation')) {
  41716. return;
  41717. }
  41718. var duration = seriesModel.get('animationDurationUpdate');
  41719. var easing = seriesModel.get('animationEasing');
  41720. var animationWrap = createWrap();
  41721. // Make delete animations.
  41722. each$8(renderResult.willDeleteEls, function (store, storageName) {
  41723. each$8(store, function (el, rawIndex) {
  41724. if (el.invisible) {
  41725. return;
  41726. }
  41727. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  41728. var target;
  41729. if (reRoot && reRoot.direction === 'drillDown') {
  41730. target = parent === reRoot.rootNodeGroup
  41731. // This is the content element of view root.
  41732. // Only `content` will enter this branch, because
  41733. // `background` and `nodeGroup` will not be deleted.
  41734. ? {
  41735. shape: {
  41736. x: 0,
  41737. y: 0,
  41738. width: parent.__tmNodeWidth,
  41739. height: parent.__tmNodeHeight
  41740. },
  41741. style: {
  41742. opacity: 0
  41743. }
  41744. }
  41745. // Others.
  41746. : {style: {opacity: 0}};
  41747. }
  41748. else {
  41749. var targetX = 0;
  41750. var targetY = 0;
  41751. if (!parent.__tmWillDelete) {
  41752. // Let node animate to right-bottom corner, cooperating with fadeout,
  41753. // which is appropriate for user understanding.
  41754. // Divided by 2 for reRoot rolling up effect.
  41755. targetX = parent.__tmNodeWidth / 2;
  41756. targetY = parent.__tmNodeHeight / 2;
  41757. }
  41758. target = storageName === 'nodeGroup'
  41759. ? {position: [targetX, targetY], style: {opacity: 0}}
  41760. : {
  41761. shape: {x: targetX, y: targetY, width: 0, height: 0},
  41762. style: {opacity: 0}
  41763. };
  41764. }
  41765. target && animationWrap.add(el, target, duration, easing);
  41766. });
  41767. });
  41768. // Make other animations
  41769. each$8(this._storage, function (store, storageName) {
  41770. each$8(store, function (el, rawIndex) {
  41771. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  41772. var target = {};
  41773. if (!last) {
  41774. return;
  41775. }
  41776. if (storageName === 'nodeGroup') {
  41777. if (last.old) {
  41778. target.position = el.position.slice();
  41779. el.attr('position', last.old);
  41780. }
  41781. }
  41782. else {
  41783. if (last.old) {
  41784. target.shape = extend({}, el.shape);
  41785. el.setShape(last.old);
  41786. }
  41787. if (last.fadein) {
  41788. el.setStyle('opacity', 0);
  41789. target.style = {opacity: 1};
  41790. }
  41791. // When animation is stopped for succedent animation starting,
  41792. // el.style.opacity might not be 1
  41793. else if (el.style.opacity !== 1) {
  41794. target.style = {opacity: 1};
  41795. }
  41796. }
  41797. animationWrap.add(el, target, duration, easing);
  41798. });
  41799. }, this);
  41800. this._state = 'animating';
  41801. animationWrap
  41802. .done(bind$1(function () {
  41803. this._state = 'ready';
  41804. renderResult.renderFinally();
  41805. }, this))
  41806. .start();
  41807. },
  41808. /**
  41809. * @private
  41810. */
  41811. _resetController: function (api) {
  41812. var controller = this._controller;
  41813. // Init controller.
  41814. if (!controller) {
  41815. controller = this._controller = new RoamController(api.getZr());
  41816. controller.enable(this.seriesModel.get('roam'));
  41817. controller.on('pan', bind$1(this._onPan, this));
  41818. controller.on('zoom', bind$1(this._onZoom, this));
  41819. }
  41820. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  41821. controller.setPointerChecker(function (e, x, y) {
  41822. return rect.contain(x, y);
  41823. });
  41824. },
  41825. /**
  41826. * @private
  41827. */
  41828. _clearController: function () {
  41829. var controller = this._controller;
  41830. if (controller) {
  41831. controller.dispose();
  41832. controller = null;
  41833. }
  41834. },
  41835. /**
  41836. * @private
  41837. */
  41838. _onPan: function (dx, dy) {
  41839. if (this._state !== 'animating'
  41840. && (Math.abs(dx) > DRAG_THRESHOLD || Math.abs(dy) > DRAG_THRESHOLD)
  41841. ) {
  41842. // These param must not be cached.
  41843. var root = this.seriesModel.getData().tree.root;
  41844. if (!root) {
  41845. return;
  41846. }
  41847. var rootLayout = root.getLayout();
  41848. if (!rootLayout) {
  41849. return;
  41850. }
  41851. this.api.dispatchAction({
  41852. type: 'treemapMove',
  41853. from: this.uid,
  41854. seriesId: this.seriesModel.id,
  41855. rootRect: {
  41856. x: rootLayout.x + dx, y: rootLayout.y + dy,
  41857. width: rootLayout.width, height: rootLayout.height
  41858. }
  41859. });
  41860. }
  41861. },
  41862. /**
  41863. * @private
  41864. */
  41865. _onZoom: function (scale, mouseX, mouseY) {
  41866. if (this._state !== 'animating') {
  41867. // These param must not be cached.
  41868. var root = this.seriesModel.getData().tree.root;
  41869. if (!root) {
  41870. return;
  41871. }
  41872. var rootLayout = root.getLayout();
  41873. if (!rootLayout) {
  41874. return;
  41875. }
  41876. var rect = new BoundingRect(
  41877. rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height
  41878. );
  41879. var layoutInfo = this.seriesModel.layoutInfo;
  41880. // Transform mouse coord from global to containerGroup.
  41881. mouseX -= layoutInfo.x;
  41882. mouseY -= layoutInfo.y;
  41883. // Scale root bounding rect.
  41884. var m = create$1();
  41885. translate(m, m, [-mouseX, -mouseY]);
  41886. scale$1(m, m, [scale, scale]);
  41887. translate(m, m, [mouseX, mouseY]);
  41888. rect.applyTransform(m);
  41889. this.api.dispatchAction({
  41890. type: 'treemapRender',
  41891. from: this.uid,
  41892. seriesId: this.seriesModel.id,
  41893. rootRect: {
  41894. x: rect.x, y: rect.y,
  41895. width: rect.width, height: rect.height
  41896. }
  41897. });
  41898. }
  41899. },
  41900. /**
  41901. * @private
  41902. */
  41903. _initEvents: function (containerGroup) {
  41904. containerGroup.on('click', function (e) {
  41905. if (this._state !== 'ready') {
  41906. return;
  41907. }
  41908. var nodeClick = this.seriesModel.get('nodeClick', true);
  41909. if (!nodeClick) {
  41910. return;
  41911. }
  41912. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  41913. if (!targetInfo) {
  41914. return;
  41915. }
  41916. var node = targetInfo.node;
  41917. if (node.getLayout().isLeafRoot) {
  41918. this._rootToNode(targetInfo);
  41919. }
  41920. else {
  41921. if (nodeClick === 'zoomToNode') {
  41922. this._zoomToNode(targetInfo);
  41923. }
  41924. else if (nodeClick === 'link') {
  41925. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  41926. var link = itemModel.get('link', true);
  41927. var linkTarget = itemModel.get('target', true) || 'blank';
  41928. link && window.open(link, linkTarget);
  41929. }
  41930. }
  41931. }, this);
  41932. },
  41933. /**
  41934. * @private
  41935. */
  41936. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  41937. if (!targetInfo) {
  41938. targetInfo = seriesModel.get('leafDepth', true) != null
  41939. ? {node: seriesModel.getViewRoot()}
  41940. // FIXME
  41941. // better way?
  41942. // Find breadcrumb tail on center of containerGroup.
  41943. : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  41944. if (!targetInfo) {
  41945. targetInfo = {node: seriesModel.getData().tree.root};
  41946. }
  41947. }
  41948. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group)))
  41949. .render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  41950. function onSelect(node) {
  41951. if (this._state !== 'animating') {
  41952. aboveViewRoot(seriesModel.getViewRoot(), node)
  41953. ? this._rootToNode({node: node})
  41954. : this._zoomToNode({node: node});
  41955. }
  41956. }
  41957. },
  41958. /**
  41959. * @override
  41960. */
  41961. remove: function () {
  41962. this._clearController();
  41963. this._containerGroup && this._containerGroup.removeAll();
  41964. this._storage = createStorage();
  41965. this._state = 'ready';
  41966. this._breadcrumb && this._breadcrumb.remove();
  41967. },
  41968. dispose: function () {
  41969. this._clearController();
  41970. },
  41971. /**
  41972. * @private
  41973. */
  41974. _zoomToNode: function (targetInfo) {
  41975. this.api.dispatchAction({
  41976. type: 'treemapZoomToNode',
  41977. from: this.uid,
  41978. seriesId: this.seriesModel.id,
  41979. targetNode: targetInfo.node
  41980. });
  41981. },
  41982. /**
  41983. * @private
  41984. */
  41985. _rootToNode: function (targetInfo) {
  41986. this.api.dispatchAction({
  41987. type: 'treemapRootToNode',
  41988. from: this.uid,
  41989. seriesId: this.seriesModel.id,
  41990. targetNode: targetInfo.node
  41991. });
  41992. },
  41993. /**
  41994. * @public
  41995. * @param {number} x Global coord x.
  41996. * @param {number} y Global coord y.
  41997. * @return {Object} info If not found, return undefined;
  41998. * @return {number} info.node Target node.
  41999. * @return {number} info.offsetX x refer to target node.
  42000. * @return {number} info.offsetY y refer to target node.
  42001. */
  42002. findTarget: function (x, y) {
  42003. var targetInfo;
  42004. var viewRoot = this.seriesModel.getViewRoot();
  42005. viewRoot.eachNode({attr: 'viewChildren', order: 'preorder'}, function (node) {
  42006. var bgEl = this._storage.background[node.getRawIndex()];
  42007. // If invisible, there might be no element.
  42008. if (bgEl) {
  42009. var point = bgEl.transformCoordToLocal(x, y);
  42010. var shape = bgEl.shape;
  42011. // For performance consideration, dont use 'getBoundingRect'.
  42012. if (shape.x <= point[0]
  42013. && point[0] <= shape.x + shape.width
  42014. && shape.y <= point[1]
  42015. && point[1] <= shape.y + shape.height
  42016. ) {
  42017. targetInfo = {node: node, offsetX: point[0], offsetY: point[1]};
  42018. }
  42019. else {
  42020. return false; // Suppress visit subtree.
  42021. }
  42022. }
  42023. }, this);
  42024. return targetInfo;
  42025. }
  42026. });
  42027. /**
  42028. * @inner
  42029. */
  42030. function createStorage() {
  42031. return {nodeGroup: [], background: [], content: []};
  42032. }
  42033. /**
  42034. * @inner
  42035. * @return Return undefined means do not travel further.
  42036. */
  42037. function renderNode(
  42038. seriesModel, thisStorage, oldStorage, reRoot,
  42039. lastsForAnimation, willInvisibleEls,
  42040. thisNode, oldNode, parentGroup, depth
  42041. ) {
  42042. // Whether under viewRoot.
  42043. if (!thisNode) {
  42044. // Deleting nodes will be performed finally. This method just find
  42045. // element from old storage, or create new element, set them to new
  42046. // storage, and set styles.
  42047. return;
  42048. }
  42049. // -------------------------------------------------------------------
  42050. // Start of closure variables available in "Procedures in renderNode".
  42051. var thisLayout = thisNode.getLayout();
  42052. if (!thisLayout || !thisLayout.isInView) {
  42053. return;
  42054. }
  42055. var thisWidth = thisLayout.width;
  42056. var thisHeight = thisLayout.height;
  42057. var borderWidth = thisLayout.borderWidth;
  42058. var thisInvisible = thisLayout.invisible;
  42059. var thisRawIndex = thisNode.getRawIndex();
  42060. var oldRawIndex = oldNode && oldNode.getRawIndex();
  42061. var thisViewChildren = thisNode.viewChildren;
  42062. var upperHeight = thisLayout.upperHeight;
  42063. var isParent = thisViewChildren && thisViewChildren.length;
  42064. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  42065. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle');
  42066. // End of closure ariables available in "Procedures in renderNode".
  42067. // -----------------------------------------------------------------
  42068. // Node group
  42069. var group = giveGraphic('nodeGroup', Group$2);
  42070. if (!group) {
  42071. return;
  42072. }
  42073. parentGroup.add(group);
  42074. // x,y are not set when el is above view root.
  42075. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  42076. group.__tmNodeWidth = thisWidth;
  42077. group.__tmNodeHeight = thisHeight;
  42078. if (thisLayout.isAboveViewRoot) {
  42079. return group;
  42080. }
  42081. // Background
  42082. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  42083. bg && renderBackground(group, bg, isParent && thisLayout.upperHeight);
  42084. // No children, render content.
  42085. if (!isParent) {
  42086. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  42087. content && renderContent(group, content);
  42088. }
  42089. return group;
  42090. // ----------------------------
  42091. // | Procedures in renderNode |
  42092. // ----------------------------
  42093. function renderBackground(group, bg, useUpperLabel) {
  42094. // For tooltip.
  42095. bg.dataIndex = thisNode.dataIndex;
  42096. bg.seriesIndex = seriesModel.seriesIndex;
  42097. bg.setShape({x: 0, y: 0, width: thisWidth, height: thisHeight});
  42098. var visualBorderColor = thisNode.getVisual('borderColor', true);
  42099. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  42100. updateStyle(bg, function () {
  42101. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  42102. normalStyle.fill = visualBorderColor;
  42103. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  42104. emphasisStyle.fill = emphasisBorderColor;
  42105. if (useUpperLabel) {
  42106. var upperLabelWidth = thisWidth - 2 * borderWidth;
  42107. prepareText(
  42108. normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight,
  42109. {x: borderWidth, y: 0, width: upperLabelWidth, height: upperHeight}
  42110. );
  42111. }
  42112. // For old bg.
  42113. else {
  42114. normalStyle.text = emphasisStyle.text = null;
  42115. }
  42116. bg.setStyle(normalStyle);
  42117. setHoverStyle(bg, emphasisStyle);
  42118. });
  42119. group.add(bg);
  42120. }
  42121. function renderContent(group, content) {
  42122. // For tooltip.
  42123. content.dataIndex = thisNode.dataIndex;
  42124. content.seriesIndex = seriesModel.seriesIndex;
  42125. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  42126. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  42127. content.culling = true;
  42128. content.setShape({
  42129. x: borderWidth,
  42130. y: borderWidth,
  42131. width: contentWidth,
  42132. height: contentHeight
  42133. });
  42134. var visualColor = thisNode.getVisual('color', true);
  42135. updateStyle(content, function () {
  42136. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  42137. normalStyle.fill = visualColor;
  42138. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  42139. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  42140. content.setStyle(normalStyle);
  42141. setHoverStyle(content, emphasisStyle);
  42142. });
  42143. group.add(content);
  42144. }
  42145. function updateStyle(element, cb) {
  42146. if (!thisInvisible) {
  42147. // If invisible, do not set visual, otherwise the element will
  42148. // change immediately before animation. We think it is OK to
  42149. // remain its origin color when moving out of the view window.
  42150. cb();
  42151. if (!element.__tmWillVisible) {
  42152. element.invisible = false;
  42153. }
  42154. }
  42155. else {
  42156. // Delay invisible setting utill animation finished,
  42157. // avoid element vanish suddenly before animation.
  42158. !element.invisible && willInvisibleEls.push(element);
  42159. }
  42160. }
  42161. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  42162. var nodeModel = thisNode.getModel();
  42163. var text = retrieve(
  42164. seriesModel.getFormattedLabel(
  42165. thisNode.dataIndex, 'normal', null, null, upperLabelRect ? 'upperLabel' : 'label'
  42166. ),
  42167. nodeModel.get('name')
  42168. );
  42169. if (!upperLabelRect && thisLayout.isLeafRoot) {
  42170. var iconChar = seriesModel.get('drillDownIcon', true);
  42171. text = iconChar ? iconChar + ' ' + text : text;
  42172. }
  42173. var normalLabelModel = nodeModel.getModel(
  42174. upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL
  42175. );
  42176. var emphasisLabelModel = nodeModel.getModel(
  42177. upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS
  42178. );
  42179. var isShow = normalLabelModel.getShallow('show');
  42180. setLabelStyle(
  42181. normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel,
  42182. {
  42183. defaultText: isShow ? text : null,
  42184. autoColor: visualColor,
  42185. isRectText: true
  42186. }
  42187. );
  42188. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  42189. normalStyle.truncate = (isShow && normalLabelModel.get('ellipsis'))
  42190. ? {
  42191. outerWidth: width,
  42192. outerHeight: height,
  42193. minChar: 2
  42194. }
  42195. : null;
  42196. }
  42197. function giveGraphic(storageName, Ctor, depth, z) {
  42198. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  42199. var lasts = lastsForAnimation[storageName];
  42200. if (element) {
  42201. // Remove from oldStorage
  42202. oldStorage[storageName][oldRawIndex] = null;
  42203. prepareAnimationWhenHasOld(lasts, element, storageName);
  42204. }
  42205. // If invisible and no old element, do not create new element (for optimizing).
  42206. else if (!thisInvisible) {
  42207. element = new Ctor({z: calculateZ(depth, z)});
  42208. element.__tmDepth = depth;
  42209. element.__tmStorageName = storageName;
  42210. prepareAnimationWhenNoOld(lasts, element, storageName);
  42211. }
  42212. // Set to thisStorage
  42213. return (thisStorage[storageName][thisRawIndex] = element);
  42214. }
  42215. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  42216. var lastCfg = lasts[thisRawIndex] = {};
  42217. lastCfg.old = storageName === 'nodeGroup'
  42218. ? element.position.slice()
  42219. : extend({}, element.shape);
  42220. }
  42221. // If a element is new, we need to find the animation start point carefully,
  42222. // otherwise it will looks strange when 'zoomToNode'.
  42223. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  42224. var lastCfg = lasts[thisRawIndex] = {};
  42225. var parentNode = thisNode.parentNode;
  42226. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  42227. var parentOldX = 0;
  42228. var parentOldY = 0;
  42229. // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  42230. // For convenience, get old bounding rect from background.
  42231. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  42232. if (!reRoot && parentOldBg && parentOldBg.old) {
  42233. parentOldX = parentOldBg.old.width;
  42234. parentOldY = parentOldBg.old.height;
  42235. }
  42236. // When no parent old shape found, its parent is new too,
  42237. // so we can just use {x:0, y:0}.
  42238. lastCfg.old = storageName === 'nodeGroup'
  42239. ? [0, parentOldY]
  42240. : {x: parentOldX, y: parentOldY, width: 0, height: 0};
  42241. }
  42242. // Fade in, user can be aware that these nodes are new.
  42243. lastCfg.fadein = storageName !== 'nodeGroup';
  42244. }
  42245. }
  42246. // We can not set all backgroud with the same z, Because the behaviour of
  42247. // drill down and roll up differ background creation sequence from tree
  42248. // hierarchy sequence, which cause that lowser background element overlap
  42249. // upper ones. So we calculate z based on depth.
  42250. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  42251. // treemap with large z overlaps other components.
  42252. function calculateZ(depth, zInLevel) {
  42253. var zb = depth * Z_BASE + zInLevel;
  42254. return (zb - 1) / zb;
  42255. }
  42256. /*
  42257. * Licensed to the Apache Software Foundation (ASF) under one
  42258. * or more contributor license agreements. See the NOTICE file
  42259. * distributed with this work for additional information
  42260. * regarding copyright ownership. The ASF licenses this file
  42261. * to you under the Apache License, Version 2.0 (the
  42262. * "License"); you may not use this file except in compliance
  42263. * with the License. You may obtain a copy of the License at
  42264. *
  42265. * http://www.apache.org/licenses/LICENSE-2.0
  42266. *
  42267. * Unless required by applicable law or agreed to in writing,
  42268. * software distributed under the License is distributed on an
  42269. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42270. * KIND, either express or implied. See the License for the
  42271. * specific language governing permissions and limitations
  42272. * under the License.
  42273. */
  42274. /**
  42275. * @file Treemap action
  42276. */
  42277. var noop$1 = function () {};
  42278. var actionTypes = [
  42279. 'treemapZoomToNode',
  42280. 'treemapRender',
  42281. 'treemapMove'
  42282. ];
  42283. for (var i$2 = 0; i$2 < actionTypes.length; i$2++) {
  42284. registerAction({type: actionTypes[i$2], update: 'updateView'}, noop$1);
  42285. }
  42286. registerAction(
  42287. {type: 'treemapRootToNode', update: 'updateView'},
  42288. function (payload, ecModel) {
  42289. ecModel.eachComponent(
  42290. {mainType: 'series', subType: 'treemap', query: payload},
  42291. handleRootToNode
  42292. );
  42293. function handleRootToNode(model, index) {
  42294. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  42295. var targetInfo = retrieveTargetInfo(payload, types, model);
  42296. if (targetInfo) {
  42297. var originViewRoot = model.getViewRoot();
  42298. if (originViewRoot) {
  42299. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  42300. ? 'rollUp' : 'drillDown';
  42301. }
  42302. model.resetViewRoot(targetInfo.node);
  42303. }
  42304. }
  42305. }
  42306. );
  42307. /*
  42308. * Licensed to the Apache Software Foundation (ASF) under one
  42309. * or more contributor license agreements. See the NOTICE file
  42310. * distributed with this work for additional information
  42311. * regarding copyright ownership. The ASF licenses this file
  42312. * to you under the Apache License, Version 2.0 (the
  42313. * "License"); you may not use this file except in compliance
  42314. * with the License. You may obtain a copy of the License at
  42315. *
  42316. * http://www.apache.org/licenses/LICENSE-2.0
  42317. *
  42318. * Unless required by applicable law or agreed to in writing,
  42319. * software distributed under the License is distributed on an
  42320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42321. * KIND, either express or implied. See the License for the
  42322. * specific language governing permissions and limitations
  42323. * under the License.
  42324. */
  42325. var each$9 = each$1;
  42326. var isObject$5 = isObject$1;
  42327. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  42328. /**
  42329. * @param {Object} option
  42330. * @param {string} [option.type] See visualHandlers.
  42331. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  42332. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  42333. * required when mappingMethod is 'linear'
  42334. * @param {Array.<Object>=} [option.pieceList] [
  42335. * {value: someValue},
  42336. * {interval: [min1, max1], visual: {...}},
  42337. * {interval: [min2, max2]}
  42338. * ],
  42339. * required when mappingMethod is 'piecewise'.
  42340. * Visual for only each piece can be specified.
  42341. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  42342. * required when mappingMethod is 'category'.
  42343. * If no option.categories, categories is set
  42344. * as [0, 1, 2, ...].
  42345. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  42346. * @param {(Array|Object|*)} [option.visual] Visual data.
  42347. * when mappingMethod is 'category',
  42348. * visual data can be array or object
  42349. * (like: {cate1: '#222', none: '#fff'})
  42350. * or primary types (which represents
  42351. * defualt category visual), otherwise visual
  42352. * can be array or primary (which will be
  42353. * normalized to array).
  42354. *
  42355. */
  42356. var VisualMapping = function (option) {
  42357. var mappingMethod = option.mappingMethod;
  42358. var visualType = option.type;
  42359. /**
  42360. * @readOnly
  42361. * @type {Object}
  42362. */
  42363. var thisOption = this.option = clone(option);
  42364. /**
  42365. * @readOnly
  42366. * @type {string}
  42367. */
  42368. this.type = visualType;
  42369. /**
  42370. * @readOnly
  42371. * @type {string}
  42372. */
  42373. this.mappingMethod = mappingMethod;
  42374. /**
  42375. * @private
  42376. * @type {Function}
  42377. */
  42378. this._normalizeData = normalizers[mappingMethod];
  42379. var visualHandler = visualHandlers[visualType];
  42380. /**
  42381. * @public
  42382. * @type {Function}
  42383. */
  42384. this.applyVisual = visualHandler.applyVisual;
  42385. /**
  42386. * @public
  42387. * @type {Function}
  42388. */
  42389. this.getColorMapper = visualHandler.getColorMapper;
  42390. /**
  42391. * @private
  42392. * @type {Function}
  42393. */
  42394. this._doMap = visualHandler._doMap[mappingMethod];
  42395. if (mappingMethod === 'piecewise') {
  42396. normalizeVisualRange(thisOption);
  42397. preprocessForPiecewise(thisOption);
  42398. }
  42399. else if (mappingMethod === 'category') {
  42400. thisOption.categories
  42401. ? preprocessForSpecifiedCategory(thisOption)
  42402. // categories is ordinal when thisOption.categories not specified,
  42403. // which need no more preprocess except normalize visual.
  42404. : normalizeVisualRange(thisOption, true);
  42405. }
  42406. else { // mappingMethod === 'linear' or 'fixed'
  42407. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  42408. normalizeVisualRange(thisOption);
  42409. }
  42410. };
  42411. VisualMapping.prototype = {
  42412. constructor: VisualMapping,
  42413. mapValueToVisual: function (value) {
  42414. var normalized = this._normalizeData(value);
  42415. return this._doMap(normalized, value);
  42416. },
  42417. getNormalizer: function () {
  42418. return bind(this._normalizeData, this);
  42419. }
  42420. };
  42421. var visualHandlers = VisualMapping.visualHandlers = {
  42422. color: {
  42423. applyVisual: makeApplyVisual('color'),
  42424. /**
  42425. * Create a mapper function
  42426. * @return {Function}
  42427. */
  42428. getColorMapper: function () {
  42429. var thisOption = this.option;
  42430. return bind(
  42431. thisOption.mappingMethod === 'category'
  42432. ? function (value, isNormalized) {
  42433. !isNormalized && (value = this._normalizeData(value));
  42434. return doMapCategory.call(this, value);
  42435. }
  42436. : function (value, isNormalized, out) {
  42437. // If output rgb array
  42438. // which will be much faster and useful in pixel manipulation
  42439. var returnRGBArray = !!out;
  42440. !isNormalized && (value = this._normalizeData(value));
  42441. out = fastLerp(value, thisOption.parsedVisual, out);
  42442. return returnRGBArray ? out : stringify(out, 'rgba');
  42443. },
  42444. this
  42445. );
  42446. },
  42447. _doMap: {
  42448. linear: function (normalized) {
  42449. return stringify(
  42450. fastLerp(normalized, this.option.parsedVisual),
  42451. 'rgba'
  42452. );
  42453. },
  42454. category: doMapCategory,
  42455. piecewise: function (normalized, value) {
  42456. var result = getSpecifiedVisual.call(this, value);
  42457. if (result == null) {
  42458. result = stringify(
  42459. fastLerp(normalized, this.option.parsedVisual),
  42460. 'rgba'
  42461. );
  42462. }
  42463. return result;
  42464. },
  42465. fixed: doMapFixed
  42466. }
  42467. },
  42468. colorHue: makePartialColorVisualHandler(function (color, value) {
  42469. return modifyHSL(color, value);
  42470. }),
  42471. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  42472. return modifyHSL(color, null, value);
  42473. }),
  42474. colorLightness: makePartialColorVisualHandler(function (color, value) {
  42475. return modifyHSL(color, null, null, value);
  42476. }),
  42477. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  42478. return modifyAlpha(color, value);
  42479. }),
  42480. opacity: {
  42481. applyVisual: makeApplyVisual('opacity'),
  42482. _doMap: makeDoMap([0, 1])
  42483. },
  42484. liftZ: {
  42485. applyVisual: makeApplyVisual('liftZ'),
  42486. _doMap: {
  42487. linear: doMapFixed,
  42488. category: doMapFixed,
  42489. piecewise: doMapFixed,
  42490. fixed: doMapFixed
  42491. }
  42492. },
  42493. symbol: {
  42494. applyVisual: function (value, getter, setter) {
  42495. var symbolCfg = this.mapValueToVisual(value);
  42496. if (isString(symbolCfg)) {
  42497. setter('symbol', symbolCfg);
  42498. }
  42499. else if (isObject$5(symbolCfg)) {
  42500. for (var name in symbolCfg) {
  42501. if (symbolCfg.hasOwnProperty(name)) {
  42502. setter(name, symbolCfg[name]);
  42503. }
  42504. }
  42505. }
  42506. },
  42507. _doMap: {
  42508. linear: doMapToArray,
  42509. category: doMapCategory,
  42510. piecewise: function (normalized, value) {
  42511. var result = getSpecifiedVisual.call(this, value);
  42512. if (result == null) {
  42513. result = doMapToArray.call(this, normalized);
  42514. }
  42515. return result;
  42516. },
  42517. fixed: doMapFixed
  42518. }
  42519. },
  42520. symbolSize: {
  42521. applyVisual: makeApplyVisual('symbolSize'),
  42522. _doMap: makeDoMap([0, 1])
  42523. }
  42524. };
  42525. function preprocessForPiecewise(thisOption) {
  42526. var pieceList = thisOption.pieceList;
  42527. thisOption.hasSpecialVisual = false;
  42528. each$1(pieceList, function (piece, index) {
  42529. piece.originIndex = index;
  42530. // piece.visual is "result visual value" but not
  42531. // a visual range, so it does not need to be normalized.
  42532. if (piece.visual != null) {
  42533. thisOption.hasSpecialVisual = true;
  42534. }
  42535. });
  42536. }
  42537. function preprocessForSpecifiedCategory(thisOption) {
  42538. // Hash categories.
  42539. var categories = thisOption.categories;
  42540. var visual = thisOption.visual;
  42541. var categoryMap = thisOption.categoryMap = {};
  42542. each$9(categories, function (cate, index) {
  42543. categoryMap[cate] = index;
  42544. });
  42545. // Process visual map input.
  42546. if (!isArray(visual)) {
  42547. var visualArr = [];
  42548. if (isObject$1(visual)) {
  42549. each$9(visual, function (v, cate) {
  42550. var index = categoryMap[cate];
  42551. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  42552. });
  42553. }
  42554. else { // Is primary type, represents default visual.
  42555. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  42556. }
  42557. visual = setVisualToOption(thisOption, visualArr);
  42558. }
  42559. // Remove categories that has no visual,
  42560. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  42561. for (var i = categories.length - 1; i >= 0; i--) {
  42562. if (visual[i] == null) {
  42563. delete categoryMap[categories[i]];
  42564. categories.pop();
  42565. }
  42566. }
  42567. }
  42568. function normalizeVisualRange(thisOption, isCategory) {
  42569. var visual = thisOption.visual;
  42570. var visualArr = [];
  42571. if (isObject$1(visual)) {
  42572. each$9(visual, function (v) {
  42573. visualArr.push(v);
  42574. });
  42575. }
  42576. else if (visual != null) {
  42577. visualArr.push(visual);
  42578. }
  42579. var doNotNeedPair = {color: 1, symbol: 1};
  42580. if (!isCategory
  42581. && visualArr.length === 1
  42582. && !doNotNeedPair.hasOwnProperty(thisOption.type)
  42583. ) {
  42584. // Do not care visualArr.length === 0, which is illegal.
  42585. visualArr[1] = visualArr[0];
  42586. }
  42587. setVisualToOption(thisOption, visualArr);
  42588. }
  42589. function makePartialColorVisualHandler(applyValue) {
  42590. return {
  42591. applyVisual: function (value, getter, setter) {
  42592. value = this.mapValueToVisual(value);
  42593. // Must not be array value
  42594. setter('color', applyValue(getter('color'), value));
  42595. },
  42596. _doMap: makeDoMap([0, 1])
  42597. };
  42598. }
  42599. function doMapToArray(normalized) {
  42600. var visual = this.option.visual;
  42601. return visual[
  42602. Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))
  42603. ] || {};
  42604. }
  42605. function makeApplyVisual(visualType) {
  42606. return function (value, getter, setter) {
  42607. setter(visualType, this.mapValueToVisual(value));
  42608. };
  42609. }
  42610. function doMapCategory(normalized) {
  42611. var visual = this.option.visual;
  42612. return visual[
  42613. (this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX)
  42614. ? normalized % visual.length
  42615. : normalized
  42616. ];
  42617. }
  42618. function doMapFixed() {
  42619. return this.option.visual[0];
  42620. }
  42621. function makeDoMap(sourceExtent) {
  42622. return {
  42623. linear: function (normalized) {
  42624. return linearMap(normalized, sourceExtent, this.option.visual, true);
  42625. },
  42626. category: doMapCategory,
  42627. piecewise: function (normalized, value) {
  42628. var result = getSpecifiedVisual.call(this, value);
  42629. if (result == null) {
  42630. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  42631. }
  42632. return result;
  42633. },
  42634. fixed: doMapFixed
  42635. };
  42636. }
  42637. function getSpecifiedVisual(value) {
  42638. var thisOption = this.option;
  42639. var pieceList = thisOption.pieceList;
  42640. if (thisOption.hasSpecialVisual) {
  42641. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  42642. var piece = pieceList[pieceIndex];
  42643. if (piece && piece.visual) {
  42644. return piece.visual[this.type];
  42645. }
  42646. }
  42647. }
  42648. function setVisualToOption(thisOption, visualArr) {
  42649. thisOption.visual = visualArr;
  42650. if (thisOption.type === 'color') {
  42651. thisOption.parsedVisual = map(visualArr, function (item) {
  42652. return parse(item);
  42653. });
  42654. }
  42655. return visualArr;
  42656. }
  42657. /**
  42658. * Normalizers by mapping methods.
  42659. */
  42660. var normalizers = {
  42661. linear: function (value) {
  42662. return linearMap(value, this.option.dataExtent, [0, 1], true);
  42663. },
  42664. piecewise: function (value) {
  42665. var pieceList = this.option.pieceList;
  42666. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  42667. if (pieceIndex != null) {
  42668. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  42669. }
  42670. },
  42671. category: function (value) {
  42672. var index = this.option.categories
  42673. ? this.option.categoryMap[value]
  42674. : value; // ordinal
  42675. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  42676. },
  42677. fixed: noop
  42678. };
  42679. /**
  42680. * List available visual types.
  42681. *
  42682. * @public
  42683. * @return {Array.<string>}
  42684. */
  42685. VisualMapping.listVisualTypes = function () {
  42686. var visualTypes = [];
  42687. each$1(visualHandlers, function (handler, key) {
  42688. visualTypes.push(key);
  42689. });
  42690. return visualTypes;
  42691. };
  42692. /**
  42693. * @public
  42694. */
  42695. VisualMapping.addVisualHandler = function (name, handler) {
  42696. visualHandlers[name] = handler;
  42697. };
  42698. /**
  42699. * @public
  42700. */
  42701. VisualMapping.isValidType = function (visualType) {
  42702. return visualHandlers.hasOwnProperty(visualType);
  42703. };
  42704. /**
  42705. * Convinent method.
  42706. * Visual can be Object or Array or primary type.
  42707. *
  42708. * @public
  42709. */
  42710. VisualMapping.eachVisual = function (visual, callback, context) {
  42711. if (isObject$1(visual)) {
  42712. each$1(visual, callback, context);
  42713. }
  42714. else {
  42715. callback.call(context, visual);
  42716. }
  42717. };
  42718. VisualMapping.mapVisual = function (visual, callback, context) {
  42719. var isPrimary;
  42720. var newVisual = isArray(visual)
  42721. ? []
  42722. : isObject$1(visual)
  42723. ? {}
  42724. : (isPrimary = true, null);
  42725. VisualMapping.eachVisual(visual, function (v, key) {
  42726. var newVal = callback.call(context, v, key);
  42727. isPrimary ? (newVisual = newVal) : (newVisual[key] = newVal);
  42728. });
  42729. return newVisual;
  42730. };
  42731. /**
  42732. * @public
  42733. * @param {Object} obj
  42734. * @return {Object} new object containers visual values.
  42735. * If no visuals, return null.
  42736. */
  42737. VisualMapping.retrieveVisuals = function (obj) {
  42738. var ret = {};
  42739. var hasVisual;
  42740. obj && each$9(visualHandlers, function (h, visualType) {
  42741. if (obj.hasOwnProperty(visualType)) {
  42742. ret[visualType] = obj[visualType];
  42743. hasVisual = true;
  42744. }
  42745. });
  42746. return hasVisual ? ret : null;
  42747. };
  42748. /**
  42749. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  42750. *
  42751. * @public
  42752. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  42753. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  42754. * @return {Array.<string>} Sorted visual types.
  42755. */
  42756. VisualMapping.prepareVisualTypes = function (visualTypes) {
  42757. if (isObject$5(visualTypes)) {
  42758. var types = [];
  42759. each$9(visualTypes, function (item, type) {
  42760. types.push(type);
  42761. });
  42762. visualTypes = types;
  42763. }
  42764. else if (isArray(visualTypes)) {
  42765. visualTypes = visualTypes.slice();
  42766. }
  42767. else {
  42768. return [];
  42769. }
  42770. visualTypes.sort(function (type1, type2) {
  42771. // color should be front of colorSaturation, colorAlpha, ...
  42772. // symbol and symbolSize do not matter.
  42773. return (type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0)
  42774. ? 1 : -1;
  42775. });
  42776. return visualTypes;
  42777. };
  42778. /**
  42779. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  42780. * Other visuals are only depends on themself.
  42781. *
  42782. * @public
  42783. * @param {string} visualType1
  42784. * @param {string} visualType2
  42785. * @return {boolean}
  42786. */
  42787. VisualMapping.dependsOn = function (visualType1, visualType2) {
  42788. return visualType2 === 'color'
  42789. ? !!(visualType1 && visualType1.indexOf(visualType2) === 0)
  42790. : visualType1 === visualType2;
  42791. };
  42792. /**
  42793. * @param {number} value
  42794. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  42795. * Always from small to big.
  42796. * @param {boolean} [findClosestWhenOutside=false]
  42797. * @return {number} index
  42798. */
  42799. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  42800. var possibleI;
  42801. var abs = Infinity;
  42802. // value has the higher priority.
  42803. for (var i = 0, len = pieceList.length; i < len; i++) {
  42804. var pieceValue = pieceList[i].value;
  42805. if (pieceValue != null) {
  42806. if (pieceValue === value
  42807. // FIXME
  42808. // It is supposed to compare value according to value type of dimension,
  42809. // but currently value type can exactly be string or number.
  42810. // Compromise for numeric-like string (like '12'), especially
  42811. // in the case that visualMap.categories is ['22', '33'].
  42812. || (typeof pieceValue === 'string' && pieceValue === value + '')
  42813. ) {
  42814. return i;
  42815. }
  42816. findClosestWhenOutside && updatePossible(pieceValue, i);
  42817. }
  42818. }
  42819. for (var i = 0, len = pieceList.length; i < len; i++) {
  42820. var piece = pieceList[i];
  42821. var interval = piece.interval;
  42822. var close = piece.close;
  42823. if (interval) {
  42824. if (interval[0] === -Infinity) {
  42825. if (littleThan(close[1], value, interval[1])) {
  42826. return i;
  42827. }
  42828. }
  42829. else if (interval[1] === Infinity) {
  42830. if (littleThan(close[0], interval[0], value)) {
  42831. return i;
  42832. }
  42833. }
  42834. else if (
  42835. littleThan(close[0], interval[0], value)
  42836. && littleThan(close[1], value, interval[1])
  42837. ) {
  42838. return i;
  42839. }
  42840. findClosestWhenOutside && updatePossible(interval[0], i);
  42841. findClosestWhenOutside && updatePossible(interval[1], i);
  42842. }
  42843. }
  42844. if (findClosestWhenOutside) {
  42845. return value === Infinity
  42846. ? pieceList.length - 1
  42847. : value === -Infinity
  42848. ? 0
  42849. : possibleI;
  42850. }
  42851. function updatePossible(val, index) {
  42852. var newAbs = Math.abs(val - value);
  42853. if (newAbs < abs) {
  42854. abs = newAbs;
  42855. possibleI = index;
  42856. }
  42857. }
  42858. };
  42859. function littleThan(close, a, b) {
  42860. return close ? a <= b : a < b;
  42861. }
  42862. /*
  42863. * Licensed to the Apache Software Foundation (ASF) under one
  42864. * or more contributor license agreements. See the NOTICE file
  42865. * distributed with this work for additional information
  42866. * regarding copyright ownership. The ASF licenses this file
  42867. * to you under the Apache License, Version 2.0 (the
  42868. * "License"); you may not use this file except in compliance
  42869. * with the License. You may obtain a copy of the License at
  42870. *
  42871. * http://www.apache.org/licenses/LICENSE-2.0
  42872. *
  42873. * Unless required by applicable law or agreed to in writing,
  42874. * software distributed under the License is distributed on an
  42875. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42876. * KIND, either express or implied. See the License for the
  42877. * specific language governing permissions and limitations
  42878. * under the License.
  42879. */
  42880. var isArray$2 = isArray;
  42881. var ITEM_STYLE_NORMAL = 'itemStyle';
  42882. var treemapVisual = {
  42883. seriesType: 'treemap',
  42884. reset: function (seriesModel, ecModel, api, payload) {
  42885. var tree = seriesModel.getData().tree;
  42886. var root = tree.root;
  42887. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  42888. if (root.isRemoved()) {
  42889. return;
  42890. }
  42891. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  42892. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  42893. });
  42894. travelTree(
  42895. root, // Visual should calculate from tree root but not view root.
  42896. {},
  42897. levelItemStyles,
  42898. seriesItemStyleModel,
  42899. seriesModel.getViewRoot().getAncestors(),
  42900. seriesModel
  42901. );
  42902. }
  42903. };
  42904. function travelTree(
  42905. node, designatedVisual, levelItemStyles, seriesItemStyleModel,
  42906. viewRootAncestors, seriesModel
  42907. ) {
  42908. var nodeModel = node.getModel();
  42909. var nodeLayout = node.getLayout();
  42910. // Optimize
  42911. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  42912. return;
  42913. }
  42914. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  42915. var levelItemStyle = levelItemStyles[node.depth];
  42916. var visuals = buildVisuals(
  42917. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  42918. );
  42919. // calculate border color
  42920. var borderColor = nodeItemStyleModel.get('borderColor');
  42921. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  42922. var thisNodeColor;
  42923. if (borderColorSaturation != null) {
  42924. // For performance, do not always execute 'calculateColor'.
  42925. thisNodeColor = calculateColor(visuals, node);
  42926. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  42927. }
  42928. node.setVisual('borderColor', borderColor);
  42929. var viewChildren = node.viewChildren;
  42930. if (!viewChildren || !viewChildren.length) {
  42931. thisNodeColor = calculateColor(visuals, node);
  42932. // Apply visual to this node.
  42933. node.setVisual('color', thisNodeColor);
  42934. }
  42935. else {
  42936. var mapping = buildVisualMapping(
  42937. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  42938. );
  42939. // Designate visual to children.
  42940. each$1(viewChildren, function (child, index) {
  42941. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  42942. if (child.depth >= viewRootAncestors.length
  42943. || child === viewRootAncestors[child.depth]
  42944. ) {
  42945. var childVisual = mapVisual$1(
  42946. nodeModel, visuals, child, index, mapping, seriesModel
  42947. );
  42948. travelTree(
  42949. child, childVisual, levelItemStyles, seriesItemStyleModel,
  42950. viewRootAncestors, seriesModel
  42951. );
  42952. }
  42953. });
  42954. }
  42955. }
  42956. function buildVisuals(
  42957. nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel
  42958. ) {
  42959. var visuals = extend({}, designatedVisual);
  42960. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  42961. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  42962. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  42963. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  42964. val == null && (val = designatedVisual[visualName]);
  42965. val == null && (val = seriesItemStyleModel.get(visualName));
  42966. val != null && (visuals[visualName] = val);
  42967. });
  42968. return visuals;
  42969. }
  42970. function calculateColor(visuals) {
  42971. var color = getValueVisualDefine(visuals, 'color');
  42972. if (color) {
  42973. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  42974. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  42975. if (colorSaturation) {
  42976. color = modifyHSL(color, null, null, colorSaturation);
  42977. }
  42978. if (colorAlpha) {
  42979. color = modifyAlpha(color, colorAlpha);
  42980. }
  42981. return color;
  42982. }
  42983. }
  42984. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  42985. return thisNodeColor != null
  42986. ? modifyHSL(thisNodeColor, null, null, borderColorSaturation)
  42987. : null;
  42988. }
  42989. function getValueVisualDefine(visuals, name) {
  42990. var value = visuals[name];
  42991. if (value != null && value !== 'none') {
  42992. return value;
  42993. }
  42994. }
  42995. function buildVisualMapping(
  42996. node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren
  42997. ) {
  42998. if (!viewChildren || !viewChildren.length) {
  42999. return;
  43000. }
  43001. var rangeVisual = getRangeVisual(nodeModel, 'color')
  43002. || (
  43003. visuals.color != null
  43004. && visuals.color !== 'none'
  43005. && (
  43006. getRangeVisual(nodeModel, 'colorAlpha')
  43007. || getRangeVisual(nodeModel, 'colorSaturation')
  43008. )
  43009. );
  43010. if (!rangeVisual) {
  43011. return;
  43012. }
  43013. var visualMin = nodeModel.get('visualMin');
  43014. var visualMax = nodeModel.get('visualMax');
  43015. var dataExtent = nodeLayout.dataExtent.slice();
  43016. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  43017. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  43018. var colorMappingBy = nodeModel.get('colorMappingBy');
  43019. var opt = {
  43020. type: rangeVisual.name,
  43021. dataExtent: dataExtent,
  43022. visual: rangeVisual.range
  43023. };
  43024. if (opt.type === 'color'
  43025. && (colorMappingBy === 'index' || colorMappingBy === 'id')
  43026. ) {
  43027. opt.mappingMethod = 'category';
  43028. opt.loop = true;
  43029. // categories is ordinal, so do not set opt.categories.
  43030. }
  43031. else {
  43032. opt.mappingMethod = 'linear';
  43033. }
  43034. var mapping = new VisualMapping(opt);
  43035. mapping.__drColorMappingBy = colorMappingBy;
  43036. return mapping;
  43037. }
  43038. // Notice: If we dont have the attribute 'colorRange', but only use
  43039. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  43040. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  43041. // this problem will be encountered:
  43042. // If a level-1 node dont have children, and its siblings has children,
  43043. // and colorRange is set on level-1, then the node can not be colored.
  43044. // So we separate 'colorRange' and 'color' to different attributes.
  43045. function getRangeVisual(nodeModel, name) {
  43046. // 'colorRange', 'colorARange', 'colorSRange'.
  43047. // If not exsits on this node, fetch from levels and series.
  43048. var range = nodeModel.get(name);
  43049. return (isArray$2(range) && range.length) ? {name: name, range: range} : null;
  43050. }
  43051. function mapVisual$1(nodeModel, visuals, child, index, mapping, seriesModel) {
  43052. var childVisuals = extend({}, visuals);
  43053. if (mapping) {
  43054. var mappingType = mapping.type;
  43055. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  43056. var value =
  43057. colorMappingBy === 'index'
  43058. ? index
  43059. : colorMappingBy === 'id'
  43060. ? seriesModel.mapIdToIndex(child.getId())
  43061. : child.getValue(nodeModel.get('visualDimension'));
  43062. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  43063. }
  43064. return childVisuals;
  43065. }
  43066. /*
  43067. * Licensed to the Apache Software Foundation (ASF) under one
  43068. * or more contributor license agreements. See the NOTICE file
  43069. * distributed with this work for additional information
  43070. * regarding copyright ownership. The ASF licenses this file
  43071. * to you under the Apache License, Version 2.0 (the
  43072. * "License"); you may not use this file except in compliance
  43073. * with the License. You may obtain a copy of the License at
  43074. *
  43075. * http://www.apache.org/licenses/LICENSE-2.0
  43076. *
  43077. * Unless required by applicable law or agreed to in writing,
  43078. * software distributed under the License is distributed on an
  43079. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43080. * KIND, either express or implied. See the License for the
  43081. * specific language governing permissions and limitations
  43082. * under the License.
  43083. */
  43084. /*
  43085. * The treemap layout implementation references to the treemap
  43086. * layout of d3.js (d3/src/layout/treemap.js in v3). The use of
  43087. * the source code of this file is also subject to the terms
  43088. * and consitions of its license (BSD-3Clause, see
  43089. * <echarts/src/licenses/LICENSE-d3>).
  43090. */
  43091. var mathMax$4 = Math.max;
  43092. var mathMin$4 = Math.min;
  43093. var retrieveValue = retrieve;
  43094. var each$10 = each$1;
  43095. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  43096. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  43097. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  43098. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  43099. /**
  43100. * @public
  43101. */
  43102. var treemapLayout = {
  43103. seriesType: 'treemap',
  43104. reset: function (seriesModel, ecModel, api, payload) {
  43105. // Layout result in each node:
  43106. // {x, y, width, height, area, borderWidth}
  43107. var ecWidth = api.getWidth();
  43108. var ecHeight = api.getHeight();
  43109. var seriesOption = seriesModel.option;
  43110. var layoutInfo = getLayoutRect(
  43111. seriesModel.getBoxLayoutParams(),
  43112. {
  43113. width: api.getWidth(),
  43114. height: api.getHeight()
  43115. }
  43116. );
  43117. var size = seriesOption.size || []; // Compatible with ec2.
  43118. var containerWidth = parsePercent$1(
  43119. retrieveValue(layoutInfo.width, size[0]),
  43120. ecWidth
  43121. );
  43122. var containerHeight = parsePercent$1(
  43123. retrieveValue(layoutInfo.height, size[1]),
  43124. ecHeight
  43125. );
  43126. // Fetch payload info.
  43127. var payloadType = payload && payload.type;
  43128. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43129. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  43130. var rootRect = (payloadType === 'treemapRender' || payloadType === 'treemapMove')
  43131. ? payload.rootRect : null;
  43132. var viewRoot = seriesModel.getViewRoot();
  43133. var viewAbovePath = getPathToRoot(viewRoot);
  43134. if (payloadType !== 'treemapMove') {
  43135. var rootSize = payloadType === 'treemapZoomToNode'
  43136. ? estimateRootSize(
  43137. seriesModel, targetInfo, viewRoot, containerWidth, containerHeight
  43138. )
  43139. : rootRect
  43140. ? [rootRect.width, rootRect.height]
  43141. : [containerWidth, containerHeight];
  43142. var sort = seriesOption.sort;
  43143. if (sort && sort !== 'asc' && sort !== 'desc') {
  43144. sort = 'desc';
  43145. }
  43146. var options = {
  43147. squareRatio: seriesOption.squareRatio,
  43148. sort: sort,
  43149. leafDepth: seriesOption.leafDepth
  43150. };
  43151. // layout should be cleared because using updateView but not update.
  43152. viewRoot.hostTree.clearLayouts();
  43153. // TODO
  43154. // optimize: if out of view clip, do not layout.
  43155. // But take care that if do not render node out of view clip,
  43156. // how to calculate start po
  43157. var viewRootLayout = {
  43158. x: 0, y: 0,
  43159. width: rootSize[0], height: rootSize[1],
  43160. area: rootSize[0] * rootSize[1]
  43161. };
  43162. viewRoot.setLayout(viewRootLayout);
  43163. squarify(viewRoot, options, false, 0);
  43164. // Supplement layout.
  43165. var viewRootLayout = viewRoot.getLayout();
  43166. each$10(viewAbovePath, function (node, index) {
  43167. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  43168. node.setLayout(extend(
  43169. {dataExtent: [childValue, childValue], borderWidth: 0, upperHeight: 0},
  43170. viewRootLayout
  43171. ));
  43172. });
  43173. }
  43174. var treeRoot = seriesModel.getData().tree.root;
  43175. treeRoot.setLayout(
  43176. calculateRootPosition(layoutInfo, rootRect, targetInfo),
  43177. true
  43178. );
  43179. seriesModel.setLayoutInfo(layoutInfo);
  43180. // FIXME
  43181. // 现在没有clip功能,暂时取ec高宽。
  43182. prunning(
  43183. treeRoot,
  43184. // Transform to base element coordinate system.
  43185. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight),
  43186. viewAbovePath,
  43187. viewRoot,
  43188. 0
  43189. );
  43190. }
  43191. };
  43192. /**
  43193. * Layout treemap with squarify algorithm.
  43194. * @see https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf
  43195. * The implementation references to the treemap layout of d3.js.
  43196. * See the license statement at the head of this file.
  43197. *
  43198. * @protected
  43199. * @param {module:echarts/data/Tree~TreeNode} node
  43200. * @param {Object} options
  43201. * @param {string} options.sort 'asc' or 'desc'
  43202. * @param {number} options.squareRatio
  43203. * @param {boolean} hideChildren
  43204. * @param {number} depth
  43205. */
  43206. function squarify(node, options, hideChildren, depth) {
  43207. var width;
  43208. var height;
  43209. if (node.isRemoved()) {
  43210. return;
  43211. }
  43212. var thisLayout = node.getLayout();
  43213. width = thisLayout.width;
  43214. height = thisLayout.height;
  43215. // Considering border and gap
  43216. var nodeModel = node.getModel();
  43217. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  43218. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  43219. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  43220. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  43221. var layoutOffset = borderWidth - halfGapWidth;
  43222. var layoutOffsetUpper = upperHeight - halfGapWidth;
  43223. var nodeModel = node.getModel();
  43224. node.setLayout({
  43225. borderWidth: borderWidth,
  43226. upperHeight: upperHeight,
  43227. upperLabelHeight: upperLabelHeight
  43228. }, true);
  43229. width = mathMax$4(width - 2 * layoutOffset, 0);
  43230. height = mathMax$4(height - layoutOffset - layoutOffsetUpper, 0);
  43231. var totalArea = width * height;
  43232. var viewChildren = initChildren(
  43233. node, nodeModel, totalArea, options, hideChildren, depth
  43234. );
  43235. if (!viewChildren.length) {
  43236. return;
  43237. }
  43238. var rect = {x: layoutOffset, y: layoutOffsetUpper, width: width, height: height};
  43239. var rowFixedLength = mathMin$4(width, height);
  43240. var best = Infinity; // the best row score so far
  43241. var row = [];
  43242. row.area = 0;
  43243. for (var i = 0, len = viewChildren.length; i < len;) {
  43244. var child = viewChildren[i];
  43245. row.push(child);
  43246. row.area += child.getLayout().area;
  43247. var score = worst(row, rowFixedLength, options.squareRatio);
  43248. // continue with this orientation
  43249. if (score <= best) {
  43250. i++;
  43251. best = score;
  43252. }
  43253. // abort, and try a different orientation
  43254. else {
  43255. row.area -= row.pop().getLayout().area;
  43256. position(row, rowFixedLength, rect, halfGapWidth, false);
  43257. rowFixedLength = mathMin$4(rect.width, rect.height);
  43258. row.length = row.area = 0;
  43259. best = Infinity;
  43260. }
  43261. }
  43262. if (row.length) {
  43263. position(row, rowFixedLength, rect, halfGapWidth, true);
  43264. }
  43265. if (!hideChildren) {
  43266. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  43267. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  43268. hideChildren = true;
  43269. }
  43270. }
  43271. for (var i = 0, len = viewChildren.length; i < len; i++) {
  43272. squarify(viewChildren[i], options, hideChildren, depth + 1);
  43273. }
  43274. }
  43275. /**
  43276. * Set area to each child, and calculate data extent for visual coding.
  43277. */
  43278. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  43279. var viewChildren = node.children || [];
  43280. var orderBy = options.sort;
  43281. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  43282. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth;
  43283. // leafDepth has higher priority.
  43284. if (hideChildren && !overLeafDepth) {
  43285. return (node.viewChildren = []);
  43286. }
  43287. // Sort children, order by desc.
  43288. viewChildren = filter(viewChildren, function (child) {
  43289. return !child.isRemoved();
  43290. });
  43291. sort$1(viewChildren, orderBy);
  43292. var info = statistic(nodeModel, viewChildren, orderBy);
  43293. if (info.sum === 0) {
  43294. return (node.viewChildren = []);
  43295. }
  43296. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  43297. if (info.sum === 0) {
  43298. return (node.viewChildren = []);
  43299. }
  43300. // Set area to each child.
  43301. for (var i = 0, len = viewChildren.length; i < len; i++) {
  43302. var area = viewChildren[i].getValue() / info.sum * totalArea;
  43303. // Do not use setLayout({...}, true), because it is needed to clear last layout.
  43304. viewChildren[i].setLayout({area: area});
  43305. }
  43306. if (overLeafDepth) {
  43307. viewChildren.length && node.setLayout({isLeafRoot: true}, true);
  43308. viewChildren.length = 0;
  43309. }
  43310. node.viewChildren = viewChildren;
  43311. node.setLayout({dataExtent: info.dataExtent}, true);
  43312. return viewChildren;
  43313. }
  43314. /**
  43315. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  43316. */
  43317. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  43318. // visibleMin is not supported yet when no option.sort.
  43319. if (!orderBy) {
  43320. return sum;
  43321. }
  43322. var visibleMin = nodeModel.get('visibleMin');
  43323. var len = orderedChildren.length;
  43324. var deletePoint = len;
  43325. // Always travel from little value to big value.
  43326. for (var i = len - 1; i >= 0; i--) {
  43327. var value = orderedChildren[
  43328. orderBy === 'asc' ? len - i - 1 : i
  43329. ].getValue();
  43330. if (value / sum * totalArea < visibleMin) {
  43331. deletePoint = i;
  43332. sum -= value;
  43333. }
  43334. }
  43335. orderBy === 'asc'
  43336. ? orderedChildren.splice(0, len - deletePoint)
  43337. : orderedChildren.splice(deletePoint, len - deletePoint);
  43338. return sum;
  43339. }
  43340. /**
  43341. * Sort
  43342. */
  43343. function sort$1(viewChildren, orderBy) {
  43344. if (orderBy) {
  43345. viewChildren.sort(function (a, b) {
  43346. var diff = orderBy === 'asc'
  43347. ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  43348. return diff === 0
  43349. ? (orderBy === 'asc'
  43350. ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex
  43351. )
  43352. : diff;
  43353. });
  43354. }
  43355. return viewChildren;
  43356. }
  43357. /**
  43358. * Statistic
  43359. */
  43360. function statistic(nodeModel, children, orderBy) {
  43361. // Calculate sum.
  43362. var sum = 0;
  43363. for (var i = 0, len = children.length; i < len; i++) {
  43364. sum += children[i].getValue();
  43365. }
  43366. // Statistic data extent for latter visual coding.
  43367. // Notice: data extent should be calculate based on raw children
  43368. // but not filtered view children, otherwise visual mapping will not
  43369. // be stable when zoom (where children is filtered by visibleMin).
  43370. var dimension = nodeModel.get('visualDimension');
  43371. var dataExtent;
  43372. // The same as area dimension.
  43373. if (!children || !children.length) {
  43374. dataExtent = [NaN, NaN];
  43375. }
  43376. else if (dimension === 'value' && orderBy) {
  43377. dataExtent = [
  43378. children[children.length - 1].getValue(),
  43379. children[0].getValue()
  43380. ];
  43381. orderBy === 'asc' && dataExtent.reverse();
  43382. }
  43383. // Other dimension.
  43384. else {
  43385. var dataExtent = [Infinity, -Infinity];
  43386. each$10(children, function (child) {
  43387. var value = child.getValue(dimension);
  43388. value < dataExtent[0] && (dataExtent[0] = value);
  43389. value > dataExtent[1] && (dataExtent[1] = value);
  43390. });
  43391. }
  43392. return {sum: sum, dataExtent: dataExtent};
  43393. }
  43394. /**
  43395. * Computes the score for the specified row,
  43396. * as the worst aspect ratio.
  43397. */
  43398. function worst(row, rowFixedLength, ratio) {
  43399. var areaMax = 0;
  43400. var areaMin = Infinity;
  43401. for (var i = 0, area, len = row.length; i < len; i++) {
  43402. area = row[i].getLayout().area;
  43403. if (area) {
  43404. area < areaMin && (areaMin = area);
  43405. area > areaMax && (areaMax = area);
  43406. }
  43407. }
  43408. var squareArea = row.area * row.area;
  43409. var f = rowFixedLength * rowFixedLength * ratio;
  43410. return squareArea
  43411. ? mathMax$4(
  43412. (f * areaMax) / squareArea,
  43413. squareArea / (f * areaMin)
  43414. )
  43415. : Infinity;
  43416. }
  43417. /**
  43418. * Positions the specified row of nodes. Modifies `rect`.
  43419. */
  43420. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  43421. // When rowFixedLength === rect.width,
  43422. // it is horizontal subdivision,
  43423. // rowFixedLength is the width of the subdivision,
  43424. // rowOtherLength is the height of the subdivision,
  43425. // and nodes will be positioned from left to right.
  43426. // wh[idx0WhenH] means: when horizontal,
  43427. // wh[idx0WhenH] => wh[0] => 'width'.
  43428. // xy[idx1WhenH] => xy[1] => 'y'.
  43429. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  43430. var idx1WhenH = 1 - idx0WhenH;
  43431. var xy = ['x', 'y'];
  43432. var wh = ['width', 'height'];
  43433. var last = rect[xy[idx0WhenH]];
  43434. var rowOtherLength = rowFixedLength
  43435. ? row.area / rowFixedLength : 0;
  43436. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  43437. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  43438. }
  43439. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  43440. var node = row[i];
  43441. var nodeLayout = {};
  43442. var step = rowOtherLength
  43443. ? node.getLayout().area / rowOtherLength : 0;
  43444. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$4(rowOtherLength - 2 * halfGapWidth, 0);
  43445. // We use Math.max/min to avoid negative width/height when considering gap width.
  43446. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  43447. var modWH = (i === rowLen - 1 || remain < step) ? remain : step;
  43448. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$4(modWH - 2 * halfGapWidth, 0);
  43449. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$4(halfGapWidth, wh1 / 2);
  43450. nodeLayout[xy[idx0WhenH]] = last + mathMin$4(halfGapWidth, wh0 / 2);
  43451. last += modWH;
  43452. node.setLayout(nodeLayout, true);
  43453. }
  43454. rect[xy[idx1WhenH]] += rowOtherLength;
  43455. rect[wh[idx1WhenH]] -= rowOtherLength;
  43456. }
  43457. // Return [containerWidth, containerHeight] as defualt.
  43458. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  43459. // If targetInfo.node exists, we zoom to the node,
  43460. // so estimate whold width and heigth by target node.
  43461. var currNode = (targetInfo || {}).node;
  43462. var defaultSize = [containerWidth, containerHeight];
  43463. if (!currNode || currNode === viewRoot) {
  43464. return defaultSize;
  43465. }
  43466. var parent;
  43467. var viewArea = containerWidth * containerHeight;
  43468. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  43469. while (parent = currNode.parentNode) { // jshint ignore:line
  43470. var sum = 0;
  43471. var siblings = parent.children;
  43472. for (var i = 0, len = siblings.length; i < len; i++) {
  43473. sum += siblings[i].getValue();
  43474. }
  43475. var currNodeValue = currNode.getValue();
  43476. if (currNodeValue === 0) {
  43477. return defaultSize;
  43478. }
  43479. area *= sum / currNodeValue;
  43480. // Considering border, suppose aspect ratio is 1.
  43481. var parentModel = parent.getModel();
  43482. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  43483. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  43484. area += 4 * borderWidth * borderWidth
  43485. + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  43486. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  43487. currNode = parent;
  43488. }
  43489. area < viewArea && (area = viewArea);
  43490. var scale = Math.pow(area / viewArea, 0.5);
  43491. return [containerWidth * scale, containerHeight * scale];
  43492. }
  43493. // Root postion base on coord of containerGroup
  43494. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  43495. if (rootRect) {
  43496. return {x: rootRect.x, y: rootRect.y};
  43497. }
  43498. var defaultPosition = {x: 0, y: 0};
  43499. if (!targetInfo) {
  43500. return defaultPosition;
  43501. }
  43502. // If targetInfo is fetched by 'retrieveTargetInfo',
  43503. // old tree and new tree are the same tree,
  43504. // so the node still exists and we can visit it.
  43505. var targetNode = targetInfo.node;
  43506. var layout = targetNode.getLayout();
  43507. if (!layout) {
  43508. return defaultPosition;
  43509. }
  43510. // Transform coord from local to container.
  43511. var targetCenter = [layout.width / 2, layout.height / 2];
  43512. var node = targetNode;
  43513. while (node) {
  43514. var nodeLayout = node.getLayout();
  43515. targetCenter[0] += nodeLayout.x;
  43516. targetCenter[1] += nodeLayout.y;
  43517. node = node.parentNode;
  43518. }
  43519. return {
  43520. x: layoutInfo.width / 2 - targetCenter[0],
  43521. y: layoutInfo.height / 2 - targetCenter[1]
  43522. };
  43523. }
  43524. // Mark nodes visible for prunning when visual coding and rendering.
  43525. // Prunning depends on layout and root position, so we have to do it after layout.
  43526. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  43527. var nodeLayout = node.getLayout();
  43528. var nodeInViewAbovePath = viewAbovePath[depth];
  43529. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  43530. if (
  43531. (nodeInViewAbovePath && !isAboveViewRoot)
  43532. || (depth === viewAbovePath.length && node !== viewRoot)
  43533. ) {
  43534. return;
  43535. }
  43536. node.setLayout({
  43537. // isInView means: viewRoot sub tree + viewAbovePath
  43538. isInView: true,
  43539. // invisible only means: outside view clip so that the node can not
  43540. // see but still layout for animation preparation but not render.
  43541. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  43542. isAboveViewRoot: isAboveViewRoot
  43543. }, true);
  43544. // Transform to child coordinate.
  43545. var childClipRect = new BoundingRect(
  43546. clipRect.x - nodeLayout.x,
  43547. clipRect.y - nodeLayout.y,
  43548. clipRect.width,
  43549. clipRect.height
  43550. );
  43551. each$10(node.viewChildren || [], function (child) {
  43552. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  43553. });
  43554. }
  43555. function getUpperLabelHeight(model) {
  43556. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  43557. }
  43558. /*
  43559. * Licensed to the Apache Software Foundation (ASF) under one
  43560. * or more contributor license agreements. See the NOTICE file
  43561. * distributed with this work for additional information
  43562. * regarding copyright ownership. The ASF licenses this file
  43563. * to you under the Apache License, Version 2.0 (the
  43564. * "License"); you may not use this file except in compliance
  43565. * with the License. You may obtain a copy of the License at
  43566. *
  43567. * http://www.apache.org/licenses/LICENSE-2.0
  43568. *
  43569. * Unless required by applicable law or agreed to in writing,
  43570. * software distributed under the License is distributed on an
  43571. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43572. * KIND, either express or implied. See the License for the
  43573. * specific language governing permissions and limitations
  43574. * under the License.
  43575. */
  43576. registerVisual(treemapVisual);
  43577. registerLayout(treemapLayout);
  43578. /*
  43579. * Licensed to the Apache Software Foundation (ASF) under one
  43580. * or more contributor license agreements. See the NOTICE file
  43581. * distributed with this work for additional information
  43582. * regarding copyright ownership. The ASF licenses this file
  43583. * to you under the Apache License, Version 2.0 (the
  43584. * "License"); you may not use this file except in compliance
  43585. * with the License. You may obtain a copy of the License at
  43586. *
  43587. * http://www.apache.org/licenses/LICENSE-2.0
  43588. *
  43589. * Unless required by applicable law or agreed to in writing,
  43590. * software distributed under the License is distributed on an
  43591. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43592. * KIND, either express or implied. See the License for the
  43593. * specific language governing permissions and limitations
  43594. * under the License.
  43595. */
  43596. /**
  43597. * Graph data structure
  43598. *
  43599. * @module echarts/data/Graph
  43600. * @author Yi Shen(https://www.github.com/pissang)
  43601. */
  43602. // id may be function name of Object, add a prefix to avoid this problem.
  43603. function generateNodeKey (id) {
  43604. return '_EC_' + id;
  43605. }
  43606. /**
  43607. * @alias module:echarts/data/Graph
  43608. * @constructor
  43609. * @param {boolean} directed
  43610. */
  43611. var Graph = function(directed) {
  43612. /**
  43613. * 是否是有向图
  43614. * @type {boolean}
  43615. * @private
  43616. */
  43617. this._directed = directed || false;
  43618. /**
  43619. * @type {Array.<module:echarts/data/Graph.Node>}
  43620. * @readOnly
  43621. */
  43622. this.nodes = [];
  43623. /**
  43624. * @type {Array.<module:echarts/data/Graph.Edge>}
  43625. * @readOnly
  43626. */
  43627. this.edges = [];
  43628. /**
  43629. * @type {Object.<string, module:echarts/data/Graph.Node>}
  43630. * @private
  43631. */
  43632. this._nodesMap = {};
  43633. /**
  43634. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  43635. * @private
  43636. */
  43637. this._edgesMap = {};
  43638. /**
  43639. * @type {module:echarts/data/List}
  43640. * @readOnly
  43641. */
  43642. this.data;
  43643. /**
  43644. * @type {module:echarts/data/List}
  43645. * @readOnly
  43646. */
  43647. this.edgeData;
  43648. };
  43649. var graphProto = Graph.prototype;
  43650. /**
  43651. * @type {string}
  43652. */
  43653. graphProto.type = 'graph';
  43654. /**
  43655. * If is directed graph
  43656. * @return {boolean}
  43657. */
  43658. graphProto.isDirected = function () {
  43659. return this._directed;
  43660. };
  43661. /**
  43662. * Add a new node
  43663. * @param {string} id
  43664. * @param {number} [dataIndex]
  43665. */
  43666. graphProto.addNode = function (id, dataIndex) {
  43667. id = id || ('' + dataIndex);
  43668. var nodesMap = this._nodesMap;
  43669. if (nodesMap[generateNodeKey(id)]) {
  43670. if (__DEV__) {
  43671. console.error('Graph nodes have duplicate name or id');
  43672. }
  43673. return;
  43674. }
  43675. var node = new Node(id, dataIndex);
  43676. node.hostGraph = this;
  43677. this.nodes.push(node);
  43678. nodesMap[generateNodeKey(id)] = node;
  43679. return node;
  43680. };
  43681. /**
  43682. * Get node by data index
  43683. * @param {number} dataIndex
  43684. * @return {module:echarts/data/Graph~Node}
  43685. */
  43686. graphProto.getNodeByIndex = function (dataIndex) {
  43687. var rawIdx = this.data.getRawIndex(dataIndex);
  43688. return this.nodes[rawIdx];
  43689. };
  43690. /**
  43691. * Get node by id
  43692. * @param {string} id
  43693. * @return {module:echarts/data/Graph.Node}
  43694. */
  43695. graphProto.getNodeById = function (id) {
  43696. return this._nodesMap[generateNodeKey(id)];
  43697. };
  43698. /**
  43699. * Add a new edge
  43700. * @param {number|string|module:echarts/data/Graph.Node} n1
  43701. * @param {number|string|module:echarts/data/Graph.Node} n2
  43702. * @param {number} [dataIndex=-1]
  43703. * @return {module:echarts/data/Graph.Edge}
  43704. */
  43705. graphProto.addEdge = function (n1, n2, dataIndex) {
  43706. var nodesMap = this._nodesMap;
  43707. var edgesMap = this._edgesMap;
  43708. // PNEDING
  43709. if (typeof n1 === 'number') {
  43710. n1 = this.nodes[n1];
  43711. }
  43712. if (typeof n2 === 'number') {
  43713. n2 = this.nodes[n2];
  43714. }
  43715. if (!Node.isInstance(n1)) {
  43716. n1 = nodesMap[generateNodeKey(n1)];
  43717. }
  43718. if (!Node.isInstance(n2)) {
  43719. n2 = nodesMap[generateNodeKey(n2)];
  43720. }
  43721. if (!n1 || !n2) {
  43722. return;
  43723. }
  43724. var key = n1.id + '-' + n2.id;
  43725. // PENDING
  43726. if (edgesMap[key]) {
  43727. return;
  43728. }
  43729. var edge = new Edge(n1, n2, dataIndex);
  43730. edge.hostGraph = this;
  43731. if (this._directed) {
  43732. n1.outEdges.push(edge);
  43733. n2.inEdges.push(edge);
  43734. }
  43735. n1.edges.push(edge);
  43736. if (n1 !== n2) {
  43737. n2.edges.push(edge);
  43738. }
  43739. this.edges.push(edge);
  43740. edgesMap[key] = edge;
  43741. return edge;
  43742. };
  43743. /**
  43744. * Get edge by data index
  43745. * @param {number} dataIndex
  43746. * @return {module:echarts/data/Graph~Node}
  43747. */
  43748. graphProto.getEdgeByIndex = function (dataIndex) {
  43749. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  43750. return this.edges[rawIdx];
  43751. };
  43752. /**
  43753. * Get edge by two linked nodes
  43754. * @param {module:echarts/data/Graph.Node|string} n1
  43755. * @param {module:echarts/data/Graph.Node|string} n2
  43756. * @return {module:echarts/data/Graph.Edge}
  43757. */
  43758. graphProto.getEdge = function (n1, n2) {
  43759. if (Node.isInstance(n1)) {
  43760. n1 = n1.id;
  43761. }
  43762. if (Node.isInstance(n2)) {
  43763. n2 = n2.id;
  43764. }
  43765. var edgesMap = this._edgesMap;
  43766. if (this._directed) {
  43767. return edgesMap[n1 + '-' + n2];
  43768. } else {
  43769. return edgesMap[n1 + '-' + n2]
  43770. || edgesMap[n2 + '-' + n1];
  43771. }
  43772. };
  43773. /**
  43774. * Iterate all nodes
  43775. * @param {Function} cb
  43776. * @param {*} [context]
  43777. */
  43778. graphProto.eachNode = function (cb, context) {
  43779. var nodes = this.nodes;
  43780. var len = nodes.length;
  43781. for (var i = 0; i < len; i++) {
  43782. if (nodes[i].dataIndex >= 0) {
  43783. cb.call(context, nodes[i], i);
  43784. }
  43785. }
  43786. };
  43787. /**
  43788. * Iterate all edges
  43789. * @param {Function} cb
  43790. * @param {*} [context]
  43791. */
  43792. graphProto.eachEdge = function (cb, context) {
  43793. var edges = this.edges;
  43794. var len = edges.length;
  43795. for (var i = 0; i < len; i++) {
  43796. if (edges[i].dataIndex >= 0
  43797. && edges[i].node1.dataIndex >= 0
  43798. && edges[i].node2.dataIndex >= 0
  43799. ) {
  43800. cb.call(context, edges[i], i);
  43801. }
  43802. }
  43803. };
  43804. /**
  43805. * Breadth first traverse
  43806. * @param {Function} cb
  43807. * @param {module:echarts/data/Graph.Node} startNode
  43808. * @param {string} [direction='none'] 'none'|'in'|'out'
  43809. * @param {*} [context]
  43810. */
  43811. graphProto.breadthFirstTraverse = function (
  43812. cb, startNode, direction, context
  43813. ) {
  43814. if (!Node.isInstance(startNode)) {
  43815. startNode = this._nodesMap[generateNodeKey(startNode)];
  43816. }
  43817. if (!startNode) {
  43818. return;
  43819. }
  43820. var edgeType = direction === 'out'
  43821. ? 'outEdges' : (direction === 'in' ? 'inEdges' : 'edges');
  43822. for (var i = 0; i < this.nodes.length; i++) {
  43823. this.nodes[i].__visited = false;
  43824. }
  43825. if (cb.call(context, startNode, null)) {
  43826. return;
  43827. }
  43828. var queue = [startNode];
  43829. while (queue.length) {
  43830. var currentNode = queue.shift();
  43831. var edges = currentNode[edgeType];
  43832. for (var i = 0; i < edges.length; i++) {
  43833. var e = edges[i];
  43834. var otherNode = e.node1 === currentNode
  43835. ? e.node2 : e.node1;
  43836. if (!otherNode.__visited) {
  43837. if (cb.call(context, otherNode, currentNode)) {
  43838. // Stop traversing
  43839. return;
  43840. }
  43841. queue.push(otherNode);
  43842. otherNode.__visited = true;
  43843. }
  43844. }
  43845. }
  43846. };
  43847. // TODO
  43848. // graphProto.depthFirstTraverse = function (
  43849. // cb, startNode, direction, context
  43850. // ) {
  43851. // };
  43852. // Filter update
  43853. graphProto.update = function () {
  43854. var data = this.data;
  43855. var edgeData = this.edgeData;
  43856. var nodes = this.nodes;
  43857. var edges = this.edges;
  43858. for (var i = 0, len = nodes.length; i < len; i++) {
  43859. nodes[i].dataIndex = -1;
  43860. }
  43861. for (var i = 0, len = data.count(); i < len; i++) {
  43862. nodes[data.getRawIndex(i)].dataIndex = i;
  43863. }
  43864. edgeData.filterSelf(function (idx) {
  43865. var edge = edges[edgeData.getRawIndex(idx)];
  43866. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  43867. });
  43868. // Update edge
  43869. for (var i = 0, len = edges.length; i < len; i++) {
  43870. edges[i].dataIndex = -1;
  43871. }
  43872. for (var i = 0, len = edgeData.count(); i < len; i++) {
  43873. edges[edgeData.getRawIndex(i)].dataIndex = i;
  43874. }
  43875. };
  43876. /**
  43877. * @return {module:echarts/data/Graph}
  43878. */
  43879. graphProto.clone = function () {
  43880. var graph = new Graph(this._directed);
  43881. var nodes = this.nodes;
  43882. var edges = this.edges;
  43883. for (var i = 0; i < nodes.length; i++) {
  43884. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  43885. }
  43886. for (var i = 0; i < edges.length; i++) {
  43887. var e = edges[i];
  43888. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  43889. }
  43890. return graph;
  43891. };
  43892. /**
  43893. * @alias module:echarts/data/Graph.Node
  43894. */
  43895. function Node(id, dataIndex) {
  43896. /**
  43897. * @type {string}
  43898. */
  43899. this.id = id == null ? '' : id;
  43900. /**
  43901. * @type {Array.<module:echarts/data/Graph.Edge>}
  43902. */
  43903. this.inEdges = [];
  43904. /**
  43905. * @type {Array.<module:echarts/data/Graph.Edge>}
  43906. */
  43907. this.outEdges = [];
  43908. /**
  43909. * @type {Array.<module:echarts/data/Graph.Edge>}
  43910. */
  43911. this.edges = [];
  43912. /**
  43913. * @type {module:echarts/data/Graph}
  43914. */
  43915. this.hostGraph;
  43916. /**
  43917. * @type {number}
  43918. */
  43919. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  43920. }
  43921. Node.prototype = {
  43922. constructor: Node,
  43923. /**
  43924. * @return {number}
  43925. */
  43926. degree: function () {
  43927. return this.edges.length;
  43928. },
  43929. /**
  43930. * @return {number}
  43931. */
  43932. inDegree: function () {
  43933. return this.inEdges.length;
  43934. },
  43935. /**
  43936. * @return {number}
  43937. */
  43938. outDegree: function () {
  43939. return this.outEdges.length;
  43940. },
  43941. /**
  43942. * @param {string} [path]
  43943. * @return {module:echarts/model/Model}
  43944. */
  43945. getModel: function (path) {
  43946. if (this.dataIndex < 0) {
  43947. return;
  43948. }
  43949. var graph = this.hostGraph;
  43950. var itemModel = graph.data.getItemModel(this.dataIndex);
  43951. return itemModel.getModel(path);
  43952. }
  43953. };
  43954. /**
  43955. * 图边
  43956. * @alias module:echarts/data/Graph.Edge
  43957. * @param {module:echarts/data/Graph.Node} n1
  43958. * @param {module:echarts/data/Graph.Node} n2
  43959. * @param {number} [dataIndex=-1]
  43960. */
  43961. function Edge(n1, n2, dataIndex) {
  43962. /**
  43963. * 节点1,如果是有向图则为源节点
  43964. * @type {module:echarts/data/Graph.Node}
  43965. */
  43966. this.node1 = n1;
  43967. /**
  43968. * 节点2,如果是有向图则为目标节点
  43969. * @type {module:echarts/data/Graph.Node}
  43970. */
  43971. this.node2 = n2;
  43972. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  43973. }
  43974. /**
  43975. * @param {string} [path]
  43976. * @return {module:echarts/model/Model}
  43977. */
  43978. Edge.prototype.getModel = function (path) {
  43979. if (this.dataIndex < 0) {
  43980. return;
  43981. }
  43982. var graph = this.hostGraph;
  43983. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  43984. return itemModel.getModel(path);
  43985. };
  43986. var createGraphDataProxyMixin = function (hostName, dataName) {
  43987. return {
  43988. /**
  43989. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  43990. * @return {number}
  43991. */
  43992. getValue: function (dimension) {
  43993. var data = this[hostName][dataName];
  43994. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  43995. },
  43996. /**
  43997. * @param {Object|string} key
  43998. * @param {*} [value]
  43999. */
  44000. setVisual: function (key, value) {
  44001. this.dataIndex >= 0
  44002. && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  44003. },
  44004. /**
  44005. * @param {string} key
  44006. * @return {boolean}
  44007. */
  44008. getVisual: function (key, ignoreParent) {
  44009. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  44010. },
  44011. /**
  44012. * @param {Object} layout
  44013. * @return {boolean} [merge=false]
  44014. */
  44015. setLayout: function (layout, merge$$1) {
  44016. this.dataIndex >= 0
  44017. && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  44018. },
  44019. /**
  44020. * @return {Object}
  44021. */
  44022. getLayout: function () {
  44023. return this[hostName][dataName].getItemLayout(this.dataIndex);
  44024. },
  44025. /**
  44026. * @return {module:zrender/Element}
  44027. */
  44028. getGraphicEl: function () {
  44029. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  44030. },
  44031. /**
  44032. * @return {number}
  44033. */
  44034. getRawIndex: function () {
  44035. return this[hostName][dataName].getRawIndex(this.dataIndex);
  44036. }
  44037. };
  44038. };
  44039. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  44040. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  44041. Graph.Node = Node;
  44042. Graph.Edge = Edge;
  44043. enableClassCheck(Node);
  44044. enableClassCheck(Edge);
  44045. /*
  44046. * Licensed to the Apache Software Foundation (ASF) under one
  44047. * or more contributor license agreements. See the NOTICE file
  44048. * distributed with this work for additional information
  44049. * regarding copyright ownership. The ASF licenses this file
  44050. * to you under the Apache License, Version 2.0 (the
  44051. * "License"); you may not use this file except in compliance
  44052. * with the License. You may obtain a copy of the License at
  44053. *
  44054. * http://www.apache.org/licenses/LICENSE-2.0
  44055. *
  44056. * Unless required by applicable law or agreed to in writing,
  44057. * software distributed under the License is distributed on an
  44058. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44059. * KIND, either express or implied. See the License for the
  44060. * specific language governing permissions and limitations
  44061. * under the License.
  44062. */
  44063. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  44064. // ??? TODO
  44065. // support dataset?
  44066. var graph = new Graph(directed);
  44067. for (var i = 0; i < nodes.length; i++) {
  44068. graph.addNode(retrieve(
  44069. // Id, name, dataIndex
  44070. nodes[i].id, nodes[i].name, i
  44071. ), i);
  44072. }
  44073. var linkNameList = [];
  44074. var validEdges = [];
  44075. var linkCount = 0;
  44076. for (var i = 0; i < edges.length; i++) {
  44077. var link = edges[i];
  44078. var source = link.source;
  44079. var target = link.target;
  44080. // addEdge may fail when source or target not exists
  44081. if (graph.addEdge(source, target, linkCount)) {
  44082. validEdges.push(link);
  44083. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  44084. linkCount++;
  44085. }
  44086. }
  44087. var coordSys = seriesModel.get('coordinateSystem');
  44088. var nodeData;
  44089. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  44090. nodeData = createListFromArray(nodes, seriesModel);
  44091. }
  44092. else {
  44093. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  44094. var coordDimensions = (coordSysCtor && coordSysCtor.type !== 'view')
  44095. ? (coordSysCtor.dimensions || []) : [];
  44096. // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  44097. // `value` dimension, but graph need `value` dimension. It's better to
  44098. // uniform this behavior.
  44099. if (indexOf(coordDimensions, 'value') < 0) {
  44100. coordDimensions.concat(['value']);
  44101. }
  44102. var dimensionNames = createDimensions(nodes, {
  44103. coordDimensions: coordDimensions
  44104. });
  44105. nodeData = new List(dimensionNames, seriesModel);
  44106. nodeData.initData(nodes);
  44107. }
  44108. var edgeData = new List(['value'], seriesModel);
  44109. edgeData.initData(validEdges, linkNameList);
  44110. beforeLink && beforeLink(nodeData, edgeData);
  44111. linkList({
  44112. mainData: nodeData,
  44113. struct: graph,
  44114. structAttr: 'graph',
  44115. datas: {node: nodeData, edge: edgeData},
  44116. datasAttr: {node: 'data', edge: 'edgeData'}
  44117. });
  44118. // Update dataIndex of nodes and edges because invalid edge may be removed
  44119. graph.update();
  44120. return graph;
  44121. };
  44122. /*
  44123. * Licensed to the Apache Software Foundation (ASF) under one
  44124. * or more contributor license agreements. See the NOTICE file
  44125. * distributed with this work for additional information
  44126. * regarding copyright ownership. The ASF licenses this file
  44127. * to you under the Apache License, Version 2.0 (the
  44128. * "License"); you may not use this file except in compliance
  44129. * with the License. You may obtain a copy of the License at
  44130. *
  44131. * http://www.apache.org/licenses/LICENSE-2.0
  44132. *
  44133. * Unless required by applicable law or agreed to in writing,
  44134. * software distributed under the License is distributed on an
  44135. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44136. * KIND, either express or implied. See the License for the
  44137. * specific language governing permissions and limitations
  44138. * under the License.
  44139. */
  44140. var GraphSeries = extendSeriesModel({
  44141. type: 'series.graph',
  44142. init: function (option) {
  44143. GraphSeries.superApply(this, 'init', arguments);
  44144. // Provide data for legend select
  44145. this.legendDataProvider = function () {
  44146. return this._categoriesData;
  44147. };
  44148. this.fillDataTextStyle(option.edges || option.links);
  44149. this._updateCategoriesData();
  44150. },
  44151. mergeOption: function (option) {
  44152. GraphSeries.superApply(this, 'mergeOption', arguments);
  44153. this.fillDataTextStyle(option.edges || option.links);
  44154. this._updateCategoriesData();
  44155. },
  44156. mergeDefaultAndTheme: function (option) {
  44157. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  44158. defaultEmphasis(option, ['edgeLabel'], ['show']);
  44159. },
  44160. getInitialData: function (option, ecModel) {
  44161. var edges = option.edges || option.links || [];
  44162. var nodes = option.data || option.nodes || [];
  44163. var self = this;
  44164. if (nodes && edges) {
  44165. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  44166. }
  44167. function beforeLink(nodeData, edgeData) {
  44168. // Overwrite nodeData.getItemModel to
  44169. nodeData.wrapMethod('getItemModel', function (model) {
  44170. var categoriesModels = self._categoriesModels;
  44171. var categoryIdx = model.getShallow('category');
  44172. var categoryModel = categoriesModels[categoryIdx];
  44173. if (categoryModel) {
  44174. categoryModel.parentModel = model.parentModel;
  44175. model.parentModel = categoryModel;
  44176. }
  44177. return model;
  44178. });
  44179. var edgeLabelModel = self.getModel('edgeLabel');
  44180. // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  44181. var fakeSeriesModel = new Model(
  44182. {label: edgeLabelModel.option},
  44183. edgeLabelModel.parentModel,
  44184. ecModel
  44185. );
  44186. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  44187. var emphasisFakeSeriesModel = new Model(
  44188. {emphasis: {label: emphasisEdgeLabelModel.option}},
  44189. emphasisEdgeLabelModel.parentModel,
  44190. ecModel
  44191. );
  44192. edgeData.wrapMethod('getItemModel', function (model) {
  44193. model.customizeGetParent(edgeGetParent);
  44194. return model;
  44195. });
  44196. function edgeGetParent(path) {
  44197. path = this.parsePath(path);
  44198. return (path && path[0] === 'label')
  44199. ? fakeSeriesModel
  44200. : (path && path[0] === 'emphasis' && path[1] === 'label')
  44201. ? emphasisFakeSeriesModel
  44202. : this.parentModel;
  44203. }
  44204. }
  44205. },
  44206. /**
  44207. * @return {module:echarts/data/Graph}
  44208. */
  44209. getGraph: function () {
  44210. return this.getData().graph;
  44211. },
  44212. /**
  44213. * @return {module:echarts/data/List}
  44214. */
  44215. getEdgeData: function () {
  44216. return this.getGraph().edgeData;
  44217. },
  44218. /**
  44219. * @return {module:echarts/data/List}
  44220. */
  44221. getCategoriesData: function () {
  44222. return this._categoriesData;
  44223. },
  44224. /**
  44225. * @override
  44226. */
  44227. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  44228. if (dataType === 'edge') {
  44229. var nodeData = this.getData();
  44230. var params = this.getDataParams(dataIndex, dataType);
  44231. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  44232. var sourceName = nodeData.getName(edge.node1.dataIndex);
  44233. var targetName = nodeData.getName(edge.node2.dataIndex);
  44234. var html = [];
  44235. sourceName != null && html.push(sourceName);
  44236. targetName != null && html.push(targetName);
  44237. html = encodeHTML(html.join(' > '));
  44238. if (params.value) {
  44239. html += ' : ' + encodeHTML(params.value);
  44240. }
  44241. return html;
  44242. }
  44243. else { // dataType === 'node' or empty
  44244. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  44245. }
  44246. },
  44247. _updateCategoriesData: function () {
  44248. var categories = map(this.option.categories || [], function (category) {
  44249. // Data must has value
  44250. return category.value != null ? category : extend({
  44251. value: 0
  44252. }, category);
  44253. });
  44254. var categoriesData = new List(['value'], this);
  44255. categoriesData.initData(categories);
  44256. this._categoriesData = categoriesData;
  44257. this._categoriesModels = categoriesData.mapArray(function (idx) {
  44258. return categoriesData.getItemModel(idx, true);
  44259. });
  44260. },
  44261. setZoom: function (zoom) {
  44262. this.option.zoom = zoom;
  44263. },
  44264. setCenter: function (center) {
  44265. this.option.center = center;
  44266. },
  44267. isAnimationEnabled: function () {
  44268. return GraphSeries.superCall(this, 'isAnimationEnabled')
  44269. // Not enable animation when do force layout
  44270. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  44271. },
  44272. defaultOption: {
  44273. zlevel: 0,
  44274. z: 2,
  44275. coordinateSystem: 'view',
  44276. // Default option for all coordinate systems
  44277. // xAxisIndex: 0,
  44278. // yAxisIndex: 0,
  44279. // polarIndex: 0,
  44280. // geoIndex: 0,
  44281. legendHoverLink: true,
  44282. hoverAnimation: true,
  44283. layout: null,
  44284. focusNodeAdjacency: false,
  44285. // Configuration of circular layout
  44286. circular: {
  44287. rotateLabel: false
  44288. },
  44289. // Configuration of force directed layout
  44290. force: {
  44291. initLayout: null,
  44292. // Node repulsion. Can be an array to represent range.
  44293. repulsion: [0, 50],
  44294. gravity: 0.1,
  44295. // Edge length. Can be an array to represent range.
  44296. edgeLength: 30,
  44297. layoutAnimation: true
  44298. },
  44299. left: 'center',
  44300. top: 'center',
  44301. // right: null,
  44302. // bottom: null,
  44303. // width: '80%',
  44304. // height: '80%',
  44305. symbol: 'circle',
  44306. symbolSize: 10,
  44307. edgeSymbol: ['none', 'none'],
  44308. edgeSymbolSize: 10,
  44309. edgeLabel: {
  44310. position: 'middle'
  44311. },
  44312. draggable: false,
  44313. roam: false,
  44314. // Default on center of graph
  44315. center: null,
  44316. zoom: 1,
  44317. // Symbol size scale ratio in roam
  44318. nodeScaleRatio: 0.6,
  44319. // cursor: null,
  44320. // categories: [],
  44321. // data: []
  44322. // Or
  44323. // nodes: []
  44324. //
  44325. // links: []
  44326. // Or
  44327. // edges: []
  44328. label: {
  44329. show: false,
  44330. formatter: '{b}'
  44331. },
  44332. itemStyle: {},
  44333. lineStyle: {
  44334. color: '#aaa',
  44335. width: 1,
  44336. curveness: 0,
  44337. opacity: 0.5
  44338. },
  44339. emphasis: {
  44340. label: {
  44341. show: true
  44342. }
  44343. }
  44344. }
  44345. });
  44346. /*
  44347. * Licensed to the Apache Software Foundation (ASF) under one
  44348. * or more contributor license agreements. See the NOTICE file
  44349. * distributed with this work for additional information
  44350. * regarding copyright ownership. The ASF licenses this file
  44351. * to you under the Apache License, Version 2.0 (the
  44352. * "License"); you may not use this file except in compliance
  44353. * with the License. You may obtain a copy of the License at
  44354. *
  44355. * http://www.apache.org/licenses/LICENSE-2.0
  44356. *
  44357. * Unless required by applicable law or agreed to in writing,
  44358. * software distributed under the License is distributed on an
  44359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44360. * KIND, either express or implied. See the License for the
  44361. * specific language governing permissions and limitations
  44362. * under the License.
  44363. */
  44364. /**
  44365. * Line path for bezier and straight line draw
  44366. */
  44367. var straightLineProto = Line.prototype;
  44368. var bezierCurveProto = BezierCurve.prototype;
  44369. function isLine(shape) {
  44370. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  44371. }
  44372. var LinePath = extendShape({
  44373. type: 'ec-line',
  44374. style: {
  44375. stroke: '#000',
  44376. fill: null
  44377. },
  44378. shape: {
  44379. x1: 0,
  44380. y1: 0,
  44381. x2: 0,
  44382. y2: 0,
  44383. percent: 1,
  44384. cpx1: null,
  44385. cpy1: null
  44386. },
  44387. buildPath: function (ctx, shape) {
  44388. (isLine(shape) ? straightLineProto : bezierCurveProto).buildPath(ctx, shape);
  44389. },
  44390. pointAt: function (t) {
  44391. return isLine(this.shape)
  44392. ? straightLineProto.pointAt.call(this, t)
  44393. : bezierCurveProto.pointAt.call(this, t);
  44394. },
  44395. tangentAt: function (t) {
  44396. var shape = this.shape;
  44397. var p = isLine(shape)
  44398. ? [shape.x2 - shape.x1, shape.y2 - shape.y1]
  44399. : bezierCurveProto.tangentAt.call(this, t);
  44400. return normalize(p, p);
  44401. }
  44402. });
  44403. /*
  44404. * Licensed to the Apache Software Foundation (ASF) under one
  44405. * or more contributor license agreements. See the NOTICE file
  44406. * distributed with this work for additional information
  44407. * regarding copyright ownership. The ASF licenses this file
  44408. * to you under the Apache License, Version 2.0 (the
  44409. * "License"); you may not use this file except in compliance
  44410. * with the License. You may obtain a copy of the License at
  44411. *
  44412. * http://www.apache.org/licenses/LICENSE-2.0
  44413. *
  44414. * Unless required by applicable law or agreed to in writing,
  44415. * software distributed under the License is distributed on an
  44416. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44417. * KIND, either express or implied. See the License for the
  44418. * specific language governing permissions and limitations
  44419. * under the License.
  44420. */
  44421. /**
  44422. * @module echarts/chart/helper/Line
  44423. */
  44424. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  44425. function makeSymbolTypeKey(symbolCategory) {
  44426. return '_' + symbolCategory + 'Type';
  44427. }
  44428. /**
  44429. * @inner
  44430. */
  44431. function createSymbol$1(name, lineData, idx) {
  44432. var color = lineData.getItemVisual(idx, 'color');
  44433. var symbolType = lineData.getItemVisual(idx, name);
  44434. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  44435. if (!symbolType || symbolType === 'none') {
  44436. return;
  44437. }
  44438. if (!isArray(symbolSize)) {
  44439. symbolSize = [symbolSize, symbolSize];
  44440. }
  44441. var symbolPath = createSymbol(
  44442. symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2,
  44443. symbolSize[0], symbolSize[1], color
  44444. );
  44445. symbolPath.name = name;
  44446. return symbolPath;
  44447. }
  44448. function createLine(points) {
  44449. var line = new LinePath({
  44450. name: 'line'
  44451. });
  44452. setLinePoints(line.shape, points);
  44453. return line;
  44454. }
  44455. function setLinePoints(targetShape, points) {
  44456. var p1 = points[0];
  44457. var p2 = points[1];
  44458. var cp1 = points[2];
  44459. targetShape.x1 = p1[0];
  44460. targetShape.y1 = p1[1];
  44461. targetShape.x2 = p2[0];
  44462. targetShape.y2 = p2[1];
  44463. targetShape.percent = 1;
  44464. if (cp1) {
  44465. targetShape.cpx1 = cp1[0];
  44466. targetShape.cpy1 = cp1[1];
  44467. }
  44468. else {
  44469. targetShape.cpx1 = NaN;
  44470. targetShape.cpy1 = NaN;
  44471. }
  44472. }
  44473. function updateSymbolAndLabelBeforeLineUpdate () {
  44474. var lineGroup = this;
  44475. var symbolFrom = lineGroup.childOfName('fromSymbol');
  44476. var symbolTo = lineGroup.childOfName('toSymbol');
  44477. var label = lineGroup.childOfName('label');
  44478. // Quick reject
  44479. if (!symbolFrom && !symbolTo && label.ignore) {
  44480. return;
  44481. }
  44482. var invScale = 1;
  44483. var parentNode = this.parent;
  44484. while (parentNode) {
  44485. if (parentNode.scale) {
  44486. invScale /= parentNode.scale[0];
  44487. }
  44488. parentNode = parentNode.parent;
  44489. }
  44490. var line = lineGroup.childOfName('line');
  44491. // If line not changed
  44492. // FIXME Parent scale changed
  44493. if (!this.__dirty && !line.__dirty) {
  44494. return;
  44495. }
  44496. var percent = line.shape.percent;
  44497. var fromPos = line.pointAt(0);
  44498. var toPos = line.pointAt(percent);
  44499. var d = sub([], toPos, fromPos);
  44500. normalize(d, d);
  44501. if (symbolFrom) {
  44502. symbolFrom.attr('position', fromPos);
  44503. var tangent = line.tangentAt(0);
  44504. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(
  44505. tangent[1], tangent[0]
  44506. ));
  44507. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  44508. }
  44509. if (symbolTo) {
  44510. symbolTo.attr('position', toPos);
  44511. var tangent = line.tangentAt(1);
  44512. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(
  44513. tangent[1], tangent[0]
  44514. ));
  44515. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  44516. }
  44517. if (!label.ignore) {
  44518. label.attr('position', toPos);
  44519. var textPosition;
  44520. var textAlign;
  44521. var textVerticalAlign;
  44522. var distance$$1 = 5 * invScale;
  44523. // End
  44524. if (label.__position === 'end') {
  44525. textPosition = [d[0] * distance$$1 + toPos[0], d[1] * distance$$1 + toPos[1]];
  44526. textAlign = d[0] > 0.8 ? 'left' : (d[0] < -0.8 ? 'right' : 'center');
  44527. textVerticalAlign = d[1] > 0.8 ? 'top' : (d[1] < -0.8 ? 'bottom' : 'middle');
  44528. }
  44529. // Middle
  44530. else if (label.__position === 'middle') {
  44531. var halfPercent = percent / 2;
  44532. var tangent = line.tangentAt(halfPercent);
  44533. var n = [tangent[1], -tangent[0]];
  44534. var cp = line.pointAt(halfPercent);
  44535. if (n[1] > 0) {
  44536. n[0] = -n[0];
  44537. n[1] = -n[1];
  44538. }
  44539. textPosition = [cp[0] + n[0] * distance$$1, cp[1] + n[1] * distance$$1];
  44540. textAlign = 'center';
  44541. textVerticalAlign = 'bottom';
  44542. var rotation = -Math.atan2(tangent[1], tangent[0]);
  44543. if (toPos[0] < fromPos[0]) {
  44544. rotation = Math.PI + rotation;
  44545. }
  44546. label.attr('rotation', rotation);
  44547. }
  44548. // Start
  44549. else {
  44550. textPosition = [-d[0] * distance$$1 + fromPos[0], -d[1] * distance$$1 + fromPos[1]];
  44551. textAlign = d[0] > 0.8 ? 'right' : (d[0] < -0.8 ? 'left' : 'center');
  44552. textVerticalAlign = d[1] > 0.8 ? 'bottom' : (d[1] < -0.8 ? 'top' : 'middle');
  44553. }
  44554. label.attr({
  44555. style: {
  44556. // Use the user specified text align and baseline first
  44557. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  44558. textAlign: label.__textAlign || textAlign
  44559. },
  44560. position: textPosition,
  44561. scale: [invScale, invScale]
  44562. });
  44563. }
  44564. }
  44565. /**
  44566. * @constructor
  44567. * @extends {module:zrender/graphic/Group}
  44568. * @alias {module:echarts/chart/helper/Line}
  44569. */
  44570. function Line$1(lineData, idx, seriesScope) {
  44571. Group.call(this);
  44572. this._createLine(lineData, idx, seriesScope);
  44573. }
  44574. var lineProto = Line$1.prototype;
  44575. // Update symbol position and rotation
  44576. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  44577. lineProto._createLine = function (lineData, idx, seriesScope) {
  44578. var seriesModel = lineData.hostModel;
  44579. var linePoints = lineData.getItemLayout(idx);
  44580. var line = createLine(linePoints);
  44581. line.shape.percent = 0;
  44582. initProps(line, {
  44583. shape: {
  44584. percent: 1
  44585. }
  44586. }, seriesModel, idx);
  44587. this.add(line);
  44588. var label = new Text({
  44589. name: 'label'
  44590. });
  44591. this.add(label);
  44592. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44593. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  44594. // symbols must added after line to make sure
  44595. // it will be updated after line#update.
  44596. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  44597. this.add(symbol);
  44598. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  44599. }, this);
  44600. this._updateCommonStl(lineData, idx, seriesScope);
  44601. };
  44602. lineProto.updateData = function (lineData, idx, seriesScope) {
  44603. var seriesModel = lineData.hostModel;
  44604. var line = this.childOfName('line');
  44605. var linePoints = lineData.getItemLayout(idx);
  44606. var target = {
  44607. shape: {}
  44608. };
  44609. setLinePoints(target.shape, linePoints);
  44610. updateProps(line, target, seriesModel, idx);
  44611. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44612. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  44613. var key = makeSymbolTypeKey(symbolCategory);
  44614. // Symbol changed
  44615. if (this[key] !== symbolType) {
  44616. this.remove(this.childOfName(symbolCategory));
  44617. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  44618. this.add(symbol);
  44619. }
  44620. this[key] = symbolType;
  44621. }, this);
  44622. this._updateCommonStl(lineData, idx, seriesScope);
  44623. };
  44624. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  44625. var seriesModel = lineData.hostModel;
  44626. var line = this.childOfName('line');
  44627. var lineStyle = seriesScope && seriesScope.lineStyle;
  44628. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  44629. var labelModel = seriesScope && seriesScope.labelModel;
  44630. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  44631. // Optimization for large dataset
  44632. if (!seriesScope || lineData.hasItemOption) {
  44633. var itemModel = lineData.getItemModel(idx);
  44634. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  44635. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  44636. labelModel = itemModel.getModel('label');
  44637. hoverLabelModel = itemModel.getModel('emphasis.label');
  44638. }
  44639. var visualColor = lineData.getItemVisual(idx, 'color');
  44640. var visualOpacity = retrieve3(
  44641. lineData.getItemVisual(idx, 'opacity'),
  44642. lineStyle.opacity,
  44643. 1
  44644. );
  44645. line.useStyle(defaults(
  44646. {
  44647. strokeNoScale: true,
  44648. fill: 'none',
  44649. stroke: visualColor,
  44650. opacity: visualOpacity
  44651. },
  44652. lineStyle
  44653. ));
  44654. line.hoverStyle = hoverLineStyle;
  44655. // Update symbol
  44656. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  44657. var symbol = this.childOfName(symbolCategory);
  44658. if (symbol) {
  44659. symbol.setColor(visualColor);
  44660. symbol.setStyle({
  44661. opacity: visualOpacity
  44662. });
  44663. }
  44664. }, this);
  44665. var showLabel = labelModel.getShallow('show');
  44666. var hoverShowLabel = hoverLabelModel.getShallow('show');
  44667. var label = this.childOfName('label');
  44668. var defaultLabelColor;
  44669. var baseText;
  44670. // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  44671. if (showLabel || hoverShowLabel) {
  44672. defaultLabelColor = visualColor || '#000';
  44673. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  44674. if (baseText == null) {
  44675. var rawVal = seriesModel.getRawValue(idx);
  44676. baseText = rawVal == null
  44677. ? lineData.getName(idx)
  44678. : isFinite(rawVal)
  44679. ? round$1(rawVal)
  44680. : rawVal;
  44681. }
  44682. }
  44683. var normalText = showLabel ? baseText : null;
  44684. var emphasisText = hoverShowLabel
  44685. ? retrieve2(
  44686. seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType),
  44687. baseText
  44688. )
  44689. : null;
  44690. var labelStyle = label.style;
  44691. // Always set `textStyle` even if `normalStyle.text` is null, because default
  44692. // values have to be set on `normalStyle`.
  44693. if (normalText != null || emphasisText != null) {
  44694. setTextStyle(label.style, labelModel, {
  44695. text: normalText
  44696. }, {
  44697. autoColor: defaultLabelColor
  44698. });
  44699. label.__textAlign = labelStyle.textAlign;
  44700. label.__verticalAlign = labelStyle.textVerticalAlign;
  44701. // 'start', 'middle', 'end'
  44702. label.__position = labelModel.get('position') || 'middle';
  44703. }
  44704. if (emphasisText != null) {
  44705. // Only these properties supported in this emphasis style here.
  44706. label.hoverStyle = {
  44707. text: emphasisText,
  44708. textFill: hoverLabelModel.getTextColor(true),
  44709. // For merging hover style to normal style, do not use
  44710. // `hoverLabelModel.getFont()` here.
  44711. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  44712. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  44713. fontSize: hoverLabelModel.getShallow('fontSize'),
  44714. fontFamily: hoverLabelModel.getShallow('fontFamily')
  44715. };
  44716. }
  44717. else {
  44718. label.hoverStyle = {
  44719. text: null
  44720. };
  44721. }
  44722. label.ignore = !showLabel && !hoverShowLabel;
  44723. setHoverStyle(this);
  44724. };
  44725. lineProto.highlight = function () {
  44726. this.trigger('emphasis');
  44727. };
  44728. lineProto.downplay = function () {
  44729. this.trigger('normal');
  44730. };
  44731. lineProto.updateLayout = function (lineData, idx) {
  44732. this.setLinePoints(lineData.getItemLayout(idx));
  44733. };
  44734. lineProto.setLinePoints = function (points) {
  44735. var linePath = this.childOfName('line');
  44736. setLinePoints(linePath.shape, points);
  44737. linePath.dirty();
  44738. };
  44739. inherits(Line$1, Group);
  44740. /*
  44741. * Licensed to the Apache Software Foundation (ASF) under one
  44742. * or more contributor license agreements. See the NOTICE file
  44743. * distributed with this work for additional information
  44744. * regarding copyright ownership. The ASF licenses this file
  44745. * to you under the Apache License, Version 2.0 (the
  44746. * "License"); you may not use this file except in compliance
  44747. * with the License. You may obtain a copy of the License at
  44748. *
  44749. * http://www.apache.org/licenses/LICENSE-2.0
  44750. *
  44751. * Unless required by applicable law or agreed to in writing,
  44752. * software distributed under the License is distributed on an
  44753. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44754. * KIND, either express or implied. See the License for the
  44755. * specific language governing permissions and limitations
  44756. * under the License.
  44757. */
  44758. /**
  44759. * @module echarts/chart/helper/LineDraw
  44760. */
  44761. // import IncrementalDisplayable from 'zrender/src/graphic/IncrementalDisplayable';
  44762. /**
  44763. * @alias module:echarts/component/marker/LineDraw
  44764. * @constructor
  44765. */
  44766. function LineDraw(ctor) {
  44767. this._ctor = ctor || Line$1;
  44768. this.group = new Group();
  44769. }
  44770. var lineDrawProto = LineDraw.prototype;
  44771. lineDrawProto.isPersistent = function () {
  44772. return true;
  44773. };
  44774. /**
  44775. * @param {module:echarts/data/List} lineData
  44776. */
  44777. lineDrawProto.updateData = function (lineData) {
  44778. var lineDraw = this;
  44779. var group = lineDraw.group;
  44780. var oldLineData = lineDraw._lineData;
  44781. lineDraw._lineData = lineData;
  44782. // There is no oldLineData only when first rendering or switching from
  44783. // stream mode to normal mode, where previous elements should be removed.
  44784. if (!oldLineData) {
  44785. group.removeAll();
  44786. }
  44787. var seriesScope = makeSeriesScope$1(lineData);
  44788. lineData.diff(oldLineData)
  44789. .add(function (idx) {
  44790. doAdd(lineDraw, lineData, idx, seriesScope);
  44791. })
  44792. .update(function (newIdx, oldIdx) {
  44793. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  44794. })
  44795. .remove(function (idx) {
  44796. group.remove(oldLineData.getItemGraphicEl(idx));
  44797. })
  44798. .execute();
  44799. };
  44800. function doAdd(lineDraw, lineData, idx, seriesScope) {
  44801. var itemLayout = lineData.getItemLayout(idx);
  44802. if (!lineNeedsDraw(itemLayout)) {
  44803. return;
  44804. }
  44805. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  44806. lineData.setItemGraphicEl(idx, el);
  44807. lineDraw.group.add(el);
  44808. }
  44809. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  44810. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  44811. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  44812. lineDraw.group.remove(itemEl);
  44813. return;
  44814. }
  44815. if (!itemEl) {
  44816. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  44817. }
  44818. else {
  44819. itemEl.updateData(newLineData, newIdx, seriesScope);
  44820. }
  44821. newLineData.setItemGraphicEl(newIdx, itemEl);
  44822. lineDraw.group.add(itemEl);
  44823. }
  44824. lineDrawProto.updateLayout = function () {
  44825. var lineData = this._lineData;
  44826. // Do not support update layout in incremental mode.
  44827. if (!lineData) {
  44828. return;
  44829. }
  44830. lineData.eachItemGraphicEl(function (el, idx) {
  44831. el.updateLayout(lineData, idx);
  44832. }, this);
  44833. };
  44834. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  44835. this._seriesScope = makeSeriesScope$1(lineData);
  44836. this._lineData = null;
  44837. this.group.removeAll();
  44838. };
  44839. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  44840. function updateIncrementalAndHover(el) {
  44841. if (!el.isGroup) {
  44842. el.incremental = el.useHoverLayer = true;
  44843. }
  44844. }
  44845. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  44846. var itemLayout = lineData.getItemLayout(idx);
  44847. if (lineNeedsDraw(itemLayout)) {
  44848. var el = new this._ctor(lineData, idx, this._seriesScope);
  44849. el.traverse(updateIncrementalAndHover);
  44850. this.group.add(el);
  44851. lineData.setItemGraphicEl(idx, el);
  44852. }
  44853. }
  44854. };
  44855. function makeSeriesScope$1(lineData) {
  44856. var hostModel = lineData.hostModel;
  44857. return {
  44858. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  44859. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  44860. labelModel: hostModel.getModel('label'),
  44861. hoverLabelModel: hostModel.getModel('emphasis.label')
  44862. };
  44863. }
  44864. lineDrawProto.remove = function () {
  44865. this._clearIncremental();
  44866. this._incremental = null;
  44867. this.group.removeAll();
  44868. };
  44869. lineDrawProto._clearIncremental = function () {
  44870. var incremental = this._incremental;
  44871. if (incremental) {
  44872. incremental.clearDisplaybles();
  44873. }
  44874. };
  44875. function isPointNaN(pt) {
  44876. return isNaN(pt[0]) || isNaN(pt[1]);
  44877. }
  44878. function lineNeedsDraw(pts) {
  44879. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  44880. }
  44881. /*
  44882. * Licensed to the Apache Software Foundation (ASF) under one
  44883. * or more contributor license agreements. See the NOTICE file
  44884. * distributed with this work for additional information
  44885. * regarding copyright ownership. The ASF licenses this file
  44886. * to you under the Apache License, Version 2.0 (the
  44887. * "License"); you may not use this file except in compliance
  44888. * with the License. You may obtain a copy of the License at
  44889. *
  44890. * http://www.apache.org/licenses/LICENSE-2.0
  44891. *
  44892. * Unless required by applicable law or agreed to in writing,
  44893. * software distributed under the License is distributed on an
  44894. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44895. * KIND, either express or implied. See the License for the
  44896. * specific language governing permissions and limitations
  44897. * under the License.
  44898. */
  44899. var v1 = [];
  44900. var v2 = [];
  44901. var v3 = [];
  44902. var quadraticAt$1 = quadraticAt;
  44903. var v2DistSquare = distSquare;
  44904. var mathAbs$1 = Math.abs;
  44905. function intersectCurveCircle(curvePoints, center, radius) {
  44906. var p0 = curvePoints[0];
  44907. var p1 = curvePoints[1];
  44908. var p2 = curvePoints[2];
  44909. var d = Infinity;
  44910. var t;
  44911. var radiusSquare = radius * radius;
  44912. var interval = 0.1;
  44913. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  44914. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  44915. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  44916. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  44917. if (diff < d) {
  44918. d = diff;
  44919. t = _t;
  44920. }
  44921. }
  44922. // Assume the segment is monotone,Find root through Bisection method
  44923. // At most 32 iteration
  44924. for (var i = 0; i < 32; i++) {
  44925. // var prev = t - interval;
  44926. var next = t + interval;
  44927. // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  44928. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  44929. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  44930. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  44931. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  44932. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  44933. var diff = v2DistSquare(v2, center) - radiusSquare;
  44934. if (mathAbs$1(diff) < 1e-2) {
  44935. break;
  44936. }
  44937. // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  44938. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  44939. interval /= 2;
  44940. if (diff < 0) {
  44941. if (nextDiff >= 0) {
  44942. t = t + interval;
  44943. }
  44944. else {
  44945. t = t - interval;
  44946. }
  44947. }
  44948. else {
  44949. if (nextDiff >= 0) {
  44950. t = t - interval;
  44951. }
  44952. else {
  44953. t = t + interval;
  44954. }
  44955. }
  44956. }
  44957. return t;
  44958. }
  44959. // Adjust edge to avoid
  44960. var adjustEdge = function (graph, scale$$1) {
  44961. var tmp0 = [];
  44962. var quadraticSubdivide$$1 = quadraticSubdivide;
  44963. var pts = [[], [], []];
  44964. var pts2 = [[], []];
  44965. var v = [];
  44966. scale$$1 /= 2;
  44967. function getSymbolSize(node) {
  44968. var symbolSize = node.getVisual('symbolSize');
  44969. if (symbolSize instanceof Array) {
  44970. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  44971. }
  44972. return symbolSize;
  44973. }
  44974. graph.eachEdge(function (edge, idx) {
  44975. var linePoints = edge.getLayout();
  44976. var fromSymbol = edge.getVisual('fromSymbol');
  44977. var toSymbol = edge.getVisual('toSymbol');
  44978. if (!linePoints.__original) {
  44979. linePoints.__original = [
  44980. clone$1(linePoints[0]),
  44981. clone$1(linePoints[1])
  44982. ];
  44983. if (linePoints[2]) {
  44984. linePoints.__original.push(clone$1(linePoints[2]));
  44985. }
  44986. }
  44987. var originalPoints = linePoints.__original;
  44988. // Quadratic curve
  44989. if (linePoints[2] != null) {
  44990. copy(pts[0], originalPoints[0]);
  44991. copy(pts[1], originalPoints[2]);
  44992. copy(pts[2], originalPoints[1]);
  44993. if (fromSymbol && fromSymbol != 'none') {
  44994. var symbolSize = getSymbolSize(edge.node1);
  44995. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1);
  44996. // Subdivide and get the second
  44997. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  44998. pts[0][0] = tmp0[3];
  44999. pts[1][0] = tmp0[4];
  45000. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  45001. pts[0][1] = tmp0[3];
  45002. pts[1][1] = tmp0[4];
  45003. }
  45004. if (toSymbol && toSymbol != 'none') {
  45005. var symbolSize = getSymbolSize(edge.node2);
  45006. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1);
  45007. // Subdivide and get the first
  45008. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  45009. pts[1][0] = tmp0[1];
  45010. pts[2][0] = tmp0[2];
  45011. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  45012. pts[1][1] = tmp0[1];
  45013. pts[2][1] = tmp0[2];
  45014. }
  45015. // Copy back to layout
  45016. copy(linePoints[0], pts[0]);
  45017. copy(linePoints[1], pts[2]);
  45018. copy(linePoints[2], pts[1]);
  45019. }
  45020. // Line
  45021. else {
  45022. copy(pts2[0], originalPoints[0]);
  45023. copy(pts2[1], originalPoints[1]);
  45024. sub(v, pts2[1], pts2[0]);
  45025. normalize(v, v);
  45026. if (fromSymbol && fromSymbol != 'none') {
  45027. var symbolSize = getSymbolSize(edge.node1);
  45028. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  45029. }
  45030. if (toSymbol && toSymbol != 'none') {
  45031. var symbolSize = getSymbolSize(edge.node2);
  45032. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  45033. }
  45034. copy(linePoints[0], pts2[0]);
  45035. copy(linePoints[1], pts2[1]);
  45036. }
  45037. });
  45038. };
  45039. /*
  45040. * Licensed to the Apache Software Foundation (ASF) under one
  45041. * or more contributor license agreements. See the NOTICE file
  45042. * distributed with this work for additional information
  45043. * regarding copyright ownership. The ASF licenses this file
  45044. * to you under the Apache License, Version 2.0 (the
  45045. * "License"); you may not use this file except in compliance
  45046. * with the License. You may obtain a copy of the License at
  45047. *
  45048. * http://www.apache.org/licenses/LICENSE-2.0
  45049. *
  45050. * Unless required by applicable law or agreed to in writing,
  45051. * software distributed under the License is distributed on an
  45052. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45053. * KIND, either express or implied. See the License for the
  45054. * specific language governing permissions and limitations
  45055. * under the License.
  45056. */
  45057. var nodeOpacityPath = ['itemStyle', 'opacity'];
  45058. var lineOpacityPath = ['lineStyle', 'opacity'];
  45059. function getItemOpacity(item, opacityPath) {
  45060. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  45061. }
  45062. function fadeOutItem(item, opacityPath, opacityRatio) {
  45063. var el = item.getGraphicEl();
  45064. var opacity = getItemOpacity(item, opacityPath);
  45065. if (opacityRatio != null) {
  45066. opacity == null && (opacity = 1);
  45067. opacity *= opacityRatio;
  45068. }
  45069. el.downplay && el.downplay();
  45070. el.traverse(function (child) {
  45071. if (child.type !== 'group') {
  45072. child.setStyle('opacity', opacity);
  45073. }
  45074. });
  45075. }
  45076. function fadeInItem(item, opacityPath) {
  45077. var opacity = getItemOpacity(item, opacityPath);
  45078. var el = item.getGraphicEl();
  45079. el.highlight && el.highlight();
  45080. el.traverse(function (child) {
  45081. if (child.type !== 'group') {
  45082. child.setStyle('opacity', opacity);
  45083. }
  45084. });
  45085. }
  45086. extendChartView({
  45087. type: 'graph',
  45088. init: function (ecModel, api) {
  45089. var symbolDraw = new SymbolDraw();
  45090. var lineDraw = new LineDraw();
  45091. var group = this.group;
  45092. this._controller = new RoamController(api.getZr());
  45093. this._controllerHost = {target: group};
  45094. group.add(symbolDraw.group);
  45095. group.add(lineDraw.group);
  45096. this._symbolDraw = symbolDraw;
  45097. this._lineDraw = lineDraw;
  45098. this._firstRender = true;
  45099. },
  45100. render: function (seriesModel, ecModel, api) {
  45101. var coordSys = seriesModel.coordinateSystem;
  45102. this._model = seriesModel;
  45103. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  45104. var symbolDraw = this._symbolDraw;
  45105. var lineDraw = this._lineDraw;
  45106. var group = this.group;
  45107. if (coordSys.type === 'view') {
  45108. var groupNewProp = {
  45109. position: coordSys.position,
  45110. scale: coordSys.scale
  45111. };
  45112. if (this._firstRender) {
  45113. group.attr(groupNewProp);
  45114. }
  45115. else {
  45116. updateProps(group, groupNewProp, seriesModel);
  45117. }
  45118. }
  45119. // Fix edge contact point with node
  45120. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45121. var data = seriesModel.getData();
  45122. symbolDraw.updateData(data);
  45123. var edgeData = seriesModel.getEdgeData();
  45124. lineDraw.updateData(edgeData);
  45125. this._updateNodeAndLinkScale();
  45126. this._updateController(seriesModel, ecModel, api);
  45127. clearTimeout(this._layoutTimeout);
  45128. var forceLayout = seriesModel.forceLayout;
  45129. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  45130. if (forceLayout) {
  45131. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  45132. }
  45133. data.eachItemGraphicEl(function (el, idx) {
  45134. var itemModel = data.getItemModel(idx);
  45135. // Update draggable
  45136. el.off('drag').off('dragend');
  45137. var draggable = data.getItemModel(idx).get('draggable');
  45138. if (draggable) {
  45139. el.on('drag', function () {
  45140. if (forceLayout) {
  45141. forceLayout.warmUp();
  45142. !this._layouting
  45143. && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  45144. forceLayout.setFixed(idx);
  45145. // Write position back to layout
  45146. data.setItemLayout(idx, el.position);
  45147. }
  45148. }, this).on('dragend', function () {
  45149. if (forceLayout) {
  45150. forceLayout.setUnfixed(idx);
  45151. }
  45152. }, this);
  45153. }
  45154. el.setDraggable(draggable && forceLayout);
  45155. el.off('mouseover', el.__focusNodeAdjacency);
  45156. el.off('mouseout', el.__unfocusNodeAdjacency);
  45157. if (itemModel.get('focusNodeAdjacency')) {
  45158. el.on('mouseover', el.__focusNodeAdjacency = function () {
  45159. api.dispatchAction({
  45160. type: 'focusNodeAdjacency',
  45161. seriesId: seriesModel.id,
  45162. dataIndex: el.dataIndex
  45163. });
  45164. });
  45165. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  45166. api.dispatchAction({
  45167. type: 'unfocusNodeAdjacency',
  45168. seriesId: seriesModel.id
  45169. });
  45170. });
  45171. }
  45172. }, this);
  45173. data.graph.eachEdge(function (edge) {
  45174. var el = edge.getGraphicEl();
  45175. el.off('mouseover', el.__focusNodeAdjacency);
  45176. el.off('mouseout', el.__unfocusNodeAdjacency);
  45177. if (edge.getModel().get('focusNodeAdjacency')) {
  45178. el.on('mouseover', el.__focusNodeAdjacency = function () {
  45179. api.dispatchAction({
  45180. type: 'focusNodeAdjacency',
  45181. seriesId: seriesModel.id,
  45182. edgeDataIndex: edge.dataIndex
  45183. });
  45184. });
  45185. el.on('mouseout', el.__unfocusNodeAdjacency = function () {
  45186. api.dispatchAction({
  45187. type: 'unfocusNodeAdjacency',
  45188. seriesId: seriesModel.id
  45189. });
  45190. });
  45191. }
  45192. });
  45193. var circularRotateLabel = seriesModel.get('layout') === 'circular'
  45194. && seriesModel.get('circular.rotateLabel');
  45195. var cx = data.getLayout('cx');
  45196. var cy = data.getLayout('cy');
  45197. data.eachItemGraphicEl(function (el, idx) {
  45198. var symbolPath = el.getSymbolPath();
  45199. if (circularRotateLabel) {
  45200. var pos = data.getItemLayout(idx);
  45201. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  45202. if (rad < 0) {
  45203. rad = Math.PI * 2 + rad;
  45204. }
  45205. var isLeft = pos[0] < cx;
  45206. if (isLeft) {
  45207. rad = rad - Math.PI;
  45208. }
  45209. var textPosition = isLeft ? 'left' : 'right';
  45210. symbolPath.setStyle({
  45211. textRotation: -rad,
  45212. textPosition: textPosition,
  45213. textOrigin: 'center'
  45214. });
  45215. symbolPath.hoverStyle && (symbolPath.hoverStyle.textPosition = textPosition);
  45216. }
  45217. else {
  45218. symbolPath.setStyle({
  45219. textRotation: 0
  45220. });
  45221. }
  45222. });
  45223. this._firstRender = false;
  45224. },
  45225. dispose: function () {
  45226. this._controller && this._controller.dispose();
  45227. this._controllerHost = {};
  45228. },
  45229. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  45230. var data = this._model.getData();
  45231. var graph = data.graph;
  45232. var dataIndex = payload.dataIndex;
  45233. var edgeDataIndex = payload.edgeDataIndex;
  45234. var node = graph.getNodeByIndex(dataIndex);
  45235. var edge = graph.getEdgeByIndex(edgeDataIndex);
  45236. if (!node && !edge) {
  45237. return;
  45238. }
  45239. graph.eachNode(function (node) {
  45240. fadeOutItem(node, nodeOpacityPath, 0.1);
  45241. });
  45242. graph.eachEdge(function (edge) {
  45243. fadeOutItem(edge, lineOpacityPath, 0.1);
  45244. });
  45245. if (node) {
  45246. fadeInItem(node, nodeOpacityPath);
  45247. each$1(node.edges, function (adjacentEdge) {
  45248. if (adjacentEdge.dataIndex < 0) {
  45249. return;
  45250. }
  45251. fadeInItem(adjacentEdge, lineOpacityPath);
  45252. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  45253. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  45254. });
  45255. }
  45256. if (edge) {
  45257. fadeInItem(edge, lineOpacityPath);
  45258. fadeInItem(edge.node1, nodeOpacityPath);
  45259. fadeInItem(edge.node2, nodeOpacityPath);
  45260. }
  45261. },
  45262. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  45263. var graph = this._model.getData().graph;
  45264. graph.eachNode(function (node) {
  45265. fadeOutItem(node, nodeOpacityPath);
  45266. });
  45267. graph.eachEdge(function (edge) {
  45268. fadeOutItem(edge, lineOpacityPath);
  45269. });
  45270. },
  45271. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  45272. var self = this;
  45273. (function step() {
  45274. forceLayout.step(function (stopped) {
  45275. self.updateLayout(self._model);
  45276. (self._layouting = !stopped) && (
  45277. layoutAnimation
  45278. ? (self._layoutTimeout = setTimeout(step, 16))
  45279. : step()
  45280. );
  45281. });
  45282. })();
  45283. },
  45284. _updateController: function (seriesModel, ecModel, api) {
  45285. var controller = this._controller;
  45286. var controllerHost = this._controllerHost;
  45287. var group = this.group;
  45288. controller.setPointerChecker(function (e, x, y) {
  45289. var rect = group.getBoundingRect();
  45290. rect.applyTransform(group.transform);
  45291. return rect.contain(x, y)
  45292. && !onIrrelevantElement(e, api, seriesModel);
  45293. });
  45294. if (seriesModel.coordinateSystem.type !== 'view') {
  45295. controller.disable();
  45296. return;
  45297. }
  45298. controller.enable(seriesModel.get('roam'));
  45299. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  45300. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  45301. controller
  45302. .off('pan')
  45303. .off('zoom')
  45304. .on('pan', function (dx, dy) {
  45305. updateViewOnPan(controllerHost, dx, dy);
  45306. api.dispatchAction({
  45307. seriesId: seriesModel.id,
  45308. type: 'graphRoam',
  45309. dx: dx,
  45310. dy: dy
  45311. });
  45312. })
  45313. .on('zoom', function (zoom, mouseX, mouseY) {
  45314. updateViewOnZoom(controllerHost, zoom, mouseX, mouseY);
  45315. api.dispatchAction({
  45316. seriesId: seriesModel.id,
  45317. type: 'graphRoam',
  45318. zoom: zoom,
  45319. originX: mouseX,
  45320. originY: mouseY
  45321. });
  45322. this._updateNodeAndLinkScale();
  45323. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45324. this._lineDraw.updateLayout();
  45325. }, this);
  45326. },
  45327. _updateNodeAndLinkScale: function () {
  45328. var seriesModel = this._model;
  45329. var data = seriesModel.getData();
  45330. var nodeScale = this._getNodeGlobalScale(seriesModel);
  45331. var invScale = [nodeScale, nodeScale];
  45332. data.eachItemGraphicEl(function (el, idx) {
  45333. el.attr('scale', invScale);
  45334. });
  45335. },
  45336. _getNodeGlobalScale: function (seriesModel) {
  45337. var coordSys = seriesModel.coordinateSystem;
  45338. if (coordSys.type !== 'view') {
  45339. return 1;
  45340. }
  45341. var nodeScaleRatio = this._nodeScaleRatio;
  45342. var groupScale = coordSys.scale;
  45343. var groupZoom = (groupScale && groupScale[0]) || 1;
  45344. // Scale node when zoom changes
  45345. var roamZoom = coordSys.getZoom();
  45346. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  45347. return nodeScale / groupZoom;
  45348. },
  45349. updateLayout: function (seriesModel) {
  45350. adjustEdge(seriesModel.getGraph(), this._getNodeGlobalScale(seriesModel));
  45351. this._symbolDraw.updateLayout();
  45352. this._lineDraw.updateLayout();
  45353. },
  45354. remove: function (ecModel, api) {
  45355. this._symbolDraw && this._symbolDraw.remove();
  45356. this._lineDraw && this._lineDraw.remove();
  45357. }
  45358. });
  45359. /*
  45360. * Licensed to the Apache Software Foundation (ASF) under one
  45361. * or more contributor license agreements. See the NOTICE file
  45362. * distributed with this work for additional information
  45363. * regarding copyright ownership. The ASF licenses this file
  45364. * to you under the Apache License, Version 2.0 (the
  45365. * "License"); you may not use this file except in compliance
  45366. * with the License. You may obtain a copy of the License at
  45367. *
  45368. * http://www.apache.org/licenses/LICENSE-2.0
  45369. *
  45370. * Unless required by applicable law or agreed to in writing,
  45371. * software distributed under the License is distributed on an
  45372. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45373. * KIND, either express or implied. See the License for the
  45374. * specific language governing permissions and limitations
  45375. * under the License.
  45376. */
  45377. var actionInfo = {
  45378. type: 'graphRoam',
  45379. event: 'graphRoam',
  45380. update: 'none'
  45381. };
  45382. /**
  45383. * @payload
  45384. * @property {string} name Series name
  45385. * @property {number} [dx]
  45386. * @property {number} [dy]
  45387. * @property {number} [zoom]
  45388. * @property {number} [originX]
  45389. * @property {number} [originY]
  45390. */
  45391. registerAction(actionInfo, function (payload, ecModel) {
  45392. ecModel.eachComponent({mainType: 'series', query: payload}, function (seriesModel) {
  45393. var coordSys = seriesModel.coordinateSystem;
  45394. var res = updateCenterAndZoom(coordSys, payload);
  45395. seriesModel.setCenter
  45396. && seriesModel.setCenter(res.center);
  45397. seriesModel.setZoom
  45398. && seriesModel.setZoom(res.zoom);
  45399. });
  45400. });
  45401. /**
  45402. * @payload
  45403. * @property {number} [seriesIndex]
  45404. * @property {string} [seriesId]
  45405. * @property {string} [seriesName]
  45406. * @property {number} [dataIndex]
  45407. */
  45408. registerAction({
  45409. type: 'focusNodeAdjacency',
  45410. event: 'focusNodeAdjacency',
  45411. update: 'series.graph:focusNodeAdjacency'
  45412. }, function () {});
  45413. /**
  45414. * @payload
  45415. * @property {number} [seriesIndex]
  45416. * @property {string} [seriesId]
  45417. * @property {string} [seriesName]
  45418. */
  45419. registerAction({
  45420. type: 'unfocusNodeAdjacency',
  45421. event: 'unfocusNodeAdjacency',
  45422. update: 'series.graph:unfocusNodeAdjacency'
  45423. }, function () {});
  45424. /*
  45425. * Licensed to the Apache Software Foundation (ASF) under one
  45426. * or more contributor license agreements. See the NOTICE file
  45427. * distributed with this work for additional information
  45428. * regarding copyright ownership. The ASF licenses this file
  45429. * to you under the Apache License, Version 2.0 (the
  45430. * "License"); you may not use this file except in compliance
  45431. * with the License. You may obtain a copy of the License at
  45432. *
  45433. * http://www.apache.org/licenses/LICENSE-2.0
  45434. *
  45435. * Unless required by applicable law or agreed to in writing,
  45436. * software distributed under the License is distributed on an
  45437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45438. * KIND, either express or implied. See the License for the
  45439. * specific language governing permissions and limitations
  45440. * under the License.
  45441. */
  45442. var categoryFilter = function (ecModel) {
  45443. var legendModels = ecModel.findComponents({
  45444. mainType: 'legend'
  45445. });
  45446. if (!legendModels || !legendModels.length) {
  45447. return;
  45448. }
  45449. ecModel.eachSeriesByType('graph', function (graphSeries) {
  45450. var categoriesData = graphSeries.getCategoriesData();
  45451. var graph = graphSeries.getGraph();
  45452. var data = graph.data;
  45453. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  45454. data.filterSelf(function (idx) {
  45455. var model = data.getItemModel(idx);
  45456. var category = model.getShallow('category');
  45457. if (category != null) {
  45458. if (typeof category === 'number') {
  45459. category = categoryNames[category];
  45460. }
  45461. // If in any legend component the status is not selected.
  45462. for (var i = 0; i < legendModels.length; i++) {
  45463. if (!legendModels[i].isSelected(category)) {
  45464. return false;
  45465. }
  45466. }
  45467. }
  45468. return true;
  45469. });
  45470. }, this);
  45471. };
  45472. /*
  45473. * Licensed to the Apache Software Foundation (ASF) under one
  45474. * or more contributor license agreements. See the NOTICE file
  45475. * distributed with this work for additional information
  45476. * regarding copyright ownership. The ASF licenses this file
  45477. * to you under the Apache License, Version 2.0 (the
  45478. * "License"); you may not use this file except in compliance
  45479. * with the License. You may obtain a copy of the License at
  45480. *
  45481. * http://www.apache.org/licenses/LICENSE-2.0
  45482. *
  45483. * Unless required by applicable law or agreed to in writing,
  45484. * software distributed under the License is distributed on an
  45485. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45486. * KIND, either express or implied. See the License for the
  45487. * specific language governing permissions and limitations
  45488. * under the License.
  45489. */
  45490. var categoryVisual = function (ecModel) {
  45491. var paletteScope = {};
  45492. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45493. var categoriesData = seriesModel.getCategoriesData();
  45494. var data = seriesModel.getData();
  45495. var categoryNameIdxMap = {};
  45496. categoriesData.each(function (idx) {
  45497. var name = categoriesData.getName(idx);
  45498. // Add prefix to avoid conflict with Object.prototype.
  45499. categoryNameIdxMap['ec-' + name] = idx;
  45500. var itemModel = categoriesData.getItemModel(idx);
  45501. var color = itemModel.get('itemStyle.color')
  45502. || seriesModel.getColorFromPalette(name, paletteScope);
  45503. categoriesData.setItemVisual(idx, 'color', color);
  45504. });
  45505. // Assign category color to visual
  45506. if (categoriesData.count()) {
  45507. data.each(function (idx) {
  45508. var model = data.getItemModel(idx);
  45509. var category = model.getShallow('category');
  45510. if (category != null) {
  45511. if (typeof category === 'string') {
  45512. category = categoryNameIdxMap['ec-' + category];
  45513. }
  45514. if (!data.getItemVisual(idx, 'color', true)) {
  45515. data.setItemVisual(
  45516. idx, 'color',
  45517. categoriesData.getItemVisual(category, 'color')
  45518. );
  45519. }
  45520. }
  45521. });
  45522. }
  45523. });
  45524. };
  45525. /*
  45526. * Licensed to the Apache Software Foundation (ASF) under one
  45527. * or more contributor license agreements. See the NOTICE file
  45528. * distributed with this work for additional information
  45529. * regarding copyright ownership. The ASF licenses this file
  45530. * to you under the Apache License, Version 2.0 (the
  45531. * "License"); you may not use this file except in compliance
  45532. * with the License. You may obtain a copy of the License at
  45533. *
  45534. * http://www.apache.org/licenses/LICENSE-2.0
  45535. *
  45536. * Unless required by applicable law or agreed to in writing,
  45537. * software distributed under the License is distributed on an
  45538. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45539. * KIND, either express or implied. See the License for the
  45540. * specific language governing permissions and limitations
  45541. * under the License.
  45542. */
  45543. function normalize$1(a) {
  45544. if (!(a instanceof Array)) {
  45545. a = [a, a];
  45546. }
  45547. return a;
  45548. }
  45549. var edgeVisual = function (ecModel) {
  45550. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45551. var graph = seriesModel.getGraph();
  45552. var edgeData = seriesModel.getEdgeData();
  45553. var symbolType = normalize$1(seriesModel.get('edgeSymbol'));
  45554. var symbolSize = normalize$1(seriesModel.get('edgeSymbolSize'));
  45555. var colorQuery = 'lineStyle.color'.split('.');
  45556. var opacityQuery = 'lineStyle.opacity'.split('.');
  45557. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  45558. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  45559. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  45560. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  45561. edgeData.setVisual('color', seriesModel.get(colorQuery));
  45562. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  45563. edgeData.each(function (idx) {
  45564. var itemModel = edgeData.getItemModel(idx);
  45565. var edge = graph.getEdgeByIndex(idx);
  45566. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  45567. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  45568. // Edge visual must after node visual
  45569. var color = itemModel.get(colorQuery);
  45570. var opacity = itemModel.get(opacityQuery);
  45571. switch (color) {
  45572. case 'source':
  45573. color = edge.node1.getVisual('color');
  45574. break;
  45575. case 'target':
  45576. color = edge.node2.getVisual('color');
  45577. break;
  45578. }
  45579. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  45580. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  45581. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  45582. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  45583. edge.setVisual('color', color);
  45584. edge.setVisual('opacity', opacity);
  45585. });
  45586. });
  45587. };
  45588. /*
  45589. * Licensed to the Apache Software Foundation (ASF) under one
  45590. * or more contributor license agreements. See the NOTICE file
  45591. * distributed with this work for additional information
  45592. * regarding copyright ownership. The ASF licenses this file
  45593. * to you under the Apache License, Version 2.0 (the
  45594. * "License"); you may not use this file except in compliance
  45595. * with the License. You may obtain a copy of the License at
  45596. *
  45597. * http://www.apache.org/licenses/LICENSE-2.0
  45598. *
  45599. * Unless required by applicable law or agreed to in writing,
  45600. * software distributed under the License is distributed on an
  45601. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45602. * KIND, either express or implied. See the License for the
  45603. * specific language governing permissions and limitations
  45604. * under the License.
  45605. */
  45606. function simpleLayout$1(seriesModel) {
  45607. var coordSys = seriesModel.coordinateSystem;
  45608. if (coordSys && coordSys.type !== 'view') {
  45609. return;
  45610. }
  45611. var graph = seriesModel.getGraph();
  45612. graph.eachNode(function (node) {
  45613. var model = node.getModel();
  45614. node.setLayout([+model.get('x'), +model.get('y')]);
  45615. });
  45616. simpleLayoutEdge(graph);
  45617. }
  45618. function simpleLayoutEdge(graph) {
  45619. graph.eachEdge(function (edge) {
  45620. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  45621. var p1 = clone$1(edge.node1.getLayout());
  45622. var p2 = clone$1(edge.node2.getLayout());
  45623. var points = [p1, p2];
  45624. if (+curveness) {
  45625. points.push([
  45626. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness,
  45627. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness
  45628. ]);
  45629. }
  45630. edge.setLayout(points);
  45631. });
  45632. }
  45633. /*
  45634. * Licensed to the Apache Software Foundation (ASF) under one
  45635. * or more contributor license agreements. See the NOTICE file
  45636. * distributed with this work for additional information
  45637. * regarding copyright ownership. The ASF licenses this file
  45638. * to you under the Apache License, Version 2.0 (the
  45639. * "License"); you may not use this file except in compliance
  45640. * with the License. You may obtain a copy of the License at
  45641. *
  45642. * http://www.apache.org/licenses/LICENSE-2.0
  45643. *
  45644. * Unless required by applicable law or agreed to in writing,
  45645. * software distributed under the License is distributed on an
  45646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45647. * KIND, either express or implied. See the License for the
  45648. * specific language governing permissions and limitations
  45649. * under the License.
  45650. */
  45651. var simpleLayout = function (ecModel, api) {
  45652. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45653. var layout = seriesModel.get('layout');
  45654. var coordSys = seriesModel.coordinateSystem;
  45655. if (coordSys && coordSys.type !== 'view') {
  45656. var data = seriesModel.getData();
  45657. var dimensions = [];
  45658. each$1(coordSys.dimensions, function (coordDim) {
  45659. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  45660. });
  45661. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  45662. var value = [];
  45663. var hasValue = false;
  45664. for (var i = 0; i < dimensions.length; i++) {
  45665. var val = data.get(dimensions[i], dataIndex);
  45666. if (!isNaN(val)) {
  45667. hasValue = true;
  45668. }
  45669. value.push(val);
  45670. }
  45671. if (hasValue) {
  45672. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  45673. }
  45674. else {
  45675. // Also {Array.<number>}, not undefined to avoid if...else... statement
  45676. data.setItemLayout(dataIndex, [NaN, NaN]);
  45677. }
  45678. }
  45679. simpleLayoutEdge(data.graph);
  45680. }
  45681. else if (!layout || layout === 'none') {
  45682. simpleLayout$1(seriesModel);
  45683. }
  45684. });
  45685. };
  45686. /*
  45687. * Licensed to the Apache Software Foundation (ASF) under one
  45688. * or more contributor license agreements. See the NOTICE file
  45689. * distributed with this work for additional information
  45690. * regarding copyright ownership. The ASF licenses this file
  45691. * to you under the Apache License, Version 2.0 (the
  45692. * "License"); you may not use this file except in compliance
  45693. * with the License. You may obtain a copy of the License at
  45694. *
  45695. * http://www.apache.org/licenses/LICENSE-2.0
  45696. *
  45697. * Unless required by applicable law or agreed to in writing,
  45698. * software distributed under the License is distributed on an
  45699. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45700. * KIND, either express or implied. See the License for the
  45701. * specific language governing permissions and limitations
  45702. * under the License.
  45703. */
  45704. function circularLayout$1(seriesModel) {
  45705. var coordSys = seriesModel.coordinateSystem;
  45706. if (coordSys && coordSys.type !== 'view') {
  45707. return;
  45708. }
  45709. var rect = coordSys.getBoundingRect();
  45710. var nodeData = seriesModel.getData();
  45711. var graph = nodeData.graph;
  45712. var angle = 0;
  45713. var sum = nodeData.getSum('value');
  45714. var unitAngle = Math.PI * 2 / (sum || nodeData.count());
  45715. var cx = rect.width / 2 + rect.x;
  45716. var cy = rect.height / 2 + rect.y;
  45717. var r = Math.min(rect.width, rect.height) / 2;
  45718. graph.eachNode(function (node) {
  45719. var value = node.getValue('value');
  45720. angle += unitAngle * (sum ? value : 1) / 2;
  45721. node.setLayout([
  45722. r * Math.cos(angle) + cx,
  45723. r * Math.sin(angle) + cy
  45724. ]);
  45725. angle += unitAngle * (sum ? value : 1) / 2;
  45726. });
  45727. nodeData.setLayout({
  45728. cx: cx,
  45729. cy: cy
  45730. });
  45731. graph.eachEdge(function (edge) {
  45732. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  45733. var p1 = clone$1(edge.node1.getLayout());
  45734. var p2 = clone$1(edge.node2.getLayout());
  45735. var cp1;
  45736. var x12 = (p1[0] + p2[0]) / 2;
  45737. var y12 = (p1[1] + p2[1]) / 2;
  45738. if (+curveness) {
  45739. curveness *= 3;
  45740. cp1 = [
  45741. cx * curveness + x12 * (1 - curveness),
  45742. cy * curveness + y12 * (1 - curveness)
  45743. ];
  45744. }
  45745. edge.setLayout([p1, p2, cp1]);
  45746. });
  45747. }
  45748. /*
  45749. * Licensed to the Apache Software Foundation (ASF) under one
  45750. * or more contributor license agreements. See the NOTICE file
  45751. * distributed with this work for additional information
  45752. * regarding copyright ownership. The ASF licenses this file
  45753. * to you under the Apache License, Version 2.0 (the
  45754. * "License"); you may not use this file except in compliance
  45755. * with the License. You may obtain a copy of the License at
  45756. *
  45757. * http://www.apache.org/licenses/LICENSE-2.0
  45758. *
  45759. * Unless required by applicable law or agreed to in writing,
  45760. * software distributed under the License is distributed on an
  45761. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45762. * KIND, either express or implied. See the License for the
  45763. * specific language governing permissions and limitations
  45764. * under the License.
  45765. */
  45766. var circularLayout = function (ecModel) {
  45767. ecModel.eachSeriesByType('graph', function (seriesModel) {
  45768. if (seriesModel.get('layout') === 'circular') {
  45769. circularLayout$1(seriesModel);
  45770. }
  45771. });
  45772. };
  45773. /*
  45774. * Licensed to the Apache Software Foundation (ASF) under one
  45775. * or more contributor license agreements. See the NOTICE file
  45776. * distributed with this work for additional information
  45777. * regarding copyright ownership. The ASF licenses this file
  45778. * to you under the Apache License, Version 2.0 (the
  45779. * "License"); you may not use this file except in compliance
  45780. * with the License. You may obtain a copy of the License at
  45781. *
  45782. * http://www.apache.org/licenses/LICENSE-2.0
  45783. *
  45784. * Unless required by applicable law or agreed to in writing,
  45785. * software distributed under the License is distributed on an
  45786. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45787. * KIND, either express or implied. See the License for the
  45788. * specific language governing permissions and limitations
  45789. * under the License.
  45790. */
  45791. /*
  45792. * The layout implementation references to d3.js. The use of
  45793. * the source code of this file is also subject to the terms
  45794. * and consitions of its license (BSD-3Clause, see
  45795. * <echarts/src/licenses/LICENSE-d3>).
  45796. */
  45797. var scaleAndAdd$2 = scaleAndAdd;
  45798. // function adjacentNode(n, e) {
  45799. // return e.n1 === n ? e.n2 : e.n1;
  45800. // }
  45801. function forceLayout$1(nodes, edges, opts) {
  45802. var rect = opts.rect;
  45803. var width = rect.width;
  45804. var height = rect.height;
  45805. var center = [rect.x + width / 2, rect.y + height / 2];
  45806. // var scale = opts.scale || 1;
  45807. var gravity = opts.gravity == null ? 0.1 : opts.gravity;
  45808. // for (var i = 0; i < edges.length; i++) {
  45809. // var e = edges[i];
  45810. // var n1 = e.n1;
  45811. // var n2 = e.n2;
  45812. // n1.edges = n1.edges || [];
  45813. // n2.edges = n2.edges || [];
  45814. // n1.edges.push(e);
  45815. // n2.edges.push(e);
  45816. // }
  45817. // Init position
  45818. for (var i = 0; i < nodes.length; i++) {
  45819. var n = nodes[i];
  45820. if (!n.p) {
  45821. // Use the position from first adjecent node with defined position
  45822. // Or use a random position
  45823. // From d3
  45824. // if (n.edges) {
  45825. // var j = -1;
  45826. // while (++j < n.edges.length) {
  45827. // var e = n.edges[j];
  45828. // var other = adjacentNode(n, e);
  45829. // if (other.p) {
  45830. // n.p = vec2.clone(other.p);
  45831. // break;
  45832. // }
  45833. // }
  45834. // }
  45835. // if (!n.p) {
  45836. n.p = create(
  45837. width * (Math.random() - 0.5) + center[0],
  45838. height * (Math.random() - 0.5) + center[1]
  45839. );
  45840. // }
  45841. }
  45842. n.pp = clone$1(n.p);
  45843. n.edges = null;
  45844. }
  45845. // Formula in 'Graph Drawing by Force-directed Placement'
  45846. // var k = scale * Math.sqrt(width * height / nodes.length);
  45847. // var k2 = k * k;
  45848. var friction = 0.6;
  45849. return {
  45850. warmUp: function () {
  45851. friction = 0.5;
  45852. },
  45853. setFixed: function (idx) {
  45854. nodes[idx].fixed = true;
  45855. },
  45856. setUnfixed: function (idx) {
  45857. nodes[idx].fixed = false;
  45858. },
  45859. step: function (cb) {
  45860. var v12 = [];
  45861. var nLen = nodes.length;
  45862. for (var i = 0; i < edges.length; i++) {
  45863. var e = edges[i];
  45864. var n1 = e.n1;
  45865. var n2 = e.n2;
  45866. sub(v12, n2.p, n1.p);
  45867. var d = len(v12) - e.d;
  45868. var w = n2.w / (n1.w + n2.w);
  45869. if (isNaN(w)) {
  45870. w = 0;
  45871. }
  45872. normalize(v12, v12);
  45873. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  45874. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  45875. }
  45876. // Gravity
  45877. for (var i = 0; i < nLen; i++) {
  45878. var n = nodes[i];
  45879. if (!n.fixed) {
  45880. sub(v12, center, n.p);
  45881. // var d = vec2.len(v12);
  45882. // vec2.scale(v12, v12, 1 / d);
  45883. // var gravityFactor = gravity;
  45884. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  45885. }
  45886. }
  45887. // Repulsive
  45888. // PENDING
  45889. for (var i = 0; i < nLen; i++) {
  45890. var n1 = nodes[i];
  45891. for (var j = i + 1; j < nLen; j++) {
  45892. var n2 = nodes[j];
  45893. sub(v12, n2.p, n1.p);
  45894. var d = len(v12);
  45895. if (d === 0) {
  45896. // Random repulse
  45897. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  45898. d = 1;
  45899. }
  45900. var repFact = (n1.rep + n2.rep) / d / d;
  45901. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  45902. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  45903. }
  45904. }
  45905. var v = [];
  45906. for (var i = 0; i < nLen; i++) {
  45907. var n = nodes[i];
  45908. if (!n.fixed) {
  45909. sub(v, n.p, n.pp);
  45910. scaleAndAdd$2(n.p, n.p, v, friction);
  45911. copy(n.pp, n.p);
  45912. }
  45913. }
  45914. friction = friction * 0.992;
  45915. cb && cb(nodes, edges, friction < 0.01);
  45916. }
  45917. };
  45918. }
  45919. /*
  45920. * Licensed to the Apache Software Foundation (ASF) under one
  45921. * or more contributor license agreements. See the NOTICE file
  45922. * distributed with this work for additional information
  45923. * regarding copyright ownership. The ASF licenses this file
  45924. * to you under the Apache License, Version 2.0 (the
  45925. * "License"); you may not use this file except in compliance
  45926. * with the License. You may obtain a copy of the License at
  45927. *
  45928. * http://www.apache.org/licenses/LICENSE-2.0
  45929. *
  45930. * Unless required by applicable law or agreed to in writing,
  45931. * software distributed under the License is distributed on an
  45932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45933. * KIND, either express or implied. See the License for the
  45934. * specific language governing permissions and limitations
  45935. * under the License.
  45936. */
  45937. var forceLayout = function (ecModel) {
  45938. ecModel.eachSeriesByType('graph', function (graphSeries) {
  45939. var coordSys = graphSeries.coordinateSystem;
  45940. if (coordSys && coordSys.type !== 'view') {
  45941. return;
  45942. }
  45943. if (graphSeries.get('layout') === 'force') {
  45944. var preservedPoints = graphSeries.preservedPoints || {};
  45945. var graph = graphSeries.getGraph();
  45946. var nodeData = graph.data;
  45947. var edgeData = graph.edgeData;
  45948. var forceModel = graphSeries.getModel('force');
  45949. var initLayout = forceModel.get('initLayout');
  45950. if (graphSeries.preservedPoints) {
  45951. nodeData.each(function (idx) {
  45952. var id = nodeData.getId(idx);
  45953. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  45954. });
  45955. }
  45956. else if (!initLayout || initLayout === 'none') {
  45957. simpleLayout$1(graphSeries);
  45958. }
  45959. else if (initLayout === 'circular') {
  45960. circularLayout$1(graphSeries);
  45961. }
  45962. var nodeDataExtent = nodeData.getDataExtent('value');
  45963. var edgeDataExtent = edgeData.getDataExtent('value');
  45964. // var edgeDataExtent = edgeData.getDataExtent('value');
  45965. var repulsion = forceModel.get('repulsion');
  45966. var edgeLength = forceModel.get('edgeLength');
  45967. if (!isArray(repulsion)) {
  45968. repulsion = [repulsion, repulsion];
  45969. }
  45970. if (!isArray(edgeLength)) {
  45971. edgeLength = [edgeLength, edgeLength];
  45972. }
  45973. // Larger value has smaller length
  45974. edgeLength = [edgeLength[1], edgeLength[0]];
  45975. var nodes = nodeData.mapArray('value', function (value, idx) {
  45976. var point = nodeData.getItemLayout(idx);
  45977. var rep = linearMap(value, nodeDataExtent, repulsion);
  45978. if (isNaN(rep)) {
  45979. rep = (repulsion[0] + repulsion[1]) / 2;
  45980. }
  45981. return {
  45982. w: rep,
  45983. rep: rep,
  45984. fixed: nodeData.getItemModel(idx).get('fixed'),
  45985. p: (!point || isNaN(point[0]) || isNaN(point[1])) ? null : point
  45986. };
  45987. });
  45988. var edges = edgeData.mapArray('value', function (value, idx) {
  45989. var edge = graph.getEdgeByIndex(idx);
  45990. var d = linearMap(value, edgeDataExtent, edgeLength);
  45991. if (isNaN(d)) {
  45992. d = (edgeLength[0] + edgeLength[1]) / 2;
  45993. }
  45994. return {
  45995. n1: nodes[edge.node1.dataIndex],
  45996. n2: nodes[edge.node2.dataIndex],
  45997. d: d,
  45998. curveness: edge.getModel().get('lineStyle.curveness') || 0
  45999. };
  46000. });
  46001. var coordSys = graphSeries.coordinateSystem;
  46002. var rect = coordSys.getBoundingRect();
  46003. var forceInstance = forceLayout$1(nodes, edges, {
  46004. rect: rect,
  46005. gravity: forceModel.get('gravity')
  46006. });
  46007. var oldStep = forceInstance.step;
  46008. forceInstance.step = function (cb) {
  46009. for (var i = 0, l = nodes.length; i < l; i++) {
  46010. if (nodes[i].fixed) {
  46011. // Write back to layout instance
  46012. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  46013. }
  46014. }
  46015. oldStep(function (nodes, edges, stopped) {
  46016. for (var i = 0, l = nodes.length; i < l; i++) {
  46017. if (!nodes[i].fixed) {
  46018. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  46019. }
  46020. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  46021. }
  46022. for (var i = 0, l = edges.length; i < l; i++) {
  46023. var e = edges[i];
  46024. var edge = graph.getEdgeByIndex(i);
  46025. var p1 = e.n1.p;
  46026. var p2 = e.n2.p;
  46027. var points = edge.getLayout();
  46028. points = points ? points.slice() : [];
  46029. points[0] = points[0] || [];
  46030. points[1] = points[1] || [];
  46031. copy(points[0], p1);
  46032. copy(points[1], p2);
  46033. if (+e.curveness) {
  46034. points[2] = [
  46035. (p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness,
  46036. (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness
  46037. ];
  46038. }
  46039. edge.setLayout(points);
  46040. }
  46041. // Update layout
  46042. cb && cb(stopped);
  46043. });
  46044. };
  46045. graphSeries.forceLayout = forceInstance;
  46046. graphSeries.preservedPoints = preservedPoints;
  46047. // Step to get the layout
  46048. forceInstance.step();
  46049. }
  46050. else {
  46051. // Remove prev injected forceLayout instance
  46052. graphSeries.forceLayout = null;
  46053. }
  46054. });
  46055. };
  46056. /*
  46057. * Licensed to the Apache Software Foundation (ASF) under one
  46058. * or more contributor license agreements. See the NOTICE file
  46059. * distributed with this work for additional information
  46060. * regarding copyright ownership. The ASF licenses this file
  46061. * to you under the Apache License, Version 2.0 (the
  46062. * "License"); you may not use this file except in compliance
  46063. * with the License. You may obtain a copy of the License at
  46064. *
  46065. * http://www.apache.org/licenses/LICENSE-2.0
  46066. *
  46067. * Unless required by applicable law or agreed to in writing,
  46068. * software distributed under the License is distributed on an
  46069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46070. * KIND, either express or implied. See the License for the
  46071. * specific language governing permissions and limitations
  46072. * under the License.
  46073. */
  46074. // FIXME Where to create the simple view coordinate system
  46075. function getViewRect$1(seriesModel, api, aspect) {
  46076. var option = seriesModel.getBoxLayoutParams();
  46077. option.aspect = aspect;
  46078. return getLayoutRect(option, {
  46079. width: api.getWidth(),
  46080. height: api.getHeight()
  46081. });
  46082. }
  46083. var createView = function (ecModel, api) {
  46084. var viewList = [];
  46085. ecModel.eachSeriesByType('graph', function (seriesModel) {
  46086. var coordSysType = seriesModel.get('coordinateSystem');
  46087. if (!coordSysType || coordSysType === 'view') {
  46088. var data = seriesModel.getData();
  46089. var positions = data.mapArray(function (idx) {
  46090. var itemModel = data.getItemModel(idx);
  46091. return [+itemModel.get('x'), +itemModel.get('y')];
  46092. });
  46093. var min = [];
  46094. var max = [];
  46095. fromPoints(positions, min, max);
  46096. // If width or height is 0
  46097. if (max[0] - min[0] === 0) {
  46098. max[0] += 1;
  46099. min[0] -= 1;
  46100. }
  46101. if (max[1] - min[1] === 0) {
  46102. max[1] += 1;
  46103. min[1] -= 1;
  46104. }
  46105. var aspect = (max[0] - min[0]) / (max[1] - min[1]);
  46106. // FIXME If get view rect after data processed?
  46107. var viewRect = getViewRect$1(seriesModel, api, aspect);
  46108. // Position may be NaN, use view rect instead
  46109. if (isNaN(aspect)) {
  46110. min = [viewRect.x, viewRect.y];
  46111. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  46112. }
  46113. var bbWidth = max[0] - min[0];
  46114. var bbHeight = max[1] - min[1];
  46115. var viewWidth = viewRect.width;
  46116. var viewHeight = viewRect.height;
  46117. var viewCoordSys = seriesModel.coordinateSystem = new View();
  46118. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  46119. viewCoordSys.setBoundingRect(
  46120. min[0], min[1], bbWidth, bbHeight
  46121. );
  46122. viewCoordSys.setViewRect(
  46123. viewRect.x, viewRect.y, viewWidth, viewHeight
  46124. );
  46125. // Update roam info
  46126. viewCoordSys.setCenter(seriesModel.get('center'));
  46127. viewCoordSys.setZoom(seriesModel.get('zoom'));
  46128. viewList.push(viewCoordSys);
  46129. }
  46130. });
  46131. return viewList;
  46132. };
  46133. /*
  46134. * Licensed to the Apache Software Foundation (ASF) under one
  46135. * or more contributor license agreements. See the NOTICE file
  46136. * distributed with this work for additional information
  46137. * regarding copyright ownership. The ASF licenses this file
  46138. * to you under the Apache License, Version 2.0 (the
  46139. * "License"); you may not use this file except in compliance
  46140. * with the License. You may obtain a copy of the License at
  46141. *
  46142. * http://www.apache.org/licenses/LICENSE-2.0
  46143. *
  46144. * Unless required by applicable law or agreed to in writing,
  46145. * software distributed under the License is distributed on an
  46146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46147. * KIND, either express or implied. See the License for the
  46148. * specific language governing permissions and limitations
  46149. * under the License.
  46150. */
  46151. registerProcessor(categoryFilter);
  46152. registerVisual(visualSymbol('graph', 'circle', null));
  46153. registerVisual(categoryVisual);
  46154. registerVisual(edgeVisual);
  46155. registerLayout(simpleLayout);
  46156. registerLayout(circularLayout);
  46157. registerLayout(forceLayout);
  46158. // Graph view coordinate system
  46159. registerCoordinateSystem('graphView', {
  46160. create: createView
  46161. });
  46162. /*
  46163. * Licensed to the Apache Software Foundation (ASF) under one
  46164. * or more contributor license agreements. See the NOTICE file
  46165. * distributed with this work for additional information
  46166. * regarding copyright ownership. The ASF licenses this file
  46167. * to you under the Apache License, Version 2.0 (the
  46168. * "License"); you may not use this file except in compliance
  46169. * with the License. You may obtain a copy of the License at
  46170. *
  46171. * http://www.apache.org/licenses/LICENSE-2.0
  46172. *
  46173. * Unless required by applicable law or agreed to in writing,
  46174. * software distributed under the License is distributed on an
  46175. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46176. * KIND, either express or implied. See the License for the
  46177. * specific language governing permissions and limitations
  46178. * under the License.
  46179. */
  46180. var GaugeSeries = SeriesModel.extend({
  46181. type: 'series.gauge',
  46182. getInitialData: function (option, ecModel) {
  46183. var dataOpt = option.data || [];
  46184. if (!isArray(dataOpt)) {
  46185. dataOpt = [dataOpt];
  46186. }
  46187. option.data = dataOpt;
  46188. return createListSimply(this, ['value']);
  46189. },
  46190. defaultOption: {
  46191. zlevel: 0,
  46192. z: 2,
  46193. // 默认全局居中
  46194. center: ['50%', '50%'],
  46195. legendHoverLink: true,
  46196. radius: '75%',
  46197. startAngle: 225,
  46198. endAngle: -45,
  46199. clockwise: true,
  46200. // 最小值
  46201. min: 0,
  46202. // 最大值
  46203. max: 100,
  46204. // 分割段数,默认为10
  46205. splitNumber: 10,
  46206. // 坐标轴线
  46207. axisLine: {
  46208. // 默认显示,属性show控制显示与否
  46209. show: true,
  46210. lineStyle: { // 属性lineStyle控制线条样式
  46211. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  46212. width: 30
  46213. }
  46214. },
  46215. // 分隔线
  46216. splitLine: {
  46217. // 默认显示,属性show控制显示与否
  46218. show: true,
  46219. // 属性length控制线长
  46220. length: 30,
  46221. // 属性lineStyle(详见lineStyle)控制线条样式
  46222. lineStyle: {
  46223. color: '#eee',
  46224. width: 2,
  46225. type: 'solid'
  46226. }
  46227. },
  46228. // 坐标轴小标记
  46229. axisTick: {
  46230. // 属性show控制显示与否,默认不显示
  46231. show: true,
  46232. // 每份split细分多少段
  46233. splitNumber: 5,
  46234. // 属性length控制线长
  46235. length: 8,
  46236. // 属性lineStyle控制线条样式
  46237. lineStyle: {
  46238. color: '#eee',
  46239. width: 1,
  46240. type: 'solid'
  46241. }
  46242. },
  46243. axisLabel: {
  46244. show: true,
  46245. distance: 5,
  46246. // formatter: null,
  46247. color: 'auto'
  46248. },
  46249. pointer: {
  46250. show: true,
  46251. length: '80%',
  46252. width: 8
  46253. },
  46254. itemStyle: {
  46255. color: 'auto'
  46256. },
  46257. title: {
  46258. show: true,
  46259. // x, y,单位px
  46260. offsetCenter: [0, '-40%'],
  46261. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  46262. color: '#333',
  46263. fontSize: 15
  46264. },
  46265. detail: {
  46266. show: true,
  46267. backgroundColor: 'rgba(0,0,0,0)',
  46268. borderWidth: 0,
  46269. borderColor: '#ccc',
  46270. width: 100,
  46271. height: null, // self-adaption
  46272. padding: [5, 10],
  46273. // x, y,单位px
  46274. offsetCenter: [0, '40%'],
  46275. // formatter: null,
  46276. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  46277. color: 'auto',
  46278. fontSize: 30
  46279. }
  46280. }
  46281. });
  46282. /*
  46283. * Licensed to the Apache Software Foundation (ASF) under one
  46284. * or more contributor license agreements. See the NOTICE file
  46285. * distributed with this work for additional information
  46286. * regarding copyright ownership. The ASF licenses this file
  46287. * to you under the Apache License, Version 2.0 (the
  46288. * "License"); you may not use this file except in compliance
  46289. * with the License. You may obtain a copy of the License at
  46290. *
  46291. * http://www.apache.org/licenses/LICENSE-2.0
  46292. *
  46293. * Unless required by applicable law or agreed to in writing,
  46294. * software distributed under the License is distributed on an
  46295. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46296. * KIND, either express or implied. See the License for the
  46297. * specific language governing permissions and limitations
  46298. * under the License.
  46299. */
  46300. var PointerPath = Path.extend({
  46301. type: 'echartsGaugePointer',
  46302. shape: {
  46303. angle: 0,
  46304. width: 10,
  46305. r: 10,
  46306. x: 0,
  46307. y: 0
  46308. },
  46309. buildPath: function (ctx, shape) {
  46310. var mathCos = Math.cos;
  46311. var mathSin = Math.sin;
  46312. var r = shape.r;
  46313. var width = shape.width;
  46314. var angle = shape.angle;
  46315. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  46316. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  46317. angle = shape.angle - Math.PI / 2;
  46318. ctx.moveTo(x, y);
  46319. ctx.lineTo(
  46320. shape.x + mathCos(angle) * width,
  46321. shape.y + mathSin(angle) * width
  46322. );
  46323. ctx.lineTo(
  46324. shape.x + mathCos(shape.angle) * r,
  46325. shape.y + mathSin(shape.angle) * r
  46326. );
  46327. ctx.lineTo(
  46328. shape.x - mathCos(angle) * width,
  46329. shape.y - mathSin(angle) * width
  46330. );
  46331. ctx.lineTo(x, y);
  46332. return;
  46333. }
  46334. });
  46335. /*
  46336. * Licensed to the Apache Software Foundation (ASF) under one
  46337. * or more contributor license agreements. See the NOTICE file
  46338. * distributed with this work for additional information
  46339. * regarding copyright ownership. The ASF licenses this file
  46340. * to you under the Apache License, Version 2.0 (the
  46341. * "License"); you may not use this file except in compliance
  46342. * with the License. You may obtain a copy of the License at
  46343. *
  46344. * http://www.apache.org/licenses/LICENSE-2.0
  46345. *
  46346. * Unless required by applicable law or agreed to in writing,
  46347. * software distributed under the License is distributed on an
  46348. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46349. * KIND, either express or implied. See the License for the
  46350. * specific language governing permissions and limitations
  46351. * under the License.
  46352. */
  46353. function parsePosition(seriesModel, api) {
  46354. var center = seriesModel.get('center');
  46355. var width = api.getWidth();
  46356. var height = api.getHeight();
  46357. var size = Math.min(width, height);
  46358. var cx = parsePercent$1(center[0], api.getWidth());
  46359. var cy = parsePercent$1(center[1], api.getHeight());
  46360. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  46361. return {
  46362. cx: cx,
  46363. cy: cy,
  46364. r: r
  46365. };
  46366. }
  46367. function formatLabel(label, labelFormatter) {
  46368. if (labelFormatter) {
  46369. if (typeof labelFormatter === 'string') {
  46370. label = labelFormatter.replace('{value}', label != null ? label : '');
  46371. }
  46372. else if (typeof labelFormatter === 'function') {
  46373. label = labelFormatter(label);
  46374. }
  46375. }
  46376. return label;
  46377. }
  46378. var PI2$5 = Math.PI * 2;
  46379. var GaugeView = Chart.extend({
  46380. type: 'gauge',
  46381. render: function (seriesModel, ecModel, api) {
  46382. this.group.removeAll();
  46383. var colorList = seriesModel.get('axisLine.lineStyle.color');
  46384. var posInfo = parsePosition(seriesModel, api);
  46385. this._renderMain(
  46386. seriesModel, ecModel, api, colorList, posInfo
  46387. );
  46388. },
  46389. dispose: function () {},
  46390. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  46391. var group = this.group;
  46392. var axisLineModel = seriesModel.getModel('axisLine');
  46393. var lineStyleModel = axisLineModel.getModel('lineStyle');
  46394. var clockwise = seriesModel.get('clockwise');
  46395. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  46396. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  46397. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  46398. var prevEndAngle = startAngle;
  46399. var axisLineWidth = lineStyleModel.get('width');
  46400. for (var i = 0; i < colorList.length; i++) {
  46401. // Clamp
  46402. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  46403. var endAngle = startAngle + angleRangeSpan * percent;
  46404. var sector = new Sector({
  46405. shape: {
  46406. startAngle: prevEndAngle,
  46407. endAngle: endAngle,
  46408. cx: posInfo.cx,
  46409. cy: posInfo.cy,
  46410. clockwise: clockwise,
  46411. r0: posInfo.r - axisLineWidth,
  46412. r: posInfo.r
  46413. },
  46414. silent: true
  46415. });
  46416. sector.setStyle({
  46417. fill: colorList[i][1]
  46418. });
  46419. sector.setStyle(lineStyleModel.getLineStyle(
  46420. // Because we use sector to simulate arc
  46421. // so the properties for stroking are useless
  46422. ['color', 'borderWidth', 'borderColor']
  46423. ));
  46424. group.add(sector);
  46425. prevEndAngle = endAngle;
  46426. }
  46427. var getColor = function (percent) {
  46428. // Less than 0
  46429. if (percent <= 0) {
  46430. return colorList[0][1];
  46431. }
  46432. for (var i = 0; i < colorList.length; i++) {
  46433. if (colorList[i][0] >= percent
  46434. && (i === 0 ? 0 : colorList[i - 1][0]) < percent
  46435. ) {
  46436. return colorList[i][1];
  46437. }
  46438. }
  46439. // More than 1
  46440. return colorList[i - 1][1];
  46441. };
  46442. if (!clockwise) {
  46443. var tmp = startAngle;
  46444. startAngle = endAngle;
  46445. endAngle = tmp;
  46446. }
  46447. this._renderTicks(
  46448. seriesModel, ecModel, api, getColor, posInfo,
  46449. startAngle, endAngle, clockwise
  46450. );
  46451. this._renderPointer(
  46452. seriesModel, ecModel, api, getColor, posInfo,
  46453. startAngle, endAngle, clockwise
  46454. );
  46455. this._renderTitle(
  46456. seriesModel, ecModel, api, getColor, posInfo
  46457. );
  46458. this._renderDetail(
  46459. seriesModel, ecModel, api, getColor, posInfo
  46460. );
  46461. },
  46462. _renderTicks: function (
  46463. seriesModel, ecModel, api, getColor, posInfo,
  46464. startAngle, endAngle, clockwise
  46465. ) {
  46466. var group = this.group;
  46467. var cx = posInfo.cx;
  46468. var cy = posInfo.cy;
  46469. var r = posInfo.r;
  46470. var minVal = +seriesModel.get('min');
  46471. var maxVal = +seriesModel.get('max');
  46472. var splitLineModel = seriesModel.getModel('splitLine');
  46473. var tickModel = seriesModel.getModel('axisTick');
  46474. var labelModel = seriesModel.getModel('axisLabel');
  46475. var splitNumber = seriesModel.get('splitNumber');
  46476. var subSplitNumber = tickModel.get('splitNumber');
  46477. var splitLineLen = parsePercent$1(
  46478. splitLineModel.get('length'), r
  46479. );
  46480. var tickLen = parsePercent$1(
  46481. tickModel.get('length'), r
  46482. );
  46483. var angle = startAngle;
  46484. var step = (endAngle - startAngle) / splitNumber;
  46485. var subStep = step / subSplitNumber;
  46486. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  46487. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  46488. for (var i = 0; i <= splitNumber; i++) {
  46489. var unitX = Math.cos(angle);
  46490. var unitY = Math.sin(angle);
  46491. // Split line
  46492. if (splitLineModel.get('show')) {
  46493. var splitLine = new Line({
  46494. shape: {
  46495. x1: unitX * r + cx,
  46496. y1: unitY * r + cy,
  46497. x2: unitX * (r - splitLineLen) + cx,
  46498. y2: unitY * (r - splitLineLen) + cy
  46499. },
  46500. style: splitLineStyle,
  46501. silent: true
  46502. });
  46503. if (splitLineStyle.stroke === 'auto') {
  46504. splitLine.setStyle({
  46505. stroke: getColor(i / splitNumber)
  46506. });
  46507. }
  46508. group.add(splitLine);
  46509. }
  46510. // Label
  46511. if (labelModel.get('show')) {
  46512. var label = formatLabel(
  46513. round$1(i / splitNumber * (maxVal - minVal) + minVal),
  46514. labelModel.get('formatter')
  46515. );
  46516. var distance = labelModel.get('distance');
  46517. var autoColor = getColor(i / splitNumber);
  46518. group.add(new Text({
  46519. style: setTextStyle({}, labelModel, {
  46520. text: label,
  46521. x: unitX * (r - splitLineLen - distance) + cx,
  46522. y: unitY * (r - splitLineLen - distance) + cy,
  46523. textVerticalAlign: unitY < -0.4 ? 'top' : (unitY > 0.4 ? 'bottom' : 'middle'),
  46524. textAlign: unitX < -0.4 ? 'left' : (unitX > 0.4 ? 'right' : 'center')
  46525. }, {autoColor: autoColor}),
  46526. silent: true
  46527. }));
  46528. }
  46529. // Axis tick
  46530. if (tickModel.get('show') && i !== splitNumber) {
  46531. for (var j = 0; j <= subSplitNumber; j++) {
  46532. var unitX = Math.cos(angle);
  46533. var unitY = Math.sin(angle);
  46534. var tickLine = new Line({
  46535. shape: {
  46536. x1: unitX * r + cx,
  46537. y1: unitY * r + cy,
  46538. x2: unitX * (r - tickLen) + cx,
  46539. y2: unitY * (r - tickLen) + cy
  46540. },
  46541. silent: true,
  46542. style: tickLineStyle
  46543. });
  46544. if (tickLineStyle.stroke === 'auto') {
  46545. tickLine.setStyle({
  46546. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  46547. });
  46548. }
  46549. group.add(tickLine);
  46550. angle += subStep;
  46551. }
  46552. angle -= subStep;
  46553. }
  46554. else {
  46555. angle += step;
  46556. }
  46557. }
  46558. },
  46559. _renderPointer: function (
  46560. seriesModel, ecModel, api, getColor, posInfo,
  46561. startAngle, endAngle, clockwise
  46562. ) {
  46563. var group = this.group;
  46564. var oldData = this._data;
  46565. if (!seriesModel.get('pointer.show')) {
  46566. // Remove old element
  46567. oldData && oldData.eachItemGraphicEl(function (el) {
  46568. group.remove(el);
  46569. });
  46570. return;
  46571. }
  46572. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  46573. var angleExtent = [startAngle, endAngle];
  46574. var data = seriesModel.getData();
  46575. var valueDim = data.mapDimension('value');
  46576. data.diff(oldData)
  46577. .add(function (idx) {
  46578. var pointer = new PointerPath({
  46579. shape: {
  46580. angle: startAngle
  46581. }
  46582. });
  46583. initProps(pointer, {
  46584. shape: {
  46585. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  46586. }
  46587. }, seriesModel);
  46588. group.add(pointer);
  46589. data.setItemGraphicEl(idx, pointer);
  46590. })
  46591. .update(function (newIdx, oldIdx) {
  46592. var pointer = oldData.getItemGraphicEl(oldIdx);
  46593. updateProps(pointer, {
  46594. shape: {
  46595. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  46596. }
  46597. }, seriesModel);
  46598. group.add(pointer);
  46599. data.setItemGraphicEl(newIdx, pointer);
  46600. })
  46601. .remove(function (idx) {
  46602. var pointer = oldData.getItemGraphicEl(idx);
  46603. group.remove(pointer);
  46604. })
  46605. .execute();
  46606. data.eachItemGraphicEl(function (pointer, idx) {
  46607. var itemModel = data.getItemModel(idx);
  46608. var pointerModel = itemModel.getModel('pointer');
  46609. pointer.setShape({
  46610. x: posInfo.cx,
  46611. y: posInfo.cy,
  46612. width: parsePercent$1(
  46613. pointerModel.get('width'), posInfo.r
  46614. ),
  46615. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  46616. });
  46617. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  46618. if (pointer.style.fill === 'auto') {
  46619. pointer.setStyle('fill', getColor(
  46620. linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)
  46621. ));
  46622. }
  46623. setHoverStyle(
  46624. pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle()
  46625. );
  46626. });
  46627. this._data = data;
  46628. },
  46629. _renderTitle: function (
  46630. seriesModel, ecModel, api, getColor, posInfo
  46631. ) {
  46632. var data = seriesModel.getData();
  46633. var valueDim = data.mapDimension('value');
  46634. var titleModel = seriesModel.getModel('title');
  46635. if (titleModel.get('show')) {
  46636. var offsetCenter = titleModel.get('offsetCenter');
  46637. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  46638. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  46639. var minVal = +seriesModel.get('min');
  46640. var maxVal = +seriesModel.get('max');
  46641. var value = seriesModel.getData().get(valueDim, 0);
  46642. var autoColor = getColor(
  46643. linearMap(value, [minVal, maxVal], [0, 1], true)
  46644. );
  46645. this.group.add(new Text({
  46646. silent: true,
  46647. style: setTextStyle({}, titleModel, {
  46648. x: x,
  46649. y: y,
  46650. // FIXME First data name ?
  46651. text: data.getName(0),
  46652. textAlign: 'center',
  46653. textVerticalAlign: 'middle'
  46654. }, {autoColor: autoColor, forceRich: true})
  46655. }));
  46656. }
  46657. },
  46658. _renderDetail: function (
  46659. seriesModel, ecModel, api, getColor, posInfo
  46660. ) {
  46661. var detailModel = seriesModel.getModel('detail');
  46662. var minVal = +seriesModel.get('min');
  46663. var maxVal = +seriesModel.get('max');
  46664. if (detailModel.get('show')) {
  46665. var offsetCenter = detailModel.get('offsetCenter');
  46666. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  46667. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  46668. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  46669. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  46670. var data = seriesModel.getData();
  46671. var value = data.get(data.mapDimension('value'), 0);
  46672. var autoColor = getColor(
  46673. linearMap(value, [minVal, maxVal], [0, 1], true)
  46674. );
  46675. this.group.add(new Text({
  46676. silent: true,
  46677. style: setTextStyle({}, detailModel, {
  46678. x: x,
  46679. y: y,
  46680. text: formatLabel(
  46681. // FIXME First data name ?
  46682. value, detailModel.get('formatter')
  46683. ),
  46684. textWidth: isNaN(width) ? null : width,
  46685. textHeight: isNaN(height) ? null : height,
  46686. textAlign: 'center',
  46687. textVerticalAlign: 'middle'
  46688. }, {autoColor: autoColor, forceRich: true})
  46689. }));
  46690. }
  46691. }
  46692. });
  46693. /*
  46694. * Licensed to the Apache Software Foundation (ASF) under one
  46695. * or more contributor license agreements. See the NOTICE file
  46696. * distributed with this work for additional information
  46697. * regarding copyright ownership. The ASF licenses this file
  46698. * to you under the Apache License, Version 2.0 (the
  46699. * "License"); you may not use this file except in compliance
  46700. * with the License. You may obtain a copy of the License at
  46701. *
  46702. * http://www.apache.org/licenses/LICENSE-2.0
  46703. *
  46704. * Unless required by applicable law or agreed to in writing,
  46705. * software distributed under the License is distributed on an
  46706. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46707. * KIND, either express or implied. See the License for the
  46708. * specific language governing permissions and limitations
  46709. * under the License.
  46710. */
  46711. /*
  46712. * Licensed to the Apache Software Foundation (ASF) under one
  46713. * or more contributor license agreements. See the NOTICE file
  46714. * distributed with this work for additional information
  46715. * regarding copyright ownership. The ASF licenses this file
  46716. * to you under the Apache License, Version 2.0 (the
  46717. * "License"); you may not use this file except in compliance
  46718. * with the License. You may obtain a copy of the License at
  46719. *
  46720. * http://www.apache.org/licenses/LICENSE-2.0
  46721. *
  46722. * Unless required by applicable law or agreed to in writing,
  46723. * software distributed under the License is distributed on an
  46724. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46725. * KIND, either express or implied. See the License for the
  46726. * specific language governing permissions and limitations
  46727. * under the License.
  46728. */
  46729. var FunnelSeries = extendSeriesModel({
  46730. type: 'series.funnel',
  46731. init: function (option) {
  46732. FunnelSeries.superApply(this, 'init', arguments);
  46733. // Enable legend selection for each data item
  46734. // Use a function instead of direct access because data reference may changed
  46735. this.legendDataProvider = function () {
  46736. return this.getRawData();
  46737. };
  46738. // Extend labelLine emphasis
  46739. this._defaultLabelLine(option);
  46740. },
  46741. getInitialData: function (option, ecModel) {
  46742. return createListSimply(this, ['value']);
  46743. },
  46744. _defaultLabelLine: function (option) {
  46745. // Extend labelLine emphasis
  46746. defaultEmphasis(option, 'labelLine', ['show']);
  46747. var labelLineNormalOpt = option.labelLine;
  46748. var labelLineEmphasisOpt = option.emphasis.labelLine;
  46749. // Not show label line if `label.normal.show = false`
  46750. labelLineNormalOpt.show = labelLineNormalOpt.show
  46751. && option.label.show;
  46752. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show
  46753. && option.emphasis.label.show;
  46754. },
  46755. // Overwrite
  46756. getDataParams: function (dataIndex) {
  46757. var data = this.getData();
  46758. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  46759. var valueDim = data.mapDimension('value');
  46760. var sum = data.getSum(valueDim);
  46761. // Percent is 0 if sum is 0
  46762. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  46763. params.$vars.push('percent');
  46764. return params;
  46765. },
  46766. defaultOption: {
  46767. zlevel: 0, // 一级层叠
  46768. z: 2, // 二级层叠
  46769. legendHoverLink: true,
  46770. left: 80,
  46771. top: 60,
  46772. right: 80,
  46773. bottom: 60,
  46774. // width: {totalWidth} - left - right,
  46775. // height: {totalHeight} - top - bottom,
  46776. // 默认取数据最小最大值
  46777. // min: 0,
  46778. // max: 100,
  46779. minSize: '0%',
  46780. maxSize: '100%',
  46781. sort: 'descending', // 'ascending', 'descending'
  46782. gap: 0,
  46783. funnelAlign: 'center',
  46784. label: {
  46785. show: true,
  46786. position: 'outer'
  46787. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  46788. },
  46789. labelLine: {
  46790. show: true,
  46791. length: 20,
  46792. lineStyle: {
  46793. // color: 各异,
  46794. width: 1,
  46795. type: 'solid'
  46796. }
  46797. },
  46798. itemStyle: {
  46799. // color: 各异,
  46800. borderColor: '#fff',
  46801. borderWidth: 1
  46802. },
  46803. emphasis: {
  46804. label: {
  46805. show: true
  46806. }
  46807. }
  46808. }
  46809. });
  46810. /*
  46811. * Licensed to the Apache Software Foundation (ASF) under one
  46812. * or more contributor license agreements. See the NOTICE file
  46813. * distributed with this work for additional information
  46814. * regarding copyright ownership. The ASF licenses this file
  46815. * to you under the Apache License, Version 2.0 (the
  46816. * "License"); you may not use this file except in compliance
  46817. * with the License. You may obtain a copy of the License at
  46818. *
  46819. * http://www.apache.org/licenses/LICENSE-2.0
  46820. *
  46821. * Unless required by applicable law or agreed to in writing,
  46822. * software distributed under the License is distributed on an
  46823. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46824. * KIND, either express or implied. See the License for the
  46825. * specific language governing permissions and limitations
  46826. * under the License.
  46827. */
  46828. /**
  46829. * Piece of pie including Sector, Label, LabelLine
  46830. * @constructor
  46831. * @extends {module:zrender/graphic/Group}
  46832. */
  46833. function FunnelPiece(data, idx) {
  46834. Group.call(this);
  46835. var polygon = new Polygon();
  46836. var labelLine = new Polyline();
  46837. var text = new Text();
  46838. this.add(polygon);
  46839. this.add(labelLine);
  46840. this.add(text);
  46841. this.updateData(data, idx, true);
  46842. // Hover to change label and labelLine
  46843. function onEmphasis() {
  46844. labelLine.ignore = labelLine.hoverIgnore;
  46845. text.ignore = text.hoverIgnore;
  46846. }
  46847. function onNormal() {
  46848. labelLine.ignore = labelLine.normalIgnore;
  46849. text.ignore = text.normalIgnore;
  46850. }
  46851. this.on('emphasis', onEmphasis)
  46852. .on('normal', onNormal)
  46853. .on('mouseover', onEmphasis)
  46854. .on('mouseout', onNormal);
  46855. }
  46856. var funnelPieceProto = FunnelPiece.prototype;
  46857. var opacityAccessPath = ['itemStyle', 'opacity'];
  46858. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  46859. var polygon = this.childAt(0);
  46860. var seriesModel = data.hostModel;
  46861. var itemModel = data.getItemModel(idx);
  46862. var layout = data.getItemLayout(idx);
  46863. var opacity = data.getItemModel(idx).get(opacityAccessPath);
  46864. opacity = opacity == null ? 1 : opacity;
  46865. // Reset style
  46866. polygon.useStyle({});
  46867. if (firstCreate) {
  46868. polygon.setShape({
  46869. points: layout.points
  46870. });
  46871. polygon.setStyle({ opacity : 0 });
  46872. initProps(polygon, {
  46873. style: {
  46874. opacity: opacity
  46875. }
  46876. }, seriesModel, idx);
  46877. }
  46878. else {
  46879. updateProps(polygon, {
  46880. style: {
  46881. opacity: opacity
  46882. },
  46883. shape: {
  46884. points: layout.points
  46885. }
  46886. }, seriesModel, idx);
  46887. }
  46888. // Update common style
  46889. var itemStyleModel = itemModel.getModel('itemStyle');
  46890. var visualColor = data.getItemVisual(idx, 'color');
  46891. polygon.setStyle(
  46892. defaults(
  46893. {
  46894. lineJoin: 'round',
  46895. fill: visualColor
  46896. },
  46897. itemStyleModel.getItemStyle(['opacity'])
  46898. )
  46899. );
  46900. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  46901. this._updateLabel(data, idx);
  46902. setHoverStyle(this);
  46903. };
  46904. funnelPieceProto._updateLabel = function (data, idx) {
  46905. var labelLine = this.childAt(1);
  46906. var labelText = this.childAt(2);
  46907. var seriesModel = data.hostModel;
  46908. var itemModel = data.getItemModel(idx);
  46909. var layout = data.getItemLayout(idx);
  46910. var labelLayout = layout.label;
  46911. var visualColor = data.getItemVisual(idx, 'color');
  46912. updateProps(labelLine, {
  46913. shape: {
  46914. points: labelLayout.linePoints || labelLayout.linePoints
  46915. }
  46916. }, seriesModel, idx);
  46917. updateProps(labelText, {
  46918. style: {
  46919. x: labelLayout.x,
  46920. y: labelLayout.y
  46921. }
  46922. }, seriesModel, idx);
  46923. labelText.attr({
  46924. rotation: labelLayout.rotation,
  46925. origin: [labelLayout.x, labelLayout.y],
  46926. z2: 10
  46927. });
  46928. var labelModel = itemModel.getModel('label');
  46929. var labelHoverModel = itemModel.getModel('emphasis.label');
  46930. var labelLineModel = itemModel.getModel('labelLine');
  46931. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  46932. var visualColor = data.getItemVisual(idx, 'color');
  46933. setLabelStyle(
  46934. labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel,
  46935. {
  46936. labelFetcher: data.hostModel,
  46937. labelDataIndex: idx,
  46938. defaultText: data.getName(idx),
  46939. autoColor: visualColor,
  46940. useInsideStyle: !!labelLayout.inside
  46941. },
  46942. {
  46943. textAlign: labelLayout.textAlign,
  46944. textVerticalAlign: labelLayout.verticalAlign
  46945. }
  46946. );
  46947. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  46948. labelText.hoverIgnore = !labelHoverModel.get('show');
  46949. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  46950. labelLine.hoverIgnore = !labelLineHoverModel.get('show');
  46951. // Default use item visual color
  46952. labelLine.setStyle({
  46953. stroke: visualColor
  46954. });
  46955. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  46956. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  46957. };
  46958. inherits(FunnelPiece, Group);
  46959. var FunnelView = Chart.extend({
  46960. type: 'funnel',
  46961. render: function (seriesModel, ecModel, api) {
  46962. var data = seriesModel.getData();
  46963. var oldData = this._data;
  46964. var group = this.group;
  46965. data.diff(oldData)
  46966. .add(function (idx) {
  46967. var funnelPiece = new FunnelPiece(data, idx);
  46968. data.setItemGraphicEl(idx, funnelPiece);
  46969. group.add(funnelPiece);
  46970. })
  46971. .update(function (newIdx, oldIdx) {
  46972. var piePiece = oldData.getItemGraphicEl(oldIdx);
  46973. piePiece.updateData(data, newIdx);
  46974. group.add(piePiece);
  46975. data.setItemGraphicEl(newIdx, piePiece);
  46976. })
  46977. .remove(function (idx) {
  46978. var piePiece = oldData.getItemGraphicEl(idx);
  46979. group.remove(piePiece);
  46980. })
  46981. .execute();
  46982. this._data = data;
  46983. },
  46984. remove: function () {
  46985. this.group.removeAll();
  46986. this._data = null;
  46987. },
  46988. dispose: function () {}
  46989. });
  46990. /*
  46991. * Licensed to the Apache Software Foundation (ASF) under one
  46992. * or more contributor license agreements. See the NOTICE file
  46993. * distributed with this work for additional information
  46994. * regarding copyright ownership. The ASF licenses this file
  46995. * to you under the Apache License, Version 2.0 (the
  46996. * "License"); you may not use this file except in compliance
  46997. * with the License. You may obtain a copy of the License at
  46998. *
  46999. * http://www.apache.org/licenses/LICENSE-2.0
  47000. *
  47001. * Unless required by applicable law or agreed to in writing,
  47002. * software distributed under the License is distributed on an
  47003. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47004. * KIND, either express or implied. See the License for the
  47005. * specific language governing permissions and limitations
  47006. * under the License.
  47007. */
  47008. function getViewRect$2(seriesModel, api) {
  47009. return getLayoutRect(
  47010. seriesModel.getBoxLayoutParams(), {
  47011. width: api.getWidth(),
  47012. height: api.getHeight()
  47013. }
  47014. );
  47015. }
  47016. function getSortedIndices(data, sort) {
  47017. var valueDim = data.mapDimension('value');
  47018. var valueArr = data.mapArray(valueDim, function (val) {
  47019. return val;
  47020. });
  47021. var indices = [];
  47022. var isAscending = sort === 'ascending';
  47023. for (var i = 0, len = data.count(); i < len; i++) {
  47024. indices[i] = i;
  47025. }
  47026. // Add custom sortable function & none sortable opetion by "options.sort"
  47027. if (typeof sort === 'function') {
  47028. indices.sort(sort);
  47029. } else if (sort !== 'none') {
  47030. indices.sort(function (a, b) {
  47031. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  47032. });
  47033. }
  47034. return indices;
  47035. }
  47036. function labelLayout$1(data) {
  47037. data.each(function (idx) {
  47038. var itemModel = data.getItemModel(idx);
  47039. var labelModel = itemModel.getModel('label');
  47040. var labelPosition = labelModel.get('position');
  47041. var labelLineModel = itemModel.getModel('labelLine');
  47042. var layout = data.getItemLayout(idx);
  47043. var points = layout.points;
  47044. var isLabelInside = labelPosition === 'inner'
  47045. || labelPosition === 'inside' || labelPosition === 'center';
  47046. var textAlign;
  47047. var textX;
  47048. var textY;
  47049. var linePoints;
  47050. if (isLabelInside) {
  47051. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  47052. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  47053. textAlign = 'center';
  47054. linePoints = [
  47055. [textX, textY], [textX, textY]
  47056. ];
  47057. }
  47058. else {
  47059. var x1;
  47060. var y1;
  47061. var x2;
  47062. var labelLineLen = labelLineModel.get('length');
  47063. if (labelPosition === 'left') {
  47064. // Left side
  47065. x1 = (points[3][0] + points[0][0]) / 2;
  47066. y1 = (points[3][1] + points[0][1]) / 2;
  47067. x2 = x1 - labelLineLen;
  47068. textX = x2 - 5;
  47069. textAlign = 'right';
  47070. }
  47071. else {
  47072. // Right side
  47073. x1 = (points[1][0] + points[2][0]) / 2;
  47074. y1 = (points[1][1] + points[2][1]) / 2;
  47075. x2 = x1 + labelLineLen;
  47076. textX = x2 + 5;
  47077. textAlign = 'left';
  47078. }
  47079. var y2 = y1;
  47080. linePoints = [[x1, y1], [x2, y2]];
  47081. textY = y2;
  47082. }
  47083. layout.label = {
  47084. linePoints: linePoints,
  47085. x: textX,
  47086. y: textY,
  47087. verticalAlign: 'middle',
  47088. textAlign: textAlign,
  47089. inside: isLabelInside
  47090. };
  47091. });
  47092. }
  47093. var funnelLayout = function (ecModel, api, payload) {
  47094. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  47095. var data = seriesModel.getData();
  47096. var valueDim = data.mapDimension('value');
  47097. var sort = seriesModel.get('sort');
  47098. var viewRect = getViewRect$2(seriesModel, api);
  47099. var indices = getSortedIndices(data, sort);
  47100. var sizeExtent = [
  47101. parsePercent$1(seriesModel.get('minSize'), viewRect.width),
  47102. parsePercent$1(seriesModel.get('maxSize'), viewRect.width)
  47103. ];
  47104. var dataExtent = data.getDataExtent(valueDim);
  47105. var min = seriesModel.get('min');
  47106. var max = seriesModel.get('max');
  47107. if (min == null) {
  47108. min = Math.min(dataExtent[0], 0);
  47109. }
  47110. if (max == null) {
  47111. max = dataExtent[1];
  47112. }
  47113. var funnelAlign = seriesModel.get('funnelAlign');
  47114. var gap = seriesModel.get('gap');
  47115. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  47116. var y = viewRect.y;
  47117. var getLinePoints = function (idx, offY) {
  47118. // End point index is data.count() and we assign it 0
  47119. var val = data.get(valueDim, idx) || 0;
  47120. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  47121. var x0;
  47122. switch (funnelAlign) {
  47123. case 'left':
  47124. x0 = viewRect.x;
  47125. break;
  47126. case 'center':
  47127. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  47128. break;
  47129. case 'right':
  47130. x0 = viewRect.x + viewRect.width - itemWidth;
  47131. break;
  47132. }
  47133. return [
  47134. [x0, offY],
  47135. [x0 + itemWidth, offY]
  47136. ];
  47137. };
  47138. if (sort === 'ascending') {
  47139. // From bottom to top
  47140. itemHeight = -itemHeight;
  47141. gap = -gap;
  47142. y += viewRect.height;
  47143. indices = indices.reverse();
  47144. }
  47145. for (var i = 0; i < indices.length; i++) {
  47146. var idx = indices[i];
  47147. var nextIdx = indices[i + 1];
  47148. var itemModel = data.getItemModel(idx);
  47149. var height = itemModel.get('itemStyle.height');
  47150. if (height == null) {
  47151. height = itemHeight;
  47152. }
  47153. else {
  47154. height = parsePercent$1(height, viewRect.height);
  47155. if (sort === 'ascending') {
  47156. height = -height;
  47157. }
  47158. }
  47159. var start = getLinePoints(idx, y);
  47160. var end = getLinePoints(nextIdx, y + height);
  47161. y += height + gap;
  47162. data.setItemLayout(idx, {
  47163. points: start.concat(end.slice().reverse())
  47164. });
  47165. }
  47166. labelLayout$1(data);
  47167. });
  47168. };
  47169. /*
  47170. * Licensed to the Apache Software Foundation (ASF) under one
  47171. * or more contributor license agreements. See the NOTICE file
  47172. * distributed with this work for additional information
  47173. * regarding copyright ownership. The ASF licenses this file
  47174. * to you under the Apache License, Version 2.0 (the
  47175. * "License"); you may not use this file except in compliance
  47176. * with the License. You may obtain a copy of the License at
  47177. *
  47178. * http://www.apache.org/licenses/LICENSE-2.0
  47179. *
  47180. * Unless required by applicable law or agreed to in writing,
  47181. * software distributed under the License is distributed on an
  47182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47183. * KIND, either express or implied. See the License for the
  47184. * specific language governing permissions and limitations
  47185. * under the License.
  47186. */
  47187. registerVisual(dataColor('funnel'));
  47188. registerLayout(funnelLayout);
  47189. registerProcessor(dataFilter('funnel'));
  47190. /*
  47191. * Licensed to the Apache Software Foundation (ASF) under one
  47192. * or more contributor license agreements. See the NOTICE file
  47193. * distributed with this work for additional information
  47194. * regarding copyright ownership. The ASF licenses this file
  47195. * to you under the Apache License, Version 2.0 (the
  47196. * "License"); you may not use this file except in compliance
  47197. * with the License. You may obtain a copy of the License at
  47198. *
  47199. * http://www.apache.org/licenses/LICENSE-2.0
  47200. *
  47201. * Unless required by applicable law or agreed to in writing,
  47202. * software distributed under the License is distributed on an
  47203. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47204. * KIND, either express or implied. See the License for the
  47205. * specific language governing permissions and limitations
  47206. * under the License.
  47207. */
  47208. var parallelPreprocessor = function (option) {
  47209. createParallelIfNeeded(option);
  47210. mergeAxisOptionFromParallel(option);
  47211. };
  47212. /**
  47213. * Create a parallel coordinate if not exists.
  47214. * @inner
  47215. */
  47216. function createParallelIfNeeded(option) {
  47217. if (option.parallel) {
  47218. return;
  47219. }
  47220. var hasParallelSeries = false;
  47221. each$1(option.series, function (seriesOpt) {
  47222. if (seriesOpt && seriesOpt.type === 'parallel') {
  47223. hasParallelSeries = true;
  47224. }
  47225. });
  47226. if (hasParallelSeries) {
  47227. option.parallel = [{}];
  47228. }
  47229. }
  47230. /**
  47231. * Merge aixs definition from parallel option (if exists) to axis option.
  47232. * @inner
  47233. */
  47234. function mergeAxisOptionFromParallel(option) {
  47235. var axes = normalizeToArray(option.parallelAxis);
  47236. each$1(axes, function (axisOption) {
  47237. if (!isObject$1(axisOption)) {
  47238. return;
  47239. }
  47240. var parallelIndex = axisOption.parallelIndex || 0;
  47241. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  47242. if (parallelOption && parallelOption.parallelAxisDefault) {
  47243. merge(axisOption, parallelOption.parallelAxisDefault, false);
  47244. }
  47245. });
  47246. }
  47247. /*
  47248. * Licensed to the Apache Software Foundation (ASF) under one
  47249. * or more contributor license agreements. See the NOTICE file
  47250. * distributed with this work for additional information
  47251. * regarding copyright ownership. The ASF licenses this file
  47252. * to you under the Apache License, Version 2.0 (the
  47253. * "License"); you may not use this file except in compliance
  47254. * with the License. You may obtain a copy of the License at
  47255. *
  47256. * http://www.apache.org/licenses/LICENSE-2.0
  47257. *
  47258. * Unless required by applicable law or agreed to in writing,
  47259. * software distributed under the License is distributed on an
  47260. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47261. * KIND, either express or implied. See the License for the
  47262. * specific language governing permissions and limitations
  47263. * under the License.
  47264. */
  47265. /**
  47266. * @constructor module:echarts/coord/parallel/ParallelAxis
  47267. * @extends {module:echarts/coord/Axis}
  47268. * @param {string} dim
  47269. * @param {*} scale
  47270. * @param {Array.<number>} coordExtent
  47271. * @param {string} axisType
  47272. */
  47273. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  47274. Axis.call(this, dim, scale, coordExtent);
  47275. /**
  47276. * Axis type
  47277. * - 'category'
  47278. * - 'value'
  47279. * - 'time'
  47280. * - 'log'
  47281. * @type {string}
  47282. */
  47283. this.type = axisType || 'value';
  47284. /**
  47285. * @type {number}
  47286. * @readOnly
  47287. */
  47288. this.axisIndex = axisIndex;
  47289. };
  47290. ParallelAxis.prototype = {
  47291. constructor: ParallelAxis,
  47292. /**
  47293. * Axis model
  47294. * @param {module:echarts/coord/parallel/AxisModel}
  47295. */
  47296. model: null,
  47297. /**
  47298. * @override
  47299. */
  47300. isHorizontal: function () {
  47301. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  47302. }
  47303. };
  47304. inherits(ParallelAxis, Axis);
  47305. /*
  47306. * Licensed to the Apache Software Foundation (ASF) under one
  47307. * or more contributor license agreements. See the NOTICE file
  47308. * distributed with this work for additional information
  47309. * regarding copyright ownership. The ASF licenses this file
  47310. * to you under the Apache License, Version 2.0 (the
  47311. * "License"); you may not use this file except in compliance
  47312. * with the License. You may obtain a copy of the License at
  47313. *
  47314. * http://www.apache.org/licenses/LICENSE-2.0
  47315. *
  47316. * Unless required by applicable law or agreed to in writing,
  47317. * software distributed under the License is distributed on an
  47318. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47319. * KIND, either express or implied. See the License for the
  47320. * specific language governing permissions and limitations
  47321. * under the License.
  47322. */
  47323. /**
  47324. * Calculate slider move result.
  47325. * Usage:
  47326. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  47327. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  47328. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  47329. *
  47330. * @param {number} delta Move length.
  47331. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  47332. * handleEnds will be modified in this method.
  47333. * @param {Array.<number>} extent handleEnds is restricted by extent.
  47334. * extent[0] should less or equals than extent[1].
  47335. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds,
  47336. * where the input minSpan and maxSpan will not work.
  47337. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  47338. * If not set, handle0 and cross handle1. If set as a non-negative
  47339. * number (including `0`), handles will push each other when reaching
  47340. * the minSpan.
  47341. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  47342. * @return {Array.<number>} The input handleEnds.
  47343. */
  47344. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  47345. // Normalize firstly.
  47346. handleEnds[0] = restrict$1(handleEnds[0], extent);
  47347. handleEnds[1] = restrict$1(handleEnds[1], extent);
  47348. delta = delta || 0;
  47349. var extentSpan = extent[1] - extent[0];
  47350. // Notice maxSpan and minSpan can be null/undefined.
  47351. if (minSpan != null) {
  47352. minSpan = restrict$1(minSpan, [0, extentSpan]);
  47353. }
  47354. if (maxSpan != null) {
  47355. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  47356. }
  47357. if (handleIndex === 'all') {
  47358. minSpan = maxSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  47359. handleIndex = 0;
  47360. }
  47361. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  47362. handleEnds[handleIndex] += delta;
  47363. // Restrict in extent.
  47364. var extentMinSpan = minSpan || 0;
  47365. var realExtent = extent.slice();
  47366. originalDistSign.sign < 0 ? (realExtent[0] += extentMinSpan) : (realExtent[1] -= extentMinSpan);
  47367. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent);
  47368. // Expand span.
  47369. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47370. if (minSpan != null && (
  47371. currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan
  47372. )) {
  47373. // If minSpan exists, 'cross' is forbinden.
  47374. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  47375. }
  47376. // Shrink span.
  47377. var currDistSign = getSpanSign(handleEnds, handleIndex);
  47378. if (maxSpan != null && currDistSign.span > maxSpan) {
  47379. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  47380. }
  47381. return handleEnds;
  47382. };
  47383. function getSpanSign(handleEnds, handleIndex) {
  47384. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex];
  47385. // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  47386. // is at left of handleEnds[1] for non-cross case.
  47387. return {span: Math.abs(dist), sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1};
  47388. }
  47389. function restrict$1(value, extend) {
  47390. return Math.min(extend[1], Math.max(extend[0], value));
  47391. }
  47392. /*
  47393. * Licensed to the Apache Software Foundation (ASF) under one
  47394. * or more contributor license agreements. See the NOTICE file
  47395. * distributed with this work for additional information
  47396. * regarding copyright ownership. The ASF licenses this file
  47397. * to you under the Apache License, Version 2.0 (the
  47398. * "License"); you may not use this file except in compliance
  47399. * with the License. You may obtain a copy of the License at
  47400. *
  47401. * http://www.apache.org/licenses/LICENSE-2.0
  47402. *
  47403. * Unless required by applicable law or agreed to in writing,
  47404. * software distributed under the License is distributed on an
  47405. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47406. * KIND, either express or implied. See the License for the
  47407. * specific language governing permissions and limitations
  47408. * under the License.
  47409. */
  47410. /**
  47411. * Parallel Coordinates
  47412. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  47413. */
  47414. var each$11 = each$1;
  47415. var mathMin$5 = Math.min;
  47416. var mathMax$5 = Math.max;
  47417. var mathFloor$2 = Math.floor;
  47418. var mathCeil$2 = Math.ceil;
  47419. var round$2 = round$1;
  47420. var PI$3 = Math.PI;
  47421. function Parallel(parallelModel, ecModel, api) {
  47422. /**
  47423. * key: dimension
  47424. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  47425. * @private
  47426. */
  47427. this._axesMap = createHashMap();
  47428. /**
  47429. * key: dimension
  47430. * value: {position: [], rotation, }
  47431. * @type {Object.<string, Object>}
  47432. * @private
  47433. */
  47434. this._axesLayout = {};
  47435. /**
  47436. * Always follow axis order.
  47437. * @type {Array.<string>}
  47438. * @readOnly
  47439. */
  47440. this.dimensions = parallelModel.dimensions;
  47441. /**
  47442. * @type {module:zrender/core/BoundingRect}
  47443. */
  47444. this._rect;
  47445. /**
  47446. * @type {module:echarts/coord/parallel/ParallelModel}
  47447. */
  47448. this._model = parallelModel;
  47449. this._init(parallelModel, ecModel, api);
  47450. }
  47451. Parallel.prototype = {
  47452. type: 'parallel',
  47453. constructor: Parallel,
  47454. /**
  47455. * Initialize cartesian coordinate systems
  47456. * @private
  47457. */
  47458. _init: function (parallelModel, ecModel, api) {
  47459. var dimensions = parallelModel.dimensions;
  47460. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  47461. each$11(dimensions, function (dim, idx) {
  47462. var axisIndex = parallelAxisIndex[idx];
  47463. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  47464. var axis = this._axesMap.set(dim, new ParallelAxis(
  47465. dim,
  47466. createScaleByModel(axisModel),
  47467. [0, 0],
  47468. axisModel.get('type'),
  47469. axisIndex
  47470. ));
  47471. var isCategory = axis.type === 'category';
  47472. axis.onBand = isCategory && axisModel.get('boundaryGap');
  47473. axis.inverse = axisModel.get('inverse');
  47474. // Injection
  47475. axisModel.axis = axis;
  47476. axis.model = axisModel;
  47477. axis.coordinateSystem = axisModel.coordinateSystem = this;
  47478. }, this);
  47479. },
  47480. /**
  47481. * Update axis scale after data processed
  47482. * @param {module:echarts/model/Global} ecModel
  47483. * @param {module:echarts/ExtensionAPI} api
  47484. */
  47485. update: function (ecModel, api) {
  47486. this._updateAxesFromSeries(this._model, ecModel);
  47487. },
  47488. /**
  47489. * @override
  47490. */
  47491. containPoint: function (point) {
  47492. var layoutInfo = this._makeLayoutInfo();
  47493. var axisBase = layoutInfo.axisBase;
  47494. var layoutBase = layoutInfo.layoutBase;
  47495. var pixelDimIndex = layoutInfo.pixelDimIndex;
  47496. var pAxis = point[1 - pixelDimIndex];
  47497. var pLayout = point[pixelDimIndex];
  47498. return pAxis >= axisBase
  47499. && pAxis <= axisBase + layoutInfo.axisLength
  47500. && pLayout >= layoutBase
  47501. && pLayout <= layoutBase + layoutInfo.layoutLength;
  47502. },
  47503. getModel: function () {
  47504. return this._model;
  47505. },
  47506. /**
  47507. * Update properties from series
  47508. * @private
  47509. */
  47510. _updateAxesFromSeries: function (parallelModel, ecModel) {
  47511. ecModel.eachSeries(function (seriesModel) {
  47512. if (!parallelModel.contains(seriesModel, ecModel)) {
  47513. return;
  47514. }
  47515. var data = seriesModel.getData();
  47516. each$11(this.dimensions, function (dim) {
  47517. var axis = this._axesMap.get(dim);
  47518. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  47519. niceScaleExtent(axis.scale, axis.model);
  47520. }, this);
  47521. }, this);
  47522. },
  47523. /**
  47524. * Resize the parallel coordinate system.
  47525. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  47526. * @param {module:echarts/ExtensionAPI} api
  47527. */
  47528. resize: function (parallelModel, api) {
  47529. this._rect = getLayoutRect(
  47530. parallelModel.getBoxLayoutParams(),
  47531. {
  47532. width: api.getWidth(),
  47533. height: api.getHeight()
  47534. }
  47535. );
  47536. this._layoutAxes();
  47537. },
  47538. /**
  47539. * @return {module:zrender/core/BoundingRect}
  47540. */
  47541. getRect: function () {
  47542. return this._rect;
  47543. },
  47544. /**
  47545. * @private
  47546. */
  47547. _makeLayoutInfo: function () {
  47548. var parallelModel = this._model;
  47549. var rect = this._rect;
  47550. var xy = ['x', 'y'];
  47551. var wh = ['width', 'height'];
  47552. var layout = parallelModel.get('layout');
  47553. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  47554. var layoutLength = rect[wh[pixelDimIndex]];
  47555. var layoutExtent = [0, layoutLength];
  47556. var axisCount = this.dimensions.length;
  47557. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  47558. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  47559. var axisExpandable = parallelModel.get('axisExpandable')
  47560. && axisCount > 3
  47561. && axisCount > axisExpandCount
  47562. && axisExpandCount > 1
  47563. && axisExpandWidth > 0
  47564. && layoutLength > 0;
  47565. // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  47566. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  47567. // where collapsed axes should be overlapped.
  47568. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  47569. var winSize;
  47570. if (!axisExpandWindow) {
  47571. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  47572. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  47573. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  47574. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  47575. }
  47576. else {
  47577. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  47578. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  47579. }
  47580. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount);
  47581. // Avoid axisCollapseWidth is too small.
  47582. axisCollapseWidth < 3 && (axisCollapseWidth = 0);
  47583. // Find the first and last indices > ewin[0] and < ewin[1].
  47584. var winInnerIndices = [
  47585. mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1,
  47586. mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1
  47587. ];
  47588. // Pos in ec coordinates.
  47589. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  47590. return {
  47591. layout: layout,
  47592. pixelDimIndex: pixelDimIndex,
  47593. layoutBase: rect[xy[pixelDimIndex]],
  47594. layoutLength: layoutLength,
  47595. axisBase: rect[xy[1 - pixelDimIndex]],
  47596. axisLength: rect[wh[1 - pixelDimIndex]],
  47597. axisExpandable: axisExpandable,
  47598. axisExpandWidth: axisExpandWidth,
  47599. axisCollapseWidth: axisCollapseWidth,
  47600. axisExpandWindow: axisExpandWindow,
  47601. axisCount: axisCount,
  47602. winInnerIndices: winInnerIndices,
  47603. axisExpandWindow0Pos: axisExpandWindow0Pos
  47604. };
  47605. },
  47606. /**
  47607. * @private
  47608. */
  47609. _layoutAxes: function () {
  47610. var rect = this._rect;
  47611. var axes = this._axesMap;
  47612. var dimensions = this.dimensions;
  47613. var layoutInfo = this._makeLayoutInfo();
  47614. var layout = layoutInfo.layout;
  47615. axes.each(function (axis) {
  47616. var axisExtent = [0, layoutInfo.axisLength];
  47617. var idx = axis.inverse ? 1 : 0;
  47618. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  47619. });
  47620. each$11(dimensions, function (dim, idx) {
  47621. var posInfo = (layoutInfo.axisExpandable
  47622. ? layoutAxisWithExpand : layoutAxisWithoutExpand
  47623. )(idx, layoutInfo);
  47624. var positionTable = {
  47625. horizontal: {
  47626. x: posInfo.position,
  47627. y: layoutInfo.axisLength
  47628. },
  47629. vertical: {
  47630. x: 0,
  47631. y: posInfo.position
  47632. }
  47633. };
  47634. var rotationTable = {
  47635. horizontal: PI$3 / 2,
  47636. vertical: 0
  47637. };
  47638. var position = [
  47639. positionTable[layout].x + rect.x,
  47640. positionTable[layout].y + rect.y
  47641. ];
  47642. var rotation = rotationTable[layout];
  47643. var transform = create$1();
  47644. rotate(transform, transform, rotation);
  47645. translate(transform, transform, position);
  47646. // TODO
  47647. // tick等排布信息。
  47648. // TODO
  47649. // 根据axis order 更新 dimensions顺序。
  47650. this._axesLayout[dim] = {
  47651. position: position,
  47652. rotation: rotation,
  47653. transform: transform,
  47654. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  47655. axisLabelShow: posInfo.axisLabelShow,
  47656. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  47657. tickDirection: 1,
  47658. labelDirection: 1
  47659. };
  47660. }, this);
  47661. },
  47662. /**
  47663. * Get axis by dim.
  47664. * @param {string} dim
  47665. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  47666. */
  47667. getAxis: function (dim) {
  47668. return this._axesMap.get(dim);
  47669. },
  47670. /**
  47671. * Convert a dim value of a single item of series data to Point.
  47672. * @param {*} value
  47673. * @param {string} dim
  47674. * @return {Array}
  47675. */
  47676. dataToPoint: function (value, dim) {
  47677. return this.axisCoordToPoint(
  47678. this._axesMap.get(dim).dataToCoord(value),
  47679. dim
  47680. );
  47681. },
  47682. /**
  47683. * Travel data for one time, get activeState of each data item.
  47684. * @param {module:echarts/data/List} data
  47685. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  47686. * {number} dataIndex
  47687. * @param {number} [start=0] the start dataIndex that travel from.
  47688. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  47689. */
  47690. eachActiveState: function (data, callback, start, end) {
  47691. start == null && (start = 0);
  47692. end == null && (end = data.count());
  47693. var axesMap = this._axesMap;
  47694. var dimensions = this.dimensions;
  47695. var dataDimensions = [];
  47696. var axisModels = [];
  47697. each$1(dimensions, function (axisDim) {
  47698. dataDimensions.push(data.mapDimension(axisDim));
  47699. axisModels.push(axesMap.get(axisDim).model);
  47700. });
  47701. var hasActiveSet = this.hasAxisBrushed();
  47702. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  47703. var activeState;
  47704. if (!hasActiveSet) {
  47705. activeState = 'normal';
  47706. }
  47707. else {
  47708. activeState = 'active';
  47709. var values = data.getValues(dataDimensions, dataIndex);
  47710. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  47711. var state = axisModels[j].getActiveState(values[j]);
  47712. if (state === 'inactive') {
  47713. activeState = 'inactive';
  47714. break;
  47715. }
  47716. }
  47717. }
  47718. callback(activeState, dataIndex);
  47719. }
  47720. },
  47721. /**
  47722. * Whether has any activeSet.
  47723. * @return {boolean}
  47724. */
  47725. hasAxisBrushed: function () {
  47726. var dimensions = this.dimensions;
  47727. var axesMap = this._axesMap;
  47728. var hasActiveSet = false;
  47729. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  47730. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  47731. hasActiveSet = true;
  47732. }
  47733. }
  47734. return hasActiveSet;
  47735. },
  47736. /**
  47737. * Convert coords of each axis to Point.
  47738. * Return point. For example: [10, 20]
  47739. * @param {Array.<number>} coords
  47740. * @param {string} dim
  47741. * @return {Array.<number>}
  47742. */
  47743. axisCoordToPoint: function (coord, dim) {
  47744. var axisLayout = this._axesLayout[dim];
  47745. return applyTransform$1([coord, 0], axisLayout.transform);
  47746. },
  47747. /**
  47748. * Get axis layout.
  47749. */
  47750. getAxisLayout: function (dim) {
  47751. return clone(this._axesLayout[dim]);
  47752. },
  47753. /**
  47754. * @param {Array.<number>} point
  47755. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  47756. */
  47757. getSlidedAxisExpandWindow: function (point) {
  47758. var layoutInfo = this._makeLayoutInfo();
  47759. var pixelDimIndex = layoutInfo.pixelDimIndex;
  47760. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  47761. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  47762. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)];
  47763. // Out of the area of coordinate system.
  47764. if (!this.containPoint(point)) {
  47765. return {behavior: 'none', axisExpandWindow: axisExpandWindow};
  47766. }
  47767. // Conver the point from global to expand coordinates.
  47768. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos;
  47769. // For dragging operation convenience, the window should not be
  47770. // slided when mouse is the center area of the window.
  47771. var delta;
  47772. var behavior = 'slide';
  47773. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  47774. var triggerArea = this._model.get('axisExpandSlideTriggerArea');
  47775. // But consider touch device, jump is necessary.
  47776. var useJump = triggerArea[0] != null;
  47777. if (axisCollapseWidth) {
  47778. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  47779. behavior = 'jump';
  47780. delta = pointCoord - winSize * triggerArea[2];
  47781. }
  47782. else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  47783. behavior = 'jump';
  47784. delta = pointCoord - winSize * (1 - triggerArea[2]);
  47785. }
  47786. else {
  47787. (delta = pointCoord - winSize * triggerArea[1]) >= 0
  47788. && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0
  47789. && (delta = 0);
  47790. }
  47791. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  47792. delta
  47793. ? sliderMove(delta, axisExpandWindow, extent, 'all')
  47794. // Avoid nonsense triger on mousemove.
  47795. : (behavior = 'none');
  47796. }
  47797. // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  47798. else {
  47799. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  47800. var pos = extent[1] * pointCoord / winSize;
  47801. axisExpandWindow = [mathMax$5(0, pos - winSize / 2)];
  47802. axisExpandWindow[1] = mathMin$5(extent[1], axisExpandWindow[0] + winSize);
  47803. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  47804. }
  47805. return {
  47806. axisExpandWindow: axisExpandWindow,
  47807. behavior: behavior
  47808. };
  47809. }
  47810. };
  47811. function restrict(len, extent) {
  47812. return mathMin$5(mathMax$5(len, extent[0]), extent[1]);
  47813. }
  47814. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  47815. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  47816. return {
  47817. position: step * axisIndex,
  47818. axisNameAvailableWidth: step,
  47819. axisLabelShow: true
  47820. };
  47821. }
  47822. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  47823. var layoutLength = layoutInfo.layoutLength;
  47824. var axisExpandWidth = layoutInfo.axisExpandWidth;
  47825. var axisCount = layoutInfo.axisCount;
  47826. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  47827. var winInnerIndices = layoutInfo.winInnerIndices;
  47828. var position;
  47829. var axisNameAvailableWidth = axisCollapseWidth;
  47830. var axisLabelShow = false;
  47831. var nameTruncateMaxWidth;
  47832. if (axisIndex < winInnerIndices[0]) {
  47833. position = axisIndex * axisCollapseWidth;
  47834. nameTruncateMaxWidth = axisCollapseWidth;
  47835. }
  47836. else if (axisIndex <= winInnerIndices[1]) {
  47837. position = layoutInfo.axisExpandWindow0Pos
  47838. + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  47839. axisNameAvailableWidth = axisExpandWidth;
  47840. axisLabelShow = true;
  47841. }
  47842. else {
  47843. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  47844. nameTruncateMaxWidth = axisCollapseWidth;
  47845. }
  47846. return {
  47847. position: position,
  47848. axisNameAvailableWidth: axisNameAvailableWidth,
  47849. axisLabelShow: axisLabelShow,
  47850. nameTruncateMaxWidth: nameTruncateMaxWidth
  47851. };
  47852. }
  47853. /*
  47854. * Licensed to the Apache Software Foundation (ASF) under one
  47855. * or more contributor license agreements. See the NOTICE file
  47856. * distributed with this work for additional information
  47857. * regarding copyright ownership. The ASF licenses this file
  47858. * to you under the Apache License, Version 2.0 (the
  47859. * "License"); you may not use this file except in compliance
  47860. * with the License. You may obtain a copy of the License at
  47861. *
  47862. * http://www.apache.org/licenses/LICENSE-2.0
  47863. *
  47864. * Unless required by applicable law or agreed to in writing,
  47865. * software distributed under the License is distributed on an
  47866. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47867. * KIND, either express or implied. See the License for the
  47868. * specific language governing permissions and limitations
  47869. * under the License.
  47870. */
  47871. /**
  47872. * Parallel coordinate system creater.
  47873. */
  47874. function create$2(ecModel, api) {
  47875. var coordSysList = [];
  47876. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  47877. var coordSys = new Parallel(parallelModel, ecModel, api);
  47878. coordSys.name = 'parallel_' + idx;
  47879. coordSys.resize(parallelModel, api);
  47880. parallelModel.coordinateSystem = coordSys;
  47881. coordSys.model = parallelModel;
  47882. coordSysList.push(coordSys);
  47883. });
  47884. // Inject the coordinateSystems into seriesModel
  47885. ecModel.eachSeries(function (seriesModel) {
  47886. if (seriesModel.get('coordinateSystem') === 'parallel') {
  47887. var parallelModel = ecModel.queryComponents({
  47888. mainType: 'parallel',
  47889. index: seriesModel.get('parallelIndex'),
  47890. id: seriesModel.get('parallelId')
  47891. })[0];
  47892. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  47893. }
  47894. });
  47895. return coordSysList;
  47896. }
  47897. CoordinateSystemManager.register('parallel', {create: create$2});
  47898. /*
  47899. * Licensed to the Apache Software Foundation (ASF) under one
  47900. * or more contributor license agreements. See the NOTICE file
  47901. * distributed with this work for additional information
  47902. * regarding copyright ownership. The ASF licenses this file
  47903. * to you under the Apache License, Version 2.0 (the
  47904. * "License"); you may not use this file except in compliance
  47905. * with the License. You may obtain a copy of the License at
  47906. *
  47907. * http://www.apache.org/licenses/LICENSE-2.0
  47908. *
  47909. * Unless required by applicable law or agreed to in writing,
  47910. * software distributed under the License is distributed on an
  47911. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47912. * KIND, either express or implied. See the License for the
  47913. * specific language governing permissions and limitations
  47914. * under the License.
  47915. */
  47916. var AxisModel$2 = ComponentModel.extend({
  47917. type: 'baseParallelAxis',
  47918. /**
  47919. * @type {module:echarts/coord/parallel/Axis}
  47920. */
  47921. axis: null,
  47922. /**
  47923. * @type {Array.<Array.<number>}
  47924. * @readOnly
  47925. */
  47926. activeIntervals: [],
  47927. /**
  47928. * @return {Object}
  47929. */
  47930. getAreaSelectStyle: function () {
  47931. return makeStyleMapper(
  47932. [
  47933. ['fill', 'color'],
  47934. ['lineWidth', 'borderWidth'],
  47935. ['stroke', 'borderColor'],
  47936. ['width', 'width'],
  47937. ['opacity', 'opacity']
  47938. ]
  47939. )(this.getModel('areaSelectStyle'));
  47940. },
  47941. /**
  47942. * The code of this feature is put on AxisModel but not ParallelAxis,
  47943. * because axisModel can be alive after echarts updating but instance of
  47944. * ParallelAxis having been disposed. this._activeInterval should be kept
  47945. * when action dispatched (i.e. legend click).
  47946. *
  47947. * @param {Array.<Array<number>>} intervals interval.length === 0
  47948. * means set all active.
  47949. * @public
  47950. */
  47951. setActiveIntervals: function (intervals) {
  47952. var activeIntervals = this.activeIntervals = clone(intervals);
  47953. // Normalize
  47954. if (activeIntervals) {
  47955. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  47956. asc(activeIntervals[i]);
  47957. }
  47958. }
  47959. },
  47960. /**
  47961. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  47962. * value can not be input.
  47963. * @return {string} 'normal': no activeIntervals set,
  47964. * 'active',
  47965. * 'inactive'.
  47966. * @public
  47967. */
  47968. getActiveState: function (value) {
  47969. var activeIntervals = this.activeIntervals;
  47970. if (!activeIntervals.length) {
  47971. return 'normal';
  47972. }
  47973. if (value == null || isNaN(value)) {
  47974. return 'inactive';
  47975. }
  47976. // Simple optimization
  47977. if (activeIntervals.length === 1) {
  47978. var interval = activeIntervals[0];
  47979. if (interval[0] <= value && value <= interval[1]) {
  47980. return 'active';
  47981. }
  47982. }
  47983. else {
  47984. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  47985. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  47986. return 'active';
  47987. }
  47988. }
  47989. }
  47990. return 'inactive';
  47991. }
  47992. });
  47993. var defaultOption$1 = {
  47994. type: 'value',
  47995. /**
  47996. * @type {Array.<number>}
  47997. */
  47998. dim: null, // 0, 1, 2, ...
  47999. // parallelIndex: null,
  48000. areaSelectStyle: {
  48001. width: 20,
  48002. borderWidth: 1,
  48003. borderColor: 'rgba(160,197,232)',
  48004. color: 'rgba(160,197,232)',
  48005. opacity: 0.3
  48006. },
  48007. realtime: true, // Whether realtime update view when select.
  48008. z: 10
  48009. };
  48010. merge(AxisModel$2.prototype, axisModelCommonMixin);
  48011. function getAxisType$1(axisName, option) {
  48012. return option.type || (option.data ? 'category' : 'value');
  48013. }
  48014. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  48015. /*
  48016. * Licensed to the Apache Software Foundation (ASF) under one
  48017. * or more contributor license agreements. See the NOTICE file
  48018. * distributed with this work for additional information
  48019. * regarding copyright ownership. The ASF licenses this file
  48020. * to you under the Apache License, Version 2.0 (the
  48021. * "License"); you may not use this file except in compliance
  48022. * with the License. You may obtain a copy of the License at
  48023. *
  48024. * http://www.apache.org/licenses/LICENSE-2.0
  48025. *
  48026. * Unless required by applicable law or agreed to in writing,
  48027. * software distributed under the License is distributed on an
  48028. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48029. * KIND, either express or implied. See the License for the
  48030. * specific language governing permissions and limitations
  48031. * under the License.
  48032. */
  48033. ComponentModel.extend({
  48034. type: 'parallel',
  48035. dependencies: ['parallelAxis'],
  48036. /**
  48037. * @type {module:echarts/coord/parallel/Parallel}
  48038. */
  48039. coordinateSystem: null,
  48040. /**
  48041. * Each item like: 'dim0', 'dim1', 'dim2', ...
  48042. * @type {Array.<string>}
  48043. * @readOnly
  48044. */
  48045. dimensions: null,
  48046. /**
  48047. * Coresponding to dimensions.
  48048. * @type {Array.<number>}
  48049. * @readOnly
  48050. */
  48051. parallelAxisIndex: null,
  48052. layoutMode: 'box',
  48053. defaultOption: {
  48054. zlevel: 0,
  48055. z: 0,
  48056. left: 80,
  48057. top: 60,
  48058. right: 80,
  48059. bottom: 60,
  48060. // width: {totalWidth} - left - right,
  48061. // height: {totalHeight} - top - bottom,
  48062. layout: 'horizontal', // 'horizontal' or 'vertical'
  48063. // FIXME
  48064. // naming?
  48065. axisExpandable: false,
  48066. axisExpandCenter: null,
  48067. axisExpandCount: 0,
  48068. axisExpandWidth: 50, // FIXME '10%' ?
  48069. axisExpandRate: 17,
  48070. axisExpandDebounce: 50,
  48071. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  48072. // Do not doc to user until necessary.
  48073. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  48074. axisExpandTriggerOn: 'click', // 'mousemove' or 'click'
  48075. parallelAxisDefault: null
  48076. },
  48077. /**
  48078. * @override
  48079. */
  48080. init: function () {
  48081. ComponentModel.prototype.init.apply(this, arguments);
  48082. this.mergeOption({});
  48083. },
  48084. /**
  48085. * @override
  48086. */
  48087. mergeOption: function (newOption) {
  48088. var thisOption = this.option;
  48089. newOption && merge(thisOption, newOption, true);
  48090. this._initDimensions();
  48091. },
  48092. /**
  48093. * Whether series or axis is in this coordinate system.
  48094. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  48095. * @param {module:echarts/model/Global} ecModel
  48096. */
  48097. contains: function (model, ecModel) {
  48098. var parallelIndex = model.get('parallelIndex');
  48099. return parallelIndex != null
  48100. && ecModel.getComponent('parallel', parallelIndex) === this;
  48101. },
  48102. setAxisExpand: function (opt) {
  48103. each$1(
  48104. ['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'],
  48105. function (name) {
  48106. if (opt.hasOwnProperty(name)) {
  48107. this.option[name] = opt[name];
  48108. }
  48109. },
  48110. this
  48111. );
  48112. },
  48113. /**
  48114. * @private
  48115. */
  48116. _initDimensions: function () {
  48117. var dimensions = this.dimensions = [];
  48118. var parallelAxisIndex = this.parallelAxisIndex = [];
  48119. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  48120. // Can not use this.contains here, because
  48121. // initialization has not been completed yet.
  48122. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  48123. }, this);
  48124. each$1(axisModels, function (axisModel) {
  48125. dimensions.push('dim' + axisModel.get('dim'));
  48126. parallelAxisIndex.push(axisModel.componentIndex);
  48127. });
  48128. }
  48129. });
  48130. /*
  48131. * Licensed to the Apache Software Foundation (ASF) under one
  48132. * or more contributor license agreements. See the NOTICE file
  48133. * distributed with this work for additional information
  48134. * regarding copyright ownership. The ASF licenses this file
  48135. * to you under the Apache License, Version 2.0 (the
  48136. * "License"); you may not use this file except in compliance
  48137. * with the License. You may obtain a copy of the License at
  48138. *
  48139. * http://www.apache.org/licenses/LICENSE-2.0
  48140. *
  48141. * Unless required by applicable law or agreed to in writing,
  48142. * software distributed under the License is distributed on an
  48143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48144. * KIND, either express or implied. See the License for the
  48145. * specific language governing permissions and limitations
  48146. * under the License.
  48147. */
  48148. /**
  48149. * @payload
  48150. * @property {string} parallelAxisId
  48151. * @property {Array.<Array.<number>>} intervals
  48152. */
  48153. var actionInfo$1 = {
  48154. type: 'axisAreaSelect',
  48155. event: 'axisAreaSelected'
  48156. // update: 'updateVisual'
  48157. };
  48158. registerAction(actionInfo$1, function (payload, ecModel) {
  48159. ecModel.eachComponent(
  48160. {mainType: 'parallelAxis', query: payload},
  48161. function (parallelAxisModel) {
  48162. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  48163. }
  48164. );
  48165. });
  48166. /**
  48167. * @payload
  48168. */
  48169. registerAction('parallelAxisExpand', function (payload, ecModel) {
  48170. ecModel.eachComponent(
  48171. {mainType: 'parallel', query: payload},
  48172. function (parallelModel) {
  48173. parallelModel.setAxisExpand(payload);
  48174. }
  48175. );
  48176. });
  48177. /*
  48178. * Licensed to the Apache Software Foundation (ASF) under one
  48179. * or more contributor license agreements. See the NOTICE file
  48180. * distributed with this work for additional information
  48181. * regarding copyright ownership. The ASF licenses this file
  48182. * to you under the Apache License, Version 2.0 (the
  48183. * "License"); you may not use this file except in compliance
  48184. * with the License. You may obtain a copy of the License at
  48185. *
  48186. * http://www.apache.org/licenses/LICENSE-2.0
  48187. *
  48188. * Unless required by applicable law or agreed to in writing,
  48189. * software distributed under the License is distributed on an
  48190. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48191. * KIND, either express or implied. See the License for the
  48192. * specific language governing permissions and limitations
  48193. * under the License.
  48194. */
  48195. var curry$2 = curry;
  48196. var each$12 = each$1;
  48197. var map$2 = map;
  48198. var mathMin$6 = Math.min;
  48199. var mathMax$6 = Math.max;
  48200. var mathPow$2 = Math.pow;
  48201. var COVER_Z = 10000;
  48202. var UNSELECT_THRESHOLD = 6;
  48203. var MIN_RESIZE_LINE_WIDTH = 6;
  48204. var MUTEX_RESOURCE_KEY = 'globalPan';
  48205. var DIRECTION_MAP = {
  48206. w: [0, 0],
  48207. e: [0, 1],
  48208. n: [1, 0],
  48209. s: [1, 1]
  48210. };
  48211. var CURSOR_MAP = {
  48212. w: 'ew',
  48213. e: 'ew',
  48214. n: 'ns',
  48215. s: 'ns',
  48216. ne: 'nesw',
  48217. sw: 'nesw',
  48218. nw: 'nwse',
  48219. se: 'nwse'
  48220. };
  48221. var DEFAULT_BRUSH_OPT = {
  48222. brushStyle: {
  48223. lineWidth: 2,
  48224. stroke: 'rgba(0,0,0,0.3)',
  48225. fill: 'rgba(0,0,0,0.1)'
  48226. },
  48227. transformable: true,
  48228. brushMode: 'single',
  48229. removeOnClick: false
  48230. };
  48231. var baseUID = 0;
  48232. /**
  48233. * @alias module:echarts/component/helper/BrushController
  48234. * @constructor
  48235. * @mixin {module:zrender/mixin/Eventful}
  48236. * @event module:echarts/component/helper/BrushController#brush
  48237. * params:
  48238. * areas: Array.<Array>, coord relates to container group,
  48239. * If no container specified, to global.
  48240. * opt {
  48241. * isEnd: boolean,
  48242. * removeOnClick: boolean
  48243. * }
  48244. *
  48245. * @param {module:zrender/zrender~ZRender} zr
  48246. */
  48247. function BrushController(zr) {
  48248. if (__DEV__) {
  48249. assert$1(zr);
  48250. }
  48251. Eventful.call(this);
  48252. /**
  48253. * @type {module:zrender/zrender~ZRender}
  48254. * @private
  48255. */
  48256. this._zr = zr;
  48257. /**
  48258. * @type {module:zrender/container/Group}
  48259. * @readOnly
  48260. */
  48261. this.group = new Group();
  48262. /**
  48263. * Only for drawing (after enabledBrush).
  48264. * 'line', 'rect', 'polygon' or false
  48265. * If passing false/null/undefined, disable brush.
  48266. * If passing 'auto', determined by panel.defaultBrushType
  48267. * @private
  48268. * @type {string}
  48269. */
  48270. this._brushType;
  48271. /**
  48272. * Only for drawing (after enabledBrush).
  48273. *
  48274. * @private
  48275. * @type {Object}
  48276. */
  48277. this._brushOption;
  48278. /**
  48279. * @private
  48280. * @type {Object}
  48281. */
  48282. this._panels;
  48283. /**
  48284. * @private
  48285. * @type {Array.<nubmer>}
  48286. */
  48287. this._track = [];
  48288. /**
  48289. * @private
  48290. * @type {boolean}
  48291. */
  48292. this._dragging;
  48293. /**
  48294. * @private
  48295. * @type {Array}
  48296. */
  48297. this._covers = [];
  48298. /**
  48299. * @private
  48300. * @type {moudule:zrender/container/Group}
  48301. */
  48302. this._creatingCover;
  48303. /**
  48304. * `true` means global panel
  48305. * @private
  48306. * @type {module:zrender/container/Group|boolean}
  48307. */
  48308. this._creatingPanel;
  48309. /**
  48310. * @private
  48311. * @type {boolean}
  48312. */
  48313. this._enableGlobalPan;
  48314. /**
  48315. * @private
  48316. * @type {boolean}
  48317. */
  48318. if (__DEV__) {
  48319. this._mounted;
  48320. }
  48321. /**
  48322. * @private
  48323. * @type {string}
  48324. */
  48325. this._uid = 'brushController_' + baseUID++;
  48326. /**
  48327. * @private
  48328. * @type {Object}
  48329. */
  48330. this._handlers = {};
  48331. each$12(mouseHandlers, function (handler, eventName) {
  48332. this._handlers[eventName] = bind(handler, this);
  48333. }, this);
  48334. }
  48335. BrushController.prototype = {
  48336. constructor: BrushController,
  48337. /**
  48338. * If set to null/undefined/false, select disabled.
  48339. * @param {Object} brushOption
  48340. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  48341. * If passing false/null/undefined, disable brush.
  48342. * If passing 'auto', determined by panel.defaultBrushType.
  48343. * ('auto' can not be used in global panel)
  48344. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  48345. * @param {boolean} [brushOption.transformable=true]
  48346. * @param {boolean} [brushOption.removeOnClick=false]
  48347. * @param {Object} [brushOption.brushStyle]
  48348. * @param {number} [brushOption.brushStyle.width]
  48349. * @param {number} [brushOption.brushStyle.lineWidth]
  48350. * @param {string} [brushOption.brushStyle.stroke]
  48351. * @param {string} [brushOption.brushStyle.fill]
  48352. * @param {number} [brushOption.z]
  48353. */
  48354. enableBrush: function (brushOption) {
  48355. if (__DEV__) {
  48356. assert$1(this._mounted);
  48357. }
  48358. this._brushType && doDisableBrush(this);
  48359. brushOption.brushType && doEnableBrush(this, brushOption);
  48360. return this;
  48361. },
  48362. /**
  48363. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  48364. * Each items: {
  48365. * panelId, // mandatory.
  48366. * clipPath, // mandatory. function.
  48367. * isTargetByCursor, // mandatory. function.
  48368. * defaultBrushType, // optional, only used when brushType is 'auto'.
  48369. * getLinearBrushOtherExtent, // optional. function.
  48370. * }
  48371. */
  48372. setPanels: function (panelOpts) {
  48373. if (panelOpts && panelOpts.length) {
  48374. var panels = this._panels = {};
  48375. each$1(panelOpts, function (panelOpts) {
  48376. panels[panelOpts.panelId] = clone(panelOpts);
  48377. });
  48378. }
  48379. else {
  48380. this._panels = null;
  48381. }
  48382. return this;
  48383. },
  48384. /**
  48385. * @param {Object} [opt]
  48386. * @return {boolean} [opt.enableGlobalPan=false]
  48387. */
  48388. mount: function (opt) {
  48389. opt = opt || {};
  48390. if (__DEV__) {
  48391. this._mounted = true; // should be at first.
  48392. }
  48393. this._enableGlobalPan = opt.enableGlobalPan;
  48394. var thisGroup = this.group;
  48395. this._zr.add(thisGroup);
  48396. thisGroup.attr({
  48397. position: opt.position || [0, 0],
  48398. rotation: opt.rotation || 0,
  48399. scale: opt.scale || [1, 1]
  48400. });
  48401. this._transform = thisGroup.getLocalTransform();
  48402. return this;
  48403. },
  48404. eachCover: function (cb, context) {
  48405. each$12(this._covers, cb, context);
  48406. },
  48407. /**
  48408. * Update covers.
  48409. * @param {Array.<Object>} brushOptionList Like:
  48410. * [
  48411. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  48412. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  48413. * ...
  48414. * ]
  48415. * `brushType` is required in each cover info. (can not be 'auto')
  48416. * `id` is not mandatory.
  48417. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  48418. * If brushOptionList is null/undefined, all covers removed.
  48419. */
  48420. updateCovers: function (brushOptionList) {
  48421. if (__DEV__) {
  48422. assert$1(this._mounted);
  48423. }
  48424. brushOptionList = map(brushOptionList, function (brushOption) {
  48425. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48426. });
  48427. var tmpIdPrefix = '\0-brush-index-';
  48428. var oldCovers = this._covers;
  48429. var newCovers = this._covers = [];
  48430. var controller = this;
  48431. var creatingCover = this._creatingCover;
  48432. (new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey))
  48433. .add(addOrUpdate)
  48434. .update(addOrUpdate)
  48435. .remove(remove)
  48436. .execute();
  48437. return this;
  48438. function getKey(brushOption, index) {
  48439. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index)
  48440. + '-' + brushOption.brushType;
  48441. }
  48442. function oldGetKey(cover, index) {
  48443. return getKey(cover.__brushOption, index);
  48444. }
  48445. function addOrUpdate(newIndex, oldIndex) {
  48446. var newBrushOption = brushOptionList[newIndex];
  48447. // Consider setOption in event listener of brushSelect,
  48448. // where updating cover when creating should be forbiden.
  48449. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  48450. newCovers[newIndex] = oldCovers[oldIndex];
  48451. }
  48452. else {
  48453. var cover = newCovers[newIndex] = oldIndex != null
  48454. ? (
  48455. oldCovers[oldIndex].__brushOption = newBrushOption,
  48456. oldCovers[oldIndex]
  48457. )
  48458. : endCreating(controller, createCover(controller, newBrushOption));
  48459. updateCoverAfterCreation(controller, cover);
  48460. }
  48461. }
  48462. function remove(oldIndex) {
  48463. if (oldCovers[oldIndex] !== creatingCover) {
  48464. controller.group.remove(oldCovers[oldIndex]);
  48465. }
  48466. }
  48467. },
  48468. unmount: function () {
  48469. if (__DEV__) {
  48470. if (!this._mounted) {
  48471. return;
  48472. }
  48473. }
  48474. this.enableBrush(false);
  48475. // container may 'removeAll' outside.
  48476. clearCovers(this);
  48477. this._zr.remove(this.group);
  48478. if (__DEV__) {
  48479. this._mounted = false; // should be at last.
  48480. }
  48481. return this;
  48482. },
  48483. dispose: function () {
  48484. this.unmount();
  48485. this.off();
  48486. }
  48487. };
  48488. mixin(BrushController, Eventful);
  48489. function doEnableBrush(controller, brushOption) {
  48490. var zr = controller._zr;
  48491. // Consider roam, which takes globalPan too.
  48492. if (!controller._enableGlobalPan) {
  48493. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48494. }
  48495. each$12(controller._handlers, function (handler, eventName) {
  48496. zr.on(eventName, handler);
  48497. });
  48498. controller._brushType = brushOption.brushType;
  48499. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  48500. }
  48501. function doDisableBrush(controller) {
  48502. var zr = controller._zr;
  48503. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  48504. each$12(controller._handlers, function (handler, eventName) {
  48505. zr.off(eventName, handler);
  48506. });
  48507. controller._brushType = controller._brushOption = null;
  48508. }
  48509. function createCover(controller, brushOption) {
  48510. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  48511. cover.__brushOption = brushOption;
  48512. updateZ$1(cover, brushOption);
  48513. controller.group.add(cover);
  48514. return cover;
  48515. }
  48516. function endCreating(controller, creatingCover) {
  48517. var coverRenderer = getCoverRenderer(creatingCover);
  48518. if (coverRenderer.endCreating) {
  48519. coverRenderer.endCreating(controller, creatingCover);
  48520. updateZ$1(creatingCover, creatingCover.__brushOption);
  48521. }
  48522. return creatingCover;
  48523. }
  48524. function updateCoverShape(controller, cover) {
  48525. var brushOption = cover.__brushOption;
  48526. getCoverRenderer(cover).updateCoverShape(
  48527. controller, cover, brushOption.range, brushOption
  48528. );
  48529. }
  48530. function updateZ$1(cover, brushOption) {
  48531. var z = brushOption.z;
  48532. z == null && (z = COVER_Z);
  48533. cover.traverse(function (el) {
  48534. el.z = z;
  48535. el.z2 = z; // Consider in given container.
  48536. });
  48537. }
  48538. function updateCoverAfterCreation(controller, cover) {
  48539. getCoverRenderer(cover).updateCommon(controller, cover);
  48540. updateCoverShape(controller, cover);
  48541. }
  48542. function getCoverRenderer(cover) {
  48543. return coverRenderers[cover.__brushOption.brushType];
  48544. }
  48545. // return target panel or `true` (means global panel)
  48546. function getPanelByPoint(controller, e, localCursorPoint) {
  48547. var panels = controller._panels;
  48548. if (!panels) {
  48549. return true; // Global panel
  48550. }
  48551. var panel;
  48552. var transform = controller._transform;
  48553. each$12(panels, function (pn) {
  48554. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  48555. });
  48556. return panel;
  48557. }
  48558. // Return a panel or true
  48559. function getPanelByCover(controller, cover) {
  48560. var panels = controller._panels;
  48561. if (!panels) {
  48562. return true; // Global panel
  48563. }
  48564. var panelId = cover.__brushOption.panelId;
  48565. // User may give cover without coord sys info,
  48566. // which is then treated as global panel.
  48567. return panelId != null ? panels[panelId] : true;
  48568. }
  48569. function clearCovers(controller) {
  48570. var covers = controller._covers;
  48571. var originalLength = covers.length;
  48572. each$12(covers, function (cover) {
  48573. controller.group.remove(cover);
  48574. }, controller);
  48575. covers.length = 0;
  48576. return !!originalLength;
  48577. }
  48578. function trigger(controller, opt) {
  48579. var areas = map$2(controller._covers, function (cover) {
  48580. var brushOption = cover.__brushOption;
  48581. var range = clone(brushOption.range);
  48582. return {
  48583. brushType: brushOption.brushType,
  48584. panelId: brushOption.panelId,
  48585. range: range
  48586. };
  48587. });
  48588. controller.trigger('brush', areas, {
  48589. isEnd: !!opt.isEnd,
  48590. removeOnClick: !!opt.removeOnClick
  48591. });
  48592. }
  48593. function shouldShowCover(controller) {
  48594. var track = controller._track;
  48595. if (!track.length) {
  48596. return false;
  48597. }
  48598. var p2 = track[track.length - 1];
  48599. var p1 = track[0];
  48600. var dx = p2[0] - p1[0];
  48601. var dy = p2[1] - p1[1];
  48602. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  48603. return dist > UNSELECT_THRESHOLD;
  48604. }
  48605. function getTrackEnds(track) {
  48606. var tail = track.length - 1;
  48607. tail < 0 && (tail = 0);
  48608. return [track[0], track[tail]];
  48609. }
  48610. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  48611. var cover = new Group();
  48612. cover.add(new Rect({
  48613. name: 'main',
  48614. style: makeStyle(brushOption),
  48615. silent: true,
  48616. draggable: true,
  48617. cursor: 'move',
  48618. drift: curry$2(doDrift, controller, cover, 'nswe'),
  48619. ondragend: curry$2(trigger, controller, {isEnd: true})
  48620. }));
  48621. each$12(
  48622. edgeNames,
  48623. function (name) {
  48624. cover.add(new Rect({
  48625. name: name,
  48626. style: {opacity: 0},
  48627. draggable: true,
  48628. silent: true,
  48629. invisible: true,
  48630. drift: curry$2(doDrift, controller, cover, name),
  48631. ondragend: curry$2(trigger, controller, {isEnd: true})
  48632. }));
  48633. }
  48634. );
  48635. return cover;
  48636. }
  48637. function updateBaseRect(controller, cover, localRange, brushOption) {
  48638. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  48639. var handleSize = mathMax$6(lineWidth, MIN_RESIZE_LINE_WIDTH);
  48640. var x = localRange[0][0];
  48641. var y = localRange[1][0];
  48642. var xa = x - lineWidth / 2;
  48643. var ya = y - lineWidth / 2;
  48644. var x2 = localRange[0][1];
  48645. var y2 = localRange[1][1];
  48646. var x2a = x2 - handleSize + lineWidth / 2;
  48647. var y2a = y2 - handleSize + lineWidth / 2;
  48648. var width = x2 - x;
  48649. var height = y2 - y;
  48650. var widtha = width + lineWidth;
  48651. var heighta = height + lineWidth;
  48652. updateRectShape(controller, cover, 'main', x, y, width, height);
  48653. if (brushOption.transformable) {
  48654. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  48655. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  48656. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  48657. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  48658. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  48659. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  48660. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  48661. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  48662. }
  48663. }
  48664. function updateCommon(controller, cover) {
  48665. var brushOption = cover.__brushOption;
  48666. var transformable = brushOption.transformable;
  48667. var mainEl = cover.childAt(0);
  48668. mainEl.useStyle(makeStyle(brushOption));
  48669. mainEl.attr({
  48670. silent: !transformable,
  48671. cursor: transformable ? 'move' : 'default'
  48672. });
  48673. each$12(
  48674. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'],
  48675. function (name) {
  48676. var el = cover.childOfName(name);
  48677. var globalDir = getGlobalDirection(controller, name);
  48678. el && el.attr({
  48679. silent: !transformable,
  48680. invisible: !transformable,
  48681. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  48682. });
  48683. }
  48684. );
  48685. }
  48686. function updateRectShape(controller, cover, name, x, y, w, h) {
  48687. var el = cover.childOfName(name);
  48688. el && el.setShape(pointsToRect(
  48689. clipByPanel(controller, cover, [[x, y], [x + w, y + h]])
  48690. ));
  48691. }
  48692. function makeStyle(brushOption) {
  48693. return defaults({strokeNoScale: true}, brushOption.brushStyle);
  48694. }
  48695. function formatRectRange(x, y, x2, y2) {
  48696. var min = [mathMin$6(x, x2), mathMin$6(y, y2)];
  48697. var max = [mathMax$6(x, x2), mathMax$6(y, y2)];
  48698. return [
  48699. [min[0], max[0]], // x range
  48700. [min[1], max[1]] // y range
  48701. ];
  48702. }
  48703. function getTransform$1(controller) {
  48704. return getTransform(controller.group);
  48705. }
  48706. function getGlobalDirection(controller, localDirection) {
  48707. if (localDirection.length > 1) {
  48708. localDirection = localDirection.split('');
  48709. var globalDir = [
  48710. getGlobalDirection(controller, localDirection[0]),
  48711. getGlobalDirection(controller, localDirection[1])
  48712. ];
  48713. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  48714. return globalDir.join('');
  48715. }
  48716. else {
  48717. var map$$1 = {w: 'left', e: 'right', n: 'top', s: 'bottom'};
  48718. var inverseMap = {left: 'w', right: 'e', top: 'n', bottom: 's'};
  48719. var globalDir = transformDirection(
  48720. map$$1[localDirection], getTransform$1(controller)
  48721. );
  48722. return inverseMap[globalDir];
  48723. }
  48724. }
  48725. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  48726. var brushOption = cover.__brushOption;
  48727. var rectRange = toRectRange(brushOption.range);
  48728. var localDelta = toLocalDelta(controller, dx, dy);
  48729. each$12(name.split(''), function (namePart) {
  48730. var ind = DIRECTION_MAP[namePart];
  48731. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  48732. });
  48733. brushOption.range = fromRectRange(formatRectRange(
  48734. rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]
  48735. ));
  48736. updateCoverAfterCreation(controller, cover);
  48737. trigger(controller, {isEnd: false});
  48738. }
  48739. function driftPolygon(controller, cover, dx, dy, e) {
  48740. var range = cover.__brushOption.range;
  48741. var localDelta = toLocalDelta(controller, dx, dy);
  48742. each$12(range, function (point) {
  48743. point[0] += localDelta[0];
  48744. point[1] += localDelta[1];
  48745. });
  48746. updateCoverAfterCreation(controller, cover);
  48747. trigger(controller, {isEnd: false});
  48748. }
  48749. function toLocalDelta(controller, dx, dy) {
  48750. var thisGroup = controller.group;
  48751. var localD = thisGroup.transformCoordToLocal(dx, dy);
  48752. var localZero = thisGroup.transformCoordToLocal(0, 0);
  48753. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  48754. }
  48755. function clipByPanel(controller, cover, data) {
  48756. var panel = getPanelByCover(controller, cover);
  48757. return (panel && panel !== true)
  48758. ? panel.clipPath(data, controller._transform)
  48759. : clone(data);
  48760. }
  48761. function pointsToRect(points) {
  48762. var xmin = mathMin$6(points[0][0], points[1][0]);
  48763. var ymin = mathMin$6(points[0][1], points[1][1]);
  48764. var xmax = mathMax$6(points[0][0], points[1][0]);
  48765. var ymax = mathMax$6(points[0][1], points[1][1]);
  48766. return {
  48767. x: xmin,
  48768. y: ymin,
  48769. width: xmax - xmin,
  48770. height: ymax - ymin
  48771. };
  48772. }
  48773. function resetCursor(controller, e, localCursorPoint) {
  48774. // Check active
  48775. if (!controller._brushType) {
  48776. return;
  48777. }
  48778. var zr = controller._zr;
  48779. var covers = controller._covers;
  48780. var currPanel = getPanelByPoint(controller, e, localCursorPoint);
  48781. // Check whether in covers.
  48782. if (!controller._dragging) {
  48783. for (var i = 0; i < covers.length; i++) {
  48784. var brushOption = covers[i].__brushOption;
  48785. if (currPanel
  48786. && (currPanel === true || brushOption.panelId === currPanel.panelId)
  48787. && coverRenderers[brushOption.brushType].contain(
  48788. covers[i], localCursorPoint[0], localCursorPoint[1]
  48789. )
  48790. ) {
  48791. // Use cursor style set on cover.
  48792. return;
  48793. }
  48794. }
  48795. }
  48796. currPanel && zr.setCursorStyle('crosshair');
  48797. }
  48798. function preventDefault(e) {
  48799. var rawE = e.event;
  48800. rawE.preventDefault && rawE.preventDefault();
  48801. }
  48802. function mainShapeContain(cover, x, y) {
  48803. return cover.childOfName('main').contain(x, y);
  48804. }
  48805. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  48806. var creatingCover = controller._creatingCover;
  48807. var panel = controller._creatingPanel;
  48808. var thisBrushOption = controller._brushOption;
  48809. var eventParams;
  48810. controller._track.push(localCursorPoint.slice());
  48811. if (shouldShowCover(controller) || creatingCover) {
  48812. if (panel && !creatingCover) {
  48813. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  48814. var brushOption = clone(thisBrushOption);
  48815. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  48816. brushOption.panelId = panel === true ? null : panel.panelId;
  48817. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  48818. controller._covers.push(creatingCover);
  48819. }
  48820. if (creatingCover) {
  48821. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  48822. var coverBrushOption = creatingCover.__brushOption;
  48823. coverBrushOption.range = coverRenderer.getCreatingRange(
  48824. clipByPanel(controller, creatingCover, controller._track)
  48825. );
  48826. if (isEnd) {
  48827. endCreating(controller, creatingCover);
  48828. coverRenderer.updateCommon(controller, creatingCover);
  48829. }
  48830. updateCoverShape(controller, creatingCover);
  48831. eventParams = {isEnd: isEnd};
  48832. }
  48833. }
  48834. else if (
  48835. isEnd
  48836. && thisBrushOption.brushMode === 'single'
  48837. && thisBrushOption.removeOnClick
  48838. ) {
  48839. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  48840. // But a single click do not clear covers, because user may have casual
  48841. // clicks (for example, click on other component and do not expect covers
  48842. // disappear).
  48843. // Only some cover removed, trigger action, but not every click trigger action.
  48844. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  48845. eventParams = {isEnd: isEnd, removeOnClick: true};
  48846. }
  48847. }
  48848. return eventParams;
  48849. }
  48850. function determineBrushType(brushType, panel) {
  48851. if (brushType === 'auto') {
  48852. if (__DEV__) {
  48853. assert$1(
  48854. panel && panel.defaultBrushType,
  48855. 'MUST have defaultBrushType when brushType is "atuo"'
  48856. );
  48857. }
  48858. return panel.defaultBrushType;
  48859. }
  48860. return brushType;
  48861. }
  48862. var mouseHandlers = {
  48863. mousedown: function (e) {
  48864. if (this._dragging) {
  48865. // In case some browser do not support globalOut,
  48866. // and release mose out side the browser.
  48867. handleDragEnd.call(this, e);
  48868. }
  48869. else if (!e.target || !e.target.draggable) {
  48870. preventDefault(e);
  48871. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48872. this._creatingCover = null;
  48873. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  48874. if (panel) {
  48875. this._dragging = true;
  48876. this._track = [localCursorPoint.slice()];
  48877. }
  48878. }
  48879. },
  48880. mousemove: function (e) {
  48881. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48882. resetCursor(this, e, localCursorPoint);
  48883. if (this._dragging) {
  48884. preventDefault(e);
  48885. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  48886. eventParams && trigger(this, eventParams);
  48887. }
  48888. },
  48889. mouseup: handleDragEnd //,
  48890. // FIXME
  48891. // in tooltip, globalout should not be triggered.
  48892. // globalout: handleDragEnd
  48893. };
  48894. function handleDragEnd(e) {
  48895. if (this._dragging) {
  48896. preventDefault(e);
  48897. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  48898. var eventParams = updateCoverByMouse(this, e, localCursorPoint, true);
  48899. this._dragging = false;
  48900. this._track = [];
  48901. this._creatingCover = null;
  48902. // trigger event shoule be at final, after procedure will be nested.
  48903. eventParams && trigger(this, eventParams);
  48904. }
  48905. }
  48906. /**
  48907. * key: brushType
  48908. * @type {Object}
  48909. */
  48910. var coverRenderers = {
  48911. lineX: getLineRenderer(0),
  48912. lineY: getLineRenderer(1),
  48913. rect: {
  48914. createCover: function (controller, brushOption) {
  48915. return createBaseRectCover(
  48916. curry$2(
  48917. driftRect,
  48918. function (range) {
  48919. return range;
  48920. },
  48921. function (range) {
  48922. return range;
  48923. }
  48924. ),
  48925. controller,
  48926. brushOption,
  48927. ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']
  48928. );
  48929. },
  48930. getCreatingRange: function (localTrack) {
  48931. var ends = getTrackEnds(localTrack);
  48932. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  48933. },
  48934. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48935. updateBaseRect(controller, cover, localRange, brushOption);
  48936. },
  48937. updateCommon: updateCommon,
  48938. contain: mainShapeContain
  48939. },
  48940. polygon: {
  48941. createCover: function (controller, brushOption) {
  48942. var cover = new Group();
  48943. // Do not use graphic.Polygon because graphic.Polyline do not close the
  48944. // border of the shape when drawing, which is a better experience for user.
  48945. cover.add(new Polyline({
  48946. name: 'main',
  48947. style: makeStyle(brushOption),
  48948. silent: true
  48949. }));
  48950. return cover;
  48951. },
  48952. getCreatingRange: function (localTrack) {
  48953. return localTrack;
  48954. },
  48955. endCreating: function (controller, cover) {
  48956. cover.remove(cover.childAt(0));
  48957. // Use graphic.Polygon close the shape.
  48958. cover.add(new Polygon({
  48959. name: 'main',
  48960. draggable: true,
  48961. drift: curry$2(driftPolygon, controller, cover),
  48962. ondragend: curry$2(trigger, controller, {isEnd: true})
  48963. }));
  48964. },
  48965. updateCoverShape: function (controller, cover, localRange, brushOption) {
  48966. cover.childAt(0).setShape({
  48967. points: clipByPanel(controller, cover, localRange)
  48968. });
  48969. },
  48970. updateCommon: updateCommon,
  48971. contain: mainShapeContain
  48972. }
  48973. };
  48974. function getLineRenderer(xyIndex) {
  48975. return {
  48976. createCover: function (controller, brushOption) {
  48977. return createBaseRectCover(
  48978. curry$2(
  48979. driftRect,
  48980. function (range) {
  48981. var rectRange = [range, [0, 100]];
  48982. xyIndex && rectRange.reverse();
  48983. return rectRange;
  48984. },
  48985. function (rectRange) {
  48986. return rectRange[xyIndex];
  48987. }
  48988. ),
  48989. controller,
  48990. brushOption,
  48991. [['w', 'e'], ['n', 's']][xyIndex]
  48992. );
  48993. },
  48994. getCreatingRange: function (localTrack) {
  48995. var ends = getTrackEnds(localTrack);
  48996. var min = mathMin$6(ends[0][xyIndex], ends[1][xyIndex]);
  48997. var max = mathMax$6(ends[0][xyIndex], ends[1][xyIndex]);
  48998. return [min, max];
  48999. },
  49000. updateCoverShape: function (controller, cover, localRange, brushOption) {
  49001. var otherExtent;
  49002. // If brushWidth not specified, fit the panel.
  49003. var panel = getPanelByCover(controller, cover);
  49004. if (panel !== true && panel.getLinearBrushOtherExtent) {
  49005. otherExtent = panel.getLinearBrushOtherExtent(
  49006. xyIndex, controller._transform
  49007. );
  49008. }
  49009. else {
  49010. var zr = controller._zr;
  49011. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  49012. }
  49013. var rectRange = [localRange, otherExtent];
  49014. xyIndex && rectRange.reverse();
  49015. updateBaseRect(controller, cover, rectRange, brushOption);
  49016. },
  49017. updateCommon: updateCommon,
  49018. contain: mainShapeContain
  49019. };
  49020. }
  49021. /*
  49022. * Licensed to the Apache Software Foundation (ASF) under one
  49023. * or more contributor license agreements. See the NOTICE file
  49024. * distributed with this work for additional information
  49025. * regarding copyright ownership. The ASF licenses this file
  49026. * to you under the Apache License, Version 2.0 (the
  49027. * "License"); you may not use this file except in compliance
  49028. * with the License. You may obtain a copy of the License at
  49029. *
  49030. * http://www.apache.org/licenses/LICENSE-2.0
  49031. *
  49032. * Unless required by applicable law or agreed to in writing,
  49033. * software distributed under the License is distributed on an
  49034. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49035. * KIND, either express or implied. See the License for the
  49036. * specific language governing permissions and limitations
  49037. * under the License.
  49038. */
  49039. function makeRectPanelClipPath(rect) {
  49040. rect = normalizeRect(rect);
  49041. return function (localPoints, transform) {
  49042. return clipPointsByRect(localPoints, rect);
  49043. };
  49044. }
  49045. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  49046. rect = normalizeRect(rect);
  49047. return function (xyIndex) {
  49048. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  49049. var brushWidth = idx ? rect.width : rect.height;
  49050. var base = idx ? rect.x : rect.y;
  49051. return [base, base + (brushWidth || 0)];
  49052. };
  49053. }
  49054. function makeRectIsTargetByCursor(rect, api, targetModel) {
  49055. rect = normalizeRect(rect);
  49056. return function (e, localCursorPoint, transform) {
  49057. return rect.contain(localCursorPoint[0], localCursorPoint[1])
  49058. && !onIrrelevantElement(e, api, targetModel);
  49059. };
  49060. }
  49061. // Consider width/height is negative.
  49062. function normalizeRect(rect) {
  49063. return BoundingRect.create(rect);
  49064. }
  49065. /*
  49066. * Licensed to the Apache Software Foundation (ASF) under one
  49067. * or more contributor license agreements. See the NOTICE file
  49068. * distributed with this work for additional information
  49069. * regarding copyright ownership. The ASF licenses this file
  49070. * to you under the Apache License, Version 2.0 (the
  49071. * "License"); you may not use this file except in compliance
  49072. * with the License. You may obtain a copy of the License at
  49073. *
  49074. * http://www.apache.org/licenses/LICENSE-2.0
  49075. *
  49076. * Unless required by applicable law or agreed to in writing,
  49077. * software distributed under the License is distributed on an
  49078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49079. * KIND, either express or implied. See the License for the
  49080. * specific language governing permissions and limitations
  49081. * under the License.
  49082. */
  49083. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  49084. var AxisView$2 = extendComponentView({
  49085. type: 'parallelAxis',
  49086. /**
  49087. * @override
  49088. */
  49089. init: function (ecModel, api) {
  49090. AxisView$2.superApply(this, 'init', arguments);
  49091. /**
  49092. * @type {module:echarts/component/helper/BrushController}
  49093. */
  49094. (this._brushController = new BrushController(api.getZr()))
  49095. .on('brush', bind(this._onBrush, this));
  49096. },
  49097. /**
  49098. * @override
  49099. */
  49100. render: function (axisModel, ecModel, api, payload) {
  49101. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  49102. return;
  49103. }
  49104. this.axisModel = axisModel;
  49105. this.api = api;
  49106. this.group.removeAll();
  49107. var oldAxisGroup = this._axisGroup;
  49108. this._axisGroup = new Group();
  49109. this.group.add(this._axisGroup);
  49110. if (!axisModel.get('show')) {
  49111. return;
  49112. }
  49113. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  49114. var coordSys = coordSysModel.coordinateSystem;
  49115. var areaSelectStyle = axisModel.getAreaSelectStyle();
  49116. var areaWidth = areaSelectStyle.width;
  49117. var dim = axisModel.axis.dim;
  49118. var axisLayout = coordSys.getAxisLayout(dim);
  49119. var builderOpt = extend(
  49120. {strokeContainThreshold: areaWidth},
  49121. axisLayout
  49122. );
  49123. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  49124. each$1(elementList, axisBuilder.add, axisBuilder);
  49125. this._axisGroup.add(axisBuilder.getGroup());
  49126. this._refreshBrushController(
  49127. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  49128. );
  49129. var animationModel = (payload && payload.animation === false) ? null : axisModel;
  49130. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  49131. },
  49132. // /**
  49133. // * @override
  49134. // */
  49135. // updateVisual: function (axisModel, ecModel, api, payload) {
  49136. // this._brushController && this._brushController
  49137. // .updateCovers(getCoverInfoList(axisModel));
  49138. // },
  49139. _refreshBrushController: function (
  49140. builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api
  49141. ) {
  49142. // After filtering, axis may change, select area needs to be update.
  49143. var extent = axisModel.axis.getExtent();
  49144. var extentLen = extent[1] - extent[0];
  49145. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  49146. // width/height might be negative, which will be
  49147. // normalized in BoundingRect.
  49148. var rect = BoundingRect.create({
  49149. x: extent[0],
  49150. y: -areaWidth / 2,
  49151. width: extentLen,
  49152. height: areaWidth
  49153. });
  49154. rect.x -= extra;
  49155. rect.width += 2 * extra;
  49156. this._brushController
  49157. .mount({
  49158. enableGlobalPan: true,
  49159. rotation: builderOpt.rotation,
  49160. position: builderOpt.position
  49161. })
  49162. .setPanels([{
  49163. panelId: 'pl',
  49164. clipPath: makeRectPanelClipPath(rect),
  49165. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  49166. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  49167. }])
  49168. .enableBrush({
  49169. brushType: 'lineX',
  49170. brushStyle: areaSelectStyle,
  49171. removeOnClick: true
  49172. })
  49173. .updateCovers(getCoverInfoList(axisModel));
  49174. },
  49175. _onBrush: function (coverInfoList, opt) {
  49176. // Do not cache these object, because the mey be changed.
  49177. var axisModel = this.axisModel;
  49178. var axis = axisModel.axis;
  49179. var intervals = map(coverInfoList, function (coverInfo) {
  49180. return [
  49181. axis.coordToData(coverInfo.range[0], true),
  49182. axis.coordToData(coverInfo.range[1], true)
  49183. ];
  49184. });
  49185. // If realtime is true, action is not dispatched on drag end, because
  49186. // the drag end emits the same params with the last drag move event,
  49187. // and may have some delay when using touch pad.
  49188. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) { // jshint ignore:line
  49189. this.api.dispatchAction({
  49190. type: 'axisAreaSelect',
  49191. parallelAxisId: axisModel.id,
  49192. intervals: intervals
  49193. });
  49194. }
  49195. },
  49196. /**
  49197. * @override
  49198. */
  49199. dispose: function () {
  49200. this._brushController.dispose();
  49201. }
  49202. });
  49203. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  49204. return payload
  49205. && payload.type === 'axisAreaSelect'
  49206. && ecModel.findComponents(
  49207. {mainType: 'parallelAxis', query: payload}
  49208. )[0] === axisModel;
  49209. }
  49210. function getCoverInfoList(axisModel) {
  49211. var axis = axisModel.axis;
  49212. return map(axisModel.activeIntervals, function (interval) {
  49213. return {
  49214. brushType: 'lineX',
  49215. panelId: 'pl',
  49216. range: [
  49217. axis.dataToCoord(interval[0], true),
  49218. axis.dataToCoord(interval[1], true)
  49219. ]
  49220. };
  49221. });
  49222. }
  49223. function getCoordSysModel(axisModel, ecModel) {
  49224. return ecModel.getComponent(
  49225. 'parallel', axisModel.get('parallelIndex')
  49226. );
  49227. }
  49228. /*
  49229. * Licensed to the Apache Software Foundation (ASF) under one
  49230. * or more contributor license agreements. See the NOTICE file
  49231. * distributed with this work for additional information
  49232. * regarding copyright ownership. The ASF licenses this file
  49233. * to you under the Apache License, Version 2.0 (the
  49234. * "License"); you may not use this file except in compliance
  49235. * with the License. You may obtain a copy of the License at
  49236. *
  49237. * http://www.apache.org/licenses/LICENSE-2.0
  49238. *
  49239. * Unless required by applicable law or agreed to in writing,
  49240. * software distributed under the License is distributed on an
  49241. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49242. * KIND, either express or implied. See the License for the
  49243. * specific language governing permissions and limitations
  49244. * under the License.
  49245. */
  49246. /*
  49247. * Licensed to the Apache Software Foundation (ASF) under one
  49248. * or more contributor license agreements. See the NOTICE file
  49249. * distributed with this work for additional information
  49250. * regarding copyright ownership. The ASF licenses this file
  49251. * to you under the Apache License, Version 2.0 (the
  49252. * "License"); you may not use this file except in compliance
  49253. * with the License. You may obtain a copy of the License at
  49254. *
  49255. * http://www.apache.org/licenses/LICENSE-2.0
  49256. *
  49257. * Unless required by applicable law or agreed to in writing,
  49258. * software distributed under the License is distributed on an
  49259. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49260. * KIND, either express or implied. See the License for the
  49261. * specific language governing permissions and limitations
  49262. * under the License.
  49263. */
  49264. var CLICK_THRESHOLD = 5; // > 4
  49265. // Parallel view
  49266. extendComponentView({
  49267. type: 'parallel',
  49268. render: function (parallelModel, ecModel, api) {
  49269. this._model = parallelModel;
  49270. this._api = api;
  49271. if (!this._handlers) {
  49272. this._handlers = {};
  49273. each$1(handlers, function (handler, eventName) {
  49274. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  49275. }, this);
  49276. }
  49277. createOrUpdate(
  49278. this,
  49279. '_throttledDispatchExpand',
  49280. parallelModel.get('axisExpandRate'),
  49281. 'fixRate'
  49282. );
  49283. },
  49284. dispose: function (ecModel, api) {
  49285. each$1(this._handlers, function (handler, eventName) {
  49286. api.getZr().off(eventName, handler);
  49287. });
  49288. this._handlers = null;
  49289. },
  49290. /**
  49291. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  49292. */
  49293. _throttledDispatchExpand: function (opt) {
  49294. this._dispatchExpand(opt);
  49295. },
  49296. _dispatchExpand: function (opt) {
  49297. opt && this._api.dispatchAction(
  49298. extend({type: 'parallelAxisExpand'}, opt)
  49299. );
  49300. }
  49301. });
  49302. var handlers = {
  49303. mousedown: function (e) {
  49304. if (checkTrigger(this, 'click')) {
  49305. this._mouseDownPoint = [e.offsetX, e.offsetY];
  49306. }
  49307. },
  49308. mouseup: function (e) {
  49309. var mouseDownPoint = this._mouseDownPoint;
  49310. if (checkTrigger(this, 'click') && mouseDownPoint) {
  49311. var point = [e.offsetX, e.offsetY];
  49312. var dist = Math.pow(mouseDownPoint[0] - point[0], 2)
  49313. + Math.pow(mouseDownPoint[1] - point[1], 2);
  49314. if (dist > CLICK_THRESHOLD) {
  49315. return;
  49316. }
  49317. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow(
  49318. [e.offsetX, e.offsetY]
  49319. );
  49320. result.behavior !== 'none' && this._dispatchExpand({
  49321. axisExpandWindow: result.axisExpandWindow
  49322. });
  49323. }
  49324. this._mouseDownPoint = null;
  49325. },
  49326. mousemove: function (e) {
  49327. // Should do nothing when brushing.
  49328. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  49329. return;
  49330. }
  49331. var model = this._model;
  49332. var result = model.coordinateSystem.getSlidedAxisExpandWindow(
  49333. [e.offsetX, e.offsetY]
  49334. );
  49335. var behavior = result.behavior;
  49336. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  49337. this._throttledDispatchExpand(
  49338. behavior === 'none'
  49339. ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  49340. : {
  49341. axisExpandWindow: result.axisExpandWindow,
  49342. // Jumping uses animation, and sliding suppresses animation.
  49343. animation: behavior === 'jump' ? null : false
  49344. }
  49345. );
  49346. }
  49347. };
  49348. function checkTrigger(view, triggerOn) {
  49349. var model = view._model;
  49350. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  49351. }
  49352. registerPreprocessor(parallelPreprocessor);
  49353. /*
  49354. * Licensed to the Apache Software Foundation (ASF) under one
  49355. * or more contributor license agreements. See the NOTICE file
  49356. * distributed with this work for additional information
  49357. * regarding copyright ownership. The ASF licenses this file
  49358. * to you under the Apache License, Version 2.0 (the
  49359. * "License"); you may not use this file except in compliance
  49360. * with the License. You may obtain a copy of the License at
  49361. *
  49362. * http://www.apache.org/licenses/LICENSE-2.0
  49363. *
  49364. * Unless required by applicable law or agreed to in writing,
  49365. * software distributed under the License is distributed on an
  49366. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49367. * KIND, either express or implied. See the License for the
  49368. * specific language governing permissions and limitations
  49369. * under the License.
  49370. */
  49371. SeriesModel.extend({
  49372. type: 'series.parallel',
  49373. dependencies: ['parallel'],
  49374. visualColorAccessPath: 'lineStyle.color',
  49375. getInitialData: function (option, ecModel) {
  49376. var source = this.getSource();
  49377. setEncodeAndDimensions(source, this);
  49378. return createListFromArray(source, this);
  49379. },
  49380. /**
  49381. * User can get data raw indices on 'axisAreaSelected' event received.
  49382. *
  49383. * @public
  49384. * @param {string} activeState 'active' or 'inactive' or 'normal'
  49385. * @return {Array.<number>} Raw indices
  49386. */
  49387. getRawIndicesByActiveState: function (activeState) {
  49388. var coordSys = this.coordinateSystem;
  49389. var data = this.getData();
  49390. var indices = [];
  49391. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  49392. if (activeState === theActiveState) {
  49393. indices.push(data.getRawIndex(dataIndex));
  49394. }
  49395. });
  49396. return indices;
  49397. },
  49398. defaultOption: {
  49399. zlevel: 0, // 一级层叠
  49400. z: 2, // 二级层叠
  49401. coordinateSystem: 'parallel',
  49402. parallelIndex: 0,
  49403. label: {
  49404. show: false
  49405. },
  49406. inactiveOpacity: 0.05,
  49407. activeOpacity: 1,
  49408. lineStyle: {
  49409. width: 1,
  49410. opacity: 0.45,
  49411. type: 'solid'
  49412. },
  49413. emphasis: {
  49414. label: {
  49415. show: false
  49416. }
  49417. },
  49418. progressive: 500,
  49419. smooth: false, // true | false | number
  49420. animationEasing: 'linear'
  49421. }
  49422. });
  49423. function setEncodeAndDimensions(source, seriesModel) {
  49424. // The mapping of parallelAxis dimension to data dimension can
  49425. // be specified in parallelAxis.option.dim. For example, if
  49426. // parallelAxis.option.dim is 'dim3', it mapping to the third
  49427. // dimension of data. But `data.encode` has higher priority.
  49428. // Moreover, parallelModel.dimension should not be regarded as data
  49429. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  49430. if (source.encodeDefine) {
  49431. return;
  49432. }
  49433. var parallelModel = seriesModel.ecModel.getComponent(
  49434. 'parallel', seriesModel.get('parallelIndex')
  49435. );
  49436. if (!parallelModel) {
  49437. return;
  49438. }
  49439. var encodeDefine = source.encodeDefine = createHashMap();
  49440. each$1(parallelModel.dimensions, function (axisDim) {
  49441. var dataDimIndex = convertDimNameToNumber(axisDim);
  49442. encodeDefine.set(axisDim, dataDimIndex);
  49443. });
  49444. }
  49445. function convertDimNameToNumber(dimName) {
  49446. return +dimName.replace('dim', '');
  49447. }
  49448. /*
  49449. * Licensed to the Apache Software Foundation (ASF) under one
  49450. * or more contributor license agreements. See the NOTICE file
  49451. * distributed with this work for additional information
  49452. * regarding copyright ownership. The ASF licenses this file
  49453. * to you under the Apache License, Version 2.0 (the
  49454. * "License"); you may not use this file except in compliance
  49455. * with the License. You may obtain a copy of the License at
  49456. *
  49457. * http://www.apache.org/licenses/LICENSE-2.0
  49458. *
  49459. * Unless required by applicable law or agreed to in writing,
  49460. * software distributed under the License is distributed on an
  49461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49462. * KIND, either express or implied. See the License for the
  49463. * specific language governing permissions and limitations
  49464. * under the License.
  49465. */
  49466. var DEFAULT_SMOOTH = 0.3;
  49467. var ParallelView = Chart.extend({
  49468. type: 'parallel',
  49469. init: function () {
  49470. /**
  49471. * @type {module:zrender/container/Group}
  49472. * @private
  49473. */
  49474. this._dataGroup = new Group();
  49475. this.group.add(this._dataGroup);
  49476. /**
  49477. * @type {module:echarts/data/List}
  49478. */
  49479. this._data;
  49480. /**
  49481. * @type {boolean}
  49482. */
  49483. this._initialized;
  49484. },
  49485. /**
  49486. * @override
  49487. */
  49488. render: function (seriesModel, ecModel, api, payload) {
  49489. var dataGroup = this._dataGroup;
  49490. var data = seriesModel.getData();
  49491. var oldData = this._data;
  49492. var coordSys = seriesModel.coordinateSystem;
  49493. var dimensions = coordSys.dimensions;
  49494. var seriesScope = makeSeriesScope$2(seriesModel);
  49495. data.diff(oldData)
  49496. .add(add)
  49497. .update(update)
  49498. .remove(remove)
  49499. .execute();
  49500. function add(newDataIndex) {
  49501. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  49502. updateElCommon(line, data, newDataIndex, seriesScope);
  49503. }
  49504. function update(newDataIndex, oldDataIndex) {
  49505. var line = oldData.getItemGraphicEl(oldDataIndex);
  49506. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  49507. data.setItemGraphicEl(newDataIndex, line);
  49508. var animationModel = (payload && payload.animation === false) ? null : seriesModel;
  49509. updateProps(line, {shape: {points: points}}, animationModel, newDataIndex);
  49510. updateElCommon(line, data, newDataIndex, seriesScope);
  49511. }
  49512. function remove(oldDataIndex) {
  49513. var line = oldData.getItemGraphicEl(oldDataIndex);
  49514. dataGroup.remove(line);
  49515. }
  49516. // First create
  49517. if (!this._initialized) {
  49518. this._initialized = true;
  49519. var clipPath = createGridClipShape$1(
  49520. coordSys, seriesModel, function () {
  49521. // Callback will be invoked immediately if there is no animation
  49522. setTimeout(function () {
  49523. dataGroup.removeClipPath();
  49524. });
  49525. }
  49526. );
  49527. dataGroup.setClipPath(clipPath);
  49528. }
  49529. this._data = data;
  49530. },
  49531. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  49532. this._initialized = true;
  49533. this._data = null;
  49534. this._dataGroup.removeAll();
  49535. },
  49536. incrementalRender: function (taskParams, seriesModel, ecModel) {
  49537. var data = seriesModel.getData();
  49538. var coordSys = seriesModel.coordinateSystem;
  49539. var dimensions = coordSys.dimensions;
  49540. var seriesScope = makeSeriesScope$2(seriesModel);
  49541. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  49542. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  49543. line.incremental = true;
  49544. updateElCommon(line, data, dataIndex, seriesScope);
  49545. }
  49546. },
  49547. dispose: function () {},
  49548. // _renderForProgressive: function (seriesModel) {
  49549. // var dataGroup = this._dataGroup;
  49550. // var data = seriesModel.getData();
  49551. // var oldData = this._data;
  49552. // var coordSys = seriesModel.coordinateSystem;
  49553. // var dimensions = coordSys.dimensions;
  49554. // var option = seriesModel.option;
  49555. // var progressive = option.progressive;
  49556. // var smooth = option.smooth ? SMOOTH : null;
  49557. // // In progressive animation is disabled, so use simple data diff,
  49558. // // which effects performance less.
  49559. // // (Typically performance for data with length 7000+ like:
  49560. // // simpleDiff: 60ms, addEl: 184ms,
  49561. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  49562. // if (simpleDiff(oldData, data, dimensions)) {
  49563. // dataGroup.removeAll();
  49564. // data.each(function (dataIndex) {
  49565. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  49566. // });
  49567. // }
  49568. // updateElCommon(data, progressive, smooth);
  49569. // // Consider switch between progressive and not.
  49570. // data.__plProgressive = true;
  49571. // this._data = data;
  49572. // },
  49573. /**
  49574. * @override
  49575. */
  49576. remove: function () {
  49577. this._dataGroup && this._dataGroup.removeAll();
  49578. this._data = null;
  49579. }
  49580. });
  49581. function createGridClipShape$1(coordSys, seriesModel, cb) {
  49582. var parallelModel = coordSys.model;
  49583. var rect = coordSys.getRect();
  49584. var rectEl = new Rect({
  49585. shape: {
  49586. x: rect.x,
  49587. y: rect.y,
  49588. width: rect.width,
  49589. height: rect.height
  49590. }
  49591. });
  49592. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  49593. rectEl.setShape(dim, 0);
  49594. initProps(rectEl, {
  49595. shape: {
  49596. width: rect.width,
  49597. height: rect.height
  49598. }
  49599. }, seriesModel, cb);
  49600. return rectEl;
  49601. }
  49602. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  49603. var points = [];
  49604. for (var i = 0; i < dimensions.length; i++) {
  49605. var dimName = dimensions[i];
  49606. var value = data.get(data.mapDimension(dimName), dataIndex);
  49607. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  49608. points.push(coordSys.dataToPoint(value, dimName));
  49609. }
  49610. }
  49611. return points;
  49612. }
  49613. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  49614. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  49615. var line = new Polyline({
  49616. shape: {points: points},
  49617. silent: true,
  49618. z2: 10
  49619. });
  49620. dataGroup.add(line);
  49621. data.setItemGraphicEl(dataIndex, line);
  49622. return line;
  49623. }
  49624. function makeSeriesScope$2(seriesModel) {
  49625. var smooth = seriesModel.get('smooth', true);
  49626. smooth === true && (smooth = DEFAULT_SMOOTH);
  49627. return {
  49628. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  49629. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  49630. };
  49631. }
  49632. function updateElCommon(el, data, dataIndex, seriesScope) {
  49633. var lineStyle = seriesScope.lineStyle;
  49634. if (data.hasItemOption) {
  49635. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  49636. lineStyle = lineStyleModel.getLineStyle();
  49637. }
  49638. el.useStyle(lineStyle);
  49639. var elStyle = el.style;
  49640. elStyle.fill = null;
  49641. // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  49642. elStyle.stroke = data.getItemVisual(dataIndex, 'color');
  49643. // lineStyle.opacity have been set to itemVisual in parallelVisual.
  49644. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  49645. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  49646. }
  49647. // function simpleDiff(oldData, newData, dimensions) {
  49648. // var oldLen;
  49649. // if (!oldData
  49650. // || !oldData.__plProgressive
  49651. // || (oldLen = oldData.count()) !== newData.count()
  49652. // ) {
  49653. // return true;
  49654. // }
  49655. // var dimLen = dimensions.length;
  49656. // for (var i = 0; i < oldLen; i++) {
  49657. // for (var j = 0; j < dimLen; j++) {
  49658. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  49659. // return true;
  49660. // }
  49661. // }
  49662. // }
  49663. // return false;
  49664. // }
  49665. // FIXME
  49666. // 公用方法?
  49667. function isEmptyValue(val, axisType) {
  49668. return axisType === 'category'
  49669. ? val == null
  49670. : (val == null || isNaN(val)); // axisType === 'value'
  49671. }
  49672. /*
  49673. * Licensed to the Apache Software Foundation (ASF) under one
  49674. * or more contributor license agreements. See the NOTICE file
  49675. * distributed with this work for additional information
  49676. * regarding copyright ownership. The ASF licenses this file
  49677. * to you under the Apache License, Version 2.0 (the
  49678. * "License"); you may not use this file except in compliance
  49679. * with the License. You may obtain a copy of the License at
  49680. *
  49681. * http://www.apache.org/licenses/LICENSE-2.0
  49682. *
  49683. * Unless required by applicable law or agreed to in writing,
  49684. * software distributed under the License is distributed on an
  49685. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49686. * KIND, either express or implied. See the License for the
  49687. * specific language governing permissions and limitations
  49688. * under the License.
  49689. */
  49690. var opacityAccessPath$1 = ['lineStyle', 'normal', 'opacity'];
  49691. var parallelVisual = {
  49692. seriesType: 'parallel',
  49693. reset: function (seriesModel, ecModel, api) {
  49694. var itemStyleModel = seriesModel.getModel('itemStyle');
  49695. var lineStyleModel = seriesModel.getModel('lineStyle');
  49696. var globalColors = ecModel.get('color');
  49697. var color = lineStyleModel.get('color')
  49698. || itemStyleModel.get('color')
  49699. || globalColors[seriesModel.seriesIndex % globalColors.length];
  49700. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  49701. var activeOpacity = seriesModel.get('activeOpacity');
  49702. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  49703. var coordSys = seriesModel.coordinateSystem;
  49704. var data = seriesModel.getData();
  49705. var opacityMap = {
  49706. normal: lineStyle.opacity,
  49707. active: activeOpacity,
  49708. inactive: inactiveOpacity
  49709. };
  49710. data.setVisual('color', color);
  49711. function progress(params, data) {
  49712. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  49713. var opacity = opacityMap[activeState];
  49714. if (activeState === 'normal' && data.hasItemOption) {
  49715. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath$1, true);
  49716. itemOpacity != null && (opacity = itemOpacity);
  49717. }
  49718. data.setItemVisual(dataIndex, 'opacity', opacity);
  49719. }, params.start, params.end);
  49720. }
  49721. return {progress: progress};
  49722. }
  49723. };
  49724. /*
  49725. * Licensed to the Apache Software Foundation (ASF) under one
  49726. * or more contributor license agreements. See the NOTICE file
  49727. * distributed with this work for additional information
  49728. * regarding copyright ownership. The ASF licenses this file
  49729. * to you under the Apache License, Version 2.0 (the
  49730. * "License"); you may not use this file except in compliance
  49731. * with the License. You may obtain a copy of the License at
  49732. *
  49733. * http://www.apache.org/licenses/LICENSE-2.0
  49734. *
  49735. * Unless required by applicable law or agreed to in writing,
  49736. * software distributed under the License is distributed on an
  49737. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49738. * KIND, either express or implied. See the License for the
  49739. * specific language governing permissions and limitations
  49740. * under the License.
  49741. */
  49742. registerVisual(parallelVisual);
  49743. /*
  49744. * Licensed to the Apache Software Foundation (ASF) under one
  49745. * or more contributor license agreements. See the NOTICE file
  49746. * distributed with this work for additional information
  49747. * regarding copyright ownership. The ASF licenses this file
  49748. * to you under the Apache License, Version 2.0 (the
  49749. * "License"); you may not use this file except in compliance
  49750. * with the License. You may obtain a copy of the License at
  49751. *
  49752. * http://www.apache.org/licenses/LICENSE-2.0
  49753. *
  49754. * Unless required by applicable law or agreed to in writing,
  49755. * software distributed under the License is distributed on an
  49756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49757. * KIND, either express or implied. See the License for the
  49758. * specific language governing permissions and limitations
  49759. * under the License.
  49760. */
  49761. /**
  49762. * @file Get initial data and define sankey view's series model
  49763. * @author Deqing Li(annong035@gmail.com)
  49764. */
  49765. var SankeySeries = SeriesModel.extend({
  49766. type: 'series.sankey',
  49767. layoutInfo: null,
  49768. /**
  49769. * Init a graph data structure from data in option series
  49770. *
  49771. * @param {Object} option the object used to config echarts view
  49772. * @return {module:echarts/data/List} storage initial data
  49773. */
  49774. getInitialData: function (option) {
  49775. var links = option.edges || option.links;
  49776. var nodes = option.data || option.nodes;
  49777. if (nodes && links) {
  49778. var graph = createGraphFromNodeEdge(nodes, links, this, true);
  49779. return graph.data;
  49780. }
  49781. },
  49782. setNodePosition: function (dataIndex, localPosition) {
  49783. var dataItem = this.option.data[dataIndex];
  49784. dataItem.localX = localPosition[0];
  49785. dataItem.localY = localPosition[1];
  49786. },
  49787. /**
  49788. * Return the graphic data structure
  49789. *
  49790. * @return {module:echarts/data/Graph} graphic data structure
  49791. */
  49792. getGraph: function () {
  49793. return this.getData().graph;
  49794. },
  49795. /**
  49796. * Get edge data of graphic data structure
  49797. *
  49798. * @return {module:echarts/data/List} data structure of list
  49799. */
  49800. getEdgeData: function () {
  49801. return this.getGraph().edgeData;
  49802. },
  49803. /**
  49804. * @override
  49805. */
  49806. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  49807. // dataType === 'node' or empty do not show tooltip by default
  49808. if (dataType === 'edge') {
  49809. var params = this.getDataParams(dataIndex, dataType);
  49810. var rawDataOpt = params.data;
  49811. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  49812. if (params.value) {
  49813. html += ' : ' + params.value;
  49814. }
  49815. return encodeHTML(html);
  49816. }
  49817. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  49818. },
  49819. defaultOption: {
  49820. zlevel: 0,
  49821. z: 2,
  49822. coordinateSystem: 'view',
  49823. layout: null,
  49824. // the position of the whole view
  49825. left: '5%',
  49826. top: '5%',
  49827. right: '20%',
  49828. bottom: '5%',
  49829. // the dx of the node
  49830. nodeWidth: 20,
  49831. // the vertical distance between two nodes
  49832. nodeGap: 8,
  49833. // control if the node can move or not
  49834. draggable: true,
  49835. // the number of iterations to change the position of the node
  49836. layoutIterations: 32,
  49837. label: {
  49838. show: true,
  49839. position: 'right',
  49840. color: '#000',
  49841. fontSize: 12
  49842. },
  49843. itemStyle: {
  49844. borderWidth: 1,
  49845. borderColor: '#333'
  49846. },
  49847. lineStyle: {
  49848. color: '#314656',
  49849. opacity: 0.2,
  49850. curveness: 0.5
  49851. },
  49852. emphasis: {
  49853. label: {
  49854. show: true
  49855. },
  49856. lineStyle: {
  49857. opacity: 0.6
  49858. }
  49859. },
  49860. animationEasing: 'linear',
  49861. animationDuration: 1000
  49862. }
  49863. });
  49864. /*
  49865. * Licensed to the Apache Software Foundation (ASF) under one
  49866. * or more contributor license agreements. See the NOTICE file
  49867. * distributed with this work for additional information
  49868. * regarding copyright ownership. The ASF licenses this file
  49869. * to you under the Apache License, Version 2.0 (the
  49870. * "License"); you may not use this file except in compliance
  49871. * with the License. You may obtain a copy of the License at
  49872. *
  49873. * http://www.apache.org/licenses/LICENSE-2.0
  49874. *
  49875. * Unless required by applicable law or agreed to in writing,
  49876. * software distributed under the License is distributed on an
  49877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49878. * KIND, either express or implied. See the License for the
  49879. * specific language governing permissions and limitations
  49880. * under the License.
  49881. */
  49882. /**
  49883. * @file The file used to draw sankey view
  49884. * @author Deqing Li(annong035@gmail.com)
  49885. */
  49886. var SankeyShape = extendShape({
  49887. shape: {
  49888. x1: 0, y1: 0,
  49889. x2: 0, y2: 0,
  49890. cpx1: 0, cpy1: 0,
  49891. cpx2: 0, cpy2: 0,
  49892. extent: 0
  49893. },
  49894. buildPath: function (ctx, shape) {
  49895. var halfExtent = shape.extent / 2;
  49896. ctx.moveTo(shape.x1, shape.y1 - halfExtent);
  49897. ctx.bezierCurveTo(
  49898. shape.cpx1, shape.cpy1 - halfExtent,
  49899. shape.cpx2, shape.cpy2 - halfExtent,
  49900. shape.x2, shape.y2 - halfExtent
  49901. );
  49902. ctx.lineTo(shape.x2, shape.y2 + halfExtent);
  49903. ctx.bezierCurveTo(
  49904. shape.cpx2, shape.cpy2 + halfExtent,
  49905. shape.cpx1, shape.cpy1 + halfExtent,
  49906. shape.x1, shape.y1 + halfExtent
  49907. );
  49908. ctx.closePath();
  49909. }
  49910. });
  49911. extendChartView({
  49912. type: 'sankey',
  49913. /**
  49914. * @private
  49915. * @type {module:echarts/chart/sankey/SankeySeries}
  49916. */
  49917. _model: null,
  49918. render: function (seriesModel, ecModel, api) {
  49919. var graph = seriesModel.getGraph();
  49920. var group = this.group;
  49921. var layoutInfo = seriesModel.layoutInfo;
  49922. // view width
  49923. var width = layoutInfo.width;
  49924. // view height
  49925. var height = layoutInfo.height;
  49926. var nodeData = seriesModel.getData();
  49927. var edgeData = seriesModel.getData('edge');
  49928. this._model = seriesModel;
  49929. group.removeAll();
  49930. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  49931. // generate a bezire Curve for each edge
  49932. graph.eachEdge(function (edge) {
  49933. var curve = new SankeyShape();
  49934. curve.dataIndex = edge.dataIndex;
  49935. curve.seriesIndex = seriesModel.seriesIndex;
  49936. curve.dataType = 'edge';
  49937. var lineStyleModel = edge.getModel('lineStyle');
  49938. var curvature = lineStyleModel.get('curveness');
  49939. var n1Layout = edge.node1.getLayout();
  49940. var node1Model =edge.node1.getModel();
  49941. var dragX1 = node1Model.get('localX');
  49942. var dragY1 = node1Model.get('localY');
  49943. var n2Layout = edge.node2.getLayout();
  49944. var node2Model = edge.node2.getModel();
  49945. var dragX2 = node2Model.get('localX');
  49946. var dragY2 = node2Model.get('localY');
  49947. var edgeLayout = edge.getLayout();
  49948. curve.shape.extent = Math.max(1, edgeLayout.dy);
  49949. var x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  49950. var y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy + edgeLayout.dy / 2;
  49951. var x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  49952. var y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty + edgeLayout.dy / 2;
  49953. var cpx1 = x1 * (1 - curvature) + x2 * curvature;
  49954. var cpy1 = y1;
  49955. var cpx2 = x1 * curvature + x2 * (1 - curvature);
  49956. var cpy2 = y2;
  49957. curve.setShape({
  49958. x1: x1,
  49959. y1: y1,
  49960. x2: x2,
  49961. y2: y2,
  49962. cpx1: cpx1,
  49963. cpy1: cpy1,
  49964. cpx2: cpx2,
  49965. cpy2: cpy2
  49966. });
  49967. curve.setStyle(lineStyleModel.getItemStyle());
  49968. // Special color, use source node color or target node color
  49969. switch (curve.style.fill) {
  49970. case 'source':
  49971. curve.style.fill = edge.node1.getVisual('color');
  49972. break;
  49973. case 'target':
  49974. curve.style.fill = edge.node2.getVisual('color');
  49975. break;
  49976. }
  49977. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  49978. group.add(curve);
  49979. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  49980. });
  49981. // generate a rect for each node
  49982. graph.eachNode(function (node) {
  49983. var layout = node.getLayout();
  49984. var itemModel = node.getModel();
  49985. var dragX = itemModel.get('localX');
  49986. var dragY = itemModel.get('localY');
  49987. var labelModel = itemModel.getModel('label');
  49988. var labelHoverModel = itemModel.getModel('emphasis.label');
  49989. var rect = new Rect({
  49990. shape: {
  49991. x: dragX != null ? dragX * width : layout.x,
  49992. y: dragY != null ? dragY * height : layout.y,
  49993. width: layout.dx,
  49994. height: layout.dy
  49995. },
  49996. style: itemModel.getModel('itemStyle').getItemStyle()
  49997. });
  49998. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  49999. setLabelStyle(
  50000. rect.style, hoverStyle, labelModel, labelHoverModel,
  50001. {
  50002. labelFetcher: seriesModel,
  50003. labelDataIndex: node.dataIndex,
  50004. defaultText: node.id,
  50005. isRectText: true
  50006. }
  50007. );
  50008. rect.setStyle('fill', node.getVisual('color'));
  50009. setHoverStyle(rect, hoverStyle);
  50010. group.add(rect);
  50011. nodeData.setItemGraphicEl(node.dataIndex, rect);
  50012. rect.dataType = 'node';
  50013. });
  50014. var draggable = seriesModel.get('draggable');
  50015. if (draggable) {
  50016. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  50017. el.drift = function (dx, dy) {
  50018. this.shape.x += dx;
  50019. this.shape.y += dy;
  50020. this.dirty();
  50021. api.dispatchAction({
  50022. type: 'dragNode',
  50023. seriesId: seriesModel.id,
  50024. dataIndex: nodeData.getRawIndex(dataIndex),
  50025. localX: this.shape.x / width,
  50026. localY: this.shape.y / height
  50027. });
  50028. };
  50029. el.draggable = true;
  50030. el.cursor = 'move';
  50031. });
  50032. }
  50033. if (!this._data && seriesModel.get('animation')) {
  50034. group.setClipPath(createGridClipShape$2(group.getBoundingRect(), seriesModel, function () {
  50035. group.removeClipPath();
  50036. }));
  50037. }
  50038. this._data = seriesModel.getData();
  50039. },
  50040. dispose: function () {}
  50041. });
  50042. // add animation to the view
  50043. function createGridClipShape$2(rect, seriesModel, cb) {
  50044. var rectEl = new Rect({
  50045. shape: {
  50046. x: rect.x - 10,
  50047. y: rect.y - 10,
  50048. width: 0,
  50049. height: rect.height + 20
  50050. }
  50051. });
  50052. initProps(rectEl, {
  50053. shape: {
  50054. width: rect.width + 20,
  50055. height: rect.height + 20
  50056. }
  50057. }, seriesModel, cb);
  50058. return rectEl;
  50059. }
  50060. /*
  50061. * Licensed to the Apache Software Foundation (ASF) under one
  50062. * or more contributor license agreements. See the NOTICE file
  50063. * distributed with this work for additional information
  50064. * regarding copyright ownership. The ASF licenses this file
  50065. * to you under the Apache License, Version 2.0 (the
  50066. * "License"); you may not use this file except in compliance
  50067. * with the License. You may obtain a copy of the License at
  50068. *
  50069. * http://www.apache.org/licenses/LICENSE-2.0
  50070. *
  50071. * Unless required by applicable law or agreed to in writing,
  50072. * software distributed under the License is distributed on an
  50073. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50074. * KIND, either express or implied. See the License for the
  50075. * specific language governing permissions and limitations
  50076. * under the License.
  50077. */
  50078. registerAction({
  50079. type: 'dragNode',
  50080. event: 'dragNode',
  50081. // here can only use 'update' now, other value is not support in echarts.
  50082. update: 'update'
  50083. }, function (payload, ecModel) {
  50084. ecModel.eachComponent({mainType: 'series', subType: 'sankey', query: payload}, function (seriesModel) {
  50085. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  50086. });
  50087. });
  50088. /*
  50089. * Licensed to the Apache Software Foundation (ASF) under one
  50090. * or more contributor license agreements. See the NOTICE file
  50091. * distributed with this work for additional information
  50092. * regarding copyright ownership. The ASF licenses this file
  50093. * to you under the Apache License, Version 2.0 (the
  50094. * "License"); you may not use this file except in compliance
  50095. * with the License. You may obtain a copy of the License at
  50096. *
  50097. * http://www.apache.org/licenses/LICENSE-2.0
  50098. *
  50099. * Unless required by applicable law or agreed to in writing,
  50100. * software distributed under the License is distributed on an
  50101. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50102. * KIND, either express or implied. See the License for the
  50103. * specific language governing permissions and limitations
  50104. * under the License.
  50105. */
  50106. /*
  50107. * The implementation references to d3.js. The use of the source
  50108. * code of this file is also subject to the terms and consitions
  50109. * of its license (BSD-3Clause, see <echarts/src/licenses/LICENSE-d3>).
  50110. */
  50111. /**
  50112. * nest helper used to group by the array.
  50113. * can specified the keys and sort the keys.
  50114. */
  50115. function nest() {
  50116. var keysFunction = [];
  50117. var sortKeysFunction = [];
  50118. /**
  50119. * map an Array into the mapObject.
  50120. * @param {Array} array
  50121. * @param {number} depth
  50122. */
  50123. function map$$1(array, depth) {
  50124. if (depth >= keysFunction.length) {
  50125. return array;
  50126. }
  50127. var i = -1;
  50128. var n = array.length;
  50129. var keyFunction = keysFunction[depth++];
  50130. var mapObject = {};
  50131. var valuesByKey = {};
  50132. while (++i < n) {
  50133. var keyValue = keyFunction(array[i]);
  50134. var values = valuesByKey[keyValue];
  50135. if (values) {
  50136. values.push(array[i]);
  50137. }
  50138. else {
  50139. valuesByKey[keyValue] = [array[i]];
  50140. }
  50141. }
  50142. each$1(valuesByKey, function (value, key) {
  50143. mapObject[key] = map$$1(value, depth);
  50144. });
  50145. return mapObject;
  50146. }
  50147. /**
  50148. * transform the Map Object to multidimensional Array
  50149. * @param {Object} map
  50150. * @param {number} depth
  50151. */
  50152. function entriesMap(mapObject, depth) {
  50153. if (depth >= keysFunction.length) {
  50154. return mapObject;
  50155. }
  50156. var array = [];
  50157. var sortKeyFunction = sortKeysFunction[depth++];
  50158. each$1(mapObject, function (value, key) {
  50159. array.push({
  50160. key: key, values: entriesMap(value, depth)
  50161. });
  50162. });
  50163. if (sortKeyFunction) {
  50164. return array.sort(function (a, b) {
  50165. return sortKeyFunction(a.key, b.key);
  50166. });
  50167. }
  50168. else {
  50169. return array;
  50170. }
  50171. }
  50172. return {
  50173. /**
  50174. * specified the key to groupby the arrays.
  50175. * users can specified one more keys.
  50176. * @param {Function} d
  50177. */
  50178. key: function (d) {
  50179. keysFunction.push(d);
  50180. return this;
  50181. },
  50182. /**
  50183. * specified the comparator to sort the keys
  50184. * @param {Function} order
  50185. */
  50186. sortKeys: function (order) {
  50187. sortKeysFunction[keysFunction.length - 1] = order;
  50188. return this;
  50189. },
  50190. /**
  50191. * the array to be grouped by.
  50192. * @param {Array} array
  50193. */
  50194. entries: function (array) {
  50195. return entriesMap(map$$1(array, 0), 0);
  50196. }
  50197. };
  50198. }
  50199. /*
  50200. * Licensed to the Apache Software Foundation (ASF) under one
  50201. * or more contributor license agreements. See the NOTICE file
  50202. * distributed with this work for additional information
  50203. * regarding copyright ownership. The ASF licenses this file
  50204. * to you under the Apache License, Version 2.0 (the
  50205. * "License"); you may not use this file except in compliance
  50206. * with the License. You may obtain a copy of the License at
  50207. *
  50208. * http://www.apache.org/licenses/LICENSE-2.0
  50209. *
  50210. * Unless required by applicable law or agreed to in writing,
  50211. * software distributed under the License is distributed on an
  50212. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50213. * KIND, either express or implied. See the License for the
  50214. * specific language governing permissions and limitations
  50215. * under the License.
  50216. */
  50217. /**
  50218. * @file The layout algorithm of sankey view
  50219. * @author Deqing Li(annong035@gmail.com)
  50220. */
  50221. var sankeyLayout = function (ecModel, api, payload) {
  50222. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  50223. var nodeWidth = seriesModel.get('nodeWidth');
  50224. var nodeGap = seriesModel.get('nodeGap');
  50225. var layoutInfo = getViewRect$3(seriesModel, api);
  50226. seriesModel.layoutInfo = layoutInfo;
  50227. var width = layoutInfo.width;
  50228. var height = layoutInfo.height;
  50229. var graph = seriesModel.getGraph();
  50230. var nodes = graph.nodes;
  50231. var edges = graph.edges;
  50232. computeNodeValues(nodes);
  50233. var filteredNodes = filter(nodes, function (node) {
  50234. return node.getLayout().value === 0;
  50235. });
  50236. var iterations = filteredNodes.length !== 0
  50237. ? 0 : seriesModel.get('layoutIterations');
  50238. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations);
  50239. });
  50240. };
  50241. /**
  50242. * Get the layout position of the whole view
  50243. *
  50244. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  50245. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  50246. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  50247. */
  50248. function getViewRect$3(seriesModel, api) {
  50249. return getLayoutRect(
  50250. seriesModel.getBoxLayoutParams(), {
  50251. width: api.getWidth(),
  50252. height: api.getHeight()
  50253. }
  50254. );
  50255. }
  50256. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations) {
  50257. computeNodeBreadths(nodes, edges, nodeWidth, width);
  50258. computeNodeDepths(nodes, edges, height, nodeGap, iterations);
  50259. computeEdgeDepths(nodes);
  50260. }
  50261. /**
  50262. * Compute the value of each node by summing the associated edge's value
  50263. *
  50264. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50265. */
  50266. function computeNodeValues(nodes) {
  50267. each$1(nodes, function (node) {
  50268. var value1 = sum(node.outEdges, getEdgeValue);
  50269. var value2 = sum(node.inEdges, getEdgeValue);
  50270. var value = Math.max(value1, value2);
  50271. node.setLayout({value: value}, true);
  50272. });
  50273. }
  50274. /**
  50275. * Compute the x-position for each node.
  50276. *
  50277. * Here we use Kahn algorithm to detect cycle when we traverse
  50278. * the node to computer the initial x position.
  50279. *
  50280. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50281. * @param {number} nodeWidth the dx of the node
  50282. * @param {number} width the whole width of the area to draw the view
  50283. */
  50284. function computeNodeBreadths(nodes, edges, nodeWidth, width) {
  50285. // Used to mark whether the edge is deleted. if it is deleted,
  50286. // the value is 0, otherwise it is 1.
  50287. var remainEdges = [];
  50288. // Storage each node's indegree.
  50289. var indegreeArr = [];
  50290. //Used to storage the node with indegree is equal to 0.
  50291. var zeroIndegrees = [];
  50292. var nextNode = [];
  50293. var x = 0;
  50294. var kx = 0;
  50295. for (var i = 0; i < edges.length; i++) {
  50296. remainEdges[i] = 1;
  50297. }
  50298. for (var i = 0; i < nodes.length; i++) {
  50299. indegreeArr[i] = nodes[i].inEdges.length;
  50300. if (indegreeArr[i] === 0) {
  50301. zeroIndegrees.push(nodes[i]);
  50302. }
  50303. }
  50304. while (zeroIndegrees.length) {
  50305. each$1(zeroIndegrees, function (node) {
  50306. node.setLayout({x: x}, true);
  50307. node.setLayout({dx: nodeWidth}, true);
  50308. each$1(node.outEdges, function (edge) {
  50309. var indexEdge = edges.indexOf(edge);
  50310. remainEdges[indexEdge] = 0;
  50311. var targetNode = edge.node2;
  50312. var nodeIndex = nodes.indexOf(targetNode);
  50313. if (--indegreeArr[nodeIndex] === 0) {
  50314. nextNode.push(targetNode);
  50315. }
  50316. });
  50317. });
  50318. ++x;
  50319. zeroIndegrees = nextNode;
  50320. nextNode = [];
  50321. }
  50322. for (var i = 0; i < remainEdges.length; i++) {
  50323. if (__DEV__) {
  50324. if (remainEdges[i] === 1) {
  50325. throw new Error('Sankey is a DAG, the original data has cycle!');
  50326. }
  50327. }
  50328. }
  50329. moveSinksRight(nodes, x);
  50330. kx = (width - nodeWidth) / (x - 1);
  50331. scaleNodeBreadths(nodes, kx);
  50332. }
  50333. /**
  50334. * All the node without outEgdes are assigned maximum x-position and
  50335. * be aligned in the last column.
  50336. *
  50337. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50338. * @param {number} x value (x-1) use to assign to node without outEdges
  50339. * as x-position
  50340. */
  50341. function moveSinksRight(nodes, x) {
  50342. each$1(nodes, function (node) {
  50343. if (!node.outEdges.length) {
  50344. node.setLayout({x: x - 1}, true);
  50345. }
  50346. });
  50347. }
  50348. /**
  50349. * Scale node x-position to the width
  50350. *
  50351. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50352. * @param {number} kx multiple used to scale nodes
  50353. */
  50354. function scaleNodeBreadths(nodes, kx) {
  50355. each$1(nodes, function (node) {
  50356. var nodeX = node.getLayout().x * kx;
  50357. node.setLayout({x: nodeX}, true);
  50358. });
  50359. }
  50360. /**
  50361. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  50362. *
  50363. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50364. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  50365. * @param {number} height the whole height of the area to draw the view
  50366. * @param {number} nodeGap the vertical distance between two nodes
  50367. * in the same column.
  50368. * @param {number} iterations the number of iterations for the algorithm
  50369. */
  50370. function computeNodeDepths(nodes, edges, height, nodeGap, iterations) {
  50371. var nodesByBreadth = nest()
  50372. .key(function (d) {
  50373. return d.getLayout().x;
  50374. })
  50375. .sortKeys(ascending)
  50376. .entries(nodes)
  50377. .map(function (d) {
  50378. return d.values;
  50379. });
  50380. initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap);
  50381. resolveCollisions(nodesByBreadth, nodeGap, height);
  50382. for (var alpha = 1; iterations > 0; iterations--) {
  50383. // 0.99 is a experience parameter, ensure that each iterations of
  50384. // changes as small as possible.
  50385. alpha *= 0.99;
  50386. relaxRightToLeft(nodesByBreadth, alpha);
  50387. resolveCollisions(nodesByBreadth, nodeGap, height);
  50388. relaxLeftToRight(nodesByBreadth, alpha);
  50389. resolveCollisions(nodesByBreadth, nodeGap, height);
  50390. }
  50391. }
  50392. /**
  50393. * Compute the original y-position for each node
  50394. *
  50395. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50396. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50397. * group by the array of all sankey nodes based on the nodes x-position.
  50398. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  50399. * @param {number} height the whole height of the area to draw the view
  50400. * @param {number} nodeGap the vertical distance between two nodes
  50401. */
  50402. function initializeNodeDepth(nodes, nodesByBreadth, edges, height, nodeGap) {
  50403. var kyArray = [];
  50404. each$1(nodesByBreadth, function (nodes) {
  50405. var n = nodes.length;
  50406. var sum = 0;
  50407. each$1(nodes, function (node) {
  50408. sum += node.getLayout().value;
  50409. });
  50410. var ky = (height - (n - 1) * nodeGap) / sum;
  50411. kyArray.push(ky);
  50412. });
  50413. kyArray.sort(function (a, b) {
  50414. return a - b;
  50415. });
  50416. var ky0 = kyArray[0];
  50417. each$1(nodesByBreadth, function (nodes) {
  50418. each$1(nodes, function (node, i) {
  50419. node.setLayout({y: i}, true);
  50420. var nodeDy = node.getLayout().value * ky0;
  50421. node.setLayout({dy: nodeDy}, true);
  50422. });
  50423. });
  50424. each$1(edges, function (edge) {
  50425. var edgeDy = +edge.getValue() * ky0;
  50426. edge.setLayout({dy: edgeDy}, true);
  50427. });
  50428. }
  50429. /**
  50430. * Resolve the collision of initialized depth (y-position)
  50431. *
  50432. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50433. * group by the array of all sankey nodes based on the nodes x-position.
  50434. * @param {number} nodeGap the vertical distance between two nodes
  50435. * @param {number} height the whole height of the area to draw the view
  50436. */
  50437. function resolveCollisions(nodesByBreadth, nodeGap, height) {
  50438. each$1(nodesByBreadth, function (nodes) {
  50439. var node;
  50440. var dy;
  50441. var y0 = 0;
  50442. var n = nodes.length;
  50443. var i;
  50444. nodes.sort(ascendingDepth);
  50445. for (i = 0; i < n; i++) {
  50446. node = nodes[i];
  50447. dy = y0 - node.getLayout().y;
  50448. if (dy > 0) {
  50449. var nodeY = node.getLayout().y + dy;
  50450. node.setLayout({y: nodeY}, true);
  50451. }
  50452. y0 = node.getLayout().y + node.getLayout().dy + nodeGap;
  50453. }
  50454. // If the bottommost node goes outside the bounds, push it back up
  50455. dy = y0 - nodeGap - height;
  50456. if (dy > 0) {
  50457. var nodeY = node.getLayout().y - dy;
  50458. node.setLayout({y: nodeY}, true);
  50459. y0 = node.getLayout().y;
  50460. for (i = n - 2; i >= 0; --i) {
  50461. node = nodes[i];
  50462. dy = node.getLayout().y + node.getLayout().dy + nodeGap - y0;
  50463. if (dy > 0) {
  50464. nodeY = node.getLayout().y - dy;
  50465. node.setLayout({y: nodeY}, true);
  50466. }
  50467. y0 = node.getLayout().y;
  50468. }
  50469. }
  50470. });
  50471. }
  50472. /**
  50473. * Change the y-position of the nodes, except most the right side nodes
  50474. *
  50475. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50476. * group by the array of all sankey nodes based on the node x-position.
  50477. * @param {number} alpha parameter used to adjust the nodes y-position
  50478. */
  50479. function relaxRightToLeft(nodesByBreadth, alpha) {
  50480. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  50481. each$1(nodes, function (node) {
  50482. if (node.outEdges.length) {
  50483. var y = sum(node.outEdges, weightedTarget) / sum(node.outEdges, getEdgeValue);
  50484. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  50485. node.setLayout({y: nodeY}, true);
  50486. }
  50487. });
  50488. });
  50489. }
  50490. function weightedTarget(edge) {
  50491. return center$1(edge.node2) * edge.getValue();
  50492. }
  50493. /**
  50494. * Change the y-position of the nodes, except most the left side nodes
  50495. *
  50496. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  50497. * group by the array of all sankey nodes based on the node x-position.
  50498. * @param {number} alpha parameter used to adjust the nodes y-position
  50499. */
  50500. function relaxLeftToRight(nodesByBreadth, alpha) {
  50501. each$1(nodesByBreadth, function (nodes) {
  50502. each$1(nodes, function (node) {
  50503. if (node.inEdges.length) {
  50504. var y = sum(node.inEdges, weightedSource) / sum(node.inEdges, getEdgeValue);
  50505. var nodeY = node.getLayout().y + (y - center$1(node)) * alpha;
  50506. node.setLayout({y: nodeY}, true);
  50507. }
  50508. });
  50509. });
  50510. }
  50511. function weightedSource(edge) {
  50512. return center$1(edge.node1) * edge.getValue();
  50513. }
  50514. /**
  50515. * Compute the depth(y-position) of each edge
  50516. *
  50517. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  50518. */
  50519. function computeEdgeDepths(nodes) {
  50520. each$1(nodes, function (node) {
  50521. node.outEdges.sort(ascendingTargetDepth);
  50522. node.inEdges.sort(ascendingSourceDepth);
  50523. });
  50524. each$1(nodes, function (node) {
  50525. var sy = 0;
  50526. var ty = 0;
  50527. each$1(node.outEdges, function (edge) {
  50528. edge.setLayout({sy: sy}, true);
  50529. sy += edge.getLayout().dy;
  50530. });
  50531. each$1(node.inEdges, function (edge) {
  50532. edge.setLayout({ty: ty}, true);
  50533. ty += edge.getLayout().dy;
  50534. });
  50535. });
  50536. }
  50537. function ascendingTargetDepth(a, b) {
  50538. return a.node2.getLayout().y - b.node2.getLayout().y;
  50539. }
  50540. function ascendingSourceDepth(a, b) {
  50541. return a.node1.getLayout().y - b.node1.getLayout().y;
  50542. }
  50543. function sum(array, f) {
  50544. var sum = 0;
  50545. var len = array.length;
  50546. var i = -1;
  50547. while (++i < len) {
  50548. var value = +f.call(array, array[i], i);
  50549. if (!isNaN(value)) {
  50550. sum += value;
  50551. }
  50552. }
  50553. return sum;
  50554. }
  50555. function center$1(node) {
  50556. return node.getLayout().y + node.getLayout().dy / 2;
  50557. }
  50558. function ascendingDepth(a, b) {
  50559. return a.getLayout().y - b.getLayout().y;
  50560. }
  50561. function ascending(a, b) {
  50562. return a - b;
  50563. }
  50564. function getEdgeValue(edge) {
  50565. return edge.getValue();
  50566. }
  50567. /*
  50568. * Licensed to the Apache Software Foundation (ASF) under one
  50569. * or more contributor license agreements. See the NOTICE file
  50570. * distributed with this work for additional information
  50571. * regarding copyright ownership. The ASF licenses this file
  50572. * to you under the Apache License, Version 2.0 (the
  50573. * "License"); you may not use this file except in compliance
  50574. * with the License. You may obtain a copy of the License at
  50575. *
  50576. * http://www.apache.org/licenses/LICENSE-2.0
  50577. *
  50578. * Unless required by applicable law or agreed to in writing,
  50579. * software distributed under the License is distributed on an
  50580. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50581. * KIND, either express or implied. See the License for the
  50582. * specific language governing permissions and limitations
  50583. * under the License.
  50584. */
  50585. /**
  50586. * @file Visual encoding for sankey view
  50587. * @author Deqing Li(annong035@gmail.com)
  50588. */
  50589. var sankeyVisual = function (ecModel, payload) {
  50590. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  50591. var graph = seriesModel.getGraph();
  50592. var nodes = graph.nodes;
  50593. if (nodes.length) {
  50594. var minValue = Infinity;
  50595. var maxValue = -Infinity;
  50596. each$1(nodes, function (node) {
  50597. var nodeValue = node.getLayout().value;
  50598. if (nodeValue < minValue) {
  50599. minValue = nodeValue;
  50600. }
  50601. if (nodeValue > maxValue) {
  50602. maxValue = nodeValue;
  50603. }
  50604. });
  50605. each$1(nodes, function (node) {
  50606. var mapping = new VisualMapping({
  50607. type: 'color',
  50608. mappingMethod: 'linear',
  50609. dataExtent: [minValue, maxValue],
  50610. visual: seriesModel.get('color')
  50611. });
  50612. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  50613. node.setVisual('color', mapValueToColor);
  50614. // If set itemStyle.normal.color
  50615. var itemModel = node.getModel();
  50616. var customColor = itemModel.get('itemStyle.color');
  50617. if (customColor != null) {
  50618. node.setVisual('color', customColor);
  50619. }
  50620. });
  50621. }
  50622. });
  50623. };
  50624. /*
  50625. * Licensed to the Apache Software Foundation (ASF) under one
  50626. * or more contributor license agreements. See the NOTICE file
  50627. * distributed with this work for additional information
  50628. * regarding copyright ownership. The ASF licenses this file
  50629. * to you under the Apache License, Version 2.0 (the
  50630. * "License"); you may not use this file except in compliance
  50631. * with the License. You may obtain a copy of the License at
  50632. *
  50633. * http://www.apache.org/licenses/LICENSE-2.0
  50634. *
  50635. * Unless required by applicable law or agreed to in writing,
  50636. * software distributed under the License is distributed on an
  50637. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50638. * KIND, either express or implied. See the License for the
  50639. * specific language governing permissions and limitations
  50640. * under the License.
  50641. */
  50642. registerLayout(sankeyLayout);
  50643. registerVisual(sankeyVisual);
  50644. /*
  50645. * Licensed to the Apache Software Foundation (ASF) under one
  50646. * or more contributor license agreements. See the NOTICE file
  50647. * distributed with this work for additional information
  50648. * regarding copyright ownership. The ASF licenses this file
  50649. * to you under the Apache License, Version 2.0 (the
  50650. * "License"); you may not use this file except in compliance
  50651. * with the License. You may obtain a copy of the License at
  50652. *
  50653. * http://www.apache.org/licenses/LICENSE-2.0
  50654. *
  50655. * Unless required by applicable law or agreed to in writing,
  50656. * software distributed under the License is distributed on an
  50657. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50658. * KIND, either express or implied. See the License for the
  50659. * specific language governing permissions and limitations
  50660. * under the License.
  50661. */
  50662. var seriesModelMixin = {
  50663. /**
  50664. * @private
  50665. * @type {string}
  50666. */
  50667. _baseAxisDim: null,
  50668. /**
  50669. * @override
  50670. */
  50671. getInitialData: function (option, ecModel) {
  50672. // When both types of xAxis and yAxis are 'value', layout is
  50673. // needed to be specified by user. Otherwise, layout can be
  50674. // judged by which axis is category.
  50675. var ordinalMeta;
  50676. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  50677. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  50678. var xAxisType = xAxisModel.get('type');
  50679. var yAxisType = yAxisModel.get('type');
  50680. var addOrdinal;
  50681. // FIXME
  50682. // 考虑时间轴
  50683. if (xAxisType === 'category') {
  50684. option.layout = 'horizontal';
  50685. ordinalMeta = xAxisModel.getOrdinalMeta();
  50686. addOrdinal = true;
  50687. }
  50688. else if (yAxisType === 'category') {
  50689. option.layout = 'vertical';
  50690. ordinalMeta = yAxisModel.getOrdinalMeta();
  50691. addOrdinal = true;
  50692. }
  50693. else {
  50694. option.layout = option.layout || 'horizontal';
  50695. }
  50696. var coordDims = ['x', 'y'];
  50697. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  50698. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  50699. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  50700. var axisModels = [xAxisModel, yAxisModel];
  50701. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  50702. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  50703. var data = option.data;
  50704. // ??? FIXME make a stage to perform data transfrom.
  50705. // MUST create a new data, consider setOption({}) again.
  50706. if (data && addOrdinal) {
  50707. var newOptionData = [];
  50708. each$1(data, function (item, index) {
  50709. var newItem;
  50710. if (item.value && isArray(item.value)) {
  50711. newItem = item.value.slice();
  50712. item.value.unshift(index);
  50713. }
  50714. else if (isArray(item)) {
  50715. newItem = item.slice();
  50716. item.unshift(index);
  50717. }
  50718. else {
  50719. newItem = item;
  50720. }
  50721. newOptionData.push(newItem);
  50722. });
  50723. option.data = newOptionData;
  50724. }
  50725. var defaultValueDimensions = this.defaultValueDimensions;
  50726. return createListSimply(
  50727. this,
  50728. {
  50729. coordDimensions: [{
  50730. name: baseAxisDim,
  50731. type: getDimensionTypeByAxis(baseAxisType),
  50732. ordinalMeta: ordinalMeta,
  50733. otherDims: {
  50734. tooltip: false,
  50735. itemName: 0
  50736. },
  50737. dimsDef: ['base']
  50738. }, {
  50739. name: otherAxisDim,
  50740. type: getDimensionTypeByAxis(otherAxisType),
  50741. dimsDef: defaultValueDimensions.slice()
  50742. }],
  50743. dimensionsCount: defaultValueDimensions.length + 1
  50744. }
  50745. );
  50746. },
  50747. /**
  50748. * If horizontal, base axis is x, otherwise y.
  50749. * @override
  50750. */
  50751. getBaseAxis: function () {
  50752. var dim = this._baseAxisDim;
  50753. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  50754. }
  50755. };
  50756. /*
  50757. * Licensed to the Apache Software Foundation (ASF) under one
  50758. * or more contributor license agreements. See the NOTICE file
  50759. * distributed with this work for additional information
  50760. * regarding copyright ownership. The ASF licenses this file
  50761. * to you under the Apache License, Version 2.0 (the
  50762. * "License"); you may not use this file except in compliance
  50763. * with the License. You may obtain a copy of the License at
  50764. *
  50765. * http://www.apache.org/licenses/LICENSE-2.0
  50766. *
  50767. * Unless required by applicable law or agreed to in writing,
  50768. * software distributed under the License is distributed on an
  50769. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50770. * KIND, either express or implied. See the License for the
  50771. * specific language governing permissions and limitations
  50772. * under the License.
  50773. */
  50774. var BoxplotSeries = SeriesModel.extend({
  50775. type: 'series.boxplot',
  50776. dependencies: ['xAxis', 'yAxis', 'grid'],
  50777. // TODO
  50778. // box width represents group size, so dimension should have 'size'.
  50779. /**
  50780. * @see <https://en.wikipedia.org/wiki/Box_plot>
  50781. * The meanings of 'min' and 'max' depend on user,
  50782. * and echarts do not need to know it.
  50783. * @readOnly
  50784. */
  50785. defaultValueDimensions: [
  50786. {name: 'min', defaultTooltip: true},
  50787. {name: 'Q1', defaultTooltip: true},
  50788. {name: 'median', defaultTooltip: true},
  50789. {name: 'Q3', defaultTooltip: true},
  50790. {name: 'max', defaultTooltip: true}
  50791. ],
  50792. /**
  50793. * @type {Array.<string>}
  50794. * @readOnly
  50795. */
  50796. dimensions: null,
  50797. /**
  50798. * @override
  50799. */
  50800. defaultOption: {
  50801. zlevel: 0, // 一级层叠
  50802. z: 2, // 二级层叠
  50803. coordinateSystem: 'cartesian2d',
  50804. legendHoverLink: true,
  50805. hoverAnimation: true,
  50806. // xAxisIndex: 0,
  50807. // yAxisIndex: 0,
  50808. layout: null, // 'horizontal' or 'vertical'
  50809. boxWidth: [7, 50], // [min, max] can be percent of band width.
  50810. itemStyle: {
  50811. color: '#fff',
  50812. borderWidth: 1
  50813. },
  50814. emphasis: {
  50815. itemStyle: {
  50816. borderWidth: 2,
  50817. shadowBlur: 5,
  50818. shadowOffsetX: 2,
  50819. shadowOffsetY: 2,
  50820. shadowColor: 'rgba(0,0,0,0.4)'
  50821. }
  50822. },
  50823. animationEasing: 'elasticOut',
  50824. animationDuration: 800
  50825. }
  50826. });
  50827. mixin(BoxplotSeries, seriesModelMixin, true);
  50828. /*
  50829. * Licensed to the Apache Software Foundation (ASF) under one
  50830. * or more contributor license agreements. See the NOTICE file
  50831. * distributed with this work for additional information
  50832. * regarding copyright ownership. The ASF licenses this file
  50833. * to you under the Apache License, Version 2.0 (the
  50834. * "License"); you may not use this file except in compliance
  50835. * with the License. You may obtain a copy of the License at
  50836. *
  50837. * http://www.apache.org/licenses/LICENSE-2.0
  50838. *
  50839. * Unless required by applicable law or agreed to in writing,
  50840. * software distributed under the License is distributed on an
  50841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50842. * KIND, either express or implied. See the License for the
  50843. * specific language governing permissions and limitations
  50844. * under the License.
  50845. */
  50846. // Update common properties
  50847. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  50848. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  50849. var BoxplotView = Chart.extend({
  50850. type: 'boxplot',
  50851. render: function (seriesModel, ecModel, api) {
  50852. var data = seriesModel.getData();
  50853. var group = this.group;
  50854. var oldData = this._data;
  50855. // There is no old data only when first rendering or switching from
  50856. // stream mode to normal mode, where previous elements should be removed.
  50857. if (!this._data) {
  50858. group.removeAll();
  50859. }
  50860. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  50861. data.diff(oldData)
  50862. .add(function (newIdx) {
  50863. if (data.hasValue(newIdx)) {
  50864. var itemLayout = data.getItemLayout(newIdx);
  50865. var symbolEl = createNormalBox(itemLayout, data, newIdx, constDim, true);
  50866. data.setItemGraphicEl(newIdx, symbolEl);
  50867. group.add(symbolEl);
  50868. }
  50869. })
  50870. .update(function (newIdx, oldIdx) {
  50871. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  50872. // Empty data
  50873. if (!data.hasValue(newIdx)) {
  50874. group.remove(symbolEl);
  50875. return;
  50876. }
  50877. var itemLayout = data.getItemLayout(newIdx);
  50878. if (!symbolEl) {
  50879. symbolEl = createNormalBox(itemLayout, data, newIdx, constDim);
  50880. }
  50881. else {
  50882. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  50883. }
  50884. group.add(symbolEl);
  50885. data.setItemGraphicEl(newIdx, symbolEl);
  50886. })
  50887. .remove(function (oldIdx) {
  50888. var el = oldData.getItemGraphicEl(oldIdx);
  50889. el && group.remove(el);
  50890. })
  50891. .execute();
  50892. this._data = data;
  50893. },
  50894. remove: function (ecModel) {
  50895. var group = this.group;
  50896. var data = this._data;
  50897. this._data = null;
  50898. data && data.eachItemGraphicEl(function (el) {
  50899. el && group.remove(el);
  50900. });
  50901. },
  50902. dispose: noop
  50903. });
  50904. var BoxPath = Path.extend({
  50905. type: 'boxplotBoxPath',
  50906. shape: {},
  50907. buildPath: function (ctx, shape) {
  50908. var ends = shape.points;
  50909. var i = 0;
  50910. ctx.moveTo(ends[i][0], ends[i][1]);
  50911. i++;
  50912. for (; i < 4; i++) {
  50913. ctx.lineTo(ends[i][0], ends[i][1]);
  50914. }
  50915. ctx.closePath();
  50916. for (; i < ends.length; i++) {
  50917. ctx.moveTo(ends[i][0], ends[i][1]);
  50918. i++;
  50919. ctx.lineTo(ends[i][0], ends[i][1]);
  50920. }
  50921. }
  50922. });
  50923. function createNormalBox(itemLayout, data, dataIndex, constDim, isInit) {
  50924. var ends = itemLayout.ends;
  50925. var el = new BoxPath({
  50926. shape: {
  50927. points: isInit
  50928. ? transInit(ends, constDim, itemLayout)
  50929. : ends
  50930. }
  50931. });
  50932. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  50933. return el;
  50934. }
  50935. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  50936. var seriesModel = data.hostModel;
  50937. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  50938. updateMethod(
  50939. el,
  50940. {shape: {points: itemLayout.ends}},
  50941. seriesModel,
  50942. dataIndex
  50943. );
  50944. var itemModel = data.getItemModel(dataIndex);
  50945. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  50946. var borderColor = data.getItemVisual(dataIndex, 'color');
  50947. // Exclude borderColor.
  50948. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  50949. itemStyle.stroke = borderColor;
  50950. itemStyle.strokeNoScale = true;
  50951. el.useStyle(itemStyle);
  50952. el.z2 = 100;
  50953. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  50954. setHoverStyle(el, hoverStyle);
  50955. }
  50956. function transInit(points, dim, itemLayout) {
  50957. return map(points, function (point) {
  50958. point = point.slice();
  50959. point[dim] = itemLayout.initBaseline;
  50960. return point;
  50961. });
  50962. }
  50963. /*
  50964. * Licensed to the Apache Software Foundation (ASF) under one
  50965. * or more contributor license agreements. See the NOTICE file
  50966. * distributed with this work for additional information
  50967. * regarding copyright ownership. The ASF licenses this file
  50968. * to you under the Apache License, Version 2.0 (the
  50969. * "License"); you may not use this file except in compliance
  50970. * with the License. You may obtain a copy of the License at
  50971. *
  50972. * http://www.apache.org/licenses/LICENSE-2.0
  50973. *
  50974. * Unless required by applicable law or agreed to in writing,
  50975. * software distributed under the License is distributed on an
  50976. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50977. * KIND, either express or implied. See the License for the
  50978. * specific language governing permissions and limitations
  50979. * under the License.
  50980. */
  50981. var borderColorQuery = ['itemStyle', 'borderColor'];
  50982. var boxplotVisual = function (ecModel, api) {
  50983. var globalColors = ecModel.get('color');
  50984. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  50985. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  50986. var data = seriesModel.getData();
  50987. data.setVisual({
  50988. legendSymbol: 'roundRect',
  50989. // Use name 'color' but not 'borderColor' for legend usage and
  50990. // visual coding from other component like dataRange.
  50991. color: seriesModel.get(borderColorQuery) || defaulColor
  50992. });
  50993. // Only visible series has each data be visual encoded
  50994. if (!ecModel.isSeriesFiltered(seriesModel)) {
  50995. data.each(function (idx) {
  50996. var itemModel = data.getItemModel(idx);
  50997. data.setItemVisual(
  50998. idx,
  50999. {color: itemModel.get(borderColorQuery, true)}
  51000. );
  51001. });
  51002. }
  51003. });
  51004. };
  51005. /*
  51006. * Licensed to the Apache Software Foundation (ASF) under one
  51007. * or more contributor license agreements. See the NOTICE file
  51008. * distributed with this work for additional information
  51009. * regarding copyright ownership. The ASF licenses this file
  51010. * to you under the Apache License, Version 2.0 (the
  51011. * "License"); you may not use this file except in compliance
  51012. * with the License. You may obtain a copy of the License at
  51013. *
  51014. * http://www.apache.org/licenses/LICENSE-2.0
  51015. *
  51016. * Unless required by applicable law or agreed to in writing,
  51017. * software distributed under the License is distributed on an
  51018. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51019. * KIND, either express or implied. See the License for the
  51020. * specific language governing permissions and limitations
  51021. * under the License.
  51022. */
  51023. var each$13 = each$1;
  51024. var boxplotLayout = function (ecModel) {
  51025. var groupResult = groupSeriesByAxis(ecModel);
  51026. each$13(groupResult, function (groupItem) {
  51027. var seriesModels = groupItem.seriesModels;
  51028. if (!seriesModels.length) {
  51029. return;
  51030. }
  51031. calculateBase(groupItem);
  51032. each$13(seriesModels, function (seriesModel, idx) {
  51033. layoutSingleSeries(
  51034. seriesModel,
  51035. groupItem.boxOffsetList[idx],
  51036. groupItem.boxWidthList[idx]
  51037. );
  51038. });
  51039. });
  51040. };
  51041. /**
  51042. * Group series by axis.
  51043. */
  51044. function groupSeriesByAxis(ecModel) {
  51045. var result = [];
  51046. var axisList = [];
  51047. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  51048. var baseAxis = seriesModel.getBaseAxis();
  51049. var idx = indexOf(axisList, baseAxis);
  51050. if (idx < 0) {
  51051. idx = axisList.length;
  51052. axisList[idx] = baseAxis;
  51053. result[idx] = {axis: baseAxis, seriesModels: []};
  51054. }
  51055. result[idx].seriesModels.push(seriesModel);
  51056. });
  51057. return result;
  51058. }
  51059. /**
  51060. * Calculate offset and box width for each series.
  51061. */
  51062. function calculateBase(groupItem) {
  51063. var extent;
  51064. var baseAxis = groupItem.axis;
  51065. var seriesModels = groupItem.seriesModels;
  51066. var seriesCount = seriesModels.length;
  51067. var boxWidthList = groupItem.boxWidthList = [];
  51068. var boxOffsetList = groupItem.boxOffsetList = [];
  51069. var boundList = [];
  51070. var bandWidth;
  51071. if (baseAxis.type === 'category') {
  51072. bandWidth = baseAxis.getBandWidth();
  51073. }
  51074. else {
  51075. var maxDataCount = 0;
  51076. each$13(seriesModels, function (seriesModel) {
  51077. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  51078. });
  51079. extent = baseAxis.getExtent(),
  51080. Math.abs(extent[1] - extent[0]) / maxDataCount;
  51081. }
  51082. each$13(seriesModels, function (seriesModel) {
  51083. var boxWidthBound = seriesModel.get('boxWidth');
  51084. if (!isArray(boxWidthBound)) {
  51085. boxWidthBound = [boxWidthBound, boxWidthBound];
  51086. }
  51087. boundList.push([
  51088. parsePercent$1(boxWidthBound[0], bandWidth) || 0,
  51089. parsePercent$1(boxWidthBound[1], bandWidth) || 0
  51090. ]);
  51091. });
  51092. var availableWidth = bandWidth * 0.8 - 2;
  51093. var boxGap = availableWidth / seriesCount * 0.3;
  51094. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  51095. var base = boxWidth / 2 - availableWidth / 2;
  51096. each$13(seriesModels, function (seriesModel, idx) {
  51097. boxOffsetList.push(base);
  51098. base += boxGap + boxWidth;
  51099. boxWidthList.push(
  51100. Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1])
  51101. );
  51102. });
  51103. }
  51104. /**
  51105. * Calculate points location for each series.
  51106. */
  51107. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  51108. var coordSys = seriesModel.coordinateSystem;
  51109. var data = seriesModel.getData();
  51110. var halfWidth = boxWidth / 2;
  51111. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  51112. var vDimIdx = 1 - cDimIdx;
  51113. var coordDims = ['x', 'y'];
  51114. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51115. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51116. if (cDim == null || vDims.length < 5) {
  51117. return;
  51118. }
  51119. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  51120. var axisDimVal = data.get(cDim, dataIndex);
  51121. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  51122. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  51123. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  51124. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  51125. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  51126. var ends = [];
  51127. addBodyEnd(ends, end2, 0);
  51128. addBodyEnd(ends, end4, 1);
  51129. ends.push(end1, end2, end5, end4);
  51130. layEndLine(ends, end1);
  51131. layEndLine(ends, end5);
  51132. layEndLine(ends, median);
  51133. data.setItemLayout(dataIndex, {
  51134. initBaseline: median[vDimIdx],
  51135. ends: ends
  51136. });
  51137. }
  51138. function getPoint(axisDimVal, dimIdx, dataIndex) {
  51139. var val = data.get(dimIdx, dataIndex);
  51140. var p = [];
  51141. p[cDimIdx] = axisDimVal;
  51142. p[vDimIdx] = val;
  51143. var point;
  51144. if (isNaN(axisDimVal) || isNaN(val)) {
  51145. point = [NaN, NaN];
  51146. }
  51147. else {
  51148. point = coordSys.dataToPoint(p);
  51149. point[cDimIdx] += offset;
  51150. }
  51151. return point;
  51152. }
  51153. function addBodyEnd(ends, point, start) {
  51154. var point1 = point.slice();
  51155. var point2 = point.slice();
  51156. point1[cDimIdx] += halfWidth;
  51157. point2[cDimIdx] -= halfWidth;
  51158. start
  51159. ? ends.push(point1, point2)
  51160. : ends.push(point2, point1);
  51161. }
  51162. function layEndLine(ends, endCenter) {
  51163. var from = endCenter.slice();
  51164. var to = endCenter.slice();
  51165. from[cDimIdx] -= halfWidth;
  51166. to[cDimIdx] += halfWidth;
  51167. ends.push(from, to);
  51168. }
  51169. }
  51170. /*
  51171. * Licensed to the Apache Software Foundation (ASF) under one
  51172. * or more contributor license agreements. See the NOTICE file
  51173. * distributed with this work for additional information
  51174. * regarding copyright ownership. The ASF licenses this file
  51175. * to you under the Apache License, Version 2.0 (the
  51176. * "License"); you may not use this file except in compliance
  51177. * with the License. You may obtain a copy of the License at
  51178. *
  51179. * http://www.apache.org/licenses/LICENSE-2.0
  51180. *
  51181. * Unless required by applicable law or agreed to in writing,
  51182. * software distributed under the License is distributed on an
  51183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51184. * KIND, either express or implied. See the License for the
  51185. * specific language governing permissions and limitations
  51186. * under the License.
  51187. */
  51188. registerVisual(boxplotVisual);
  51189. registerLayout(boxplotLayout);
  51190. /*
  51191. * Licensed to the Apache Software Foundation (ASF) under one
  51192. * or more contributor license agreements. See the NOTICE file
  51193. * distributed with this work for additional information
  51194. * regarding copyright ownership. The ASF licenses this file
  51195. * to you under the Apache License, Version 2.0 (the
  51196. * "License"); you may not use this file except in compliance
  51197. * with the License. You may obtain a copy of the License at
  51198. *
  51199. * http://www.apache.org/licenses/LICENSE-2.0
  51200. *
  51201. * Unless required by applicable law or agreed to in writing,
  51202. * software distributed under the License is distributed on an
  51203. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51204. * KIND, either express or implied. See the License for the
  51205. * specific language governing permissions and limitations
  51206. * under the License.
  51207. */
  51208. var CandlestickSeries = SeriesModel.extend({
  51209. type: 'series.candlestick',
  51210. dependencies: ['xAxis', 'yAxis', 'grid'],
  51211. /**
  51212. * @readOnly
  51213. */
  51214. defaultValueDimensions: [
  51215. {name: 'open', defaultTooltip: true},
  51216. {name: 'close', defaultTooltip: true},
  51217. {name: 'lowest', defaultTooltip: true},
  51218. {name: 'highest', defaultTooltip: true}
  51219. ],
  51220. /**
  51221. * @type {Array.<string>}
  51222. * @readOnly
  51223. */
  51224. dimensions: null,
  51225. /**
  51226. * @override
  51227. */
  51228. defaultOption: {
  51229. zlevel: 0,
  51230. z: 2,
  51231. coordinateSystem: 'cartesian2d',
  51232. legendHoverLink: true,
  51233. hoverAnimation: true,
  51234. // xAxisIndex: 0,
  51235. // yAxisIndex: 0,
  51236. layout: null, // 'horizontal' or 'vertical'
  51237. itemStyle: {
  51238. color: '#c23531', // 阳线 positive
  51239. color0: '#314656', // 阴线 negative '#c23531', '#314656'
  51240. borderWidth: 1,
  51241. // FIXME
  51242. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  51243. borderColor: '#c23531',
  51244. borderColor0: '#314656'
  51245. },
  51246. emphasis: {
  51247. itemStyle: {
  51248. borderWidth: 2
  51249. }
  51250. },
  51251. barMaxWidth: null,
  51252. barMinWidth: null,
  51253. barWidth: null,
  51254. large: true,
  51255. largeThreshold: 600,
  51256. progressive: 3e3,
  51257. progressiveThreshold: 1e4,
  51258. progressiveChunkMode: 'mod',
  51259. animationUpdate: false,
  51260. animationEasing: 'linear',
  51261. animationDuration: 300
  51262. },
  51263. /**
  51264. * Get dimension for shadow in dataZoom
  51265. * @return {string} dimension name
  51266. */
  51267. getShadowDim: function () {
  51268. return 'open';
  51269. },
  51270. brushSelector: function (dataIndex, data, selectors) {
  51271. var itemLayout = data.getItemLayout(dataIndex);
  51272. return itemLayout && selectors.rect(itemLayout.brushRect);
  51273. }
  51274. });
  51275. mixin(CandlestickSeries, seriesModelMixin, true);
  51276. /*
  51277. * Licensed to the Apache Software Foundation (ASF) under one
  51278. * or more contributor license agreements. See the NOTICE file
  51279. * distributed with this work for additional information
  51280. * regarding copyright ownership. The ASF licenses this file
  51281. * to you under the Apache License, Version 2.0 (the
  51282. * "License"); you may not use this file except in compliance
  51283. * with the License. You may obtain a copy of the License at
  51284. *
  51285. * http://www.apache.org/licenses/LICENSE-2.0
  51286. *
  51287. * Unless required by applicable law or agreed to in writing,
  51288. * software distributed under the License is distributed on an
  51289. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51290. * KIND, either express or implied. See the License for the
  51291. * specific language governing permissions and limitations
  51292. * under the License.
  51293. */
  51294. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  51295. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  51296. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  51297. var CandlestickView = Chart.extend({
  51298. type: 'candlestick',
  51299. render: function (seriesModel, ecModel, api) {
  51300. this._updateDrawMode(seriesModel);
  51301. this._isLargeDraw
  51302. ? this._renderLarge(seriesModel)
  51303. : this._renderNormal(seriesModel);
  51304. },
  51305. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  51306. this._clear();
  51307. this._updateDrawMode(seriesModel);
  51308. },
  51309. incrementalRender: function (params, seriesModel, ecModel, api) {
  51310. this._isLargeDraw
  51311. ? this._incrementalRenderLarge(params, seriesModel)
  51312. : this._incrementalRenderNormal(params, seriesModel);
  51313. },
  51314. _updateDrawMode: function (seriesModel) {
  51315. var isLargeDraw = seriesModel.pipelineContext.large;
  51316. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  51317. this._isLargeDraw = isLargeDraw;
  51318. this._clear();
  51319. }
  51320. },
  51321. _renderNormal: function (seriesModel) {
  51322. var data = seriesModel.getData();
  51323. var oldData = this._data;
  51324. var group = this.group;
  51325. var isSimpleBox = data.getLayout('isSimpleBox');
  51326. // There is no old data only when first rendering or switching from
  51327. // stream mode to normal mode, where previous elements should be removed.
  51328. if (!this._data) {
  51329. group.removeAll();
  51330. }
  51331. data.diff(oldData)
  51332. .add(function (newIdx) {
  51333. if (data.hasValue(newIdx)) {
  51334. var el;
  51335. var itemLayout = data.getItemLayout(newIdx);
  51336. el = createNormalBox$1(itemLayout, newIdx, true);
  51337. initProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  51338. setBoxCommon(el, data, newIdx, isSimpleBox);
  51339. group.add(el);
  51340. data.setItemGraphicEl(newIdx, el);
  51341. }
  51342. })
  51343. .update(function (newIdx, oldIdx) {
  51344. var el = oldData.getItemGraphicEl(oldIdx);
  51345. // Empty data
  51346. if (!data.hasValue(newIdx)) {
  51347. group.remove(el);
  51348. return;
  51349. }
  51350. var itemLayout = data.getItemLayout(newIdx);
  51351. if (!el) {
  51352. el = createNormalBox$1(itemLayout, newIdx);
  51353. }
  51354. else {
  51355. updateProps(el, {shape: {points: itemLayout.ends}}, seriesModel, newIdx);
  51356. }
  51357. setBoxCommon(el, data, newIdx, isSimpleBox);
  51358. group.add(el);
  51359. data.setItemGraphicEl(newIdx, el);
  51360. })
  51361. .remove(function (oldIdx) {
  51362. var el = oldData.getItemGraphicEl(oldIdx);
  51363. el && group.remove(el);
  51364. })
  51365. .execute();
  51366. this._data = data;
  51367. },
  51368. _renderLarge: function (seriesModel) {
  51369. this._clear();
  51370. createLarge$1(seriesModel, this.group);
  51371. },
  51372. _incrementalRenderNormal: function (params, seriesModel) {
  51373. var data = seriesModel.getData();
  51374. var isSimpleBox = data.getLayout('isSimpleBox');
  51375. var dataIndex;
  51376. while ((dataIndex = params.next()) != null) {
  51377. var el;
  51378. var itemLayout = data.getItemLayout(dataIndex);
  51379. el = createNormalBox$1(itemLayout, dataIndex);
  51380. setBoxCommon(el, data, dataIndex, isSimpleBox);
  51381. el.incremental = true;
  51382. this.group.add(el);
  51383. }
  51384. },
  51385. _incrementalRenderLarge: function (params, seriesModel) {
  51386. createLarge$1(seriesModel, this.group, true);
  51387. },
  51388. remove: function (ecModel) {
  51389. this._clear();
  51390. },
  51391. _clear: function () {
  51392. this.group.removeAll();
  51393. this._data = null;
  51394. },
  51395. dispose: noop
  51396. });
  51397. var NormalBoxPath = Path.extend({
  51398. type: 'normalCandlestickBox',
  51399. shape: {},
  51400. buildPath: function (ctx, shape) {
  51401. var ends = shape.points;
  51402. if (this.__simpleBox) {
  51403. ctx.moveTo(ends[4][0], ends[4][1]);
  51404. ctx.lineTo(ends[6][0], ends[6][1]);
  51405. }
  51406. else {
  51407. ctx.moveTo(ends[0][0], ends[0][1]);
  51408. ctx.lineTo(ends[1][0], ends[1][1]);
  51409. ctx.lineTo(ends[2][0], ends[2][1]);
  51410. ctx.lineTo(ends[3][0], ends[3][1]);
  51411. ctx.closePath();
  51412. ctx.moveTo(ends[4][0], ends[4][1]);
  51413. ctx.lineTo(ends[5][0], ends[5][1]);
  51414. ctx.moveTo(ends[6][0], ends[6][1]);
  51415. ctx.lineTo(ends[7][0], ends[7][1]);
  51416. }
  51417. }
  51418. });
  51419. function createNormalBox$1(itemLayout, dataIndex, isInit) {
  51420. var ends = itemLayout.ends;
  51421. return new NormalBoxPath({
  51422. shape: {
  51423. points: isInit
  51424. ? transInit$1(ends, itemLayout)
  51425. : ends
  51426. },
  51427. z2: 100
  51428. });
  51429. }
  51430. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  51431. var itemModel = data.getItemModel(dataIndex);
  51432. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  51433. var color = data.getItemVisual(dataIndex, 'color');
  51434. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color;
  51435. // Color must be excluded.
  51436. // Because symbol provide setColor individually to set fill and stroke
  51437. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  51438. el.useStyle(itemStyle);
  51439. el.style.strokeNoScale = true;
  51440. el.style.fill = color;
  51441. el.style.stroke = borderColor;
  51442. el.__simpleBox = isSimpleBox;
  51443. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  51444. setHoverStyle(el, hoverStyle);
  51445. }
  51446. function transInit$1(points, itemLayout) {
  51447. return map(points, function (point) {
  51448. point = point.slice();
  51449. point[1] = itemLayout.initBaseline;
  51450. return point;
  51451. });
  51452. }
  51453. var LargeBoxPath = Path.extend({
  51454. type: 'largeCandlestickBox',
  51455. shape: {},
  51456. buildPath: function (ctx, shape) {
  51457. // Drawing lines is more efficient than drawing
  51458. // a whole line or drawing rects.
  51459. var points = shape.points;
  51460. for (var i = 0; i < points.length;) {
  51461. if (this.__sign === points[i++]) {
  51462. var x = points[i++];
  51463. ctx.moveTo(x, points[i++]);
  51464. ctx.lineTo(x, points[i++]);
  51465. }
  51466. else {
  51467. i += 3;
  51468. }
  51469. }
  51470. }
  51471. });
  51472. function createLarge$1(seriesModel, group, incremental) {
  51473. var data = seriesModel.getData();
  51474. var largePoints = data.getLayout('largePoints');
  51475. var elP = new LargeBoxPath({
  51476. shape: {points: largePoints},
  51477. __sign: 1
  51478. });
  51479. group.add(elP);
  51480. var elN = new LargeBoxPath({
  51481. shape: {points: largePoints},
  51482. __sign: -1
  51483. });
  51484. group.add(elN);
  51485. setLargeStyle$1(1, elP, seriesModel, data);
  51486. setLargeStyle$1(-1, elN, seriesModel, data);
  51487. if (incremental) {
  51488. elP.incremental = true;
  51489. elN.incremental = true;
  51490. }
  51491. }
  51492. function setLargeStyle$1(sign, el, seriesModel, data) {
  51493. var suffix = sign > 0 ? 'P' : 'N';
  51494. var borderColor = data.getVisual('borderColor' + suffix)
  51495. || data.getVisual('color' + suffix);
  51496. // Color must be excluded.
  51497. // Because symbol provide setColor individually to set fill and stroke
  51498. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH$1).getItemStyle(SKIP_PROPS);
  51499. el.useStyle(itemStyle);
  51500. el.style.fill = null;
  51501. el.style.stroke = borderColor;
  51502. // No different
  51503. // el.style.lineWidth = .5;
  51504. }
  51505. /*
  51506. * Licensed to the Apache Software Foundation (ASF) under one
  51507. * or more contributor license agreements. See the NOTICE file
  51508. * distributed with this work for additional information
  51509. * regarding copyright ownership. The ASF licenses this file
  51510. * to you under the Apache License, Version 2.0 (the
  51511. * "License"); you may not use this file except in compliance
  51512. * with the License. You may obtain a copy of the License at
  51513. *
  51514. * http://www.apache.org/licenses/LICENSE-2.0
  51515. *
  51516. * Unless required by applicable law or agreed to in writing,
  51517. * software distributed under the License is distributed on an
  51518. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51519. * KIND, either express or implied. See the License for the
  51520. * specific language governing permissions and limitations
  51521. * under the License.
  51522. */
  51523. var preprocessor = function (option) {
  51524. if (!option || !isArray(option.series)) {
  51525. return;
  51526. }
  51527. // Translate 'k' to 'candlestick'.
  51528. each$1(option.series, function (seriesItem) {
  51529. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  51530. seriesItem.type = 'candlestick';
  51531. }
  51532. });
  51533. };
  51534. /*
  51535. * Licensed to the Apache Software Foundation (ASF) under one
  51536. * or more contributor license agreements. See the NOTICE file
  51537. * distributed with this work for additional information
  51538. * regarding copyright ownership. The ASF licenses this file
  51539. * to you under the Apache License, Version 2.0 (the
  51540. * "License"); you may not use this file except in compliance
  51541. * with the License. You may obtain a copy of the License at
  51542. *
  51543. * http://www.apache.org/licenses/LICENSE-2.0
  51544. *
  51545. * Unless required by applicable law or agreed to in writing,
  51546. * software distributed under the License is distributed on an
  51547. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51548. * KIND, either express or implied. See the License for the
  51549. * specific language governing permissions and limitations
  51550. * under the License.
  51551. */
  51552. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  51553. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  51554. var positiveColorQuery = ['itemStyle', 'color'];
  51555. var negativeColorQuery = ['itemStyle', 'color0'];
  51556. var candlestickVisual = {
  51557. seriesType: 'candlestick',
  51558. plan: createRenderPlanner(),
  51559. // For legend.
  51560. performRawSeries: true,
  51561. reset: function (seriesModel, ecModel) {
  51562. var data = seriesModel.getData();
  51563. var isLargeRender = seriesModel.pipelineContext.large;
  51564. data.setVisual({
  51565. legendSymbol: 'roundRect',
  51566. colorP: getColor(1, seriesModel),
  51567. colorN: getColor(-1, seriesModel),
  51568. borderColorP: getBorderColor(1, seriesModel),
  51569. borderColorN: getBorderColor(-1, seriesModel)
  51570. });
  51571. // Only visible series has each data be visual encoded
  51572. if (ecModel.isSeriesFiltered(seriesModel)) {
  51573. return;
  51574. }
  51575. return !isLargeRender && {progress: progress};
  51576. function progress(params, data) {
  51577. var dataIndex;
  51578. while ((dataIndex = params.next()) != null) {
  51579. var itemModel = data.getItemModel(dataIndex);
  51580. var sign = data.getItemLayout(dataIndex).sign;
  51581. data.setItemVisual(
  51582. dataIndex,
  51583. {
  51584. color: getColor(sign, itemModel),
  51585. borderColor: getBorderColor(sign, itemModel)
  51586. }
  51587. );
  51588. }
  51589. }
  51590. function getColor(sign, model) {
  51591. return model.get(
  51592. sign > 0 ? positiveColorQuery : negativeColorQuery
  51593. );
  51594. }
  51595. function getBorderColor(sign, model) {
  51596. return model.get(
  51597. sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery
  51598. );
  51599. }
  51600. }
  51601. };
  51602. /*
  51603. * Licensed to the Apache Software Foundation (ASF) under one
  51604. * or more contributor license agreements. See the NOTICE file
  51605. * distributed with this work for additional information
  51606. * regarding copyright ownership. The ASF licenses this file
  51607. * to you under the Apache License, Version 2.0 (the
  51608. * "License"); you may not use this file except in compliance
  51609. * with the License. You may obtain a copy of the License at
  51610. *
  51611. * http://www.apache.org/licenses/LICENSE-2.0
  51612. *
  51613. * Unless required by applicable law or agreed to in writing,
  51614. * software distributed under the License is distributed on an
  51615. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51616. * KIND, either express or implied. See the License for the
  51617. * specific language governing permissions and limitations
  51618. * under the License.
  51619. */
  51620. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  51621. var candlestickLayout = {
  51622. seriesType: 'candlestick',
  51623. plan: createRenderPlanner(),
  51624. reset: function (seriesModel) {
  51625. var coordSys = seriesModel.coordinateSystem;
  51626. var data = seriesModel.getData();
  51627. var candleWidth = calculateCandleWidth(seriesModel, data);
  51628. var cDimIdx = 0;
  51629. var vDimIdx = 1;
  51630. var coordDims = ['x', 'y'];
  51631. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51632. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51633. var openDim = vDims[0];
  51634. var closeDim = vDims[1];
  51635. var lowestDim = vDims[2];
  51636. var highestDim = vDims[3];
  51637. data.setLayout({
  51638. candleWidth: candleWidth,
  51639. // The value is experimented visually.
  51640. isSimpleBox: candleWidth <= 1.3
  51641. });
  51642. if (cDim == null || vDims.length < 4) {
  51643. return;
  51644. }
  51645. return {
  51646. progress: seriesModel.pipelineContext.large
  51647. ? largeProgress : normalProgress
  51648. };
  51649. function normalProgress(params, data) {
  51650. var dataIndex;
  51651. while ((dataIndex = params.next()) != null) {
  51652. var axisDimVal = data.get(cDim, dataIndex);
  51653. var openVal = data.get(openDim, dataIndex);
  51654. var closeVal = data.get(closeDim, dataIndex);
  51655. var lowestVal = data.get(lowestDim, dataIndex);
  51656. var highestVal = data.get(highestDim, dataIndex);
  51657. var ocLow = Math.min(openVal, closeVal);
  51658. var ocHigh = Math.max(openVal, closeVal);
  51659. var ocLowPoint = getPoint(ocLow, axisDimVal);
  51660. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  51661. var lowestPoint = getPoint(lowestVal, axisDimVal);
  51662. var highestPoint = getPoint(highestVal, axisDimVal);
  51663. var ends = [];
  51664. addBodyEnd(ends, ocHighPoint, 0);
  51665. addBodyEnd(ends, ocLowPoint, 1);
  51666. ends.push(
  51667. subPixelOptimizePoint(highestPoint),
  51668. subPixelOptimizePoint(ocHighPoint),
  51669. subPixelOptimizePoint(lowestPoint),
  51670. subPixelOptimizePoint(ocLowPoint)
  51671. );
  51672. data.setItemLayout(dataIndex, {
  51673. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  51674. initBaseline: openVal > closeVal
  51675. ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx], // open point.
  51676. ends: ends,
  51677. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  51678. });
  51679. }
  51680. function getPoint(val, axisDimVal) {
  51681. var p = [];
  51682. p[cDimIdx] = axisDimVal;
  51683. p[vDimIdx] = val;
  51684. return (isNaN(axisDimVal) || isNaN(val))
  51685. ? [NaN, NaN]
  51686. : coordSys.dataToPoint(p);
  51687. }
  51688. function addBodyEnd(ends, point, start) {
  51689. var point1 = point.slice();
  51690. var point2 = point.slice();
  51691. point1[cDimIdx] = subPixelOptimize(
  51692. point1[cDimIdx] + candleWidth / 2, 1, false
  51693. );
  51694. point2[cDimIdx] = subPixelOptimize(
  51695. point2[cDimIdx] - candleWidth / 2, 1, true
  51696. );
  51697. start
  51698. ? ends.push(point1, point2)
  51699. : ends.push(point2, point1);
  51700. }
  51701. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  51702. var pmin = getPoint(lowestVal, axisDimVal);
  51703. var pmax = getPoint(highestVal, axisDimVal);
  51704. pmin[cDimIdx] -= candleWidth / 2;
  51705. pmax[cDimIdx] -= candleWidth / 2;
  51706. return {
  51707. x: pmin[0],
  51708. y: pmin[1],
  51709. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  51710. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  51711. };
  51712. }
  51713. function subPixelOptimizePoint(point) {
  51714. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  51715. return point;
  51716. }
  51717. }
  51718. function largeProgress(params, data) {
  51719. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  51720. var points = new LargeArr$1(params.count * 5);
  51721. var offset = 0;
  51722. var point;
  51723. var tmpIn = [];
  51724. var tmpOut = [];
  51725. var dataIndex;
  51726. while ((dataIndex = params.next()) != null) {
  51727. var axisDimVal = data.get(cDim, dataIndex);
  51728. var openVal = data.get(openDim, dataIndex);
  51729. var closeVal = data.get(closeDim, dataIndex);
  51730. var lowestVal = data.get(lowestDim, dataIndex);
  51731. var highestVal = data.get(highestDim, dataIndex);
  51732. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  51733. points[offset++] = NaN;
  51734. offset += 4;
  51735. continue;
  51736. }
  51737. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  51738. tmpIn[cDimIdx] = axisDimVal;
  51739. tmpIn[vDimIdx] = lowestVal;
  51740. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  51741. points[offset++] = point ? point[0] : NaN;
  51742. points[offset++] = point ? point[1] : NaN;
  51743. tmpIn[vDimIdx] = highestVal;
  51744. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  51745. points[offset++] = point ? point[1] : NaN;
  51746. }
  51747. data.setLayout('largePoints', points);
  51748. }
  51749. }
  51750. };
  51751. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  51752. var sign;
  51753. if (openVal > closeVal) {
  51754. sign = -1;
  51755. }
  51756. else if (openVal < closeVal) {
  51757. sign = 1;
  51758. }
  51759. else {
  51760. sign = dataIndex > 0
  51761. // If close === open, compare with close of last record
  51762. ? (data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1)
  51763. // No record of previous, set to be positive
  51764. : 1;
  51765. }
  51766. return sign;
  51767. }
  51768. function calculateCandleWidth(seriesModel, data) {
  51769. var baseAxis = seriesModel.getBaseAxis();
  51770. var extent;
  51771. var bandWidth = baseAxis.type === 'category'
  51772. ? baseAxis.getBandWidth()
  51773. : (
  51774. extent = baseAxis.getExtent(),
  51775. Math.abs(extent[1] - extent[0]) / data.count()
  51776. );
  51777. var barMaxWidth = parsePercent$1(
  51778. retrieve2(seriesModel.get('barMaxWidth'), bandWidth),
  51779. bandWidth
  51780. );
  51781. var barMinWidth = parsePercent$1(
  51782. retrieve2(seriesModel.get('barMinWidth'), 1),
  51783. bandWidth
  51784. );
  51785. var barWidth = seriesModel.get('barWidth');
  51786. return barWidth != null
  51787. ? parsePercent$1(barWidth, bandWidth)
  51788. // Put max outer to ensure bar visible in spite of overlap.
  51789. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  51790. }
  51791. /*
  51792. * Licensed to the Apache Software Foundation (ASF) under one
  51793. * or more contributor license agreements. See the NOTICE file
  51794. * distributed with this work for additional information
  51795. * regarding copyright ownership. The ASF licenses this file
  51796. * to you under the Apache License, Version 2.0 (the
  51797. * "License"); you may not use this file except in compliance
  51798. * with the License. You may obtain a copy of the License at
  51799. *
  51800. * http://www.apache.org/licenses/LICENSE-2.0
  51801. *
  51802. * Unless required by applicable law or agreed to in writing,
  51803. * software distributed under the License is distributed on an
  51804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51805. * KIND, either express or implied. See the License for the
  51806. * specific language governing permissions and limitations
  51807. * under the License.
  51808. */
  51809. registerPreprocessor(preprocessor);
  51810. registerVisual(candlestickVisual);
  51811. registerLayout(candlestickLayout);
  51812. /*
  51813. * Licensed to the Apache Software Foundation (ASF) under one
  51814. * or more contributor license agreements. See the NOTICE file
  51815. * distributed with this work for additional information
  51816. * regarding copyright ownership. The ASF licenses this file
  51817. * to you under the Apache License, Version 2.0 (the
  51818. * "License"); you may not use this file except in compliance
  51819. * with the License. You may obtain a copy of the License at
  51820. *
  51821. * http://www.apache.org/licenses/LICENSE-2.0
  51822. *
  51823. * Unless required by applicable law or agreed to in writing,
  51824. * software distributed under the License is distributed on an
  51825. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51826. * KIND, either express or implied. See the License for the
  51827. * specific language governing permissions and limitations
  51828. * under the License.
  51829. */
  51830. SeriesModel.extend({
  51831. type: 'series.effectScatter',
  51832. dependencies: ['grid', 'polar'],
  51833. getInitialData: function (option, ecModel) {
  51834. return createListFromArray(this.getSource(), this);
  51835. },
  51836. brushSelector: 'point',
  51837. defaultOption: {
  51838. coordinateSystem: 'cartesian2d',
  51839. zlevel: 0,
  51840. z: 2,
  51841. legendHoverLink: true,
  51842. effectType: 'ripple',
  51843. progressive: 0,
  51844. // When to show the effect, option: 'render'|'emphasis'
  51845. showEffectOn: 'render',
  51846. // Ripple effect config
  51847. rippleEffect: {
  51848. period: 4,
  51849. // Scale of ripple
  51850. scale: 2.5,
  51851. // Brush type can be fill or stroke
  51852. brushType: 'fill'
  51853. },
  51854. // Cartesian coordinate system
  51855. // xAxisIndex: 0,
  51856. // yAxisIndex: 0,
  51857. // Polar coordinate system
  51858. // polarIndex: 0,
  51859. // Geo coordinate system
  51860. // geoIndex: 0,
  51861. // symbol: null, // 图形类型
  51862. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  51863. // symbolRotate: null, // 图形旋转控制
  51864. // large: false,
  51865. // Available when large is true
  51866. // largeThreshold: 2000,
  51867. // itemStyle: {
  51868. // opacity: 1
  51869. // }
  51870. }
  51871. });
  51872. /*
  51873. * Licensed to the Apache Software Foundation (ASF) under one
  51874. * or more contributor license agreements. See the NOTICE file
  51875. * distributed with this work for additional information
  51876. * regarding copyright ownership. The ASF licenses this file
  51877. * to you under the Apache License, Version 2.0 (the
  51878. * "License"); you may not use this file except in compliance
  51879. * with the License. You may obtain a copy of the License at
  51880. *
  51881. * http://www.apache.org/licenses/LICENSE-2.0
  51882. *
  51883. * Unless required by applicable law or agreed to in writing,
  51884. * software distributed under the License is distributed on an
  51885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51886. * KIND, either express or implied. See the License for the
  51887. * specific language governing permissions and limitations
  51888. * under the License.
  51889. */
  51890. /**
  51891. * Symbol with ripple effect
  51892. * @module echarts/chart/helper/EffectSymbol
  51893. */
  51894. var EFFECT_RIPPLE_NUMBER = 3;
  51895. function normalizeSymbolSize$1(symbolSize) {
  51896. if (!isArray(symbolSize)) {
  51897. symbolSize = [+symbolSize, +symbolSize];
  51898. }
  51899. return symbolSize;
  51900. }
  51901. function updateRipplePath(rippleGroup, effectCfg) {
  51902. rippleGroup.eachChild(function (ripplePath) {
  51903. ripplePath.attr({
  51904. z: effectCfg.z,
  51905. zlevel: effectCfg.zlevel,
  51906. style: {
  51907. stroke: effectCfg.brushType === 'stroke' ? effectCfg.color : null,
  51908. fill: effectCfg.brushType === 'fill' ? effectCfg.color : null
  51909. }
  51910. });
  51911. });
  51912. }
  51913. /**
  51914. * @constructor
  51915. * @param {module:echarts/data/List} data
  51916. * @param {number} idx
  51917. * @extends {module:zrender/graphic/Group}
  51918. */
  51919. function EffectSymbol(data, idx) {
  51920. Group.call(this);
  51921. var symbol = new SymbolClz$1(data, idx);
  51922. var rippleGroup = new Group();
  51923. this.add(symbol);
  51924. this.add(rippleGroup);
  51925. rippleGroup.beforeUpdate = function () {
  51926. this.attr(symbol.getScale());
  51927. };
  51928. this.updateData(data, idx);
  51929. }
  51930. var effectSymbolProto = EffectSymbol.prototype;
  51931. effectSymbolProto.stopEffectAnimation = function () {
  51932. this.childAt(1).removeAll();
  51933. };
  51934. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  51935. var symbolType = effectCfg.symbolType;
  51936. var color = effectCfg.color;
  51937. var rippleGroup = this.childAt(1);
  51938. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  51939. // var ripplePath = createSymbol(
  51940. // symbolType, -0.5, -0.5, 1, 1, color
  51941. // );
  51942. // If width/height are set too small (e.g., set to 1) on ios10
  51943. // and macOS Sierra, a circle stroke become a rect, no matter what
  51944. // the scale is set. So we set width/height as 2. See #4136.
  51945. var ripplePath = createSymbol(
  51946. symbolType, -1, -1, 2, 2, color
  51947. );
  51948. ripplePath.attr({
  51949. style: {
  51950. strokeNoScale: true
  51951. },
  51952. z2: 99,
  51953. silent: true,
  51954. scale: [0.5, 0.5]
  51955. });
  51956. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset;
  51957. // TODO Configurable effectCfg.period
  51958. ripplePath.animate('', true)
  51959. .when(effectCfg.period, {
  51960. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  51961. })
  51962. .delay(delay)
  51963. .start();
  51964. ripplePath.animateStyle(true)
  51965. .when(effectCfg.period, {
  51966. opacity: 0
  51967. })
  51968. .delay(delay)
  51969. .start();
  51970. rippleGroup.add(ripplePath);
  51971. }
  51972. updateRipplePath(rippleGroup, effectCfg);
  51973. };
  51974. /**
  51975. * Update effect symbol
  51976. */
  51977. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  51978. var oldEffectCfg = this._effectCfg;
  51979. var rippleGroup = this.childAt(1);
  51980. // Must reinitialize effect if following configuration changed
  51981. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  51982. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  51983. var propName = DIFFICULT_PROPS[i];
  51984. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  51985. this.stopEffectAnimation();
  51986. this.startEffectAnimation(effectCfg);
  51987. return;
  51988. }
  51989. }
  51990. updateRipplePath(rippleGroup, effectCfg);
  51991. };
  51992. /**
  51993. * Highlight symbol
  51994. */
  51995. effectSymbolProto.highlight = function () {
  51996. this.trigger('emphasis');
  51997. };
  51998. /**
  51999. * Downplay symbol
  52000. */
  52001. effectSymbolProto.downplay = function () {
  52002. this.trigger('normal');
  52003. };
  52004. /**
  52005. * Update symbol properties
  52006. * @param {module:echarts/data/List} data
  52007. * @param {number} idx
  52008. */
  52009. effectSymbolProto.updateData = function (data, idx) {
  52010. var seriesModel = data.hostModel;
  52011. this.childAt(0).updateData(data, idx);
  52012. var rippleGroup = this.childAt(1);
  52013. var itemModel = data.getItemModel(idx);
  52014. var symbolType = data.getItemVisual(idx, 'symbol');
  52015. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  52016. var color = data.getItemVisual(idx, 'color');
  52017. rippleGroup.attr('scale', symbolSize);
  52018. rippleGroup.traverse(function (ripplePath) {
  52019. ripplePath.attr({
  52020. fill: color
  52021. });
  52022. });
  52023. var symbolOffset = itemModel.getShallow('symbolOffset');
  52024. if (symbolOffset) {
  52025. var pos = rippleGroup.position;
  52026. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  52027. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  52028. }
  52029. rippleGroup.rotation = (itemModel.getShallow('symbolRotate') || 0) * Math.PI / 180 || 0;
  52030. var effectCfg = {};
  52031. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  52032. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  52033. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  52034. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  52035. effectCfg.effectOffset = idx / data.count();
  52036. effectCfg.z = itemModel.getShallow('z') || 0;
  52037. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  52038. effectCfg.symbolType = symbolType;
  52039. effectCfg.color = color;
  52040. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  52041. if (effectCfg.showEffectOn === 'render') {
  52042. this._effectCfg
  52043. ? this.updateEffectAnimation(effectCfg)
  52044. : this.startEffectAnimation(effectCfg);
  52045. this._effectCfg = effectCfg;
  52046. }
  52047. else {
  52048. // Not keep old effect config
  52049. this._effectCfg = null;
  52050. this.stopEffectAnimation();
  52051. var symbol = this.childAt(0);
  52052. var onEmphasis = function () {
  52053. symbol.highlight();
  52054. if (effectCfg.showEffectOn !== 'render') {
  52055. this.startEffectAnimation(effectCfg);
  52056. }
  52057. };
  52058. var onNormal = function () {
  52059. symbol.downplay();
  52060. if (effectCfg.showEffectOn !== 'render') {
  52061. this.stopEffectAnimation();
  52062. }
  52063. };
  52064. this.on('mouseover', onEmphasis, this)
  52065. .on('mouseout', onNormal, this)
  52066. .on('emphasis', onEmphasis, this)
  52067. .on('normal', onNormal, this);
  52068. }
  52069. this._effectCfg = effectCfg;
  52070. };
  52071. effectSymbolProto.fadeOut = function (cb) {
  52072. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  52073. cb && cb();
  52074. };
  52075. inherits(EffectSymbol, Group);
  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. extendChartView({
  52095. type: 'effectScatter',
  52096. init: function () {
  52097. this._symbolDraw = new SymbolDraw(EffectSymbol);
  52098. },
  52099. render: function (seriesModel, ecModel, api) {
  52100. var data = seriesModel.getData();
  52101. var effectSymbolDraw = this._symbolDraw;
  52102. effectSymbolDraw.updateData(data);
  52103. this.group.add(effectSymbolDraw.group);
  52104. },
  52105. updateTransform: function (seriesModel, ecModel, api) {
  52106. var data = seriesModel.getData();
  52107. this.group.dirty();
  52108. var res = pointsLayout().reset(seriesModel);
  52109. if (res.progress) {
  52110. res.progress({ start: 0, end: data.count() }, data);
  52111. }
  52112. this._symbolDraw.updateLayout(data);
  52113. },
  52114. _updateGroupTransform: function (seriesModel) {
  52115. var coordSys = seriesModel.coordinateSystem;
  52116. if (coordSys && coordSys.getRoamTransform) {
  52117. this.group.transform = clone$2(coordSys.getRoamTransform());
  52118. this.group.decomposeTransform();
  52119. }
  52120. },
  52121. remove: function (ecModel, api) {
  52122. this._symbolDraw && this._symbolDraw.remove(api);
  52123. },
  52124. dispose: function () {}
  52125. });
  52126. /*
  52127. * Licensed to the Apache Software Foundation (ASF) under one
  52128. * or more contributor license agreements. See the NOTICE file
  52129. * distributed with this work for additional information
  52130. * regarding copyright ownership. The ASF licenses this file
  52131. * to you under the Apache License, Version 2.0 (the
  52132. * "License"); you may not use this file except in compliance
  52133. * with the License. You may obtain a copy of the License at
  52134. *
  52135. * http://www.apache.org/licenses/LICENSE-2.0
  52136. *
  52137. * Unless required by applicable law or agreed to in writing,
  52138. * software distributed under the License is distributed on an
  52139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52140. * KIND, either express or implied. See the License for the
  52141. * specific language governing permissions and limitations
  52142. * under the License.
  52143. */
  52144. registerVisual(visualSymbol('effectScatter', 'circle'));
  52145. registerLayout(pointsLayout('effectScatter'));
  52146. /*
  52147. * Licensed to the Apache Software Foundation (ASF) under one
  52148. * or more contributor license agreements. See the NOTICE file
  52149. * distributed with this work for additional information
  52150. * regarding copyright ownership. The ASF licenses this file
  52151. * to you under the Apache License, Version 2.0 (the
  52152. * "License"); you may not use this file except in compliance
  52153. * with the License. You may obtain a copy of the License at
  52154. *
  52155. * http://www.apache.org/licenses/LICENSE-2.0
  52156. *
  52157. * Unless required by applicable law or agreed to in writing,
  52158. * software distributed under the License is distributed on an
  52159. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52160. * KIND, either express or implied. See the License for the
  52161. * specific language governing permissions and limitations
  52162. * under the License.
  52163. */
  52164. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  52165. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  52166. function compatEc2(seriesOpt) {
  52167. var data = seriesOpt.data;
  52168. if (data && data[0] && data[0][0] && data[0][0].coord) {
  52169. if (__DEV__) {
  52170. console.warn('Lines data configuration has been changed to'
  52171. + ' { coords:[[1,2],[2,3]] }');
  52172. }
  52173. seriesOpt.data = map(data, function (itemOpt) {
  52174. var coords = [
  52175. itemOpt[0].coord, itemOpt[1].coord
  52176. ];
  52177. var target = {
  52178. coords: coords
  52179. };
  52180. if (itemOpt[0].name) {
  52181. target.fromName = itemOpt[0].name;
  52182. }
  52183. if (itemOpt[1].name) {
  52184. target.toName = itemOpt[1].name;
  52185. }
  52186. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  52187. });
  52188. }
  52189. }
  52190. var LinesSeries = SeriesModel.extend({
  52191. type: 'series.lines',
  52192. dependencies: ['grid', 'polar'],
  52193. visualColorAccessPath: 'lineStyle.color',
  52194. init: function (option) {
  52195. // The input data may be null/undefined.
  52196. option.data = option.data || [];
  52197. // Not using preprocessor because mergeOption may not have series.type
  52198. compatEc2(option);
  52199. var result = this._processFlatCoordsArray(option.data);
  52200. this._flatCoords = result.flatCoords;
  52201. this._flatCoordsOffset = result.flatCoordsOffset;
  52202. if (result.flatCoords) {
  52203. option.data = new Float32Array(result.count);
  52204. }
  52205. LinesSeries.superApply(this, 'init', arguments);
  52206. },
  52207. mergeOption: function (option) {
  52208. // The input data may be null/undefined.
  52209. option.data = option.data || [];
  52210. compatEc2(option);
  52211. if (option.data) {
  52212. // Only update when have option data to merge.
  52213. var result = this._processFlatCoordsArray(option.data);
  52214. this._flatCoords = result.flatCoords;
  52215. this._flatCoordsOffset = result.flatCoordsOffset;
  52216. if (result.flatCoords) {
  52217. option.data = new Float32Array(result.count);
  52218. }
  52219. }
  52220. LinesSeries.superApply(this, 'mergeOption', arguments);
  52221. },
  52222. appendData: function (params) {
  52223. var result = this._processFlatCoordsArray(params.data);
  52224. if (result.flatCoords) {
  52225. if (!this._flatCoords) {
  52226. this._flatCoords = result.flatCoords;
  52227. this._flatCoordsOffset = result.flatCoordsOffset;
  52228. }
  52229. else {
  52230. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  52231. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  52232. }
  52233. params.data = new Float32Array(result.count);
  52234. }
  52235. this.getRawData().appendData(params.data);
  52236. },
  52237. _getCoordsFromItemModel: function (idx) {
  52238. var itemModel = this.getData().getItemModel(idx);
  52239. var coords = (itemModel.option instanceof Array)
  52240. ? itemModel.option : itemModel.getShallow('coords');
  52241. if (__DEV__) {
  52242. if (!(coords instanceof Array && coords.length > 0 && coords[0] instanceof Array)) {
  52243. throw new Error('Invalid coords ' + JSON.stringify(coords) + '. Lines must have 2d coords array in data item.');
  52244. }
  52245. }
  52246. return coords;
  52247. },
  52248. getLineCoordsCount: function (idx) {
  52249. if (this._flatCoordsOffset) {
  52250. return this._flatCoordsOffset[idx * 2 + 1];
  52251. }
  52252. else {
  52253. return this._getCoordsFromItemModel(idx).length;
  52254. }
  52255. },
  52256. getLineCoords: function (idx, out) {
  52257. if (this._flatCoordsOffset) {
  52258. var offset = this._flatCoordsOffset[idx * 2];
  52259. var len = this._flatCoordsOffset[idx * 2 + 1];
  52260. for (var i = 0; i < len; i++) {
  52261. out[i] = out[i] || [];
  52262. out[i][0] = this._flatCoords[offset + i * 2];
  52263. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  52264. }
  52265. return len;
  52266. }
  52267. else {
  52268. var coords = this._getCoordsFromItemModel(idx);
  52269. for (var i = 0; i < coords.length; i++) {
  52270. out[i] = out[i] || [];
  52271. out[i][0] = coords[i][0];
  52272. out[i][1] = coords[i][1];
  52273. }
  52274. return coords.length;
  52275. }
  52276. },
  52277. _processFlatCoordsArray: function (data) {
  52278. var startOffset = 0;
  52279. if (this._flatCoords) {
  52280. startOffset = this._flatCoords.length;
  52281. }
  52282. // Stored as a typed array. In format
  52283. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  52284. if (typeof data[0] === 'number') {
  52285. var len = data.length;
  52286. // Store offset and len of each segment
  52287. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  52288. var coordsStorage = new Float64Arr(len);
  52289. var coordsCursor = 0;
  52290. var offsetCursor = 0;
  52291. var dataCount = 0;
  52292. for (var i = 0; i < len;) {
  52293. dataCount++;
  52294. var count = data[i++];
  52295. // Offset
  52296. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset;
  52297. // Len
  52298. coordsOffsetAndLenStorage[offsetCursor++] = count;
  52299. for (var k = 0; k < count; k++) {
  52300. var x = data[i++];
  52301. var y = data[i++];
  52302. coordsStorage[coordsCursor++] = x;
  52303. coordsStorage[coordsCursor++] = y;
  52304. if (i > len) {
  52305. if (__DEV__) {
  52306. throw new Error('Invalid data format.');
  52307. }
  52308. }
  52309. }
  52310. }
  52311. return {
  52312. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  52313. flatCoords: coordsStorage,
  52314. count: dataCount
  52315. };
  52316. }
  52317. return {
  52318. flatCoordsOffset: null,
  52319. flatCoords: null,
  52320. count: data.length
  52321. };
  52322. },
  52323. getInitialData: function (option, ecModel) {
  52324. if (__DEV__) {
  52325. var CoordSys = CoordinateSystemManager.get(option.coordinateSystem);
  52326. if (!CoordSys) {
  52327. throw new Error('Unkown coordinate system ' + option.coordinateSystem);
  52328. }
  52329. }
  52330. var lineData = new List(['value'], this);
  52331. lineData.hasItemOption = false;
  52332. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  52333. // dataItem is simply coords
  52334. if (dataItem instanceof Array) {
  52335. return NaN;
  52336. }
  52337. else {
  52338. lineData.hasItemOption = true;
  52339. var value = dataItem.value;
  52340. if (value != null) {
  52341. return value instanceof Array ? value[dimIndex] : value;
  52342. }
  52343. }
  52344. });
  52345. return lineData;
  52346. },
  52347. formatTooltip: function (dataIndex) {
  52348. var data = this.getData();
  52349. var itemModel = data.getItemModel(dataIndex);
  52350. var name = itemModel.get('name');
  52351. if (name) {
  52352. return name;
  52353. }
  52354. var fromName = itemModel.get('fromName');
  52355. var toName = itemModel.get('toName');
  52356. var html = [];
  52357. fromName != null && html.push(fromName);
  52358. toName != null && html.push(toName);
  52359. return encodeHTML(html.join(' > '));
  52360. },
  52361. preventIncremental: function () {
  52362. return !!this.get('effect.show');
  52363. },
  52364. getProgressive: function () {
  52365. var progressive = this.option.progressive;
  52366. if (progressive == null) {
  52367. return this.option.large ? 1e4 : this.get('progressive');
  52368. }
  52369. return progressive;
  52370. },
  52371. getProgressiveThreshold: function () {
  52372. var progressiveThreshold = this.option.progressiveThreshold;
  52373. if (progressiveThreshold == null) {
  52374. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  52375. }
  52376. return progressiveThreshold;
  52377. },
  52378. defaultOption: {
  52379. coordinateSystem: 'geo',
  52380. zlevel: 0,
  52381. z: 2,
  52382. legendHoverLink: true,
  52383. hoverAnimation: true,
  52384. // Cartesian coordinate system
  52385. xAxisIndex: 0,
  52386. yAxisIndex: 0,
  52387. symbol: ['none', 'none'],
  52388. symbolSize: [10, 10],
  52389. // Geo coordinate system
  52390. geoIndex: 0,
  52391. effect: {
  52392. show: false,
  52393. period: 4,
  52394. // Animation delay. support callback
  52395. // delay: 0,
  52396. // If move with constant speed px/sec
  52397. // period will be ignored if this property is > 0,
  52398. constantSpeed: 0,
  52399. symbol: 'circle',
  52400. symbolSize: 3,
  52401. loop: true,
  52402. // Length of trail, 0 - 1
  52403. trailLength: 0.2
  52404. // Same with lineStyle.color
  52405. // color
  52406. },
  52407. large: false,
  52408. // Available when large is true
  52409. largeThreshold: 2000,
  52410. // If lines are polyline
  52411. // polyline not support curveness, label, animation
  52412. polyline: false,
  52413. label: {
  52414. show: false,
  52415. position: 'end'
  52416. // distance: 5,
  52417. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  52418. },
  52419. lineStyle: {
  52420. opacity: 0.5
  52421. }
  52422. }
  52423. });
  52424. /*
  52425. * Licensed to the Apache Software Foundation (ASF) under one
  52426. * or more contributor license agreements. See the NOTICE file
  52427. * distributed with this work for additional information
  52428. * regarding copyright ownership. The ASF licenses this file
  52429. * to you under the Apache License, Version 2.0 (the
  52430. * "License"); you may not use this file except in compliance
  52431. * with the License. You may obtain a copy of the License at
  52432. *
  52433. * http://www.apache.org/licenses/LICENSE-2.0
  52434. *
  52435. * Unless required by applicable law or agreed to in writing,
  52436. * software distributed under the License is distributed on an
  52437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52438. * KIND, either express or implied. See the License for the
  52439. * specific language governing permissions and limitations
  52440. * under the License.
  52441. */
  52442. /**
  52443. * Provide effect for line
  52444. * @module echarts/chart/helper/EffectLine
  52445. */
  52446. /**
  52447. * @constructor
  52448. * @extends {module:zrender/graphic/Group}
  52449. * @alias {module:echarts/chart/helper/Line}
  52450. */
  52451. function EffectLine(lineData, idx, seriesScope) {
  52452. Group.call(this);
  52453. this.add(this.createLine(lineData, idx, seriesScope));
  52454. this._updateEffectSymbol(lineData, idx);
  52455. }
  52456. var effectLineProto = EffectLine.prototype;
  52457. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  52458. return new Line$1(lineData, idx, seriesScope);
  52459. };
  52460. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  52461. var itemModel = lineData.getItemModel(idx);
  52462. var effectModel = itemModel.getModel('effect');
  52463. var size = effectModel.get('symbolSize');
  52464. var symbolType = effectModel.get('symbol');
  52465. if (!isArray(size)) {
  52466. size = [size, size];
  52467. }
  52468. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  52469. var symbol = this.childAt(1);
  52470. if (this._symbolType !== symbolType) {
  52471. // Remove previous
  52472. this.remove(symbol);
  52473. symbol = createSymbol(
  52474. symbolType, -0.5, -0.5, 1, 1, color
  52475. );
  52476. symbol.z2 = 100;
  52477. symbol.culling = true;
  52478. this.add(symbol);
  52479. }
  52480. // Symbol may be removed if loop is false
  52481. if (!symbol) {
  52482. return;
  52483. }
  52484. // Shadow color is same with color in default
  52485. symbol.setStyle('shadowColor', color);
  52486. symbol.setStyle(effectModel.getItemStyle(['color']));
  52487. symbol.attr('scale', size);
  52488. symbol.setColor(color);
  52489. symbol.attr('scale', size);
  52490. this._symbolType = symbolType;
  52491. this._updateEffectAnimation(lineData, effectModel, idx);
  52492. };
  52493. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  52494. var symbol = this.childAt(1);
  52495. if (!symbol) {
  52496. return;
  52497. }
  52498. var self = this;
  52499. var points = lineData.getItemLayout(idx);
  52500. var period = effectModel.get('period') * 1000;
  52501. var loop = effectModel.get('loop');
  52502. var constantSpeed = effectModel.get('constantSpeed');
  52503. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  52504. return idx / lineData.count() * period / 3;
  52505. });
  52506. var isDelayFunc = typeof delayExpr === 'function';
  52507. // Ignore when updating
  52508. symbol.ignore = true;
  52509. this.updateAnimationPoints(symbol, points);
  52510. if (constantSpeed > 0) {
  52511. period = this.getLineLength(symbol) / constantSpeed * 1000;
  52512. }
  52513. if (period !== this._period || loop !== this._loop) {
  52514. symbol.stopAnimation();
  52515. var delay = delayExpr;
  52516. if (isDelayFunc) {
  52517. delay = delayExpr(idx);
  52518. }
  52519. if (symbol.__t > 0) {
  52520. delay = -period * symbol.__t;
  52521. }
  52522. symbol.__t = 0;
  52523. var animator = symbol.animate('', loop)
  52524. .when(period, {
  52525. __t: 1
  52526. })
  52527. .delay(delay)
  52528. .during(function () {
  52529. self.updateSymbolPosition(symbol);
  52530. });
  52531. if (!loop) {
  52532. animator.done(function () {
  52533. self.remove(symbol);
  52534. });
  52535. }
  52536. animator.start();
  52537. }
  52538. this._period = period;
  52539. this._loop = loop;
  52540. };
  52541. effectLineProto.getLineLength = function (symbol) {
  52542. // Not so accurate
  52543. return (dist(symbol.__p1, symbol.__cp1)
  52544. + dist(symbol.__cp1, symbol.__p2));
  52545. };
  52546. effectLineProto.updateAnimationPoints = function (symbol, points) {
  52547. symbol.__p1 = points[0];
  52548. symbol.__p2 = points[1];
  52549. symbol.__cp1 = points[2] || [
  52550. (points[0][0] + points[1][0]) / 2,
  52551. (points[0][1] + points[1][1]) / 2
  52552. ];
  52553. };
  52554. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  52555. this.childAt(0).updateData(lineData, idx, seriesScope);
  52556. this._updateEffectSymbol(lineData, idx);
  52557. };
  52558. effectLineProto.updateSymbolPosition = function (symbol) {
  52559. var p1 = symbol.__p1;
  52560. var p2 = symbol.__p2;
  52561. var cp1 = symbol.__cp1;
  52562. var t = symbol.__t;
  52563. var pos = symbol.position;
  52564. var quadraticAt$$1 = quadraticAt;
  52565. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  52566. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  52567. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t);
  52568. // Tangent
  52569. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  52570. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  52571. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  52572. symbol.ignore = false;
  52573. };
  52574. effectLineProto.updateLayout = function (lineData, idx) {
  52575. this.childAt(0).updateLayout(lineData, idx);
  52576. var effectModel = lineData.getItemModel(idx).getModel('effect');
  52577. this._updateEffectAnimation(lineData, effectModel, idx);
  52578. };
  52579. inherits(EffectLine, Group);
  52580. /*
  52581. * Licensed to the Apache Software Foundation (ASF) under one
  52582. * or more contributor license agreements. See the NOTICE file
  52583. * distributed with this work for additional information
  52584. * regarding copyright ownership. The ASF licenses this file
  52585. * to you under the Apache License, Version 2.0 (the
  52586. * "License"); you may not use this file except in compliance
  52587. * with the License. You may obtain a copy of the License at
  52588. *
  52589. * http://www.apache.org/licenses/LICENSE-2.0
  52590. *
  52591. * Unless required by applicable law or agreed to in writing,
  52592. * software distributed under the License is distributed on an
  52593. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52594. * KIND, either express or implied. See the License for the
  52595. * specific language governing permissions and limitations
  52596. * under the License.
  52597. */
  52598. /**
  52599. * @module echarts/chart/helper/Line
  52600. */
  52601. /**
  52602. * @constructor
  52603. * @extends {module:zrender/graphic/Group}
  52604. * @alias {module:echarts/chart/helper/Polyline}
  52605. */
  52606. function Polyline$2(lineData, idx, seriesScope) {
  52607. Group.call(this);
  52608. this._createPolyline(lineData, idx, seriesScope);
  52609. }
  52610. var polylineProto = Polyline$2.prototype;
  52611. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  52612. // var seriesModel = lineData.hostModel;
  52613. var points = lineData.getItemLayout(idx);
  52614. var line = new Polyline({
  52615. shape: {
  52616. points: points
  52617. }
  52618. });
  52619. this.add(line);
  52620. this._updateCommonStl(lineData, idx, seriesScope);
  52621. };
  52622. polylineProto.updateData = function (lineData, idx, seriesScope) {
  52623. var seriesModel = lineData.hostModel;
  52624. var line = this.childAt(0);
  52625. var target = {
  52626. shape: {
  52627. points: lineData.getItemLayout(idx)
  52628. }
  52629. };
  52630. updateProps(line, target, seriesModel, idx);
  52631. this._updateCommonStl(lineData, idx, seriesScope);
  52632. };
  52633. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  52634. var line = this.childAt(0);
  52635. var itemModel = lineData.getItemModel(idx);
  52636. var visualColor = lineData.getItemVisual(idx, 'color');
  52637. var lineStyle = seriesScope && seriesScope.lineStyle;
  52638. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  52639. if (!seriesScope || lineData.hasItemOption) {
  52640. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  52641. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  52642. }
  52643. line.useStyle(defaults(
  52644. {
  52645. strokeNoScale: true,
  52646. fill: 'none',
  52647. stroke: visualColor
  52648. },
  52649. lineStyle
  52650. ));
  52651. line.hoverStyle = hoverLineStyle;
  52652. setHoverStyle(this);
  52653. };
  52654. polylineProto.updateLayout = function (lineData, idx) {
  52655. var polyline = this.childAt(0);
  52656. polyline.setShape('points', lineData.getItemLayout(idx));
  52657. };
  52658. inherits(Polyline$2, Group);
  52659. /*
  52660. * Licensed to the Apache Software Foundation (ASF) under one
  52661. * or more contributor license agreements. See the NOTICE file
  52662. * distributed with this work for additional information
  52663. * regarding copyright ownership. The ASF licenses this file
  52664. * to you under the Apache License, Version 2.0 (the
  52665. * "License"); you may not use this file except in compliance
  52666. * with the License. You may obtain a copy of the License at
  52667. *
  52668. * http://www.apache.org/licenses/LICENSE-2.0
  52669. *
  52670. * Unless required by applicable law or agreed to in writing,
  52671. * software distributed under the License is distributed on an
  52672. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52673. * KIND, either express or implied. See the License for the
  52674. * specific language governing permissions and limitations
  52675. * under the License.
  52676. */
  52677. /**
  52678. * Provide effect for line
  52679. * @module echarts/chart/helper/EffectLine
  52680. */
  52681. /**
  52682. * @constructor
  52683. * @extends {module:echarts/chart/helper/EffectLine}
  52684. * @alias {module:echarts/chart/helper/Polyline}
  52685. */
  52686. function EffectPolyline(lineData, idx, seriesScope) {
  52687. EffectLine.call(this, lineData, idx, seriesScope);
  52688. this._lastFrame = 0;
  52689. this._lastFramePercent = 0;
  52690. }
  52691. var effectPolylineProto = EffectPolyline.prototype;
  52692. // Overwrite
  52693. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  52694. return new Polyline$2(lineData, idx, seriesScope);
  52695. };
  52696. // Overwrite
  52697. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  52698. this._points = points;
  52699. var accLenArr = [0];
  52700. var len$$1 = 0;
  52701. for (var i = 1; i < points.length; i++) {
  52702. var p1 = points[i - 1];
  52703. var p2 = points[i];
  52704. len$$1 += dist(p1, p2);
  52705. accLenArr.push(len$$1);
  52706. }
  52707. if (len$$1 === 0) {
  52708. return;
  52709. }
  52710. for (var i = 0; i < accLenArr.length; i++) {
  52711. accLenArr[i] /= len$$1;
  52712. }
  52713. this._offsets = accLenArr;
  52714. this._length = len$$1;
  52715. };
  52716. // Overwrite
  52717. effectPolylineProto.getLineLength = function (symbol) {
  52718. return this._length;
  52719. };
  52720. // Overwrite
  52721. effectPolylineProto.updateSymbolPosition = function (symbol) {
  52722. var t = symbol.__t;
  52723. var points = this._points;
  52724. var offsets = this._offsets;
  52725. var len$$1 = points.length;
  52726. if (!offsets) {
  52727. // Has length 0
  52728. return;
  52729. }
  52730. var lastFrame = this._lastFrame;
  52731. var frame;
  52732. if (t < this._lastFramePercent) {
  52733. // Start from the next frame
  52734. // PENDING start from lastFrame ?
  52735. var start = Math.min(lastFrame + 1, len$$1 - 1);
  52736. for (frame = start; frame >= 0; frame--) {
  52737. if (offsets[frame] <= t) {
  52738. break;
  52739. }
  52740. }
  52741. // PENDING really need to do this ?
  52742. frame = Math.min(frame, len$$1 - 2);
  52743. }
  52744. else {
  52745. for (var frame = lastFrame; frame < len$$1; frame++) {
  52746. if (offsets[frame] > t) {
  52747. break;
  52748. }
  52749. }
  52750. frame = Math.min(frame - 1, len$$1 - 2);
  52751. }
  52752. lerp(
  52753. symbol.position, points[frame], points[frame + 1],
  52754. (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame])
  52755. );
  52756. var tx = points[frame + 1][0] - points[frame][0];
  52757. var ty = points[frame + 1][1] - points[frame][1];
  52758. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  52759. this._lastFrame = frame;
  52760. this._lastFramePercent = t;
  52761. symbol.ignore = false;
  52762. };
  52763. inherits(EffectPolyline, EffectLine);
  52764. /*
  52765. * Licensed to the Apache Software Foundation (ASF) under one
  52766. * or more contributor license agreements. See the NOTICE file
  52767. * distributed with this work for additional information
  52768. * regarding copyright ownership. The ASF licenses this file
  52769. * to you under the Apache License, Version 2.0 (the
  52770. * "License"); you may not use this file except in compliance
  52771. * with the License. You may obtain a copy of the License at
  52772. *
  52773. * http://www.apache.org/licenses/LICENSE-2.0
  52774. *
  52775. * Unless required by applicable law or agreed to in writing,
  52776. * software distributed under the License is distributed on an
  52777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52778. * KIND, either express or implied. See the License for the
  52779. * specific language governing permissions and limitations
  52780. * under the License.
  52781. */
  52782. // TODO Batch by color
  52783. var LargeLineShape = extendShape({
  52784. shape: {
  52785. polyline: false,
  52786. curveness: 0,
  52787. segs: []
  52788. },
  52789. buildPath: function (path, shape) {
  52790. var segs = shape.segs;
  52791. var curveness = shape.curveness;
  52792. if (shape.polyline) {
  52793. for (var i = 0; i < segs.length;) {
  52794. var count = segs[i++];
  52795. if (count > 0) {
  52796. path.moveTo(segs[i++], segs[i++]);
  52797. for (var k = 1; k < count; k++) {
  52798. path.lineTo(segs[i++], segs[i++]);
  52799. }
  52800. }
  52801. }
  52802. }
  52803. else {
  52804. for (var i = 0; i < segs.length;) {
  52805. var x0 = segs[i++];
  52806. var y0 = segs[i++];
  52807. var x1 = segs[i++];
  52808. var y1 = segs[i++];
  52809. path.moveTo(x0, y0);
  52810. if (curveness > 0) {
  52811. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  52812. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  52813. path.quadraticCurveTo(x2, y2, x1, y1);
  52814. }
  52815. else {
  52816. path.lineTo(x1, y1);
  52817. }
  52818. }
  52819. }
  52820. },
  52821. findDataIndex: function (x, y) {
  52822. var shape = this.shape;
  52823. var segs = shape.segs;
  52824. var curveness = shape.curveness;
  52825. if (shape.polyline) {
  52826. var dataIndex = 0;
  52827. for (var i = 0; i < segs.length;) {
  52828. var count = segs[i++];
  52829. if (count > 0) {
  52830. var x0 = segs[i++];
  52831. var y0 = segs[i++];
  52832. for (var k = 1; k < count; k++) {
  52833. var x1 = segs[i++];
  52834. var y1 = segs[i++];
  52835. if (containStroke$1(x0, y0, x1, y1)) {
  52836. return dataIndex;
  52837. }
  52838. }
  52839. }
  52840. dataIndex++;
  52841. }
  52842. }
  52843. else {
  52844. var dataIndex = 0;
  52845. for (var i = 0; i < segs.length;) {
  52846. var x0 = segs[i++];
  52847. var y0 = segs[i++];
  52848. var x1 = segs[i++];
  52849. var y1 = segs[i++];
  52850. if (curveness > 0) {
  52851. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  52852. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  52853. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  52854. return dataIndex;
  52855. }
  52856. }
  52857. else {
  52858. if (containStroke$1(x0, y0, x1, y1)) {
  52859. return dataIndex;
  52860. }
  52861. }
  52862. dataIndex++;
  52863. }
  52864. }
  52865. return -1;
  52866. }
  52867. });
  52868. function LargeLineDraw() {
  52869. this.group = new Group();
  52870. }
  52871. var largeLineProto = LargeLineDraw.prototype;
  52872. largeLineProto.isPersistent = function () {
  52873. return !this._incremental;
  52874. };
  52875. /**
  52876. * Update symbols draw by new data
  52877. * @param {module:echarts/data/List} data
  52878. */
  52879. largeLineProto.updateData = function (data) {
  52880. this.group.removeAll();
  52881. var lineEl = new LargeLineShape({
  52882. rectHover: true,
  52883. cursor: 'default'
  52884. });
  52885. lineEl.setShape({
  52886. segs: data.getLayout('linesPoints')
  52887. });
  52888. this._setCommon(lineEl, data);
  52889. // Add back
  52890. this.group.add(lineEl);
  52891. this._incremental = null;
  52892. };
  52893. /**
  52894. * @override
  52895. */
  52896. largeLineProto.incrementalPrepareUpdate = function (data) {
  52897. this.group.removeAll();
  52898. this._clearIncremental();
  52899. if (data.count() > 5e5) {
  52900. if (!this._incremental) {
  52901. this._incremental = new IncrementalDisplayble({
  52902. silent: true
  52903. });
  52904. }
  52905. this.group.add(this._incremental);
  52906. }
  52907. else {
  52908. this._incremental = null;
  52909. }
  52910. };
  52911. /**
  52912. * @override
  52913. */
  52914. largeLineProto.incrementalUpdate = function (taskParams, data) {
  52915. var lineEl = new LargeLineShape();
  52916. lineEl.setShape({
  52917. segs: data.getLayout('linesPoints')
  52918. });
  52919. this._setCommon(lineEl, data, !!this._incremental);
  52920. if (!this._incremental) {
  52921. lineEl.rectHover = true;
  52922. lineEl.cursor = 'default';
  52923. lineEl.__startIndex = taskParams.start;
  52924. this.group.add(lineEl);
  52925. }
  52926. else {
  52927. this._incremental.addDisplayable(lineEl, true);
  52928. }
  52929. };
  52930. /**
  52931. * @override
  52932. */
  52933. largeLineProto.remove = function () {
  52934. this._clearIncremental();
  52935. this._incremental = null;
  52936. this.group.removeAll();
  52937. };
  52938. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  52939. var hostModel = data.hostModel;
  52940. lineEl.setShape({
  52941. polyline: hostModel.get('polyline'),
  52942. curveness: hostModel.get('lineStyle.curveness')
  52943. });
  52944. lineEl.useStyle(
  52945. hostModel.getModel('lineStyle').getLineStyle()
  52946. );
  52947. lineEl.style.strokeNoScale = true;
  52948. var visualColor = data.getVisual('color');
  52949. if (visualColor) {
  52950. lineEl.setStyle('stroke', visualColor);
  52951. }
  52952. lineEl.setStyle('fill');
  52953. if (!isIncremental) {
  52954. // Enable tooltip
  52955. // PENDING May have performance issue when path is extremely large
  52956. lineEl.seriesIndex = hostModel.seriesIndex;
  52957. lineEl.on('mousemove', function (e) {
  52958. lineEl.dataIndex = null;
  52959. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  52960. if (dataIndex > 0) {
  52961. // Provide dataIndex for tooltip
  52962. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  52963. }
  52964. });
  52965. }
  52966. };
  52967. largeLineProto._clearIncremental = function () {
  52968. var incremental = this._incremental;
  52969. if (incremental) {
  52970. incremental.clearDisplaybles();
  52971. }
  52972. };
  52973. /*
  52974. * Licensed to the Apache Software Foundation (ASF) under one
  52975. * or more contributor license agreements. See the NOTICE file
  52976. * distributed with this work for additional information
  52977. * regarding copyright ownership. The ASF licenses this file
  52978. * to you under the Apache License, Version 2.0 (the
  52979. * "License"); you may not use this file except in compliance
  52980. * with the License. You may obtain a copy of the License at
  52981. *
  52982. * http://www.apache.org/licenses/LICENSE-2.0
  52983. *
  52984. * Unless required by applicable law or agreed to in writing,
  52985. * software distributed under the License is distributed on an
  52986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52987. * KIND, either express or implied. See the License for the
  52988. * specific language governing permissions and limitations
  52989. * under the License.
  52990. */
  52991. var linesLayout = {
  52992. seriesType: 'lines',
  52993. plan: createRenderPlanner(),
  52994. reset: function (seriesModel) {
  52995. var coordSys = seriesModel.coordinateSystem;
  52996. var isPolyline = seriesModel.get('polyline');
  52997. var isLarge = seriesModel.pipelineContext.large;
  52998. function progress(params, lineData) {
  52999. var lineCoords = [];
  53000. if (isLarge) {
  53001. var points;
  53002. var segCount = params.end - params.start;
  53003. if (isPolyline) {
  53004. var totalCoordsCount = 0;
  53005. for (var i = params.start; i < params.end; i++) {
  53006. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  53007. }
  53008. points = new Float32Array(segCount + totalCoordsCount * 2);
  53009. }
  53010. else {
  53011. points = new Float32Array(segCount * 4);
  53012. }
  53013. var offset = 0;
  53014. var pt = [];
  53015. for (var i = params.start; i < params.end; i++) {
  53016. var len = seriesModel.getLineCoords(i, lineCoords);
  53017. if (isPolyline) {
  53018. points[offset++] = len;
  53019. }
  53020. for (var k = 0; k < len; k++) {
  53021. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  53022. points[offset++] = pt[0];
  53023. points[offset++] = pt[1];
  53024. }
  53025. }
  53026. lineData.setLayout('linesPoints', points);
  53027. }
  53028. else {
  53029. for (var i = params.start; i < params.end; i++) {
  53030. var itemModel = lineData.getItemModel(i);
  53031. var len = seriesModel.getLineCoords(i, lineCoords);
  53032. var pts = [];
  53033. if (isPolyline) {
  53034. for (var j = 0; j < len; j++) {
  53035. pts.push(coordSys.dataToPoint(lineCoords[j]));
  53036. }
  53037. }
  53038. else {
  53039. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  53040. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  53041. var curveness = itemModel.get('lineStyle.curveness');
  53042. if (+curveness) {
  53043. pts[2] = [
  53044. (pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness,
  53045. (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness
  53046. ];
  53047. }
  53048. }
  53049. lineData.setItemLayout(i, pts);
  53050. }
  53051. }
  53052. }
  53053. return { progress: progress };
  53054. }
  53055. };
  53056. /*
  53057. * Licensed to the Apache Software Foundation (ASF) under one
  53058. * or more contributor license agreements. See the NOTICE file
  53059. * distributed with this work for additional information
  53060. * regarding copyright ownership. The ASF licenses this file
  53061. * to you under the Apache License, Version 2.0 (the
  53062. * "License"); you may not use this file except in compliance
  53063. * with the License. You may obtain a copy of the License at
  53064. *
  53065. * http://www.apache.org/licenses/LICENSE-2.0
  53066. *
  53067. * Unless required by applicable law or agreed to in writing,
  53068. * software distributed under the License is distributed on an
  53069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53070. * KIND, either express or implied. See the License for the
  53071. * specific language governing permissions and limitations
  53072. * under the License.
  53073. */
  53074. extendChartView({
  53075. type: 'lines',
  53076. init: function () {},
  53077. render: function (seriesModel, ecModel, api) {
  53078. var data = seriesModel.getData();
  53079. var lineDraw = this._updateLineDraw(data, seriesModel);
  53080. var zlevel = seriesModel.get('zlevel');
  53081. var trailLength = seriesModel.get('effect.trailLength');
  53082. var zr = api.getZr();
  53083. // Avoid the drag cause ghost shadow
  53084. // FIXME Better way ?
  53085. // SVG doesn't support
  53086. var isSvg = zr.painter.getType() === 'svg';
  53087. if (!isSvg) {
  53088. zr.painter.getLayer(zlevel).clear(true);
  53089. }
  53090. // Config layer with motion blur
  53091. if (this._lastZlevel != null && !isSvg) {
  53092. zr.configLayer(this._lastZlevel, {
  53093. motionBlur: false
  53094. });
  53095. }
  53096. if (this._showEffect(seriesModel) && trailLength) {
  53097. if (__DEV__) {
  53098. var notInIndividual = false;
  53099. ecModel.eachSeries(function (otherSeriesModel) {
  53100. if (otherSeriesModel !== seriesModel && otherSeriesModel.get('zlevel') === zlevel) {
  53101. notInIndividual = true;
  53102. }
  53103. });
  53104. notInIndividual && console.warn('Lines with trail effect should have an individual zlevel');
  53105. }
  53106. if (!isSvg) {
  53107. zr.configLayer(zlevel, {
  53108. motionBlur: true,
  53109. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  53110. });
  53111. }
  53112. }
  53113. lineDraw.updateData(data);
  53114. this._lastZlevel = zlevel;
  53115. this._finished = true;
  53116. },
  53117. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53118. var data = seriesModel.getData();
  53119. var lineDraw = this._updateLineDraw(data, seriesModel);
  53120. lineDraw.incrementalPrepareUpdate(data);
  53121. this._clearLayer(api);
  53122. this._finished = false;
  53123. },
  53124. incrementalRender: function (taskParams, seriesModel, ecModel) {
  53125. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  53126. this._finished = taskParams.end === seriesModel.getData().count();
  53127. },
  53128. updateTransform: function (seriesModel, ecModel, api) {
  53129. var data = seriesModel.getData();
  53130. var pipelineContext = seriesModel.pipelineContext;
  53131. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  53132. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  53133. return {
  53134. update: true
  53135. };
  53136. }
  53137. else {
  53138. // TODO Use same logic with ScatterView.
  53139. // Manually update layout
  53140. var res = linesLayout.reset(seriesModel);
  53141. if (res.progress) {
  53142. res.progress({ start: 0, end: data.count() }, data);
  53143. }
  53144. this._lineDraw.updateLayout();
  53145. this._clearLayer(api);
  53146. }
  53147. },
  53148. _updateLineDraw: function (data, seriesModel) {
  53149. var lineDraw = this._lineDraw;
  53150. var hasEffect = this._showEffect(seriesModel);
  53151. var isPolyline = !!seriesModel.get('polyline');
  53152. var pipelineContext = seriesModel.pipelineContext;
  53153. var isLargeDraw = pipelineContext.large;
  53154. if (__DEV__) {
  53155. if (hasEffect && isLargeDraw) {
  53156. console.warn('Large lines not support effect');
  53157. }
  53158. }
  53159. if (!lineDraw
  53160. || hasEffect !== this._hasEffet
  53161. || isPolyline !== this._isPolyline
  53162. || isLargeDraw !== this._isLargeDraw
  53163. ) {
  53164. if (lineDraw) {
  53165. lineDraw.remove();
  53166. }
  53167. lineDraw = this._lineDraw = isLargeDraw
  53168. ? new LargeLineDraw()
  53169. : new LineDraw(
  53170. isPolyline
  53171. ? (hasEffect ? EffectPolyline : Polyline$2)
  53172. : (hasEffect ? EffectLine : Line$1)
  53173. );
  53174. this._hasEffet = hasEffect;
  53175. this._isPolyline = isPolyline;
  53176. this._isLargeDraw = isLargeDraw;
  53177. this.group.removeAll();
  53178. }
  53179. this.group.add(lineDraw.group);
  53180. return lineDraw;
  53181. },
  53182. _showEffect: function (seriesModel) {
  53183. return !!seriesModel.get('effect.show');
  53184. },
  53185. _clearLayer: function (api) {
  53186. // Not use motion when dragging or zooming
  53187. var zr = api.getZr();
  53188. var isSvg = zr.painter.getType() === 'svg';
  53189. if (!isSvg && this._lastZlevel != null) {
  53190. zr.painter.getLayer(this._lastZlevel).clear(true);
  53191. }
  53192. },
  53193. remove: function (ecModel, api) {
  53194. this._lineDraw && this._lineDraw.remove();
  53195. this._lineDraw = null;
  53196. // Clear motion when lineDraw is removed
  53197. this._clearLayer(api);
  53198. },
  53199. dispose: function () {}
  53200. });
  53201. /*
  53202. * Licensed to the Apache Software Foundation (ASF) under one
  53203. * or more contributor license agreements. See the NOTICE file
  53204. * distributed with this work for additional information
  53205. * regarding copyright ownership. The ASF licenses this file
  53206. * to you under the Apache License, Version 2.0 (the
  53207. * "License"); you may not use this file except in compliance
  53208. * with the License. You may obtain a copy of the License at
  53209. *
  53210. * http://www.apache.org/licenses/LICENSE-2.0
  53211. *
  53212. * Unless required by applicable law or agreed to in writing,
  53213. * software distributed under the License is distributed on an
  53214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53215. * KIND, either express or implied. See the License for the
  53216. * specific language governing permissions and limitations
  53217. * under the License.
  53218. */
  53219. function normalize$2(a) {
  53220. if (!(a instanceof Array)) {
  53221. a = [a, a];
  53222. }
  53223. return a;
  53224. }
  53225. var opacityQuery = 'lineStyle.opacity'.split('.');
  53226. var linesVisual = {
  53227. seriesType: 'lines',
  53228. reset: function (seriesModel, ecModel, api) {
  53229. var symbolType = normalize$2(seriesModel.get('symbol'));
  53230. var symbolSize = normalize$2(seriesModel.get('symbolSize'));
  53231. var data = seriesModel.getData();
  53232. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  53233. data.setVisual('toSymbol', symbolType && symbolType[1]);
  53234. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  53235. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  53236. data.setVisual('opacity', seriesModel.get(opacityQuery));
  53237. function dataEach(data, idx) {
  53238. var itemModel = data.getItemModel(idx);
  53239. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  53240. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true));
  53241. var opacity = itemModel.get(opacityQuery);
  53242. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  53243. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  53244. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  53245. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  53246. data.setItemVisual(idx, 'opacity', opacity);
  53247. }
  53248. return {dataEach: data.hasItemOption ? dataEach : null};
  53249. }
  53250. };
  53251. /*
  53252. * Licensed to the Apache Software Foundation (ASF) under one
  53253. * or more contributor license agreements. See the NOTICE file
  53254. * distributed with this work for additional information
  53255. * regarding copyright ownership. The ASF licenses this file
  53256. * to you under the Apache License, Version 2.0 (the
  53257. * "License"); you may not use this file except in compliance
  53258. * with the License. You may obtain a copy of the License at
  53259. *
  53260. * http://www.apache.org/licenses/LICENSE-2.0
  53261. *
  53262. * Unless required by applicable law or agreed to in writing,
  53263. * software distributed under the License is distributed on an
  53264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53265. * KIND, either express or implied. See the License for the
  53266. * specific language governing permissions and limitations
  53267. * under the License.
  53268. */
  53269. registerLayout(linesLayout);
  53270. registerVisual(linesVisual);
  53271. /*
  53272. * Licensed to the Apache Software Foundation (ASF) under one
  53273. * or more contributor license agreements. See the NOTICE file
  53274. * distributed with this work for additional information
  53275. * regarding copyright ownership. The ASF licenses this file
  53276. * to you under the Apache License, Version 2.0 (the
  53277. * "License"); you may not use this file except in compliance
  53278. * with the License. You may obtain a copy of the License at
  53279. *
  53280. * http://www.apache.org/licenses/LICENSE-2.0
  53281. *
  53282. * Unless required by applicable law or agreed to in writing,
  53283. * software distributed under the License is distributed on an
  53284. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53285. * KIND, either express or implied. See the License for the
  53286. * specific language governing permissions and limitations
  53287. * under the License.
  53288. */
  53289. SeriesModel.extend({
  53290. type: 'series.heatmap',
  53291. getInitialData: function (option, ecModel) {
  53292. return createListFromArray(this.getSource(), this, {
  53293. generateCoord: 'value'
  53294. });
  53295. },
  53296. preventIncremental: function () {
  53297. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  53298. if (coordSysCreator && coordSysCreator.dimensions) {
  53299. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  53300. }
  53301. },
  53302. defaultOption: {
  53303. // Cartesian2D or geo
  53304. coordinateSystem: 'cartesian2d',
  53305. zlevel: 0,
  53306. z: 2,
  53307. // Cartesian coordinate system
  53308. // xAxisIndex: 0,
  53309. // yAxisIndex: 0,
  53310. // Geo coordinate system
  53311. geoIndex: 0,
  53312. blurSize: 30,
  53313. pointSize: 20,
  53314. maxOpacity: 1,
  53315. minOpacity: 0
  53316. }
  53317. });
  53318. /*
  53319. * Licensed to the Apache Software Foundation (ASF) under one
  53320. * or more contributor license agreements. See the NOTICE file
  53321. * distributed with this work for additional information
  53322. * regarding copyright ownership. The ASF licenses this file
  53323. * to you under the Apache License, Version 2.0 (the
  53324. * "License"); you may not use this file except in compliance
  53325. * with the License. You may obtain a copy of the License at
  53326. *
  53327. * http://www.apache.org/licenses/LICENSE-2.0
  53328. *
  53329. * Unless required by applicable law or agreed to in writing,
  53330. * software distributed under the License is distributed on an
  53331. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53332. * KIND, either express or implied. See the License for the
  53333. * specific language governing permissions and limitations
  53334. * under the License.
  53335. */
  53336. /**
  53337. * @file defines echarts Heatmap Chart
  53338. * @author Ovilia (me@zhangwenli.com)
  53339. * Inspired by https://github.com/mourner/simpleheat
  53340. *
  53341. * @module
  53342. */
  53343. var GRADIENT_LEVELS = 256;
  53344. /**
  53345. * Heatmap Chart
  53346. *
  53347. * @class
  53348. */
  53349. function Heatmap() {
  53350. var canvas = createCanvas();
  53351. this.canvas = canvas;
  53352. this.blurSize = 30;
  53353. this.pointSize = 20;
  53354. this.maxOpacity = 1;
  53355. this.minOpacity = 0;
  53356. this._gradientPixels = {};
  53357. }
  53358. Heatmap.prototype = {
  53359. /**
  53360. * Renders Heatmap and returns the rendered canvas
  53361. * @param {Array} data array of data, each has x, y, value
  53362. * @param {number} width canvas width
  53363. * @param {number} height canvas height
  53364. */
  53365. update: function(data, width, height, normalize, colorFunc, isInRange) {
  53366. var brush = this._getBrush();
  53367. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  53368. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  53369. var r = this.pointSize + this.blurSize;
  53370. var canvas = this.canvas;
  53371. var ctx = canvas.getContext('2d');
  53372. var len = data.length;
  53373. canvas.width = width;
  53374. canvas.height = height;
  53375. for (var i = 0; i < len; ++i) {
  53376. var p = data[i];
  53377. var x = p[0];
  53378. var y = p[1];
  53379. var value = p[2];
  53380. // calculate alpha using value
  53381. var alpha = normalize(value);
  53382. // draw with the circle brush with alpha
  53383. ctx.globalAlpha = alpha;
  53384. ctx.drawImage(brush, x - r, y - r);
  53385. }
  53386. if (!canvas.width || !canvas.height) {
  53387. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  53388. // 'CanvasRenderingContext2D': The source height is 0."
  53389. return canvas;
  53390. }
  53391. // colorize the canvas using alpha value and set with gradient
  53392. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  53393. var pixels = imageData.data;
  53394. var offset = 0;
  53395. var pixelLen = pixels.length;
  53396. var minOpacity = this.minOpacity;
  53397. var maxOpacity = this.maxOpacity;
  53398. var diffOpacity = maxOpacity - minOpacity;
  53399. while(offset < pixelLen) {
  53400. var alpha = pixels[offset + 3] / 256;
  53401. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4;
  53402. // Simple optimize to ignore the empty data
  53403. if (alpha > 0) {
  53404. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange;
  53405. // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  53406. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  53407. pixels[offset++] = gradient[gradientOffset];
  53408. pixels[offset++] = gradient[gradientOffset + 1];
  53409. pixels[offset++] = gradient[gradientOffset + 2];
  53410. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  53411. }
  53412. else {
  53413. offset += 4;
  53414. }
  53415. }
  53416. ctx.putImageData(imageData, 0, 0);
  53417. return canvas;
  53418. },
  53419. /**
  53420. * get canvas of a black circle brush used for canvas to draw later
  53421. * @private
  53422. * @returns {Object} circle brush canvas
  53423. */
  53424. _getBrush: function() {
  53425. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas());
  53426. // set brush size
  53427. var r = this.pointSize + this.blurSize;
  53428. var d = r * 2;
  53429. brushCanvas.width = d;
  53430. brushCanvas.height = d;
  53431. var ctx = brushCanvas.getContext('2d');
  53432. ctx.clearRect(0, 0, d, d);
  53433. // in order to render shadow without the distinct circle,
  53434. // draw the distinct circle in an invisible place,
  53435. // and use shadowOffset to draw shadow in the center of the canvas
  53436. ctx.shadowOffsetX = d;
  53437. ctx.shadowBlur = this.blurSize;
  53438. // draw the shadow in black, and use alpha and shadow blur to generate
  53439. // color in color map
  53440. ctx.shadowColor = '#000';
  53441. // draw circle in the left to the canvas
  53442. ctx.beginPath();
  53443. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  53444. ctx.closePath();
  53445. ctx.fill();
  53446. return brushCanvas;
  53447. },
  53448. /**
  53449. * get gradient color map
  53450. * @private
  53451. */
  53452. _getGradient: function (data, colorFunc, state) {
  53453. var gradientPixels = this._gradientPixels;
  53454. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  53455. var color = [0, 0, 0, 0];
  53456. var off = 0;
  53457. for (var i = 0; i < 256; i++) {
  53458. colorFunc[state](i / 255, true, color);
  53459. pixelsSingleState[off++] = color[0];
  53460. pixelsSingleState[off++] = color[1];
  53461. pixelsSingleState[off++] = color[2];
  53462. pixelsSingleState[off++] = color[3];
  53463. }
  53464. return pixelsSingleState;
  53465. }
  53466. };
  53467. /*
  53468. * Licensed to the Apache Software Foundation (ASF) under one
  53469. * or more contributor license agreements. See the NOTICE file
  53470. * distributed with this work for additional information
  53471. * regarding copyright ownership. The ASF licenses this file
  53472. * to you under the Apache License, Version 2.0 (the
  53473. * "License"); you may not use this file except in compliance
  53474. * with the License. You may obtain a copy of the License at
  53475. *
  53476. * http://www.apache.org/licenses/LICENSE-2.0
  53477. *
  53478. * Unless required by applicable law or agreed to in writing,
  53479. * software distributed under the License is distributed on an
  53480. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53481. * KIND, either express or implied. See the License for the
  53482. * specific language governing permissions and limitations
  53483. * under the License.
  53484. */
  53485. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  53486. var dataSpan = dataExtent[1] - dataExtent[0];
  53487. pieceList = map(pieceList, function (piece) {
  53488. return {
  53489. interval: [
  53490. (piece.interval[0] - dataExtent[0]) / dataSpan,
  53491. (piece.interval[1] - dataExtent[0]) / dataSpan
  53492. ]
  53493. };
  53494. });
  53495. var len = pieceList.length;
  53496. var lastIndex = 0;
  53497. return function (val) {
  53498. // Try to find in the location of the last found
  53499. for (var i = lastIndex; i < len; i++) {
  53500. var interval = pieceList[i].interval;
  53501. if (interval[0] <= val && val <= interval[1]) {
  53502. lastIndex = i;
  53503. break;
  53504. }
  53505. }
  53506. if (i === len) { // Not found, back interation
  53507. for (var i = lastIndex - 1; i >= 0; i--) {
  53508. var interval = pieceList[i].interval;
  53509. if (interval[0] <= val && val <= interval[1]) {
  53510. lastIndex = i;
  53511. break;
  53512. }
  53513. }
  53514. }
  53515. return i >= 0 && i < len && selected[i];
  53516. };
  53517. }
  53518. function getIsInContinuousRange(dataExtent, range) {
  53519. var dataSpan = dataExtent[1] - dataExtent[0];
  53520. range = [
  53521. (range[0] - dataExtent[0]) / dataSpan,
  53522. (range[1] - dataExtent[0]) / dataSpan
  53523. ];
  53524. return function (val) {
  53525. return val >= range[0] && val <= range[1];
  53526. };
  53527. }
  53528. function isGeoCoordSys(coordSys) {
  53529. var dimensions = coordSys.dimensions;
  53530. // Not use coorSys.type === 'geo' because coordSys maybe extended
  53531. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  53532. }
  53533. extendChartView({
  53534. type: 'heatmap',
  53535. render: function (seriesModel, ecModel, api) {
  53536. var visualMapOfThisSeries;
  53537. ecModel.eachComponent('visualMap', function (visualMap) {
  53538. visualMap.eachTargetSeries(function (targetSeries) {
  53539. if (targetSeries === seriesModel) {
  53540. visualMapOfThisSeries = visualMap;
  53541. }
  53542. });
  53543. });
  53544. if (__DEV__) {
  53545. if (!visualMapOfThisSeries) {
  53546. throw new Error('Heatmap must use with visualMap');
  53547. }
  53548. }
  53549. this.group.removeAll();
  53550. this._incrementalDisplayable = null;
  53551. var coordSys = seriesModel.coordinateSystem;
  53552. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  53553. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  53554. }
  53555. else if (isGeoCoordSys(coordSys)) {
  53556. this._renderOnGeo(
  53557. coordSys, seriesModel, visualMapOfThisSeries, api
  53558. );
  53559. }
  53560. },
  53561. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53562. this.group.removeAll();
  53563. },
  53564. incrementalRender: function (params, seriesModel, ecModel, api) {
  53565. var coordSys = seriesModel.coordinateSystem;
  53566. if (coordSys) {
  53567. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  53568. }
  53569. },
  53570. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  53571. var coordSys = seriesModel.coordinateSystem;
  53572. var width;
  53573. var height;
  53574. if (coordSys.type === 'cartesian2d') {
  53575. var xAxis = coordSys.getAxis('x');
  53576. var yAxis = coordSys.getAxis('y');
  53577. if (__DEV__) {
  53578. if (!(xAxis.type === 'category' && yAxis.type === 'category')) {
  53579. throw new Error('Heatmap on cartesian must have two category axes');
  53580. }
  53581. if (!(xAxis.onBand && yAxis.onBand)) {
  53582. throw new Error('Heatmap on cartesian must have two axes with boundaryGap true');
  53583. }
  53584. }
  53585. width = xAxis.getBandWidth();
  53586. height = yAxis.getBandWidth();
  53587. }
  53588. var group = this.group;
  53589. var data = seriesModel.getData();
  53590. var itemStyleQuery = 'itemStyle';
  53591. var hoverItemStyleQuery = 'emphasis.itemStyle';
  53592. var labelQuery = 'label';
  53593. var hoverLabelQuery = 'emphasis.label';
  53594. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  53595. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  53596. var labelModel = seriesModel.getModel(labelQuery);
  53597. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  53598. var coordSysType = coordSys.type;
  53599. var dataDims = coordSysType === 'cartesian2d'
  53600. ? [
  53601. data.mapDimension('x'),
  53602. data.mapDimension('y'),
  53603. data.mapDimension('value')
  53604. ]
  53605. : [
  53606. data.mapDimension('time'),
  53607. data.mapDimension('value')
  53608. ];
  53609. for (var idx = start; idx < end; idx++) {
  53610. var rect;
  53611. if (coordSysType === 'cartesian2d') {
  53612. // Ignore empty data
  53613. if (isNaN(data.get(dataDims[2], idx))) {
  53614. continue;
  53615. }
  53616. var point = coordSys.dataToPoint([
  53617. data.get(dataDims[0], idx),
  53618. data.get(dataDims[1], idx)
  53619. ]);
  53620. rect = new Rect({
  53621. shape: {
  53622. x: point[0] - width / 2,
  53623. y: point[1] - height / 2,
  53624. width: width,
  53625. height: height
  53626. },
  53627. style: {
  53628. fill: data.getItemVisual(idx, 'color'),
  53629. opacity: data.getItemVisual(idx, 'opacity')
  53630. }
  53631. });
  53632. }
  53633. else {
  53634. // Ignore empty data
  53635. if (isNaN(data.get(dataDims[1], idx))) {
  53636. continue;
  53637. }
  53638. rect = new Rect({
  53639. z2: 1,
  53640. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  53641. style: {
  53642. fill: data.getItemVisual(idx, 'color'),
  53643. opacity: data.getItemVisual(idx, 'opacity')
  53644. }
  53645. });
  53646. }
  53647. var itemModel = data.getItemModel(idx);
  53648. // Optimization for large datset
  53649. if (data.hasItemOption) {
  53650. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  53651. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  53652. labelModel = itemModel.getModel(labelQuery);
  53653. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  53654. }
  53655. var rawValue = seriesModel.getRawValue(idx);
  53656. var defaultText = '-';
  53657. if (rawValue && rawValue[2] != null) {
  53658. defaultText = rawValue[2];
  53659. }
  53660. setLabelStyle(
  53661. style, hoverStl, labelModel, hoverLabelModel,
  53662. {
  53663. labelFetcher: seriesModel,
  53664. labelDataIndex: idx,
  53665. defaultText: defaultText,
  53666. isRectText: true
  53667. }
  53668. );
  53669. rect.setStyle(style);
  53670. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  53671. rect.incremental = incremental;
  53672. // PENDING
  53673. if (incremental) {
  53674. // Rect must use hover layer if it's incremental.
  53675. rect.useHoverLayer = true;
  53676. }
  53677. group.add(rect);
  53678. data.setItemGraphicEl(idx, rect);
  53679. }
  53680. },
  53681. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  53682. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  53683. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange;
  53684. // if (!visualMapping) {
  53685. // throw new Error('Data range must have color visuals');
  53686. // }
  53687. var data = seriesModel.getData();
  53688. var hmLayer = this._hmLayer || (this._hmLayer || new Heatmap());
  53689. hmLayer.blurSize = seriesModel.get('blurSize');
  53690. hmLayer.pointSize = seriesModel.get('pointSize');
  53691. hmLayer.minOpacity = seriesModel.get('minOpacity');
  53692. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  53693. var rect = geo.getViewRect().clone();
  53694. var roamTransform = geo.getRoamTransform();
  53695. rect.applyTransform(roamTransform);
  53696. // Clamp on viewport
  53697. var x = Math.max(rect.x, 0);
  53698. var y = Math.max(rect.y, 0);
  53699. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  53700. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  53701. var width = x2 - x;
  53702. var height = y2 - y;
  53703. var dims = [
  53704. data.mapDimension('lng'),
  53705. data.mapDimension('lat'),
  53706. data.mapDimension('value')
  53707. ];
  53708. var points = data.mapArray(dims, function (lng, lat, value) {
  53709. var pt = geo.dataToPoint([lng, lat]);
  53710. pt[0] -= x;
  53711. pt[1] -= y;
  53712. pt.push(value);
  53713. return pt;
  53714. });
  53715. var dataExtent = visualMapModel.getExtent();
  53716. var isInRange = visualMapModel.type === 'visualMap.continuous'
  53717. ? getIsInContinuousRange(dataExtent, visualMapModel.option.range)
  53718. : getIsInPiecewiseRange(
  53719. dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected
  53720. );
  53721. hmLayer.update(
  53722. points, width, height,
  53723. inRangeVisuals.color.getNormalizer(),
  53724. {
  53725. inRange: inRangeVisuals.color.getColorMapper(),
  53726. outOfRange: outOfRangeVisuals.color.getColorMapper()
  53727. },
  53728. isInRange
  53729. );
  53730. var img = new ZImage({
  53731. style: {
  53732. width: width,
  53733. height: height,
  53734. x: x,
  53735. y: y,
  53736. image: hmLayer.canvas
  53737. },
  53738. silent: true
  53739. });
  53740. this.group.add(img);
  53741. },
  53742. dispose: function () {}
  53743. });
  53744. /*
  53745. * Licensed to the Apache Software Foundation (ASF) under one
  53746. * or more contributor license agreements. See the NOTICE file
  53747. * distributed with this work for additional information
  53748. * regarding copyright ownership. The ASF licenses this file
  53749. * to you under the Apache License, Version 2.0 (the
  53750. * "License"); you may not use this file except in compliance
  53751. * with the License. You may obtain a copy of the License at
  53752. *
  53753. * http://www.apache.org/licenses/LICENSE-2.0
  53754. *
  53755. * Unless required by applicable law or agreed to in writing,
  53756. * software distributed under the License is distributed on an
  53757. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53758. * KIND, either express or implied. See the License for the
  53759. * specific language governing permissions and limitations
  53760. * under the License.
  53761. */
  53762. /*
  53763. * Licensed to the Apache Software Foundation (ASF) under one
  53764. * or more contributor license agreements. See the NOTICE file
  53765. * distributed with this work for additional information
  53766. * regarding copyright ownership. The ASF licenses this file
  53767. * to you under the Apache License, Version 2.0 (the
  53768. * "License"); you may not use this file except in compliance
  53769. * with the License. You may obtain a copy of the License at
  53770. *
  53771. * http://www.apache.org/licenses/LICENSE-2.0
  53772. *
  53773. * Unless required by applicable law or agreed to in writing,
  53774. * software distributed under the License is distributed on an
  53775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53776. * KIND, either express or implied. See the License for the
  53777. * specific language governing permissions and limitations
  53778. * under the License.
  53779. */
  53780. var PictorialBarSeries = BaseBarSeries.extend({
  53781. type: 'series.pictorialBar',
  53782. dependencies: ['grid'],
  53783. defaultOption: {
  53784. symbol: 'circle', // Customized bar shape
  53785. symbolSize: null, // Can be ['100%', '100%'], null means auto.
  53786. symbolRotate: null,
  53787. symbolPosition: null, // 'start' or 'end' or 'center', null means auto.
  53788. symbolOffset: null,
  53789. symbolMargin: null, // start margin and end margin. Can be a number or a percent string.
  53790. // Auto margin by defualt.
  53791. symbolRepeat: false, // false/null/undefined, means no repeat.
  53792. // Can be true, means auto calculate repeat times and cut by data.
  53793. // Can be a number, specifies repeat times, and do not cut by data.
  53794. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  53795. symbolRepeatDirection: 'end', // 'end' means from 'start' to 'end'.
  53796. symbolClip: false,
  53797. symbolBoundingData: null, // Can be 60 or -40 or [-40, 60]
  53798. symbolPatternSize: 400, // 400 * 400 px
  53799. barGap: '-100%', // In most case, overlap is needed.
  53800. // z can be set in data item, which is z2 actually.
  53801. // Disable progressive
  53802. progressive: 0,
  53803. hoverAnimation: false // Open only when needed.
  53804. },
  53805. getInitialData: function (option) {
  53806. // Disable stack.
  53807. option.stack = null;
  53808. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  53809. }
  53810. });
  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 BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth'];
  53830. // index: +isHorizontal
  53831. var LAYOUT_ATTRS = [
  53832. {xy: 'x', wh: 'width', index: 0, posDesc: ['left', 'right']},
  53833. {xy: 'y', wh: 'height', index: 1, posDesc: ['top', 'bottom']}
  53834. ];
  53835. var pathForLineWidth = new Circle();
  53836. var BarView$1 = extendChartView({
  53837. type: 'pictorialBar',
  53838. render: function (seriesModel, ecModel, api) {
  53839. var group = this.group;
  53840. var data = seriesModel.getData();
  53841. var oldData = this._data;
  53842. var cartesian = seriesModel.coordinateSystem;
  53843. var baseAxis = cartesian.getBaseAxis();
  53844. var isHorizontal = !!baseAxis.isHorizontal();
  53845. var coordSysRect = cartesian.grid.getRect();
  53846. var opt = {
  53847. ecSize: {width: api.getWidth(), height: api.getHeight()},
  53848. seriesModel: seriesModel,
  53849. coordSys: cartesian,
  53850. coordSysExtent: [
  53851. [coordSysRect.x, coordSysRect.x + coordSysRect.width],
  53852. [coordSysRect.y, coordSysRect.y + coordSysRect.height]
  53853. ],
  53854. isHorizontal: isHorizontal,
  53855. valueDim: LAYOUT_ATTRS[+isHorizontal],
  53856. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  53857. };
  53858. data.diff(oldData)
  53859. .add(function (dataIndex) {
  53860. if (!data.hasValue(dataIndex)) {
  53861. return;
  53862. }
  53863. var itemModel = getItemModel(data, dataIndex);
  53864. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  53865. var bar = createBar(data, opt, symbolMeta);
  53866. data.setItemGraphicEl(dataIndex, bar);
  53867. group.add(bar);
  53868. updateCommon$1(bar, opt, symbolMeta);
  53869. })
  53870. .update(function (newIndex, oldIndex) {
  53871. var bar = oldData.getItemGraphicEl(oldIndex);
  53872. if (!data.hasValue(newIndex)) {
  53873. group.remove(bar);
  53874. return;
  53875. }
  53876. var itemModel = getItemModel(data, newIndex);
  53877. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  53878. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  53879. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  53880. group.remove(bar);
  53881. data.setItemGraphicEl(newIndex, null);
  53882. bar = null;
  53883. }
  53884. if (bar) {
  53885. updateBar(bar, opt, symbolMeta);
  53886. }
  53887. else {
  53888. bar = createBar(data, opt, symbolMeta, true);
  53889. }
  53890. data.setItemGraphicEl(newIndex, bar);
  53891. bar.__pictorialSymbolMeta = symbolMeta;
  53892. // Add back
  53893. group.add(bar);
  53894. updateCommon$1(bar, opt, symbolMeta);
  53895. })
  53896. .remove(function (dataIndex) {
  53897. var bar = oldData.getItemGraphicEl(dataIndex);
  53898. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  53899. })
  53900. .execute();
  53901. this._data = data;
  53902. return this.group;
  53903. },
  53904. dispose: noop,
  53905. remove: function (ecModel, api) {
  53906. var group = this.group;
  53907. var data = this._data;
  53908. if (ecModel.get('animation')) {
  53909. if (data) {
  53910. data.eachItemGraphicEl(function (bar) {
  53911. removeBar(data, bar.dataIndex, ecModel, bar);
  53912. });
  53913. }
  53914. }
  53915. else {
  53916. group.removeAll();
  53917. }
  53918. }
  53919. });
  53920. // Set or calculate default value about symbol, and calculate layout info.
  53921. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  53922. var layout = data.getItemLayout(dataIndex);
  53923. var symbolRepeat = itemModel.get('symbolRepeat');
  53924. var symbolClip = itemModel.get('symbolClip');
  53925. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  53926. var symbolRotate = itemModel.get('symbolRotate');
  53927. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  53928. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  53929. var isAnimationEnabled = itemModel.isAnimationEnabled();
  53930. var symbolMeta = {
  53931. dataIndex: dataIndex,
  53932. layout: layout,
  53933. itemModel: itemModel,
  53934. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  53935. color: data.getItemVisual(dataIndex, 'color'),
  53936. symbolClip: symbolClip,
  53937. symbolRepeat: symbolRepeat,
  53938. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  53939. symbolPatternSize: symbolPatternSize,
  53940. rotation: rotation,
  53941. animationModel: isAnimationEnabled ? itemModel : null,
  53942. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  53943. z2: itemModel.getShallow('z', true) || 0
  53944. };
  53945. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  53946. prepareSymbolSize(
  53947. data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength,
  53948. symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta
  53949. );
  53950. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  53951. var symbolSize = symbolMeta.symbolSize;
  53952. var symbolOffset = itemModel.get('symbolOffset');
  53953. if (isArray(symbolOffset)) {
  53954. symbolOffset = [
  53955. parsePercent$1(symbolOffset[0], symbolSize[0]),
  53956. parsePercent$1(symbolOffset[1], symbolSize[1])
  53957. ];
  53958. }
  53959. prepareLayoutInfo(
  53960. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  53961. symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength,
  53962. opt, symbolMeta
  53963. );
  53964. return symbolMeta;
  53965. }
  53966. // bar length can be negative.
  53967. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  53968. var valueDim = opt.valueDim;
  53969. var symbolBoundingData = itemModel.get('symbolBoundingData');
  53970. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  53971. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  53972. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  53973. var boundingLength;
  53974. if (isArray(symbolBoundingData)) {
  53975. var symbolBoundingExtent = [
  53976. convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx,
  53977. convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx
  53978. ];
  53979. symbolBoundingExtent[1] < symbolBoundingExtent[0] && (symbolBoundingExtent.reverse());
  53980. boundingLength = symbolBoundingExtent[pxSignIdx];
  53981. }
  53982. else if (symbolBoundingData != null) {
  53983. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  53984. }
  53985. else if (symbolRepeat) {
  53986. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  53987. }
  53988. else {
  53989. boundingLength = layout[valueDim.wh];
  53990. }
  53991. output.boundingLength = boundingLength;
  53992. if (symbolRepeat) {
  53993. output.repeatCutLength = layout[valueDim.wh];
  53994. }
  53995. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  53996. }
  53997. function convertToCoordOnAxis(axis, value) {
  53998. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  53999. }
  54000. // Support ['100%', '100%']
  54001. function prepareSymbolSize(
  54002. data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength,
  54003. pxSign, symbolPatternSize, opt, output
  54004. ) {
  54005. var valueDim = opt.valueDim;
  54006. var categoryDim = opt.categoryDim;
  54007. var categorySize = Math.abs(layout[categoryDim.wh]);
  54008. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  54009. if (isArray(symbolSize)) {
  54010. symbolSize = symbolSize.slice();
  54011. }
  54012. else {
  54013. if (symbolSize == null) {
  54014. symbolSize = '100%';
  54015. }
  54016. symbolSize = [symbolSize, symbolSize];
  54017. }
  54018. // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  54019. // to complicated to calculate real percent value if considering scaled lineWidth.
  54020. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  54021. // which can be tolerated in pictorial chart.
  54022. symbolSize[categoryDim.index] = parsePercent$1(
  54023. symbolSize[categoryDim.index],
  54024. categorySize
  54025. );
  54026. symbolSize[valueDim.index] = parsePercent$1(
  54027. symbolSize[valueDim.index],
  54028. symbolRepeat ? categorySize : Math.abs(boundingLength)
  54029. );
  54030. output.symbolSize = symbolSize;
  54031. // If x or y is less than zero, show reversed shape.
  54032. var symbolScale = output.symbolScale = [
  54033. symbolSize[0] / symbolPatternSize,
  54034. symbolSize[1] / symbolPatternSize
  54035. ];
  54036. // Follow convention, 'right' and 'top' is the normal scale.
  54037. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  54038. }
  54039. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  54040. // In symbols are drawn with scale, so do not need to care about the case that width
  54041. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  54042. // be calculated.
  54043. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  54044. if (valueLineWidth) {
  54045. pathForLineWidth.attr({
  54046. scale: symbolScale.slice(),
  54047. rotation: rotation
  54048. });
  54049. pathForLineWidth.updateTransform();
  54050. valueLineWidth /= pathForLineWidth.getLineScale();
  54051. valueLineWidth *= symbolScale[opt.valueDim.index];
  54052. }
  54053. output.valueLineWidth = valueLineWidth;
  54054. }
  54055. function prepareLayoutInfo(
  54056. itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset,
  54057. symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output
  54058. ) {
  54059. var categoryDim = opt.categoryDim;
  54060. var valueDim = opt.valueDim;
  54061. var pxSign = output.pxSign;
  54062. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  54063. var pathLen = unitLength;
  54064. // Note: rotation will not effect the layout of symbols, because user may
  54065. // want symbols to rotate on its center, which should not be translated
  54066. // when rotating.
  54067. if (symbolRepeat) {
  54068. var absBoundingLength = Math.abs(boundingLength);
  54069. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  54070. var hasEndGap = false;
  54071. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  54072. hasEndGap = true;
  54073. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  54074. }
  54075. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  54076. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0);
  54077. // When symbol margin is less than 0, margin at both ends will be subtracted
  54078. // to ensure that all of the symbols will not be overflow the given area.
  54079. var endFix = hasEndGap ? 0 : symbolMargin * 2;
  54080. // Both final repeatTimes and final symbolMargin area calculated based on
  54081. // boundingLength.
  54082. var repeatSpecified = isNumeric(symbolRepeat);
  54083. var repeatTimes = repeatSpecified
  54084. ? symbolRepeat
  54085. : toIntTimes((absBoundingLength + endFix) / uLenWithMargin);
  54086. // Adjust calculate margin, to ensure each symbol is displayed
  54087. // entirely in the given layout area.
  54088. var mDiff = absBoundingLength - repeatTimes * unitLength;
  54089. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  54090. uLenWithMargin = unitLength + symbolMargin * 2;
  54091. endFix = hasEndGap ? 0 : symbolMargin * 2;
  54092. // Update repeatTimes when not all symbol will be shown.
  54093. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  54094. repeatTimes = repeatCutLength
  54095. ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin)
  54096. : 0;
  54097. }
  54098. pathLen = repeatTimes * uLenWithMargin - endFix;
  54099. output.repeatTimes = repeatTimes;
  54100. output.symbolMargin = symbolMargin;
  54101. }
  54102. var sizeFix = pxSign * (pathLen / 2);
  54103. var pathPosition = output.pathPosition = [];
  54104. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  54105. pathPosition[valueDim.index] = symbolPosition === 'start'
  54106. ? sizeFix
  54107. : symbolPosition === 'end'
  54108. ? boundingLength - sizeFix
  54109. : boundingLength / 2; // 'center'
  54110. if (symbolOffset) {
  54111. pathPosition[0] += symbolOffset[0];
  54112. pathPosition[1] += symbolOffset[1];
  54113. }
  54114. var bundlePosition = output.bundlePosition = [];
  54115. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  54116. bundlePosition[valueDim.index] = layout[valueDim.xy];
  54117. var barRectShape = output.barRectShape = extend({}, layout);
  54118. barRectShape[valueDim.wh] = pxSign * Math.max(
  54119. Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix)
  54120. );
  54121. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  54122. var clipShape = output.clipShape = {};
  54123. // Consider that symbol may be overflow layout rect.
  54124. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  54125. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  54126. clipShape[valueDim.xy] = 0;
  54127. clipShape[valueDim.wh] = layout[valueDim.wh];
  54128. }
  54129. function createPath(symbolMeta) {
  54130. var symbolPatternSize = symbolMeta.symbolPatternSize;
  54131. var path = createSymbol(
  54132. // Consider texture img, make a big size.
  54133. symbolMeta.symbolType,
  54134. -symbolPatternSize / 2,
  54135. -symbolPatternSize / 2,
  54136. symbolPatternSize,
  54137. symbolPatternSize,
  54138. symbolMeta.color
  54139. );
  54140. path.attr({
  54141. culling: true
  54142. });
  54143. path.type !== 'image' && path.setStyle({
  54144. strokeNoScale: true
  54145. });
  54146. return path;
  54147. }
  54148. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  54149. var bundle = bar.__pictorialBundle;
  54150. var symbolSize = symbolMeta.symbolSize;
  54151. var valueLineWidth = symbolMeta.valueLineWidth;
  54152. var pathPosition = symbolMeta.pathPosition;
  54153. var valueDim = opt.valueDim;
  54154. var repeatTimes = symbolMeta.repeatTimes || 0;
  54155. var index = 0;
  54156. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  54157. eachPath(bar, function (path) {
  54158. path.__pictorialAnimationIndex = index;
  54159. path.__pictorialRepeatTimes = repeatTimes;
  54160. if (index < repeatTimes) {
  54161. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  54162. }
  54163. else {
  54164. updateAttr(path, null, {scale: [0, 0]}, symbolMeta, isUpdate, function () {
  54165. bundle.remove(path);
  54166. });
  54167. }
  54168. updateHoverAnimation(path, symbolMeta);
  54169. index++;
  54170. });
  54171. for (; index < repeatTimes; index++) {
  54172. var path = createPath(symbolMeta);
  54173. path.__pictorialAnimationIndex = index;
  54174. path.__pictorialRepeatTimes = repeatTimes;
  54175. bundle.add(path);
  54176. var target = makeTarget(index);
  54177. updateAttr(
  54178. path,
  54179. {
  54180. position: target.position,
  54181. scale: [0, 0]
  54182. },
  54183. {
  54184. scale: target.scale,
  54185. rotation: target.rotation
  54186. },
  54187. symbolMeta,
  54188. isUpdate
  54189. );
  54190. // FIXME
  54191. // If all emphasis/normal through action.
  54192. path
  54193. .on('mouseover', onMouseOver)
  54194. .on('mouseout', onMouseOut);
  54195. updateHoverAnimation(path, symbolMeta);
  54196. }
  54197. function makeTarget(index) {
  54198. var position = pathPosition.slice();
  54199. // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  54200. // Otherwise: i = index;
  54201. var pxSign = symbolMeta.pxSign;
  54202. var i = index;
  54203. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  54204. i = repeatTimes - 1 - index;
  54205. }
  54206. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  54207. return {
  54208. position: position,
  54209. scale: symbolMeta.symbolScale.slice(),
  54210. rotation: symbolMeta.rotation
  54211. };
  54212. }
  54213. function onMouseOver() {
  54214. eachPath(bar, function (path) {
  54215. path.trigger('emphasis');
  54216. });
  54217. }
  54218. function onMouseOut() {
  54219. eachPath(bar, function (path) {
  54220. path.trigger('normal');
  54221. });
  54222. }
  54223. }
  54224. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  54225. var bundle = bar.__pictorialBundle;
  54226. var mainPath = bar.__pictorialMainPath;
  54227. if (!mainPath) {
  54228. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  54229. bundle.add(mainPath);
  54230. updateAttr(
  54231. mainPath,
  54232. {
  54233. position: symbolMeta.pathPosition.slice(),
  54234. scale: [0, 0],
  54235. rotation: symbolMeta.rotation
  54236. },
  54237. {
  54238. scale: symbolMeta.symbolScale.slice()
  54239. },
  54240. symbolMeta,
  54241. isUpdate
  54242. );
  54243. mainPath
  54244. .on('mouseover', onMouseOver)
  54245. .on('mouseout', onMouseOut);
  54246. }
  54247. else {
  54248. updateAttr(
  54249. mainPath,
  54250. null,
  54251. {
  54252. position: symbolMeta.pathPosition.slice(),
  54253. scale: symbolMeta.symbolScale.slice(),
  54254. rotation: symbolMeta.rotation
  54255. },
  54256. symbolMeta,
  54257. isUpdate
  54258. );
  54259. }
  54260. updateHoverAnimation(mainPath, symbolMeta);
  54261. function onMouseOver() {
  54262. this.trigger('emphasis');
  54263. }
  54264. function onMouseOut() {
  54265. this.trigger('normal');
  54266. }
  54267. }
  54268. // bar rect is used for label.
  54269. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  54270. var rectShape = extend({}, symbolMeta.barRectShape);
  54271. var barRect = bar.__pictorialBarRect;
  54272. if (!barRect) {
  54273. barRect = bar.__pictorialBarRect = new Rect({
  54274. z2: 2,
  54275. shape: rectShape,
  54276. silent: true,
  54277. style: {
  54278. stroke: 'transparent',
  54279. fill: 'transparent',
  54280. lineWidth: 0
  54281. }
  54282. });
  54283. bar.add(barRect);
  54284. }
  54285. else {
  54286. updateAttr(barRect, null, {shape: rectShape}, symbolMeta, isUpdate);
  54287. }
  54288. }
  54289. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  54290. // If not clip, symbol will be remove and rebuilt.
  54291. if (symbolMeta.symbolClip) {
  54292. var clipPath = bar.__pictorialClipPath;
  54293. var clipShape = extend({}, symbolMeta.clipShape);
  54294. var valueDim = opt.valueDim;
  54295. var animationModel = symbolMeta.animationModel;
  54296. var dataIndex = symbolMeta.dataIndex;
  54297. if (clipPath) {
  54298. updateProps(
  54299. clipPath, {shape: clipShape}, animationModel, dataIndex
  54300. );
  54301. }
  54302. else {
  54303. clipShape[valueDim.wh] = 0;
  54304. clipPath = new Rect({shape: clipShape});
  54305. bar.__pictorialBundle.setClipPath(clipPath);
  54306. bar.__pictorialClipPath = clipPath;
  54307. var target = {};
  54308. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  54309. graphic[isUpdate ? 'updateProps' : 'initProps'](
  54310. clipPath, {shape: target}, animationModel, dataIndex
  54311. );
  54312. }
  54313. }
  54314. }
  54315. function getItemModel(data, dataIndex) {
  54316. var itemModel = data.getItemModel(dataIndex);
  54317. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  54318. itemModel.isAnimationEnabled = isAnimationEnabled;
  54319. return itemModel;
  54320. }
  54321. function getAnimationDelayParams(path) {
  54322. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  54323. return {
  54324. index: path.__pictorialAnimationIndex,
  54325. count: path.__pictorialRepeatTimes
  54326. };
  54327. }
  54328. function isAnimationEnabled() {
  54329. // `animation` prop can be set on itemModel in pictorial bar chart.
  54330. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  54331. }
  54332. function updateHoverAnimation(path, symbolMeta) {
  54333. path.off('emphasis').off('normal');
  54334. var scale = symbolMeta.symbolScale.slice();
  54335. symbolMeta.hoverAnimation && path
  54336. .on('emphasis', function() {
  54337. this.animateTo({
  54338. scale: [scale[0] * 1.1, scale[1] * 1.1]
  54339. }, 400, 'elasticOut');
  54340. })
  54341. .on('normal', function() {
  54342. this.animateTo({
  54343. scale: scale.slice()
  54344. }, 400, 'elasticOut');
  54345. });
  54346. }
  54347. function createBar(data, opt, symbolMeta, isUpdate) {
  54348. // bar is the main element for each data.
  54349. var bar = new Group();
  54350. // bundle is used for location and clip.
  54351. var bundle = new Group();
  54352. bar.add(bundle);
  54353. bar.__pictorialBundle = bundle;
  54354. bundle.attr('position', symbolMeta.bundlePosition.slice());
  54355. if (symbolMeta.symbolRepeat) {
  54356. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  54357. }
  54358. else {
  54359. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  54360. }
  54361. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  54362. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  54363. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  54364. bar.__pictorialSymbolMeta = symbolMeta;
  54365. return bar;
  54366. }
  54367. function updateBar(bar, opt, symbolMeta) {
  54368. var animationModel = symbolMeta.animationModel;
  54369. var dataIndex = symbolMeta.dataIndex;
  54370. var bundle = bar.__pictorialBundle;
  54371. updateProps(
  54372. bundle, {position: symbolMeta.bundlePosition.slice()}, animationModel, dataIndex
  54373. );
  54374. if (symbolMeta.symbolRepeat) {
  54375. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  54376. }
  54377. else {
  54378. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  54379. }
  54380. createOrUpdateBarRect(bar, symbolMeta, true);
  54381. createOrUpdateClip(bar, opt, symbolMeta, true);
  54382. }
  54383. function removeBar(data, dataIndex, animationModel, bar) {
  54384. // Not show text when animating
  54385. var labelRect = bar.__pictorialBarRect;
  54386. labelRect && (labelRect.style.text = null);
  54387. var pathes = [];
  54388. eachPath(bar, function (path) {
  54389. pathes.push(path);
  54390. });
  54391. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath);
  54392. // I do not find proper remove animation for clip yet.
  54393. bar.__pictorialClipPath && (animationModel = null);
  54394. each$1(pathes, function (path) {
  54395. updateProps(
  54396. path, {scale: [0, 0]}, animationModel, dataIndex,
  54397. function () {
  54398. bar.parent && bar.parent.remove(bar);
  54399. }
  54400. );
  54401. });
  54402. data.setItemGraphicEl(dataIndex, null);
  54403. }
  54404. function getShapeStr(data, symbolMeta) {
  54405. return [
  54406. data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none',
  54407. !!symbolMeta.symbolRepeat,
  54408. !!symbolMeta.symbolClip
  54409. ].join(':');
  54410. }
  54411. function eachPath(bar, cb, context) {
  54412. // Do not use Group#eachChild, because it do not support remove.
  54413. each$1(bar.__pictorialBundle.children(), function (el) {
  54414. el !== bar.__pictorialBarRect && cb.call(context, el);
  54415. });
  54416. }
  54417. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  54418. immediateAttrs && el.attr(immediateAttrs);
  54419. // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  54420. if (symbolMeta.symbolClip && !isUpdate) {
  54421. animationAttrs && el.attr(animationAttrs);
  54422. }
  54423. else {
  54424. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](
  54425. el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb
  54426. );
  54427. }
  54428. }
  54429. function updateCommon$1(bar, opt, symbolMeta) {
  54430. var color = symbolMeta.color;
  54431. var dataIndex = symbolMeta.dataIndex;
  54432. var itemModel = symbolMeta.itemModel;
  54433. // Color must be excluded.
  54434. // Because symbol provide setColor individually to set fill and stroke
  54435. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  54436. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  54437. var cursorStyle = itemModel.getShallow('cursor');
  54438. eachPath(bar, function (path) {
  54439. // PENDING setColor should be before setStyle!!!
  54440. path.setColor(color);
  54441. path.setStyle(defaults(
  54442. {
  54443. fill: color,
  54444. opacity: symbolMeta.opacity
  54445. },
  54446. normalStyle
  54447. ));
  54448. setHoverStyle(path, hoverStyle);
  54449. cursorStyle && (path.cursor = cursorStyle);
  54450. path.z2 = symbolMeta.z2;
  54451. });
  54452. var barRectHoverStyle = {};
  54453. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  54454. var barRect = bar.__pictorialBarRect;
  54455. setLabel(
  54456. barRect.style, barRectHoverStyle, itemModel,
  54457. color, opt.seriesModel, dataIndex, barPositionOutside
  54458. );
  54459. setHoverStyle(barRect, barRectHoverStyle);
  54460. }
  54461. function toIntTimes(times) {
  54462. var roundedTimes = Math.round(times);
  54463. // Escapse accurate error
  54464. return Math.abs(times - roundedTimes) < 1e-4
  54465. ? roundedTimes
  54466. : Math.ceil(times);
  54467. }
  54468. /*
  54469. * Licensed to the Apache Software Foundation (ASF) under one
  54470. * or more contributor license agreements. See the NOTICE file
  54471. * distributed with this work for additional information
  54472. * regarding copyright ownership. The ASF licenses this file
  54473. * to you under the Apache License, Version 2.0 (the
  54474. * "License"); you may not use this file except in compliance
  54475. * with the License. You may obtain a copy of the License at
  54476. *
  54477. * http://www.apache.org/licenses/LICENSE-2.0
  54478. *
  54479. * Unless required by applicable law or agreed to in writing,
  54480. * software distributed under the License is distributed on an
  54481. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54482. * KIND, either express or implied. See the License for the
  54483. * specific language governing permissions and limitations
  54484. * under the License.
  54485. */
  54486. // In case developer forget to include grid component
  54487. registerLayout(curry(
  54488. layout, 'pictorialBar'
  54489. ));
  54490. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  54491. /*
  54492. * Licensed to the Apache Software Foundation (ASF) under one
  54493. * or more contributor license agreements. See the NOTICE file
  54494. * distributed with this work for additional information
  54495. * regarding copyright ownership. The ASF licenses this file
  54496. * to you under the Apache License, Version 2.0 (the
  54497. * "License"); you may not use this file except in compliance
  54498. * with the License. You may obtain a copy of the License at
  54499. *
  54500. * http://www.apache.org/licenses/LICENSE-2.0
  54501. *
  54502. * Unless required by applicable law or agreed to in writing,
  54503. * software distributed under the License is distributed on an
  54504. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54505. * KIND, either express or implied. See the License for the
  54506. * specific language governing permissions and limitations
  54507. * under the License.
  54508. */
  54509. /**
  54510. * @constructor module:echarts/coord/single/SingleAxis
  54511. * @extends {module:echarts/coord/Axis}
  54512. * @param {string} dim
  54513. * @param {*} scale
  54514. * @param {Array.<number>} coordExtent
  54515. * @param {string} axisType
  54516. * @param {string} position
  54517. */
  54518. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  54519. Axis.call(this, dim, scale, coordExtent);
  54520. /**
  54521. * Axis type
  54522. * - 'category'
  54523. * - 'value'
  54524. * - 'time'
  54525. * - 'log'
  54526. * @type {string}
  54527. */
  54528. this.type = axisType || 'value';
  54529. /**
  54530. * Axis position
  54531. * - 'top'
  54532. * - 'bottom'
  54533. * - 'left'
  54534. * - 'right'
  54535. * @type {string}
  54536. */
  54537. this.position = position || 'bottom';
  54538. /**
  54539. * Axis orient
  54540. * - 'horizontal'
  54541. * - 'vertical'
  54542. * @type {[type]}
  54543. */
  54544. this.orient = null;
  54545. };
  54546. SingleAxis.prototype = {
  54547. constructor: SingleAxis,
  54548. /**
  54549. * Axis model
  54550. * @type {module:echarts/coord/single/AxisModel}
  54551. */
  54552. model: null,
  54553. /**
  54554. * Judge the orient of the axis.
  54555. * @return {boolean}
  54556. */
  54557. isHorizontal: function () {
  54558. var position = this.position;
  54559. return position === 'top' || position === 'bottom';
  54560. },
  54561. /**
  54562. * @override
  54563. */
  54564. pointToData: function (point, clamp) {
  54565. return this.coordinateSystem.pointToData(point, clamp)[0];
  54566. },
  54567. /**
  54568. * Convert the local coord(processed by dataToCoord())
  54569. * to global coord(concrete pixel coord).
  54570. * designated by module:echarts/coord/single/Single.
  54571. * @type {Function}
  54572. */
  54573. toGlobalCoord: null,
  54574. /**
  54575. * Convert the global coord to local coord.
  54576. * designated by module:echarts/coord/single/Single.
  54577. * @type {Function}
  54578. */
  54579. toLocalCoord: null
  54580. };
  54581. inherits(SingleAxis, Axis);
  54582. /*
  54583. * Licensed to the Apache Software Foundation (ASF) under one
  54584. * or more contributor license agreements. See the NOTICE file
  54585. * distributed with this work for additional information
  54586. * regarding copyright ownership. The ASF licenses this file
  54587. * to you under the Apache License, Version 2.0 (the
  54588. * "License"); you may not use this file except in compliance
  54589. * with the License. You may obtain a copy of the License at
  54590. *
  54591. * http://www.apache.org/licenses/LICENSE-2.0
  54592. *
  54593. * Unless required by applicable law or agreed to in writing,
  54594. * software distributed under the License is distributed on an
  54595. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54596. * KIND, either express or implied. See the License for the
  54597. * specific language governing permissions and limitations
  54598. * under the License.
  54599. */
  54600. /**
  54601. * Single coordinates system.
  54602. */
  54603. /**
  54604. * Create a single coordinates system.
  54605. *
  54606. * @param {module:echarts/coord/single/AxisModel} axisModel
  54607. * @param {module:echarts/model/Global} ecModel
  54608. * @param {module:echarts/ExtensionAPI} api
  54609. */
  54610. function Single(axisModel, ecModel, api) {
  54611. /**
  54612. * @type {string}
  54613. * @readOnly
  54614. */
  54615. this.dimension = 'single';
  54616. /**
  54617. * Add it just for draw tooltip.
  54618. *
  54619. * @type {Array.<string>}
  54620. * @readOnly
  54621. */
  54622. this.dimensions = ['single'];
  54623. /**
  54624. * @private
  54625. * @type {module:echarts/coord/single/SingleAxis}.
  54626. */
  54627. this._axis = null;
  54628. /**
  54629. * @private
  54630. * @type {module:zrender/core/BoundingRect}
  54631. */
  54632. this._rect;
  54633. this._init(axisModel, ecModel, api);
  54634. /**
  54635. * @type {module:echarts/coord/single/AxisModel}
  54636. */
  54637. this.model = axisModel;
  54638. }
  54639. Single.prototype = {
  54640. type: 'singleAxis',
  54641. axisPointerEnabled: true,
  54642. constructor: Single,
  54643. /**
  54644. * Initialize single coordinate system.
  54645. *
  54646. * @param {module:echarts/coord/single/AxisModel} axisModel
  54647. * @param {module:echarts/model/Global} ecModel
  54648. * @param {module:echarts/ExtensionAPI} api
  54649. * @private
  54650. */
  54651. _init: function (axisModel, ecModel, api) {
  54652. var dim = this.dimension;
  54653. var axis = new SingleAxis(
  54654. dim,
  54655. createScaleByModel(axisModel),
  54656. [0, 0],
  54657. axisModel.get('type'),
  54658. axisModel.get('position')
  54659. );
  54660. var isCategory = axis.type === 'category';
  54661. axis.onBand = isCategory && axisModel.get('boundaryGap');
  54662. axis.inverse = axisModel.get('inverse');
  54663. axis.orient = axisModel.get('orient');
  54664. axisModel.axis = axis;
  54665. axis.model = axisModel;
  54666. axis.coordinateSystem = this;
  54667. this._axis = axis;
  54668. },
  54669. /**
  54670. * Update axis scale after data processed
  54671. * @param {module:echarts/model/Global} ecModel
  54672. * @param {module:echarts/ExtensionAPI} api
  54673. */
  54674. update: function (ecModel, api) {
  54675. ecModel.eachSeries(function (seriesModel) {
  54676. if (seriesModel.coordinateSystem === this) {
  54677. var data = seriesModel.getData();
  54678. each$1(data.mapDimension(this.dimension, true), function (dim) {
  54679. this._axis.scale.unionExtentFromData(data, dim);
  54680. }, this);
  54681. niceScaleExtent(this._axis.scale, this._axis.model);
  54682. }
  54683. }, this);
  54684. },
  54685. /**
  54686. * Resize the single coordinate system.
  54687. *
  54688. * @param {module:echarts/coord/single/AxisModel} axisModel
  54689. * @param {module:echarts/ExtensionAPI} api
  54690. */
  54691. resize: function (axisModel, api) {
  54692. this._rect = getLayoutRect(
  54693. {
  54694. left: axisModel.get('left'),
  54695. top: axisModel.get('top'),
  54696. right: axisModel.get('right'),
  54697. bottom: axisModel.get('bottom'),
  54698. width: axisModel.get('width'),
  54699. height: axisModel.get('height')
  54700. },
  54701. {
  54702. width: api.getWidth(),
  54703. height: api.getHeight()
  54704. }
  54705. );
  54706. this._adjustAxis();
  54707. },
  54708. /**
  54709. * @return {module:zrender/core/BoundingRect}
  54710. */
  54711. getRect: function () {
  54712. return this._rect;
  54713. },
  54714. /**
  54715. * @private
  54716. */
  54717. _adjustAxis: function () {
  54718. var rect = this._rect;
  54719. var axis = this._axis;
  54720. var isHorizontal = axis.isHorizontal();
  54721. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  54722. var idx = axis.reverse ? 1 : 0;
  54723. axis.setExtent(extent[idx], extent[1 - idx]);
  54724. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  54725. },
  54726. /**
  54727. * @param {module:echarts/coord/single/SingleAxis} axis
  54728. * @param {number} coordBase
  54729. */
  54730. _updateAxisTransform: function (axis, coordBase) {
  54731. var axisExtent = axis.getExtent();
  54732. var extentSum = axisExtent[0] + axisExtent[1];
  54733. var isHorizontal = axis.isHorizontal();
  54734. axis.toGlobalCoord = isHorizontal
  54735. ? function (coord) {
  54736. return coord + coordBase;
  54737. }
  54738. : function (coord) {
  54739. return extentSum - coord + coordBase;
  54740. };
  54741. axis.toLocalCoord = isHorizontal
  54742. ? function (coord) {
  54743. return coord - coordBase;
  54744. }
  54745. : function (coord) {
  54746. return extentSum - coord + coordBase;
  54747. };
  54748. },
  54749. /**
  54750. * Get axis.
  54751. *
  54752. * @return {module:echarts/coord/single/SingleAxis}
  54753. */
  54754. getAxis: function () {
  54755. return this._axis;
  54756. },
  54757. /**
  54758. * Get axis, add it just for draw tooltip.
  54759. *
  54760. * @return {[type]} [description]
  54761. */
  54762. getBaseAxis: function () {
  54763. return this._axis;
  54764. },
  54765. /**
  54766. * @return {Array.<module:echarts/coord/Axis>}
  54767. */
  54768. getAxes: function () {
  54769. return [this._axis];
  54770. },
  54771. /**
  54772. * @return {Object} {baseAxes: [], otherAxes: []}
  54773. */
  54774. getTooltipAxes: function () {
  54775. return {baseAxes: [this.getAxis()]};
  54776. },
  54777. /**
  54778. * If contain point.
  54779. *
  54780. * @param {Array.<number>} point
  54781. * @return {boolean}
  54782. */
  54783. containPoint: function (point) {
  54784. var rect = this.getRect();
  54785. var axis = this.getAxis();
  54786. var orient = axis.orient;
  54787. if (orient === 'horizontal') {
  54788. return axis.contain(axis.toLocalCoord(point[0]))
  54789. && (point[1] >= rect.y && point[1] <= (rect.y + rect.height));
  54790. }
  54791. else {
  54792. return axis.contain(axis.toLocalCoord(point[1]))
  54793. && (point[0] >= rect.y && point[0] <= (rect.y + rect.height));
  54794. }
  54795. },
  54796. /**
  54797. * @param {Array.<number>} point
  54798. * @return {Array.<number>}
  54799. */
  54800. pointToData: function (point) {
  54801. var axis = this.getAxis();
  54802. return [axis.coordToData(axis.toLocalCoord(
  54803. point[axis.orient === 'horizontal' ? 0 : 1]
  54804. ))];
  54805. },
  54806. /**
  54807. * Convert the series data to concrete point.
  54808. *
  54809. * @param {number|Array.<number>} val
  54810. * @return {Array.<number>}
  54811. */
  54812. dataToPoint: function (val) {
  54813. var axis = this.getAxis();
  54814. var rect = this.getRect();
  54815. var pt = [];
  54816. var idx = axis.orient === 'horizontal' ? 0 : 1;
  54817. if (val instanceof Array) {
  54818. val = val[0];
  54819. }
  54820. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  54821. pt[1 - idx] = idx === 0 ? (rect.y + rect.height / 2) : (rect.x + rect.width / 2);
  54822. return pt;
  54823. }
  54824. };
  54825. /*
  54826. * Licensed to the Apache Software Foundation (ASF) under one
  54827. * or more contributor license agreements. See the NOTICE file
  54828. * distributed with this work for additional information
  54829. * regarding copyright ownership. The ASF licenses this file
  54830. * to you under the Apache License, Version 2.0 (the
  54831. * "License"); you may not use this file except in compliance
  54832. * with the License. You may obtain a copy of the License at
  54833. *
  54834. * http://www.apache.org/licenses/LICENSE-2.0
  54835. *
  54836. * Unless required by applicable law or agreed to in writing,
  54837. * software distributed under the License is distributed on an
  54838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54839. * KIND, either express or implied. See the License for the
  54840. * specific language governing permissions and limitations
  54841. * under the License.
  54842. */
  54843. /**
  54844. * Single coordinate system creator.
  54845. */
  54846. /**
  54847. * Create single coordinate system and inject it into seriesModel.
  54848. *
  54849. * @param {module:echarts/model/Global} ecModel
  54850. * @param {module:echarts/ExtensionAPI} api
  54851. * @return {Array.<module:echarts/coord/single/Single>}
  54852. */
  54853. function create$3(ecModel, api) {
  54854. var singles = [];
  54855. ecModel.eachComponent('singleAxis', function(axisModel, idx) {
  54856. var single = new Single(axisModel, ecModel, api);
  54857. single.name = 'single_' + idx;
  54858. single.resize(axisModel, api);
  54859. axisModel.coordinateSystem = single;
  54860. singles.push(single);
  54861. });
  54862. ecModel.eachSeries(function (seriesModel) {
  54863. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  54864. var singleAxisModel = ecModel.queryComponents({
  54865. mainType: 'singleAxis',
  54866. index: seriesModel.get('singleAxisIndex'),
  54867. id: seriesModel.get('singleAxisId')
  54868. })[0];
  54869. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  54870. }
  54871. });
  54872. return singles;
  54873. }
  54874. CoordinateSystemManager.register('single', {
  54875. create: create$3,
  54876. dimensions: Single.prototype.dimensions
  54877. });
  54878. /*
  54879. * Licensed to the Apache Software Foundation (ASF) under one
  54880. * or more contributor license agreements. See the NOTICE file
  54881. * distributed with this work for additional information
  54882. * regarding copyright ownership. The ASF licenses this file
  54883. * to you under the Apache License, Version 2.0 (the
  54884. * "License"); you may not use this file except in compliance
  54885. * with the License. You may obtain a copy of the License at
  54886. *
  54887. * http://www.apache.org/licenses/LICENSE-2.0
  54888. *
  54889. * Unless required by applicable law or agreed to in writing,
  54890. * software distributed under the License is distributed on an
  54891. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54892. * KIND, either express or implied. See the License for the
  54893. * specific language governing permissions and limitations
  54894. * under the License.
  54895. */
  54896. /**
  54897. * @param {Object} opt {labelInside}
  54898. * @return {Object} {
  54899. * position, rotation, labelDirection, labelOffset,
  54900. * tickDirection, labelRotate, z2
  54901. * }
  54902. */
  54903. function layout$2(axisModel, opt) {
  54904. opt = opt || {};
  54905. var single = axisModel.coordinateSystem;
  54906. var axis = axisModel.axis;
  54907. var layout = {};
  54908. var axisPosition = axis.position;
  54909. var orient = axis.orient;
  54910. var rect = single.getRect();
  54911. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  54912. var positionMap = {
  54913. horizontal: {top: rectBound[2], bottom: rectBound[3]},
  54914. vertical: {left: rectBound[0], right: rectBound[1]}
  54915. };
  54916. layout.position = [
  54917. orient === 'vertical'
  54918. ? positionMap.vertical[axisPosition]
  54919. : rectBound[0],
  54920. orient === 'horizontal'
  54921. ? positionMap.horizontal[axisPosition]
  54922. : rectBound[3]
  54923. ];
  54924. var r = {horizontal: 0, vertical: 1};
  54925. layout.rotation = Math.PI / 2 * r[orient];
  54926. var directionMap = {top: -1, bottom: 1, right: 1, left: -1};
  54927. layout.labelDirection = layout.tickDirection
  54928. = layout.nameDirection
  54929. = directionMap[axisPosition];
  54930. if (axisModel.get('axisTick.inside')) {
  54931. layout.tickDirection = -layout.tickDirection;
  54932. }
  54933. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  54934. layout.labelDirection = -layout.labelDirection;
  54935. }
  54936. var labelRotation = opt.rotate;
  54937. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  54938. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  54939. layout.z2 = 1;
  54940. return layout;
  54941. }
  54942. /*
  54943. * Licensed to the Apache Software Foundation (ASF) under one
  54944. * or more contributor license agreements. See the NOTICE file
  54945. * distributed with this work for additional information
  54946. * regarding copyright ownership. The ASF licenses this file
  54947. * to you under the Apache License, Version 2.0 (the
  54948. * "License"); you may not use this file except in compliance
  54949. * with the License. You may obtain a copy of the License at
  54950. *
  54951. * http://www.apache.org/licenses/LICENSE-2.0
  54952. *
  54953. * Unless required by applicable law or agreed to in writing,
  54954. * software distributed under the License is distributed on an
  54955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54956. * KIND, either express or implied. See the License for the
  54957. * specific language governing permissions and limitations
  54958. * under the License.
  54959. */
  54960. var axisBuilderAttrs$2 = [
  54961. 'axisLine', 'axisTickLabel', 'axisName'
  54962. ];
  54963. var selfBuilderAttr = 'splitLine';
  54964. var SingleAxisView = AxisView.extend({
  54965. type: 'singleAxis',
  54966. axisPointerClass: 'SingleAxisPointer',
  54967. render: function (axisModel, ecModel, api, payload) {
  54968. var group = this.group;
  54969. group.removeAll();
  54970. var layout = layout$2(axisModel);
  54971. var axisBuilder = new AxisBuilder(axisModel, layout);
  54972. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  54973. group.add(axisBuilder.getGroup());
  54974. if (axisModel.get(selfBuilderAttr + '.show')) {
  54975. this['_' + selfBuilderAttr](axisModel);
  54976. }
  54977. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  54978. },
  54979. _splitLine: function(axisModel) {
  54980. var axis = axisModel.axis;
  54981. if (axis.scale.isBlank()) {
  54982. return;
  54983. }
  54984. var splitLineModel = axisModel.getModel('splitLine');
  54985. var lineStyleModel = splitLineModel.getModel('lineStyle');
  54986. var lineWidth = lineStyleModel.get('width');
  54987. var lineColors = lineStyleModel.get('color');
  54988. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  54989. var gridRect = axisModel.coordinateSystem.getRect();
  54990. var isHorizontal = axis.isHorizontal();
  54991. var splitLines = [];
  54992. var lineCount = 0;
  54993. var ticksCoords = axis.getTicksCoords({
  54994. tickModel: splitLineModel
  54995. });
  54996. var p1 = [];
  54997. var p2 = [];
  54998. for (var i = 0; i < ticksCoords.length; ++i) {
  54999. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  55000. if (isHorizontal) {
  55001. p1[0] = tickCoord;
  55002. p1[1] = gridRect.y;
  55003. p2[0] = tickCoord;
  55004. p2[1] = gridRect.y + gridRect.height;
  55005. }
  55006. else {
  55007. p1[0] = gridRect.x;
  55008. p1[1] = tickCoord;
  55009. p2[0] = gridRect.x + gridRect.width;
  55010. p2[1] = tickCoord;
  55011. }
  55012. var colorIndex = (lineCount++) % lineColors.length;
  55013. splitLines[colorIndex] = splitLines[colorIndex] || [];
  55014. splitLines[colorIndex].push(new Line(
  55015. subPixelOptimizeLine({
  55016. shape: {
  55017. x1: p1[0],
  55018. y1: p1[1],
  55019. x2: p2[0],
  55020. y2: p2[1]
  55021. },
  55022. style: {
  55023. lineWidth: lineWidth
  55024. },
  55025. silent: true
  55026. })));
  55027. }
  55028. for (var i = 0; i < splitLines.length; ++i) {
  55029. this.group.add(mergePath(splitLines[i], {
  55030. style: {
  55031. stroke: lineColors[i % lineColors.length],
  55032. lineDash: lineStyleModel.getLineDash(lineWidth),
  55033. lineWidth: lineWidth
  55034. },
  55035. silent: true
  55036. }));
  55037. }
  55038. }
  55039. });
  55040. /*
  55041. * Licensed to the Apache Software Foundation (ASF) under one
  55042. * or more contributor license agreements. See the NOTICE file
  55043. * distributed with this work for additional information
  55044. * regarding copyright ownership. The ASF licenses this file
  55045. * to you under the Apache License, Version 2.0 (the
  55046. * "License"); you may not use this file except in compliance
  55047. * with the License. You may obtain a copy of the License at
  55048. *
  55049. * http://www.apache.org/licenses/LICENSE-2.0
  55050. *
  55051. * Unless required by applicable law or agreed to in writing,
  55052. * software distributed under the License is distributed on an
  55053. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55054. * KIND, either express or implied. See the License for the
  55055. * specific language governing permissions and limitations
  55056. * under the License.
  55057. */
  55058. var AxisModel$4 = ComponentModel.extend({
  55059. type: 'singleAxis',
  55060. layoutMode: 'box',
  55061. /**
  55062. * @type {module:echarts/coord/single/SingleAxis}
  55063. */
  55064. axis: null,
  55065. /**
  55066. * @type {module:echarts/coord/single/Single}
  55067. */
  55068. coordinateSystem: null,
  55069. /**
  55070. * @override
  55071. */
  55072. getCoordSysModel: function () {
  55073. return this;
  55074. }
  55075. });
  55076. var defaultOption$2 = {
  55077. left: '5%',
  55078. top: '5%',
  55079. right: '5%',
  55080. bottom: '5%',
  55081. type: 'value',
  55082. position: 'bottom',
  55083. orient: 'horizontal',
  55084. axisLine: {
  55085. show: true,
  55086. lineStyle: {
  55087. width: 2,
  55088. type: 'solid'
  55089. }
  55090. },
  55091. // Single coordinate system and single axis is the,
  55092. // which is used as the parent tooltip model.
  55093. // same model, so we set default tooltip show as true.
  55094. tooltip: {
  55095. show: true
  55096. },
  55097. axisTick: {
  55098. show: true,
  55099. length: 6,
  55100. lineStyle: {
  55101. width: 2
  55102. }
  55103. },
  55104. axisLabel: {
  55105. show: true,
  55106. interval: 'auto'
  55107. },
  55108. splitLine: {
  55109. show: true,
  55110. lineStyle: {
  55111. type: 'dashed',
  55112. opacity: 0.2
  55113. }
  55114. }
  55115. };
  55116. function getAxisType$2(axisName, option) {
  55117. return option.type || (option.data ? 'category' : 'value');
  55118. }
  55119. merge(AxisModel$4.prototype, axisModelCommonMixin);
  55120. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  55121. /*
  55122. * Licensed to the Apache Software Foundation (ASF) under one
  55123. * or more contributor license agreements. See the NOTICE file
  55124. * distributed with this work for additional information
  55125. * regarding copyright ownership. The ASF licenses this file
  55126. * to you under the Apache License, Version 2.0 (the
  55127. * "License"); you may not use this file except in compliance
  55128. * with the License. You may obtain a copy of the License at
  55129. *
  55130. * http://www.apache.org/licenses/LICENSE-2.0
  55131. *
  55132. * Unless required by applicable law or agreed to in writing,
  55133. * software distributed under the License is distributed on an
  55134. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55135. * KIND, either express or implied. See the License for the
  55136. * specific language governing permissions and limitations
  55137. * under the License.
  55138. */
  55139. /**
  55140. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  55141. * @param {module:echarts/model/Global} ecModel
  55142. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  55143. */
  55144. var findPointFromSeries = function (finder, ecModel) {
  55145. var point = [];
  55146. var seriesIndex = finder.seriesIndex;
  55147. var seriesModel;
  55148. if (seriesIndex == null || !(
  55149. seriesModel = ecModel.getSeriesByIndex(seriesIndex)
  55150. )) {
  55151. return {point: []};
  55152. }
  55153. var data = seriesModel.getData();
  55154. var dataIndex = queryDataIndex(data, finder);
  55155. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  55156. return {point: []};
  55157. }
  55158. var el = data.getItemGraphicEl(dataIndex);
  55159. var coordSys = seriesModel.coordinateSystem;
  55160. if (seriesModel.getTooltipPosition) {
  55161. point = seriesModel.getTooltipPosition(dataIndex) || [];
  55162. }
  55163. else if (coordSys && coordSys.dataToPoint) {
  55164. point = coordSys.dataToPoint(
  55165. data.getValues(
  55166. map(coordSys.dimensions, function (dim) {
  55167. return data.mapDimension(dim);
  55168. }), dataIndex, true
  55169. )
  55170. ) || [];
  55171. }
  55172. else if (el) {
  55173. // Use graphic bounding rect
  55174. var rect = el.getBoundingRect().clone();
  55175. rect.applyTransform(el.transform);
  55176. point = [
  55177. rect.x + rect.width / 2,
  55178. rect.y + rect.height / 2
  55179. ];
  55180. }
  55181. return {point: point, el: el};
  55182. };
  55183. /*
  55184. * Licensed to the Apache Software Foundation (ASF) under one
  55185. * or more contributor license agreements. See the NOTICE file
  55186. * distributed with this work for additional information
  55187. * regarding copyright ownership. The ASF licenses this file
  55188. * to you under the Apache License, Version 2.0 (the
  55189. * "License"); you may not use this file except in compliance
  55190. * with the License. You may obtain a copy of the License at
  55191. *
  55192. * http://www.apache.org/licenses/LICENSE-2.0
  55193. *
  55194. * Unless required by applicable law or agreed to in writing,
  55195. * software distributed under the License is distributed on an
  55196. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55197. * KIND, either express or implied. See the License for the
  55198. * specific language governing permissions and limitations
  55199. * under the License.
  55200. */
  55201. var each$14 = each$1;
  55202. var curry$3 = curry;
  55203. var inner$7 = makeInner();
  55204. /**
  55205. * Basic logic: check all axis, if they do not demand show/highlight,
  55206. * then hide/downplay them.
  55207. *
  55208. * @param {Object} coordSysAxesInfo
  55209. * @param {Object} payload
  55210. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  55211. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  55212. * trigger axisPointer and tooltip.
  55213. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  55214. * trigger axisPointer and tooltip.
  55215. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  55216. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  55217. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  55218. * [{
  55219. * axisDim: 'x'|'y'|'angle'|...,
  55220. * axisIndex: ...,
  55221. * value: ...
  55222. * }, ...]
  55223. * @param {Function} [payload.dispatchAction]
  55224. * @param {Object} [payload.tooltipOption]
  55225. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  55226. * which can be specified in dispatchAction
  55227. * @param {module:echarts/model/Global} ecModel
  55228. * @param {module:echarts/ExtensionAPI} api
  55229. * @return {Object} content of event obj for echarts.connect.
  55230. */
  55231. var axisTrigger = function (payload, ecModel, api) {
  55232. var currTrigger = payload.currTrigger;
  55233. var point = [payload.x, payload.y];
  55234. var finder = payload;
  55235. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  55236. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  55237. // Pending
  55238. // See #6121. But we are not able to reproduce it yet.
  55239. if (!coordSysAxesInfo) {
  55240. return;
  55241. }
  55242. if (illegalPoint(point)) {
  55243. // Used in the default behavior of `connection`: use the sample seriesIndex
  55244. // and dataIndex. And also used in the tooltipView trigger.
  55245. point = findPointFromSeries({
  55246. seriesIndex: finder.seriesIndex,
  55247. // Do not use dataIndexInside from other ec instance.
  55248. // FIXME: auto detect it?
  55249. dataIndex: finder.dataIndex
  55250. }, ecModel).point;
  55251. }
  55252. var isIllegalPoint = illegalPoint(point);
  55253. // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  55254. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  55255. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  55256. // and dataIndex.
  55257. var inputAxesInfo = finder.axesInfo;
  55258. var axesInfo = coordSysAxesInfo.axesInfo;
  55259. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  55260. var outputFinder = {};
  55261. var showValueMap = {};
  55262. var dataByCoordSys = {list: [], map: {}};
  55263. var updaters = {
  55264. showPointer: curry$3(showPointer, showValueMap),
  55265. showTooltip: curry$3(showTooltip, dataByCoordSys)
  55266. };
  55267. // Process for triggered axes.
  55268. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  55269. // If a point given, it must be contained by the coordinate system.
  55270. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  55271. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  55272. var axis = axisInfo.axis;
  55273. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo);
  55274. // If no inputAxesInfo, no axis is restricted.
  55275. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  55276. var val = inputAxisInfo && inputAxisInfo.value;
  55277. if (val == null && !isIllegalPoint) {
  55278. val = axis.pointToData(point);
  55279. }
  55280. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  55281. }
  55282. });
  55283. });
  55284. // Process for linked axes.
  55285. var linkTriggers = {};
  55286. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  55287. var linkGroup = tarAxisInfo.linkGroup;
  55288. // If axis has been triggered in the previous stage, it should not be triggered by link.
  55289. if (linkGroup && !showValueMap[tarKey]) {
  55290. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  55291. var srcValItem = showValueMap[srcKey];
  55292. // If srcValItem exist, source axis is triggered, so link to target axis.
  55293. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  55294. var val = srcValItem.value;
  55295. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(
  55296. val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo)
  55297. )));
  55298. linkTriggers[tarAxisInfo.key] = val;
  55299. }
  55300. });
  55301. }
  55302. });
  55303. each$14(linkTriggers, function (val, tarKey) {
  55304. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  55305. });
  55306. updateModelActually(showValueMap, axesInfo, outputFinder);
  55307. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  55308. dispatchHighDownActually(axesInfo, dispatchAction, api);
  55309. return outputFinder;
  55310. };
  55311. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  55312. var axis = axisInfo.axis;
  55313. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  55314. return;
  55315. }
  55316. if (!axisInfo.involveSeries) {
  55317. updaters.showPointer(axisInfo, newValue);
  55318. return;
  55319. }
  55320. // Heavy calculation. So put it after axis.containData checking.
  55321. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  55322. var payloadBatch = payloadInfo.payloadBatch;
  55323. var snapToValue = payloadInfo.snapToValue;
  55324. // Fill content of event obj for echarts.connect.
  55325. // By defualt use the first involved series data as a sample to connect.
  55326. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  55327. extend(outputFinder, payloadBatch[0]);
  55328. }
  55329. // If no linkSource input, this process is for collecting link
  55330. // target, where snap should not be accepted.
  55331. if (!dontSnap && axisInfo.snap) {
  55332. if (axis.containData(snapToValue) && snapToValue != null) {
  55333. newValue = snapToValue;
  55334. }
  55335. }
  55336. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder);
  55337. // Tooltip should always be snapToValue, otherwise there will be
  55338. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  55339. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  55340. }
  55341. function buildPayloadsBySeries(value, axisInfo) {
  55342. var axis = axisInfo.axis;
  55343. var dim = axis.dim;
  55344. var snapToValue = value;
  55345. var payloadBatch = [];
  55346. var minDist = Number.MAX_VALUE;
  55347. var minDiff = -1;
  55348. each$14(axisInfo.seriesModels, function (series, idx) {
  55349. var dataDim = series.getData().mapDimension(dim, true);
  55350. var seriesNestestValue;
  55351. var dataIndices;
  55352. if (series.getAxisTooltipData) {
  55353. var result = series.getAxisTooltipData(dataDim, value, axis);
  55354. dataIndices = result.dataIndices;
  55355. seriesNestestValue = result.nestestValue;
  55356. }
  55357. else {
  55358. dataIndices = series.getData().indicesOfNearest(
  55359. dataDim[0],
  55360. value,
  55361. // Add a threshold to avoid find the wrong dataIndex
  55362. // when data length is not same.
  55363. // false,
  55364. axis.type === 'category' ? 0.5 : null
  55365. );
  55366. if (!dataIndices.length) {
  55367. return;
  55368. }
  55369. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  55370. }
  55371. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  55372. return;
  55373. }
  55374. var diff = value - seriesNestestValue;
  55375. var dist = Math.abs(diff);
  55376. // Consider category case
  55377. if (dist <= minDist) {
  55378. if (dist < minDist || (diff >= 0 && minDiff < 0)) {
  55379. minDist = dist;
  55380. minDiff = diff;
  55381. snapToValue = seriesNestestValue;
  55382. payloadBatch.length = 0;
  55383. }
  55384. each$14(dataIndices, function (dataIndex) {
  55385. payloadBatch.push({
  55386. seriesIndex: series.seriesIndex,
  55387. dataIndexInside: dataIndex,
  55388. dataIndex: series.getData().getRawIndex(dataIndex)
  55389. });
  55390. });
  55391. }
  55392. });
  55393. return {
  55394. payloadBatch: payloadBatch,
  55395. snapToValue: snapToValue
  55396. };
  55397. }
  55398. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  55399. showValueMap[axisInfo.key] = {value: value, payloadBatch: payloadBatch};
  55400. }
  55401. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  55402. var payloadBatch = payloadInfo.payloadBatch;
  55403. var axis = axisInfo.axis;
  55404. var axisModel = axis.model;
  55405. var axisPointerModel = axisInfo.axisPointerModel;
  55406. // If no data, do not create anything in dataByCoordSys,
  55407. // whose length will be used to judge whether dispatch action.
  55408. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  55409. return;
  55410. }
  55411. var coordSysModel = axisInfo.coordSys.model;
  55412. var coordSysKey = makeKey(coordSysModel);
  55413. var coordSysItem = dataByCoordSys.map[coordSysKey];
  55414. if (!coordSysItem) {
  55415. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  55416. coordSysId: coordSysModel.id,
  55417. coordSysIndex: coordSysModel.componentIndex,
  55418. coordSysType: coordSysModel.type,
  55419. coordSysMainType: coordSysModel.mainType,
  55420. dataByAxis: []
  55421. };
  55422. dataByCoordSys.list.push(coordSysItem);
  55423. }
  55424. coordSysItem.dataByAxis.push({
  55425. axisDim: axis.dim,
  55426. axisIndex: axisModel.componentIndex,
  55427. axisType: axisModel.type,
  55428. axisId: axisModel.id,
  55429. value: value,
  55430. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  55431. // depends that all models have been updated. So it should not be performed
  55432. // here. Considering axisPointerModel used here is volatile, which is hard
  55433. // to be retrieve in TooltipView, we prepare parameters here.
  55434. valueLabelOpt: {
  55435. precision: axisPointerModel.get('label.precision'),
  55436. formatter: axisPointerModel.get('label.formatter')
  55437. },
  55438. seriesDataIndices: payloadBatch.slice()
  55439. });
  55440. }
  55441. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  55442. var outputAxesInfo = outputFinder.axesInfo = [];
  55443. // Basic logic: If no 'show' required, 'hide' this axisPointer.
  55444. each$14(axesInfo, function (axisInfo, key) {
  55445. var option = axisInfo.axisPointerModel.option;
  55446. var valItem = showValueMap[key];
  55447. if (valItem) {
  55448. !axisInfo.useHandle && (option.status = 'show');
  55449. option.value = valItem.value;
  55450. // For label formatter param and highlight.
  55451. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  55452. }
  55453. // When always show (e.g., handle used), remain
  55454. // original value and status.
  55455. else {
  55456. // If hide, value still need to be set, consider
  55457. // click legend to toggle axis blank.
  55458. !axisInfo.useHandle && (option.status = 'hide');
  55459. }
  55460. // If status is 'hide', should be no info in payload.
  55461. option.status === 'show' && outputAxesInfo.push({
  55462. axisDim: axisInfo.axis.dim,
  55463. axisIndex: axisInfo.axis.model.componentIndex,
  55464. value: option.value
  55465. });
  55466. });
  55467. }
  55468. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  55469. // Basic logic: If no showTip required, hideTip will be dispatched.
  55470. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  55471. dispatchAction({type: 'hideTip'});
  55472. return;
  55473. }
  55474. // In most case only one axis (or event one series is used). It is
  55475. // convinient to fetch payload.seriesIndex and payload.dataIndex
  55476. // dirtectly. So put the first seriesIndex and dataIndex of the first
  55477. // axis on the payload.
  55478. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  55479. dispatchAction({
  55480. type: 'showTip',
  55481. escapeConnect: true,
  55482. x: point[0],
  55483. y: point[1],
  55484. tooltipOption: payload.tooltipOption,
  55485. position: payload.position,
  55486. dataIndexInside: sampleItem.dataIndexInside,
  55487. dataIndex: sampleItem.dataIndex,
  55488. seriesIndex: sampleItem.seriesIndex,
  55489. dataByCoordSys: dataByCoordSys.list
  55490. });
  55491. }
  55492. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  55493. // FIXME
  55494. // highlight status modification shoule be a stage of main process?
  55495. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  55496. var zr = api.getZr();
  55497. var highDownKey = 'axisPointerLastHighlights';
  55498. var lastHighlights = inner$7(zr)[highDownKey] || {};
  55499. var newHighlights = inner$7(zr)[highDownKey] = {};
  55500. // Update highlight/downplay status according to axisPointer model.
  55501. // Build hash map and remove duplicate incidentally.
  55502. each$14(axesInfo, function (axisInfo, key) {
  55503. var option = axisInfo.axisPointerModel.option;
  55504. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  55505. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  55506. newHighlights[key] = batchItem;
  55507. });
  55508. });
  55509. // Diff.
  55510. var toHighlight = [];
  55511. var toDownplay = [];
  55512. each$1(lastHighlights, function (batchItem, key) {
  55513. !newHighlights[key] && toDownplay.push(batchItem);
  55514. });
  55515. each$1(newHighlights, function (batchItem, key) {
  55516. !lastHighlights[key] && toHighlight.push(batchItem);
  55517. });
  55518. toDownplay.length && api.dispatchAction({
  55519. type: 'downplay', escapeConnect: true, batch: toDownplay
  55520. });
  55521. toHighlight.length && api.dispatchAction({
  55522. type: 'highlight', escapeConnect: true, batch: toHighlight
  55523. });
  55524. }
  55525. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  55526. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  55527. var inputAxisInfo = inputAxesInfo[i];
  55528. if (axisInfo.axis.dim === inputAxisInfo.axisDim
  55529. && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex
  55530. ) {
  55531. return inputAxisInfo;
  55532. }
  55533. }
  55534. }
  55535. function makeMapperParam(axisInfo) {
  55536. var axisModel = axisInfo.axis.model;
  55537. var item = {};
  55538. var dim = item.axisDim = axisInfo.axis.dim;
  55539. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  55540. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  55541. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  55542. return item;
  55543. }
  55544. function illegalPoint(point) {
  55545. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  55546. }
  55547. /*
  55548. * Licensed to the Apache Software Foundation (ASF) under one
  55549. * or more contributor license agreements. See the NOTICE file
  55550. * distributed with this work for additional information
  55551. * regarding copyright ownership. The ASF licenses this file
  55552. * to you under the Apache License, Version 2.0 (the
  55553. * "License"); you may not use this file except in compliance
  55554. * with the License. You may obtain a copy of the License at
  55555. *
  55556. * http://www.apache.org/licenses/LICENSE-2.0
  55557. *
  55558. * Unless required by applicable law or agreed to in writing,
  55559. * software distributed under the License is distributed on an
  55560. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55561. * KIND, either express or implied. See the License for the
  55562. * specific language governing permissions and limitations
  55563. * under the License.
  55564. */
  55565. var AxisPointerModel = extendComponentModel({
  55566. type: 'axisPointer',
  55567. coordSysAxesInfo: null,
  55568. defaultOption: {
  55569. // 'auto' means that show when triggered by tooltip or handle.
  55570. show: 'auto',
  55571. // 'click' | 'mousemove' | 'none'
  55572. triggerOn: null, // set default in AxisPonterView.js
  55573. zlevel: 0,
  55574. z: 50,
  55575. type: 'line',
  55576. // axispointer triggered by tootip determine snap automatically,
  55577. // see `modelHelper`.
  55578. snap: false,
  55579. triggerTooltip: true,
  55580. value: null,
  55581. status: null, // Init value depends on whether handle is used.
  55582. // [group0, group1, ...]
  55583. // Each group can be: {
  55584. // mapper: function () {},
  55585. // singleTooltip: 'multiple', // 'multiple' or 'single'
  55586. // xAxisId: ...,
  55587. // yAxisName: ...,
  55588. // angleAxisIndex: ...
  55589. // }
  55590. // mapper: can be ignored.
  55591. // input: {axisInfo, value}
  55592. // output: {axisInfo, value}
  55593. link: [],
  55594. // Do not set 'auto' here, otherwise global animation: false
  55595. // will not effect at this axispointer.
  55596. animation: null,
  55597. animationDurationUpdate: 200,
  55598. lineStyle: {
  55599. color: '#aaa',
  55600. width: 1,
  55601. type: 'solid'
  55602. },
  55603. shadowStyle: {
  55604. color: 'rgba(150,150,150,0.3)'
  55605. },
  55606. label: {
  55607. show: true,
  55608. formatter: null, // string | Function
  55609. precision: 'auto', // Or a number like 0, 1, 2 ...
  55610. margin: 3,
  55611. color: '#fff',
  55612. padding: [5, 7, 5, 7],
  55613. backgroundColor: 'auto', // default: axis line color
  55614. borderColor: null,
  55615. borderWidth: 0,
  55616. shadowBlur: 3,
  55617. shadowColor: '#aaa'
  55618. // Considering applicability, common style should
  55619. // better not have shadowOffset.
  55620. // shadowOffsetX: 0,
  55621. // shadowOffsetY: 2
  55622. },
  55623. handle: {
  55624. show: false,
  55625. 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
  55626. size: 45,
  55627. // handle margin is from symbol center to axis, which is stable when circular move.
  55628. margin: 50,
  55629. // color: '#1b8bbd'
  55630. // color: '#2f4554'
  55631. color: '#333',
  55632. shadowBlur: 3,
  55633. shadowColor: '#aaa',
  55634. shadowOffsetX: 0,
  55635. shadowOffsetY: 2,
  55636. // For mobile performance
  55637. throttle: 40
  55638. }
  55639. }
  55640. });
  55641. /*
  55642. * Licensed to the Apache Software Foundation (ASF) under one
  55643. * or more contributor license agreements. See the NOTICE file
  55644. * distributed with this work for additional information
  55645. * regarding copyright ownership. The ASF licenses this file
  55646. * to you under the Apache License, Version 2.0 (the
  55647. * "License"); you may not use this file except in compliance
  55648. * with the License. You may obtain a copy of the License at
  55649. *
  55650. * http://www.apache.org/licenses/LICENSE-2.0
  55651. *
  55652. * Unless required by applicable law or agreed to in writing,
  55653. * software distributed under the License is distributed on an
  55654. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55655. * KIND, either express or implied. See the License for the
  55656. * specific language governing permissions and limitations
  55657. * under the License.
  55658. */
  55659. var inner$8 = makeInner();
  55660. var each$15 = each$1;
  55661. /**
  55662. * @param {string} key
  55663. * @param {module:echarts/ExtensionAPI} api
  55664. * @param {Function} handler
  55665. * param: {string} currTrigger
  55666. * param: {Array.<number>} point
  55667. */
  55668. function register(key, api, handler) {
  55669. if (env$1.node) {
  55670. return;
  55671. }
  55672. var zr = api.getZr();
  55673. inner$8(zr).records || (inner$8(zr).records = {});
  55674. initGlobalListeners(zr, api);
  55675. var record = inner$8(zr).records[key] || (inner$8(zr).records[key] = {});
  55676. record.handler = handler;
  55677. }
  55678. function initGlobalListeners(zr, api) {
  55679. if (inner$8(zr).initialized) {
  55680. return;
  55681. }
  55682. inner$8(zr).initialized = true;
  55683. useHandler('click', curry(doEnter, 'click'));
  55684. useHandler('mousemove', curry(doEnter, 'mousemove'));
  55685. // useHandler('mouseout', onLeave);
  55686. useHandler('globalout', onLeave);
  55687. function useHandler(eventType, cb) {
  55688. zr.on(eventType, function (e) {
  55689. var dis = makeDispatchAction(api);
  55690. each$15(inner$8(zr).records, function (record) {
  55691. record && cb(record, e, dis.dispatchAction);
  55692. });
  55693. dispatchTooltipFinally(dis.pendings, api);
  55694. });
  55695. }
  55696. }
  55697. function dispatchTooltipFinally(pendings, api) {
  55698. var showLen = pendings.showTip.length;
  55699. var hideLen = pendings.hideTip.length;
  55700. var actuallyPayload;
  55701. if (showLen) {
  55702. actuallyPayload = pendings.showTip[showLen - 1];
  55703. }
  55704. else if (hideLen) {
  55705. actuallyPayload = pendings.hideTip[hideLen - 1];
  55706. }
  55707. if (actuallyPayload) {
  55708. actuallyPayload.dispatchAction = null;
  55709. api.dispatchAction(actuallyPayload);
  55710. }
  55711. }
  55712. function onLeave(record, e, dispatchAction) {
  55713. record.handler('leave', null, dispatchAction);
  55714. }
  55715. function doEnter(currTrigger, record, e, dispatchAction) {
  55716. record.handler(currTrigger, e, dispatchAction);
  55717. }
  55718. function makeDispatchAction(api) {
  55719. var pendings = {
  55720. showTip: [],
  55721. hideTip: []
  55722. };
  55723. // FIXME
  55724. // better approach?
  55725. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  55726. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  55727. // So we have to add "final stage" to merge those dispatched actions.
  55728. var dispatchAction = function (payload) {
  55729. var pendingList = pendings[payload.type];
  55730. if (pendingList) {
  55731. pendingList.push(payload);
  55732. }
  55733. else {
  55734. payload.dispatchAction = dispatchAction;
  55735. api.dispatchAction(payload);
  55736. }
  55737. };
  55738. return {
  55739. dispatchAction: dispatchAction,
  55740. pendings: pendings
  55741. };
  55742. }
  55743. /**
  55744. * @param {string} key
  55745. * @param {module:echarts/ExtensionAPI} api
  55746. */
  55747. function unregister(key, api) {
  55748. if (env$1.node) {
  55749. return;
  55750. }
  55751. var zr = api.getZr();
  55752. var record = (inner$8(zr).records || {})[key];
  55753. if (record) {
  55754. inner$8(zr).records[key] = null;
  55755. }
  55756. }
  55757. /*
  55758. * Licensed to the Apache Software Foundation (ASF) under one
  55759. * or more contributor license agreements. See the NOTICE file
  55760. * distributed with this work for additional information
  55761. * regarding copyright ownership. The ASF licenses this file
  55762. * to you under the Apache License, Version 2.0 (the
  55763. * "License"); you may not use this file except in compliance
  55764. * with the License. You may obtain a copy of the License at
  55765. *
  55766. * http://www.apache.org/licenses/LICENSE-2.0
  55767. *
  55768. * Unless required by applicable law or agreed to in writing,
  55769. * software distributed under the License is distributed on an
  55770. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55771. * KIND, either express or implied. See the License for the
  55772. * specific language governing permissions and limitations
  55773. * under the License.
  55774. */
  55775. var AxisPointerView = extendComponentView({
  55776. type: 'axisPointer',
  55777. render: function (globalAxisPointerModel, ecModel, api) {
  55778. var globalTooltipModel = ecModel.getComponent('tooltip');
  55779. var triggerOn = globalAxisPointerModel.get('triggerOn')
  55780. || (globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click');
  55781. // Register global listener in AxisPointerView to enable
  55782. // AxisPointerView to be independent to Tooltip.
  55783. register(
  55784. 'axisPointer',
  55785. api,
  55786. function (currTrigger, e, dispatchAction) {
  55787. // If 'none', it is not controlled by mouse totally.
  55788. if (triggerOn !== 'none'
  55789. && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)
  55790. ) {
  55791. dispatchAction({
  55792. type: 'updateAxisPointer',
  55793. currTrigger: currTrigger,
  55794. x: e && e.offsetX,
  55795. y: e && e.offsetY
  55796. });
  55797. }
  55798. }
  55799. );
  55800. },
  55801. /**
  55802. * @override
  55803. */
  55804. remove: function (ecModel, api) {
  55805. unregister(api.getZr(), 'axisPointer');
  55806. AxisPointerView.superApply(this._model, 'remove', arguments);
  55807. },
  55808. /**
  55809. * @override
  55810. */
  55811. dispose: function (ecModel, api) {
  55812. unregister('axisPointer', api);
  55813. AxisPointerView.superApply(this._model, 'dispose', arguments);
  55814. }
  55815. });
  55816. /*
  55817. * Licensed to the Apache Software Foundation (ASF) under one
  55818. * or more contributor license agreements. See the NOTICE file
  55819. * distributed with this work for additional information
  55820. * regarding copyright ownership. The ASF licenses this file
  55821. * to you under the Apache License, Version 2.0 (the
  55822. * "License"); you may not use this file except in compliance
  55823. * with the License. You may obtain a copy of the License at
  55824. *
  55825. * http://www.apache.org/licenses/LICENSE-2.0
  55826. *
  55827. * Unless required by applicable law or agreed to in writing,
  55828. * software distributed under the License is distributed on an
  55829. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55830. * KIND, either express or implied. See the License for the
  55831. * specific language governing permissions and limitations
  55832. * under the License.
  55833. */
  55834. var inner$9 = makeInner();
  55835. var clone$4 = clone;
  55836. var bind$2 = bind;
  55837. /**
  55838. * Base axis pointer class in 2D.
  55839. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  55840. */
  55841. function BaseAxisPointer () {
  55842. }
  55843. BaseAxisPointer.prototype = {
  55844. /**
  55845. * @private
  55846. */
  55847. _group: null,
  55848. /**
  55849. * @private
  55850. */
  55851. _lastGraphicKey: null,
  55852. /**
  55853. * @private
  55854. */
  55855. _handle: null,
  55856. /**
  55857. * @private
  55858. */
  55859. _dragging: false,
  55860. /**
  55861. * @private
  55862. */
  55863. _lastValue: null,
  55864. /**
  55865. * @private
  55866. */
  55867. _lastStatus: null,
  55868. /**
  55869. * @private
  55870. */
  55871. _payloadInfo: null,
  55872. /**
  55873. * In px, arbitrary value. Do not set too small,
  55874. * no animation is ok for most cases.
  55875. * @protected
  55876. */
  55877. animationThreshold: 15,
  55878. /**
  55879. * @implement
  55880. */
  55881. render: function (axisModel, axisPointerModel, api, forceRender) {
  55882. var value = axisPointerModel.get('value');
  55883. var status = axisPointerModel.get('status');
  55884. // Bind them to `this`, not in closure, otherwise they will not
  55885. // be replaced when user calling setOption in not merge mode.
  55886. this._axisModel = axisModel;
  55887. this._axisPointerModel = axisPointerModel;
  55888. this._api = api;
  55889. // Optimize: `render` will be called repeatly during mouse move.
  55890. // So it is power consuming if performing `render` each time,
  55891. // especially on mobile device.
  55892. if (!forceRender
  55893. && this._lastValue === value
  55894. && this._lastStatus === status
  55895. ) {
  55896. return;
  55897. }
  55898. this._lastValue = value;
  55899. this._lastStatus = status;
  55900. var group = this._group;
  55901. var handle = this._handle;
  55902. if (!status || status === 'hide') {
  55903. // Do not clear here, for animation better.
  55904. group && group.hide();
  55905. handle && handle.hide();
  55906. return;
  55907. }
  55908. group && group.show();
  55909. handle && handle.show();
  55910. // Otherwise status is 'show'
  55911. var elOption = {};
  55912. this.makeElOption(elOption, value, axisModel, axisPointerModel, api);
  55913. // Enable change axis pointer type.
  55914. var graphicKey = elOption.graphicKey;
  55915. if (graphicKey !== this._lastGraphicKey) {
  55916. this.clear(api);
  55917. }
  55918. this._lastGraphicKey = graphicKey;
  55919. var moveAnimation = this._moveAnimation =
  55920. this.determineAnimation(axisModel, axisPointerModel);
  55921. if (!group) {
  55922. group = this._group = new Group();
  55923. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  55924. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  55925. api.getZr().add(group);
  55926. }
  55927. else {
  55928. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  55929. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  55930. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  55931. }
  55932. updateMandatoryProps(group, axisPointerModel, true);
  55933. this._renderHandle(value);
  55934. },
  55935. /**
  55936. * @implement
  55937. */
  55938. remove: function (api) {
  55939. this.clear(api);
  55940. },
  55941. /**
  55942. * @implement
  55943. */
  55944. dispose: function (api) {
  55945. this.clear(api);
  55946. },
  55947. /**
  55948. * @protected
  55949. */
  55950. determineAnimation: function (axisModel, axisPointerModel) {
  55951. var animation = axisPointerModel.get('animation');
  55952. var axis = axisModel.axis;
  55953. var isCategoryAxis = axis.type === 'category';
  55954. var useSnap = axisPointerModel.get('snap');
  55955. // Value axis without snap always do not snap.
  55956. if (!useSnap && !isCategoryAxis) {
  55957. return false;
  55958. }
  55959. if (animation === 'auto' || animation == null) {
  55960. var animationThreshold = this.animationThreshold;
  55961. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  55962. return true;
  55963. }
  55964. // It is important to auto animation when snap used. Consider if there is
  55965. // a dataZoom, animation will be disabled when too many points exist, while
  55966. // it will be enabled for better visual effect when little points exist.
  55967. if (useSnap) {
  55968. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  55969. var axisExtent = axis.getExtent();
  55970. // Approximate band width
  55971. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  55972. }
  55973. return false;
  55974. }
  55975. return animation === true;
  55976. },
  55977. /**
  55978. * add {pointer, label, graphicKey} to elOption
  55979. * @protected
  55980. */
  55981. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  55982. // Shoule be implemenented by sub-class.
  55983. },
  55984. /**
  55985. * @protected
  55986. */
  55987. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  55988. var pointerOption = elOption.pointer;
  55989. if (pointerOption) {
  55990. var pointerEl = inner$9(group).pointerEl = new graphic[pointerOption.type](
  55991. clone$4(elOption.pointer)
  55992. );
  55993. group.add(pointerEl);
  55994. }
  55995. },
  55996. /**
  55997. * @protected
  55998. */
  55999. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  56000. if (elOption.label) {
  56001. var labelEl = inner$9(group).labelEl = new Rect(
  56002. clone$4(elOption.label)
  56003. );
  56004. group.add(labelEl);
  56005. updateLabelShowHide(labelEl, axisPointerModel);
  56006. }
  56007. },
  56008. /**
  56009. * @protected
  56010. */
  56011. updatePointerEl: function (group, elOption, updateProps$$1) {
  56012. var pointerEl = inner$9(group).pointerEl;
  56013. if (pointerEl) {
  56014. pointerEl.setStyle(elOption.pointer.style);
  56015. updateProps$$1(pointerEl, {shape: elOption.pointer.shape});
  56016. }
  56017. },
  56018. /**
  56019. * @protected
  56020. */
  56021. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  56022. var labelEl = inner$9(group).labelEl;
  56023. if (labelEl) {
  56024. labelEl.setStyle(elOption.label.style);
  56025. updateProps$$1(labelEl, {
  56026. // Consider text length change in vertical axis, animation should
  56027. // be used on shape, otherwise the effect will be weird.
  56028. shape: elOption.label.shape,
  56029. position: elOption.label.position
  56030. });
  56031. updateLabelShowHide(labelEl, axisPointerModel);
  56032. }
  56033. },
  56034. /**
  56035. * @private
  56036. */
  56037. _renderHandle: function (value) {
  56038. if (this._dragging || !this.updateHandleTransform) {
  56039. return;
  56040. }
  56041. var axisPointerModel = this._axisPointerModel;
  56042. var zr = this._api.getZr();
  56043. var handle = this._handle;
  56044. var handleModel = axisPointerModel.getModel('handle');
  56045. var status = axisPointerModel.get('status');
  56046. if (!handleModel.get('show') || !status || status === 'hide') {
  56047. handle && zr.remove(handle);
  56048. this._handle = null;
  56049. return;
  56050. }
  56051. var isInit;
  56052. if (!this._handle) {
  56053. isInit = true;
  56054. handle = this._handle = createIcon(
  56055. handleModel.get('icon'),
  56056. {
  56057. cursor: 'move',
  56058. draggable: true,
  56059. onmousemove: function (e) {
  56060. // Fot mobile devicem, prevent screen slider on the button.
  56061. stop(e.event);
  56062. },
  56063. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  56064. drift: bind$2(this._onHandleDragMove, this),
  56065. ondragend: bind$2(this._onHandleDragEnd, this)
  56066. }
  56067. );
  56068. zr.add(handle);
  56069. }
  56070. updateMandatoryProps(handle, axisPointerModel, false);
  56071. // update style
  56072. var includeStyles = [
  56073. 'color', 'borderColor', 'borderWidth', 'opacity',
  56074. 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'
  56075. ];
  56076. handle.setStyle(handleModel.getItemStyle(null, includeStyles));
  56077. // update position
  56078. var handleSize = handleModel.get('size');
  56079. if (!isArray(handleSize)) {
  56080. handleSize = [handleSize, handleSize];
  56081. }
  56082. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  56083. createOrUpdate(
  56084. this,
  56085. '_doDispatchAxisPointer',
  56086. handleModel.get('throttle') || 0,
  56087. 'fixRate'
  56088. );
  56089. this._moveHandleToValue(value, isInit);
  56090. },
  56091. /**
  56092. * @private
  56093. */
  56094. _moveHandleToValue: function (value, isInit) {
  56095. updateProps$1(
  56096. this._axisPointerModel,
  56097. !isInit && this._moveAnimation,
  56098. this._handle,
  56099. getHandleTransProps(this.getHandleTransform(
  56100. value, this._axisModel, this._axisPointerModel
  56101. ))
  56102. );
  56103. },
  56104. /**
  56105. * @private
  56106. */
  56107. _onHandleDragMove: function (dx, dy) {
  56108. var handle = this._handle;
  56109. if (!handle) {
  56110. return;
  56111. }
  56112. this._dragging = true;
  56113. // Persistent for throttle.
  56114. var trans = this.updateHandleTransform(
  56115. getHandleTransProps(handle),
  56116. [dx, dy],
  56117. this._axisModel,
  56118. this._axisPointerModel
  56119. );
  56120. this._payloadInfo = trans;
  56121. handle.stopAnimation();
  56122. handle.attr(getHandleTransProps(trans));
  56123. inner$9(handle).lastProp = null;
  56124. this._doDispatchAxisPointer();
  56125. },
  56126. /**
  56127. * Throttled method.
  56128. * @private
  56129. */
  56130. _doDispatchAxisPointer: function () {
  56131. var handle = this._handle;
  56132. if (!handle) {
  56133. return;
  56134. }
  56135. var payloadInfo = this._payloadInfo;
  56136. var axisModel = this._axisModel;
  56137. this._api.dispatchAction({
  56138. type: 'updateAxisPointer',
  56139. x: payloadInfo.cursorPoint[0],
  56140. y: payloadInfo.cursorPoint[1],
  56141. tooltipOption: payloadInfo.tooltipOption,
  56142. axesInfo: [{
  56143. axisDim: axisModel.axis.dim,
  56144. axisIndex: axisModel.componentIndex
  56145. }]
  56146. });
  56147. },
  56148. /**
  56149. * @private
  56150. */
  56151. _onHandleDragEnd: function (moveAnimation) {
  56152. this._dragging = false;
  56153. var handle = this._handle;
  56154. if (!handle) {
  56155. return;
  56156. }
  56157. var value = this._axisPointerModel.get('value');
  56158. // Consider snap or categroy axis, handle may be not consistent with
  56159. // axisPointer. So move handle to align the exact value position when
  56160. // drag ended.
  56161. this._moveHandleToValue(value);
  56162. // For the effect: tooltip will be shown when finger holding on handle
  56163. // button, and will be hidden after finger left handle button.
  56164. this._api.dispatchAction({
  56165. type: 'hideTip'
  56166. });
  56167. },
  56168. /**
  56169. * Should be implemenented by sub-class if support `handle`.
  56170. * @protected
  56171. * @param {number} value
  56172. * @param {module:echarts/model/Model} axisModel
  56173. * @param {module:echarts/model/Model} axisPointerModel
  56174. * @return {Object} {position: [x, y], rotation: 0}
  56175. */
  56176. getHandleTransform: null,
  56177. /**
  56178. * * Should be implemenented by sub-class if support `handle`.
  56179. * @protected
  56180. * @param {Object} transform {position, rotation}
  56181. * @param {Array.<number>} delta [dx, dy]
  56182. * @param {module:echarts/model/Model} axisModel
  56183. * @param {module:echarts/model/Model} axisPointerModel
  56184. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  56185. */
  56186. updateHandleTransform: null,
  56187. /**
  56188. * @private
  56189. */
  56190. clear: function (api) {
  56191. this._lastValue = null;
  56192. this._lastStatus = null;
  56193. var zr = api.getZr();
  56194. var group = this._group;
  56195. var handle = this._handle;
  56196. if (zr && group) {
  56197. this._lastGraphicKey = null;
  56198. group && zr.remove(group);
  56199. handle && zr.remove(handle);
  56200. this._group = null;
  56201. this._handle = null;
  56202. this._payloadInfo = null;
  56203. }
  56204. },
  56205. /**
  56206. * @protected
  56207. */
  56208. doClear: function () {
  56209. // Implemented by sub-class if necessary.
  56210. },
  56211. /**
  56212. * @protected
  56213. * @param {Array.<number>} xy
  56214. * @param {Array.<number>} wh
  56215. * @param {number} [xDimIndex=0] or 1
  56216. */
  56217. buildLabel: function (xy, wh, xDimIndex) {
  56218. xDimIndex = xDimIndex || 0;
  56219. return {
  56220. x: xy[xDimIndex],
  56221. y: xy[1 - xDimIndex],
  56222. width: wh[xDimIndex],
  56223. height: wh[1 - xDimIndex]
  56224. };
  56225. }
  56226. };
  56227. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  56228. function updateProps$1(animationModel, moveAnimation, el, props) {
  56229. // Animation optimize.
  56230. if (!propsEqual(inner$9(el).lastProp, props)) {
  56231. inner$9(el).lastProp = props;
  56232. moveAnimation
  56233. ? updateProps(el, props, animationModel)
  56234. : (el.stopAnimation(), el.attr(props));
  56235. }
  56236. }
  56237. function propsEqual(lastProps, newProps) {
  56238. if (isObject$1(lastProps) && isObject$1(newProps)) {
  56239. var equals = true;
  56240. each$1(newProps, function (item, key) {
  56241. equals = equals && propsEqual(lastProps[key], item);
  56242. });
  56243. return !!equals;
  56244. }
  56245. else {
  56246. return lastProps === newProps;
  56247. }
  56248. }
  56249. function updateLabelShowHide(labelEl, axisPointerModel) {
  56250. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  56251. }
  56252. function getHandleTransProps(trans) {
  56253. return {
  56254. position: trans.position.slice(),
  56255. rotation: trans.rotation || 0
  56256. };
  56257. }
  56258. function updateMandatoryProps(group, axisPointerModel, silent) {
  56259. var z = axisPointerModel.get('z');
  56260. var zlevel = axisPointerModel.get('zlevel');
  56261. group && group.traverse(function (el) {
  56262. if (el.type !== 'group') {
  56263. z != null && (el.z = z);
  56264. zlevel != null && (el.zlevel = zlevel);
  56265. el.silent = silent;
  56266. }
  56267. });
  56268. }
  56269. enableClassExtend(BaseAxisPointer);
  56270. /*
  56271. * Licensed to the Apache Software Foundation (ASF) under one
  56272. * or more contributor license agreements. See the NOTICE file
  56273. * distributed with this work for additional information
  56274. * regarding copyright ownership. The ASF licenses this file
  56275. * to you under the Apache License, Version 2.0 (the
  56276. * "License"); you may not use this file except in compliance
  56277. * with the License. You may obtain a copy of the License at
  56278. *
  56279. * http://www.apache.org/licenses/LICENSE-2.0
  56280. *
  56281. * Unless required by applicable law or agreed to in writing,
  56282. * software distributed under the License is distributed on an
  56283. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56284. * KIND, either express or implied. See the License for the
  56285. * specific language governing permissions and limitations
  56286. * under the License.
  56287. */
  56288. /**
  56289. * @param {module:echarts/model/Model} axisPointerModel
  56290. */
  56291. function buildElStyle(axisPointerModel) {
  56292. var axisPointerType = axisPointerModel.get('type');
  56293. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  56294. var style;
  56295. if (axisPointerType === 'line') {
  56296. style = styleModel.getLineStyle();
  56297. style.fill = null;
  56298. }
  56299. else if (axisPointerType === 'shadow') {
  56300. style = styleModel.getAreaStyle();
  56301. style.stroke = null;
  56302. }
  56303. return style;
  56304. }
  56305. /**
  56306. * @param {Function} labelPos {align, verticalAlign, position}
  56307. */
  56308. function buildLabelElOption(
  56309. elOption, axisModel, axisPointerModel, api, labelPos
  56310. ) {
  56311. var value = axisPointerModel.get('value');
  56312. var text = getValueLabel(
  56313. value, axisModel.axis, axisModel.ecModel,
  56314. axisPointerModel.get('seriesDataIndices'),
  56315. {
  56316. precision: axisPointerModel.get('label.precision'),
  56317. formatter: axisPointerModel.get('label.formatter')
  56318. }
  56319. );
  56320. var labelModel = axisPointerModel.getModel('label');
  56321. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  56322. var font = labelModel.getFont();
  56323. var textRect = getBoundingRect(text, font);
  56324. var position = labelPos.position;
  56325. var width = textRect.width + paddings[1] + paddings[3];
  56326. var height = textRect.height + paddings[0] + paddings[2];
  56327. // Adjust by align.
  56328. var align = labelPos.align;
  56329. align === 'right' && (position[0] -= width);
  56330. align === 'center' && (position[0] -= width / 2);
  56331. var verticalAlign = labelPos.verticalAlign;
  56332. verticalAlign === 'bottom' && (position[1] -= height);
  56333. verticalAlign === 'middle' && (position[1] -= height / 2);
  56334. // Not overflow ec container
  56335. confineInContainer(position, width, height, api);
  56336. var bgColor = labelModel.get('backgroundColor');
  56337. if (!bgColor || bgColor === 'auto') {
  56338. bgColor = axisModel.get('axisLine.lineStyle.color');
  56339. }
  56340. elOption.label = {
  56341. shape: {x: 0, y: 0, width: width, height: height, r: labelModel.get('borderRadius')},
  56342. position: position.slice(),
  56343. // TODO: rich
  56344. style: {
  56345. text: text,
  56346. textFont: font,
  56347. textFill: labelModel.getTextColor(),
  56348. textPosition: 'inside',
  56349. fill: bgColor,
  56350. stroke: labelModel.get('borderColor') || 'transparent',
  56351. lineWidth: labelModel.get('borderWidth') || 0,
  56352. shadowBlur: labelModel.get('shadowBlur'),
  56353. shadowColor: labelModel.get('shadowColor'),
  56354. shadowOffsetX: labelModel.get('shadowOffsetX'),
  56355. shadowOffsetY: labelModel.get('shadowOffsetY')
  56356. },
  56357. // Lable should be over axisPointer.
  56358. z2: 10
  56359. };
  56360. }
  56361. // Do not overflow ec container
  56362. function confineInContainer(position, width, height, api) {
  56363. var viewWidth = api.getWidth();
  56364. var viewHeight = api.getHeight();
  56365. position[0] = Math.min(position[0] + width, viewWidth) - width;
  56366. position[1] = Math.min(position[1] + height, viewHeight) - height;
  56367. position[0] = Math.max(position[0], 0);
  56368. position[1] = Math.max(position[1], 0);
  56369. }
  56370. /**
  56371. * @param {number} value
  56372. * @param {module:echarts/coord/Axis} axis
  56373. * @param {module:echarts/model/Global} ecModel
  56374. * @param {Object} opt
  56375. * @param {Array.<Object>} seriesDataIndices
  56376. * @param {number|string} opt.precision 'auto' or a number
  56377. * @param {string|Function} opt.formatter label formatter
  56378. */
  56379. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  56380. value = axis.scale.parse(value);
  56381. var text = axis.scale.getLabel(
  56382. // If `precision` is set, width can be fixed (like '12.00500'), which
  56383. // helps to debounce when when moving label.
  56384. value, {precision: opt.precision}
  56385. );
  56386. var formatter = opt.formatter;
  56387. if (formatter) {
  56388. var params = {
  56389. value: getAxisRawValue(axis, value),
  56390. seriesData: []
  56391. };
  56392. each$1(seriesDataIndices, function (idxItem) {
  56393. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  56394. var dataIndex = idxItem.dataIndexInside;
  56395. var dataParams = series && series.getDataParams(dataIndex);
  56396. dataParams && params.seriesData.push(dataParams);
  56397. });
  56398. if (isString(formatter)) {
  56399. text = formatter.replace('{value}', text);
  56400. }
  56401. else if (isFunction$1(formatter)) {
  56402. text = formatter(params);
  56403. }
  56404. }
  56405. return text;
  56406. }
  56407. /**
  56408. * @param {module:echarts/coord/Axis} axis
  56409. * @param {number} value
  56410. * @param {Object} layoutInfo {
  56411. * rotation, position, labelOffset, labelDirection, labelMargin
  56412. * }
  56413. */
  56414. function getTransformedPosition (axis, value, layoutInfo) {
  56415. var transform = create$1();
  56416. rotate(transform, transform, layoutInfo.rotation);
  56417. translate(transform, transform, layoutInfo.position);
  56418. return applyTransform$1([
  56419. axis.dataToCoord(value),
  56420. (layoutInfo.labelOffset || 0)
  56421. + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)
  56422. ], transform);
  56423. }
  56424. function buildCartesianSingleLabelElOption(
  56425. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56426. ) {
  56427. var textLayout = AxisBuilder.innerTextLayout(
  56428. layoutInfo.rotation, 0, layoutInfo.labelDirection
  56429. );
  56430. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  56431. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  56432. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56433. align: textLayout.textAlign,
  56434. verticalAlign: textLayout.textVerticalAlign
  56435. });
  56436. }
  56437. /**
  56438. * @param {Array.<number>} p1
  56439. * @param {Array.<number>} p2
  56440. * @param {number} [xDimIndex=0] or 1
  56441. */
  56442. function makeLineShape(p1, p2, xDimIndex) {
  56443. xDimIndex = xDimIndex || 0;
  56444. return {
  56445. x1: p1[xDimIndex],
  56446. y1: p1[1 - xDimIndex],
  56447. x2: p2[xDimIndex],
  56448. y2: p2[1 - xDimIndex]
  56449. };
  56450. }
  56451. /**
  56452. * @param {Array.<number>} xy
  56453. * @param {Array.<number>} wh
  56454. * @param {number} [xDimIndex=0] or 1
  56455. */
  56456. function makeRectShape(xy, wh, xDimIndex) {
  56457. xDimIndex = xDimIndex || 0;
  56458. return {
  56459. x: xy[xDimIndex],
  56460. y: xy[1 - xDimIndex],
  56461. width: wh[xDimIndex],
  56462. height: wh[1 - xDimIndex]
  56463. };
  56464. }
  56465. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  56466. return {
  56467. cx: cx,
  56468. cy: cy,
  56469. r0: r0,
  56470. r: r,
  56471. startAngle: startAngle,
  56472. endAngle: endAngle,
  56473. clockwise: true
  56474. };
  56475. }
  56476. /*
  56477. * Licensed to the Apache Software Foundation (ASF) under one
  56478. * or more contributor license agreements. See the NOTICE file
  56479. * distributed with this work for additional information
  56480. * regarding copyright ownership. The ASF licenses this file
  56481. * to you under the Apache License, Version 2.0 (the
  56482. * "License"); you may not use this file except in compliance
  56483. * with the License. You may obtain a copy of the License at
  56484. *
  56485. * http://www.apache.org/licenses/LICENSE-2.0
  56486. *
  56487. * Unless required by applicable law or agreed to in writing,
  56488. * software distributed under the License is distributed on an
  56489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56490. * KIND, either express or implied. See the License for the
  56491. * specific language governing permissions and limitations
  56492. * under the License.
  56493. */
  56494. var CartesianAxisPointer = BaseAxisPointer.extend({
  56495. /**
  56496. * @override
  56497. */
  56498. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56499. var axis = axisModel.axis;
  56500. var grid = axis.grid;
  56501. var axisPointerType = axisPointerModel.get('type');
  56502. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  56503. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  56504. if (axisPointerType && axisPointerType !== 'none') {
  56505. var elStyle = buildElStyle(axisPointerModel);
  56506. var pointerOption = pointerShapeBuilder[axisPointerType](
  56507. axis, pixelValue, otherExtent, elStyle
  56508. );
  56509. pointerOption.style = elStyle;
  56510. elOption.graphicKey = pointerOption.type;
  56511. elOption.pointer = pointerOption;
  56512. }
  56513. var layoutInfo = layout$1(grid.model, axisModel);
  56514. buildCartesianSingleLabelElOption(
  56515. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56516. );
  56517. },
  56518. /**
  56519. * @override
  56520. */
  56521. getHandleTransform: function (value, axisModel, axisPointerModel) {
  56522. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  56523. labelInside: false
  56524. });
  56525. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  56526. return {
  56527. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56528. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  56529. };
  56530. },
  56531. /**
  56532. * @override
  56533. */
  56534. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  56535. var axis = axisModel.axis;
  56536. var grid = axis.grid;
  56537. var axisExtent = axis.getGlobalExtent(true);
  56538. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  56539. var dimIndex = axis.dim === 'x' ? 0 : 1;
  56540. var currPosition = transform.position;
  56541. currPosition[dimIndex] += delta[dimIndex];
  56542. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  56543. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  56544. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  56545. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  56546. cursorPoint[dimIndex] = currPosition[dimIndex];
  56547. // Make tooltip do not overlap axisPointer and in the middle of the grid.
  56548. var tooltipOptions = [{verticalAlign: 'middle'}, {align: 'center'}];
  56549. return {
  56550. position: currPosition,
  56551. rotation: transform.rotation,
  56552. cursorPoint: cursorPoint,
  56553. tooltipOption: tooltipOptions[dimIndex]
  56554. };
  56555. }
  56556. });
  56557. function getCartesian(grid, axis) {
  56558. var opt = {};
  56559. opt[axis.dim + 'AxisIndex'] = axis.index;
  56560. return grid.getCartesian(opt);
  56561. }
  56562. var pointerShapeBuilder = {
  56563. line: function (axis, pixelValue, otherExtent, elStyle) {
  56564. var targetShape = makeLineShape(
  56565. [pixelValue, otherExtent[0]],
  56566. [pixelValue, otherExtent[1]],
  56567. getAxisDimIndex(axis)
  56568. );
  56569. subPixelOptimizeLine({
  56570. shape: targetShape,
  56571. style: elStyle
  56572. });
  56573. return {
  56574. type: 'Line',
  56575. shape: targetShape
  56576. };
  56577. },
  56578. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  56579. var bandWidth = Math.max(1, axis.getBandWidth());
  56580. var span = otherExtent[1] - otherExtent[0];
  56581. return {
  56582. type: 'Rect',
  56583. shape: makeRectShape(
  56584. [pixelValue - bandWidth / 2, otherExtent[0]],
  56585. [bandWidth, span],
  56586. getAxisDimIndex(axis)
  56587. )
  56588. };
  56589. }
  56590. };
  56591. function getAxisDimIndex(axis) {
  56592. return axis.dim === 'x' ? 0 : 1;
  56593. }
  56594. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  56595. /*
  56596. * Licensed to the Apache Software Foundation (ASF) under one
  56597. * or more contributor license agreements. See the NOTICE file
  56598. * distributed with this work for additional information
  56599. * regarding copyright ownership. The ASF licenses this file
  56600. * to you under the Apache License, Version 2.0 (the
  56601. * "License"); you may not use this file except in compliance
  56602. * with the License. You may obtain a copy of the License at
  56603. *
  56604. * http://www.apache.org/licenses/LICENSE-2.0
  56605. *
  56606. * Unless required by applicable law or agreed to in writing,
  56607. * software distributed under the License is distributed on an
  56608. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56609. * KIND, either express or implied. See the License for the
  56610. * specific language governing permissions and limitations
  56611. * under the License.
  56612. */
  56613. // CartesianAxisPointer is not supposed to be required here. But consider
  56614. // echarts.simple.js and online build tooltip, which only require gridSimple,
  56615. // CartesianAxisPointer should be able to required somewhere.
  56616. registerPreprocessor(function (option) {
  56617. // Always has a global axisPointerModel for default setting.
  56618. if (option) {
  56619. (!option.axisPointer || option.axisPointer.length === 0)
  56620. && (option.axisPointer = {});
  56621. var link = option.axisPointer.link;
  56622. // Normalize to array to avoid object mergin. But if link
  56623. // is not set, remain null/undefined, otherwise it will
  56624. // override existent link setting.
  56625. if (link && !isArray(link)) {
  56626. option.axisPointer.link = [link];
  56627. }
  56628. }
  56629. });
  56630. // This process should proformed after coordinate systems created
  56631. // and series data processed. So put it on statistic processing stage.
  56632. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  56633. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  56634. // allAxesInfo should be updated when setOption performed.
  56635. ecModel.getComponent('axisPointer').coordSysAxesInfo
  56636. = collect(ecModel, api);
  56637. });
  56638. // Broadcast to all views.
  56639. registerAction({
  56640. type: 'updateAxisPointer',
  56641. event: 'updateAxisPointer',
  56642. update: ':updateAxisPointer'
  56643. }, axisTrigger);
  56644. /*
  56645. * Licensed to the Apache Software Foundation (ASF) under one
  56646. * or more contributor license agreements. See the NOTICE file
  56647. * distributed with this work for additional information
  56648. * regarding copyright ownership. The ASF licenses this file
  56649. * to you under the Apache License, Version 2.0 (the
  56650. * "License"); you may not use this file except in compliance
  56651. * with the License. You may obtain a copy of the License at
  56652. *
  56653. * http://www.apache.org/licenses/LICENSE-2.0
  56654. *
  56655. * Unless required by applicable law or agreed to in writing,
  56656. * software distributed under the License is distributed on an
  56657. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56658. * KIND, either express or implied. See the License for the
  56659. * specific language governing permissions and limitations
  56660. * under the License.
  56661. */
  56662. var XY = ['x', 'y'];
  56663. var WH = ['width', 'height'];
  56664. var SingleAxisPointer = BaseAxisPointer.extend({
  56665. /**
  56666. * @override
  56667. */
  56668. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  56669. var axis = axisModel.axis;
  56670. var coordSys = axis.coordinateSystem;
  56671. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  56672. var pixelValue = coordSys.dataToPoint(value)[0];
  56673. var axisPointerType = axisPointerModel.get('type');
  56674. if (axisPointerType && axisPointerType !== 'none') {
  56675. var elStyle = buildElStyle(axisPointerModel);
  56676. var pointerOption = pointerShapeBuilder$1[axisPointerType](
  56677. axis, pixelValue, otherExtent, elStyle
  56678. );
  56679. pointerOption.style = elStyle;
  56680. elOption.graphicKey = pointerOption.type;
  56681. elOption.pointer = pointerOption;
  56682. }
  56683. var layoutInfo = layout$2(axisModel);
  56684. buildCartesianSingleLabelElOption(
  56685. value, elOption, layoutInfo, axisModel, axisPointerModel, api
  56686. );
  56687. },
  56688. /**
  56689. * @override
  56690. */
  56691. getHandleTransform: function (value, axisModel, axisPointerModel) {
  56692. var layoutInfo = layout$2(axisModel, {labelInside: false});
  56693. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  56694. return {
  56695. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  56696. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  56697. };
  56698. },
  56699. /**
  56700. * @override
  56701. */
  56702. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  56703. var axis = axisModel.axis;
  56704. var coordSys = axis.coordinateSystem;
  56705. var dimIndex = getPointDimIndex(axis);
  56706. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  56707. var currPosition = transform.position;
  56708. currPosition[dimIndex] += delta[dimIndex];
  56709. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  56710. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  56711. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  56712. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  56713. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  56714. cursorPoint[dimIndex] = currPosition[dimIndex];
  56715. return {
  56716. position: currPosition,
  56717. rotation: transform.rotation,
  56718. cursorPoint: cursorPoint,
  56719. tooltipOption: {
  56720. verticalAlign: 'middle'
  56721. }
  56722. };
  56723. }
  56724. });
  56725. var pointerShapeBuilder$1 = {
  56726. line: function (axis, pixelValue, otherExtent, elStyle) {
  56727. var targetShape = makeLineShape(
  56728. [pixelValue, otherExtent[0]],
  56729. [pixelValue, otherExtent[1]],
  56730. getPointDimIndex(axis)
  56731. );
  56732. subPixelOptimizeLine({
  56733. shape: targetShape,
  56734. style: elStyle
  56735. });
  56736. return {
  56737. type: 'Line',
  56738. shape: targetShape
  56739. };
  56740. },
  56741. shadow: function (axis, pixelValue, otherExtent, elStyle) {
  56742. var bandWidth = axis.getBandWidth();
  56743. var span = otherExtent[1] - otherExtent[0];
  56744. return {
  56745. type: 'Rect',
  56746. shape: makeRectShape(
  56747. [pixelValue - bandWidth / 2, otherExtent[0]],
  56748. [bandWidth, span],
  56749. getPointDimIndex(axis)
  56750. )
  56751. };
  56752. }
  56753. };
  56754. function getPointDimIndex(axis) {
  56755. return axis.isHorizontal() ? 0 : 1;
  56756. }
  56757. function getGlobalExtent(coordSys, dimIndex) {
  56758. var rect = coordSys.getRect();
  56759. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  56760. }
  56761. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  56762. /*
  56763. * Licensed to the Apache Software Foundation (ASF) under one
  56764. * or more contributor license agreements. See the NOTICE file
  56765. * distributed with this work for additional information
  56766. * regarding copyright ownership. The ASF licenses this file
  56767. * to you under the Apache License, Version 2.0 (the
  56768. * "License"); you may not use this file except in compliance
  56769. * with the License. You may obtain a copy of the License at
  56770. *
  56771. * http://www.apache.org/licenses/LICENSE-2.0
  56772. *
  56773. * Unless required by applicable law or agreed to in writing,
  56774. * software distributed under the License is distributed on an
  56775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56776. * KIND, either express or implied. See the License for the
  56777. * specific language governing permissions and limitations
  56778. * under the License.
  56779. */
  56780. extendComponentView({
  56781. type: 'single'
  56782. });
  56783. /*
  56784. * Licensed to the Apache Software Foundation (ASF) under one
  56785. * or more contributor license agreements. See the NOTICE file
  56786. * distributed with this work for additional information
  56787. * regarding copyright ownership. The ASF licenses this file
  56788. * to you under the Apache License, Version 2.0 (the
  56789. * "License"); you may not use this file except in compliance
  56790. * with the License. You may obtain a copy of the License at
  56791. *
  56792. * http://www.apache.org/licenses/LICENSE-2.0
  56793. *
  56794. * Unless required by applicable law or agreed to in writing,
  56795. * software distributed under the License is distributed on an
  56796. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56797. * KIND, either express or implied. See the License for the
  56798. * specific language governing permissions and limitations
  56799. * under the License.
  56800. */
  56801. /**
  56802. * @file Define the themeRiver view's series model
  56803. * @author Deqing Li(annong035@gmail.com)
  56804. */
  56805. var DATA_NAME_INDEX = 2;
  56806. var ThemeRiverSeries = SeriesModel.extend({
  56807. type: 'series.themeRiver',
  56808. dependencies: ['singleAxis'],
  56809. /**
  56810. * @readOnly
  56811. * @type {module:zrender/core/util#HashMap}
  56812. */
  56813. nameMap: null,
  56814. /**
  56815. * @override
  56816. */
  56817. init: function (option) {
  56818. ThemeRiverSeries.superApply(this, 'init', arguments);
  56819. // Put this function here is for the sake of consistency of code style.
  56820. // Enable legend selection for each data item
  56821. // Use a function instead of direct access because data reference may changed
  56822. this.legendDataProvider = function () {
  56823. return this.getRawData();
  56824. };
  56825. },
  56826. /**
  56827. * If there is no value of a certain point in the time for some event,set it value to 0.
  56828. *
  56829. * @param {Array} data initial data in the option
  56830. * @return {Array}
  56831. */
  56832. fixData: function (data) {
  56833. var rawDataLength = data.length;
  56834. // grouped data by name
  56835. var dataByName = nest()
  56836. .key(function (dataItem) {
  56837. return dataItem[2];
  56838. })
  56839. .entries(data);
  56840. // data group in each layer
  56841. var layData = map(dataByName, function (d) {
  56842. return {
  56843. name: d.key,
  56844. dataList: d.values
  56845. };
  56846. });
  56847. var layerNum = layData.length;
  56848. var largestLayer = -1;
  56849. var index = -1;
  56850. for (var i = 0; i < layerNum; ++i) {
  56851. var len = layData[i].dataList.length;
  56852. if (len > largestLayer) {
  56853. largestLayer = len;
  56854. index = i;
  56855. }
  56856. }
  56857. for (var k = 0; k < layerNum; ++k) {
  56858. if (k === index) {
  56859. continue;
  56860. }
  56861. var name = layData[k].name;
  56862. for (var j = 0; j < largestLayer; ++j) {
  56863. var timeValue = layData[index].dataList[j][0];
  56864. var length = layData[k].dataList.length;
  56865. var keyIndex = -1;
  56866. for (var l = 0; l < length; ++l) {
  56867. var value = layData[k].dataList[l][0];
  56868. if (value === timeValue) {
  56869. keyIndex = l;
  56870. break;
  56871. }
  56872. }
  56873. if (keyIndex === -1) {
  56874. data[rawDataLength] = [];
  56875. data[rawDataLength][0] = timeValue;
  56876. data[rawDataLength][1] = 0;
  56877. data[rawDataLength][2] = name;
  56878. rawDataLength++;
  56879. }
  56880. }
  56881. }
  56882. return data;
  56883. },
  56884. /**
  56885. * @override
  56886. * @param {Object} option the initial option that user gived
  56887. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  56888. * @return {module:echarts/data/List}
  56889. */
  56890. getInitialData: function (option, ecModel) {
  56891. var singleAxisModel = ecModel.queryComponents({
  56892. mainType: 'singleAxis',
  56893. index: this.get('singleAxisIndex'),
  56894. id: this.get('singleAxisId')
  56895. })[0];
  56896. var axisType = singleAxisModel.get('type');
  56897. // filter the data item with the value of label is undefined
  56898. var filterData = filter(option.data, function (dataItem) {
  56899. return dataItem[2] !== undefined;
  56900. });
  56901. // ??? TODO design a stage to transfer data for themeRiver and lines?
  56902. var data = this.fixData(filterData || []);
  56903. var nameList = [];
  56904. var nameMap = this.nameMap = createHashMap();
  56905. var count = 0;
  56906. for (var i = 0; i < data.length; ++i) {
  56907. nameList.push(data[i][DATA_NAME_INDEX]);
  56908. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  56909. nameMap.set(data[i][DATA_NAME_INDEX], count);
  56910. count++;
  56911. }
  56912. }
  56913. var dimensionsInfo = createDimensions(data, {
  56914. coordDimensions: ['single'],
  56915. dimensionsDefine: [
  56916. {
  56917. name: 'time',
  56918. type: getDimensionTypeByAxis(axisType)
  56919. },
  56920. {
  56921. name: 'value',
  56922. type: 'float'
  56923. },
  56924. {
  56925. name: 'name',
  56926. type: 'ordinal'
  56927. }
  56928. ],
  56929. encodeDefine: {
  56930. single: 0,
  56931. value: 1,
  56932. itemName: 2
  56933. }
  56934. });
  56935. var list = new List(dimensionsInfo, this);
  56936. list.initData(data);
  56937. return list;
  56938. },
  56939. /**
  56940. * The raw data is divided into multiple layers and each layer
  56941. * has same name.
  56942. *
  56943. * @return {Array.<Array.<number>>}
  56944. */
  56945. getLayerSeries: function () {
  56946. var data = this.getData();
  56947. var lenCount = data.count();
  56948. var indexArr = [];
  56949. for (var i = 0; i < lenCount; ++i) {
  56950. indexArr[i] = i;
  56951. }
  56952. // data group by name
  56953. var dataByName = nest()
  56954. .key(function (index) {
  56955. return data.get('name', index);
  56956. })
  56957. .entries(indexArr);
  56958. var layerSeries = map(dataByName, function (d) {
  56959. return {
  56960. name: d.key,
  56961. indices: d.values
  56962. };
  56963. });
  56964. var timeDim = data.mapDimension('single');
  56965. for (var j = 0; j < layerSeries.length; ++j) {
  56966. layerSeries[j].indices.sort(comparer);
  56967. }
  56968. function comparer(index1, index2) {
  56969. return data.get(timeDim, index1) - data.get(timeDim, index2);
  56970. }
  56971. return layerSeries;
  56972. },
  56973. /**
  56974. * Get data indices for show tooltip content
  56975. *
  56976. * @param {Array.<string>|string} dim single coordinate dimension
  56977. * @param {number} value axis value
  56978. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  56979. * the themeRiver.
  56980. * @return {Object} {dataIndices, nestestValue}
  56981. */
  56982. getAxisTooltipData: function (dim, value, baseAxis) {
  56983. if (!isArray(dim)) {
  56984. dim = dim ? [dim] : [];
  56985. }
  56986. var data = this.getData();
  56987. var layerSeries = this.getLayerSeries();
  56988. var indices = [];
  56989. var layerNum = layerSeries.length;
  56990. var nestestValue;
  56991. for (var i = 0; i < layerNum; ++i) {
  56992. var minDist = Number.MAX_VALUE;
  56993. var nearestIdx = -1;
  56994. var pointNum = layerSeries[i].indices.length;
  56995. for (var j = 0; j < pointNum; ++j) {
  56996. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  56997. var dist = Math.abs(theValue - value);
  56998. if (dist <= minDist) {
  56999. nestestValue = theValue;
  57000. minDist = dist;
  57001. nearestIdx = layerSeries[i].indices[j];
  57002. }
  57003. }
  57004. indices.push(nearestIdx);
  57005. }
  57006. return {dataIndices: indices, nestestValue: nestestValue};
  57007. },
  57008. /**
  57009. * @override
  57010. * @param {number} dataIndex index of data
  57011. */
  57012. formatTooltip: function (dataIndex) {
  57013. var data = this.getData();
  57014. var htmlName = data.getName(dataIndex);
  57015. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  57016. if (isNaN(htmlValue) || htmlValue == null) {
  57017. htmlValue = '-';
  57018. }
  57019. return encodeHTML(htmlName + ' : ' + htmlValue);
  57020. },
  57021. defaultOption: {
  57022. zlevel: 0,
  57023. z: 2,
  57024. coordinateSystem: 'singleAxis',
  57025. // gap in axis's orthogonal orientation
  57026. boundaryGap: ['10%', '10%'],
  57027. // legendHoverLink: true,
  57028. singleAxisIndex: 0,
  57029. animationEasing: 'linear',
  57030. label: {
  57031. margin: 4,
  57032. show: true,
  57033. position: 'left',
  57034. color: '#000',
  57035. fontSize: 11
  57036. },
  57037. emphasis: {
  57038. label: {
  57039. show: true
  57040. }
  57041. }
  57042. }
  57043. });
  57044. /*
  57045. * Licensed to the Apache Software Foundation (ASF) under one
  57046. * or more contributor license agreements. See the NOTICE file
  57047. * distributed with this work for additional information
  57048. * regarding copyright ownership. The ASF licenses this file
  57049. * to you under the Apache License, Version 2.0 (the
  57050. * "License"); you may not use this file except in compliance
  57051. * with the License. You may obtain a copy of the License at
  57052. *
  57053. * http://www.apache.org/licenses/LICENSE-2.0
  57054. *
  57055. * Unless required by applicable law or agreed to in writing,
  57056. * software distributed under the License is distributed on an
  57057. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57058. * KIND, either express or implied. See the License for the
  57059. * specific language governing permissions and limitations
  57060. * under the License.
  57061. */
  57062. /**
  57063. * @file The file used to draw themeRiver view
  57064. * @author Deqing Li(annong035@gmail.com)
  57065. */
  57066. extendChartView({
  57067. type: 'themeRiver',
  57068. init: function () {
  57069. this._layers = [];
  57070. },
  57071. render: function (seriesModel, ecModel, api) {
  57072. var data = seriesModel.getData();
  57073. var group = this.group;
  57074. var layerSeries = seriesModel.getLayerSeries();
  57075. var layoutInfo = data.getLayout('layoutInfo');
  57076. var rect = layoutInfo.rect;
  57077. var boundaryGap = layoutInfo.boundaryGap;
  57078. group.attr('position', [0, rect.y + boundaryGap[0]]);
  57079. function keyGetter(item) {
  57080. return item.name;
  57081. }
  57082. var dataDiffer = new DataDiffer(
  57083. this._layersSeries || [], layerSeries,
  57084. keyGetter, keyGetter
  57085. );
  57086. var newLayersGroups = {};
  57087. dataDiffer
  57088. .add(bind(process, this, 'add'))
  57089. .update(bind(process, this, 'update'))
  57090. .remove(bind(process, this, 'remove'))
  57091. .execute();
  57092. function process(status, idx, oldIdx) {
  57093. var oldLayersGroups = this._layers;
  57094. if (status === 'remove') {
  57095. group.remove(oldLayersGroups[idx]);
  57096. return;
  57097. }
  57098. var points0 = [];
  57099. var points1 = [];
  57100. var color;
  57101. var indices = layerSeries[idx].indices;
  57102. for (var j = 0; j < indices.length; j++) {
  57103. var layout = data.getItemLayout(indices[j]);
  57104. var x = layout.x;
  57105. var y0 = layout.y0;
  57106. var y = layout.y;
  57107. points0.push([x, y0]);
  57108. points1.push([x, y0 + y]);
  57109. color = data.getItemVisual(indices[j], 'color');
  57110. }
  57111. var polygon;
  57112. var text;
  57113. var textLayout = data.getItemLayout(indices[0]);
  57114. var itemModel = data.getItemModel(indices[j - 1]);
  57115. var labelModel = itemModel.getModel('label');
  57116. var margin = labelModel.get('margin');
  57117. if (status === 'add') {
  57118. var layerGroup = newLayersGroups[idx] = new Group();
  57119. polygon = new Polygon$1({
  57120. shape: {
  57121. points: points0,
  57122. stackedOnPoints: points1,
  57123. smooth: 0.4,
  57124. stackedOnSmooth: 0.4,
  57125. smoothConstraint: false
  57126. },
  57127. z2: 0
  57128. });
  57129. text = new Text({
  57130. style: {
  57131. x: textLayout.x - margin,
  57132. y: textLayout.y0 + textLayout.y / 2
  57133. }
  57134. });
  57135. layerGroup.add(polygon);
  57136. layerGroup.add(text);
  57137. group.add(layerGroup);
  57138. polygon.setClipPath(createGridClipShape$3(polygon.getBoundingRect(), seriesModel, function () {
  57139. polygon.removeClipPath();
  57140. }));
  57141. }
  57142. else {
  57143. var layerGroup = oldLayersGroups[oldIdx];
  57144. polygon = layerGroup.childAt(0);
  57145. text = layerGroup.childAt(1);
  57146. group.add(layerGroup);
  57147. newLayersGroups[idx] = layerGroup;
  57148. updateProps(polygon, {
  57149. shape: {
  57150. points: points0,
  57151. stackedOnPoints: points1
  57152. }
  57153. }, seriesModel);
  57154. updateProps(text, {
  57155. style: {
  57156. x: textLayout.x - margin,
  57157. y: textLayout.y0 + textLayout.y / 2
  57158. }
  57159. }, seriesModel);
  57160. }
  57161. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  57162. var itemStyleModel = itemModel.getModel('itemStyle');
  57163. setTextStyle(text.style, labelModel, {
  57164. text: labelModel.get('show')
  57165. ? seriesModel.getFormattedLabel(indices[j - 1], 'normal')
  57166. || data.getName(indices[j - 1])
  57167. : null,
  57168. textVerticalAlign: 'middle'
  57169. });
  57170. polygon.setStyle(extend({
  57171. fill: color
  57172. }, itemStyleModel.getItemStyle(['color'])));
  57173. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  57174. }
  57175. this._layersSeries = layerSeries;
  57176. this._layers = newLayersGroups;
  57177. },
  57178. dispose: function () {}
  57179. });
  57180. // add animation to the view
  57181. function createGridClipShape$3(rect, seriesModel, cb) {
  57182. var rectEl = new Rect({
  57183. shape: {
  57184. x: rect.x - 10,
  57185. y: rect.y - 10,
  57186. width: 0,
  57187. height: rect.height + 20
  57188. }
  57189. });
  57190. initProps(rectEl, {
  57191. shape: {
  57192. width: rect.width + 20,
  57193. height: rect.height + 20
  57194. }
  57195. }, seriesModel, cb);
  57196. return rectEl;
  57197. }
  57198. /*
  57199. * Licensed to the Apache Software Foundation (ASF) under one
  57200. * or more contributor license agreements. See the NOTICE file
  57201. * distributed with this work for additional information
  57202. * regarding copyright ownership. The ASF licenses this file
  57203. * to you under the Apache License, Version 2.0 (the
  57204. * "License"); you may not use this file except in compliance
  57205. * with the License. You may obtain a copy of the License at
  57206. *
  57207. * http://www.apache.org/licenses/LICENSE-2.0
  57208. *
  57209. * Unless required by applicable law or agreed to in writing,
  57210. * software distributed under the License is distributed on an
  57211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57212. * KIND, either express or implied. See the License for the
  57213. * specific language governing permissions and limitations
  57214. * under the License.
  57215. */
  57216. /**
  57217. * @file Using layout algorithm transform the raw data to layout information.
  57218. * @author Deqing Li(annong035@gmail.com)
  57219. */
  57220. var themeRiverLayout = function (ecModel, api) {
  57221. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  57222. var data = seriesModel.getData();
  57223. var single = seriesModel.coordinateSystem;
  57224. var layoutInfo = {};
  57225. // use the axis boundingRect for view
  57226. var rect = single.getRect();
  57227. layoutInfo.rect = rect;
  57228. var boundaryGap = seriesModel.get('boundaryGap');
  57229. var axis = single.getAxis();
  57230. layoutInfo.boundaryGap = boundaryGap;
  57231. if (axis.orient === 'horizontal') {
  57232. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  57233. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  57234. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  57235. themeRiverLayout$1(data, seriesModel, height);
  57236. }
  57237. else {
  57238. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  57239. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  57240. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  57241. themeRiverLayout$1(data, seriesModel, width);
  57242. }
  57243. data.setLayout('layoutInfo', layoutInfo);
  57244. });
  57245. };
  57246. /**
  57247. * The layout information about themeriver
  57248. *
  57249. * @param {module:echarts/data/List} data data in the series
  57250. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  57251. * @param {number} height value used to compute every series height
  57252. */
  57253. function themeRiverLayout$1(data, seriesModel, height) {
  57254. if (!data.count()) {
  57255. return;
  57256. }
  57257. var coordSys = seriesModel.coordinateSystem;
  57258. // the data in each layer are organized into a series.
  57259. var layerSeries = seriesModel.getLayerSeries();
  57260. // the points in each layer.
  57261. var timeDim = data.mapDimension('single');
  57262. var valueDim = data.mapDimension('value');
  57263. var layerPoints = map(layerSeries, function (singleLayer) {
  57264. return map(singleLayer.indices, function (idx) {
  57265. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  57266. pt[1] = data.get(valueDim, idx);
  57267. return pt;
  57268. });
  57269. });
  57270. var base = computeBaseline(layerPoints);
  57271. var baseLine = base.y0;
  57272. var ky = height / base.max;
  57273. // set layout information for each item.
  57274. var n = layerSeries.length;
  57275. var m = layerSeries[0].indices.length;
  57276. var baseY0;
  57277. for (var j = 0; j < m; ++j) {
  57278. baseY0 = baseLine[j] * ky;
  57279. data.setItemLayout(layerSeries[0].indices[j], {
  57280. layerIndex: 0,
  57281. x: layerPoints[0][j][0],
  57282. y0: baseY0,
  57283. y: layerPoints[0][j][1] * ky
  57284. });
  57285. for (var i = 1; i < n; ++i) {
  57286. baseY0 += layerPoints[i - 1][j][1] * ky;
  57287. data.setItemLayout(layerSeries[i].indices[j], {
  57288. layerIndex: i,
  57289. x: layerPoints[i][j][0],
  57290. y0: baseY0,
  57291. y: layerPoints[i][j][1] * ky
  57292. });
  57293. }
  57294. }
  57295. }
  57296. /**
  57297. * Compute the baseLine of the rawdata
  57298. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  57299. *
  57300. * @param {Array.<Array>} data the points in each layer
  57301. * @return {Object}
  57302. */
  57303. function computeBaseline(data) {
  57304. var layerNum = data.length;
  57305. var pointNum = data[0].length;
  57306. var sums = [];
  57307. var y0 = [];
  57308. var max = 0;
  57309. var temp;
  57310. var base = {};
  57311. for (var i = 0; i < pointNum; ++i) {
  57312. for (var j = 0, temp = 0; j < layerNum; ++j) {
  57313. temp += data[j][i][1];
  57314. }
  57315. if (temp > max) {
  57316. max = temp;
  57317. }
  57318. sums.push(temp);
  57319. }
  57320. for (var k = 0; k < pointNum; ++k) {
  57321. y0[k] = (max - sums[k]) / 2;
  57322. }
  57323. max = 0;
  57324. for (var l = 0; l < pointNum; ++l) {
  57325. var sum = sums[l] + y0[l];
  57326. if (sum > max) {
  57327. max = sum;
  57328. }
  57329. }
  57330. base.y0 = y0;
  57331. base.max = max;
  57332. return base;
  57333. }
  57334. /*
  57335. * Licensed to the Apache Software Foundation (ASF) under one
  57336. * or more contributor license agreements. See the NOTICE file
  57337. * distributed with this work for additional information
  57338. * regarding copyright ownership. The ASF licenses this file
  57339. * to you under the Apache License, Version 2.0 (the
  57340. * "License"); you may not use this file except in compliance
  57341. * with the License. You may obtain a copy of the License at
  57342. *
  57343. * http://www.apache.org/licenses/LICENSE-2.0
  57344. *
  57345. * Unless required by applicable law or agreed to in writing,
  57346. * software distributed under the License is distributed on an
  57347. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57348. * KIND, either express or implied. See the License for the
  57349. * specific language governing permissions and limitations
  57350. * under the License.
  57351. */
  57352. /**
  57353. * @file Visual encoding for themeRiver view
  57354. * @author Deqing Li(annong035@gmail.com)
  57355. */
  57356. var themeRiverVisual = function (ecModel) {
  57357. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  57358. var data = seriesModel.getData();
  57359. var rawData = seriesModel.getRawData();
  57360. var colorList = seriesModel.get('color');
  57361. var idxMap = createHashMap();
  57362. data.each(function (idx) {
  57363. idxMap.set(data.getRawIndex(idx), idx);
  57364. });
  57365. rawData.each(function (rawIndex) {
  57366. var name = rawData.getName(rawIndex);
  57367. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  57368. rawData.setItemVisual(rawIndex, 'color', color);
  57369. var idx = idxMap.get(rawIndex);
  57370. if (idx != null) {
  57371. data.setItemVisual(idx, 'color', color);
  57372. }
  57373. });
  57374. });
  57375. };
  57376. /*
  57377. * Licensed to the Apache Software Foundation (ASF) under one
  57378. * or more contributor license agreements. See the NOTICE file
  57379. * distributed with this work for additional information
  57380. * regarding copyright ownership. The ASF licenses this file
  57381. * to you under the Apache License, Version 2.0 (the
  57382. * "License"); you may not use this file except in compliance
  57383. * with the License. You may obtain a copy of the License at
  57384. *
  57385. * http://www.apache.org/licenses/LICENSE-2.0
  57386. *
  57387. * Unless required by applicable law or agreed to in writing,
  57388. * software distributed under the License is distributed on an
  57389. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57390. * KIND, either express or implied. See the License for the
  57391. * specific language governing permissions and limitations
  57392. * under the License.
  57393. */
  57394. registerLayout(themeRiverLayout);
  57395. registerVisual(themeRiverVisual);
  57396. registerProcessor(dataFilter('themeRiver'));
  57397. /*
  57398. * Licensed to the Apache Software Foundation (ASF) under one
  57399. * or more contributor license agreements. See the NOTICE file
  57400. * distributed with this work for additional information
  57401. * regarding copyright ownership. The ASF licenses this file
  57402. * to you under the Apache License, Version 2.0 (the
  57403. * "License"); you may not use this file except in compliance
  57404. * with the License. You may obtain a copy of the License at
  57405. *
  57406. * http://www.apache.org/licenses/LICENSE-2.0
  57407. *
  57408. * Unless required by applicable law or agreed to in writing,
  57409. * software distributed under the License is distributed on an
  57410. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57411. * KIND, either express or implied. See the License for the
  57412. * specific language governing permissions and limitations
  57413. * under the License.
  57414. */
  57415. SeriesModel.extend({
  57416. type: 'series.sunburst',
  57417. /**
  57418. * @type {module:echarts/data/Tree~Node}
  57419. */
  57420. _viewRoot: null,
  57421. getInitialData: function (option, ecModel) {
  57422. // Create a virtual root.
  57423. var root = { name: option.name, children: option.data };
  57424. completeTreeValue$1(root);
  57425. var levels = option.levels || [];
  57426. // levels = option.levels = setDefault(levels, ecModel);
  57427. var treeOption = {};
  57428. treeOption.levels = levels;
  57429. // Make sure always a new tree is created when setOption,
  57430. // in TreemapView, we check whether oldTree === newTree
  57431. // to choose mappings approach among old shapes and new shapes.
  57432. return Tree.createTree(root, this, treeOption).data;
  57433. },
  57434. optionUpdated: function () {
  57435. this.resetViewRoot();
  57436. },
  57437. /*
  57438. * @override
  57439. */
  57440. getDataParams: function (dataIndex) {
  57441. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  57442. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  57443. params.treePathInfo = wrapTreePathInfo(node, this);
  57444. return params;
  57445. },
  57446. defaultOption: {
  57447. zlevel: 0,
  57448. z: 2,
  57449. // 默认全局居中
  57450. center: ['50%', '50%'],
  57451. radius: [0, '75%'],
  57452. // 默认顺时针
  57453. clockwise: true,
  57454. startAngle: 90,
  57455. // 最小角度改为0
  57456. minAngle: 0,
  57457. percentPrecision: 2,
  57458. // If still show when all data zero.
  57459. stillShowZeroSum: true,
  57460. // Policy of highlighting pieces when hover on one
  57461. // Valid values: 'none' (for not downplay others), 'descendant',
  57462. // 'ancestor', 'self'
  57463. highlightPolicy: 'descendant',
  57464. // 'rootToNode', 'link', or false
  57465. nodeClick: 'rootToNode',
  57466. renderLabelForZeroData: false,
  57467. label: {
  57468. // could be: 'radial', 'tangential', or 'none'
  57469. rotate: 'radial',
  57470. show: true,
  57471. opacity: 1,
  57472. // 'left' is for inner side of inside, and 'right' is for outter
  57473. // side for inside
  57474. align: 'center',
  57475. position: 'inside',
  57476. distance: 5,
  57477. silent: true,
  57478. emphasis: {}
  57479. },
  57480. itemStyle: {
  57481. borderWidth: 1,
  57482. borderColor: 'white',
  57483. opacity: 1,
  57484. emphasis: {},
  57485. highlight: {
  57486. opacity: 1
  57487. },
  57488. downplay: {
  57489. opacity: 0.9
  57490. }
  57491. },
  57492. // Animation type canbe expansion, scale
  57493. animationType: 'expansion',
  57494. animationDuration: 1000,
  57495. animationDurationUpdate: 500,
  57496. animationEasing: 'cubicOut',
  57497. data: [],
  57498. levels: [],
  57499. /**
  57500. * Sort order.
  57501. *
  57502. * Valid values: 'desc', 'asc', null, or callback function.
  57503. * 'desc' and 'asc' for descend and ascendant order;
  57504. * null for not sorting;
  57505. * example of callback function:
  57506. * function(nodeA, nodeB) {
  57507. * return nodeA.getValue() - nodeB.getValue();
  57508. * }
  57509. */
  57510. sort: 'desc'
  57511. },
  57512. getViewRoot: function () {
  57513. return this._viewRoot;
  57514. },
  57515. /**
  57516. * @param {module:echarts/data/Tree~Node} [viewRoot]
  57517. */
  57518. resetViewRoot: function (viewRoot) {
  57519. viewRoot
  57520. ? (this._viewRoot = viewRoot)
  57521. : (viewRoot = this._viewRoot);
  57522. var root = this.getRawData().tree.root;
  57523. if (!viewRoot
  57524. || (viewRoot !== root && !root.contains(viewRoot))
  57525. ) {
  57526. this._viewRoot = root;
  57527. }
  57528. }
  57529. });
  57530. /**
  57531. * @param {Object} dataNode
  57532. */
  57533. function completeTreeValue$1(dataNode) {
  57534. // Postorder travel tree.
  57535. // If value of none-leaf node is not set,
  57536. // calculate it by suming up the value of all children.
  57537. var sum = 0;
  57538. each$1(dataNode.children, function (child) {
  57539. completeTreeValue$1(child);
  57540. var childValue = child.value;
  57541. isArray(childValue) && (childValue = childValue[0]);
  57542. sum += childValue;
  57543. });
  57544. var thisValue = dataNode.value;
  57545. if (isArray(thisValue)) {
  57546. thisValue = thisValue[0];
  57547. }
  57548. if (thisValue == null || isNaN(thisValue)) {
  57549. thisValue = sum;
  57550. }
  57551. // Value should not less than 0.
  57552. if (thisValue < 0) {
  57553. thisValue = 0;
  57554. }
  57555. isArray(dataNode.value)
  57556. ? (dataNode.value[0] = thisValue)
  57557. : (dataNode.value = thisValue);
  57558. }
  57559. /*
  57560. * Licensed to the Apache Software Foundation (ASF) under one
  57561. * or more contributor license agreements. See the NOTICE file
  57562. * distributed with this work for additional information
  57563. * regarding copyright ownership. The ASF licenses this file
  57564. * to you under the Apache License, Version 2.0 (the
  57565. * "License"); you may not use this file except in compliance
  57566. * with the License. You may obtain a copy of the License at
  57567. *
  57568. * http://www.apache.org/licenses/LICENSE-2.0
  57569. *
  57570. * Unless required by applicable law or agreed to in writing,
  57571. * software distributed under the License is distributed on an
  57572. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57573. * KIND, either express or implied. See the License for the
  57574. * specific language governing permissions and limitations
  57575. * under the License.
  57576. */
  57577. var NodeHighlightPolicy = {
  57578. NONE: 'none', // not downplay others
  57579. DESCENDANT: 'descendant',
  57580. ANCESTOR: 'ancestor',
  57581. SELF: 'self'
  57582. };
  57583. var DEFAULT_SECTOR_Z = 2;
  57584. var DEFAULT_TEXT_Z = 4;
  57585. /**
  57586. * Sunburstce of Sunburst including Sector, Label, LabelLine
  57587. * @constructor
  57588. * @extends {module:zrender/graphic/Group}
  57589. */
  57590. function SunburstPiece(node, seriesModel, ecModel) {
  57591. Group.call(this);
  57592. var sector = new Sector({
  57593. z2: DEFAULT_SECTOR_Z
  57594. });
  57595. sector.seriesIndex = seriesModel.seriesIndex;
  57596. var text = new Text({
  57597. z2: DEFAULT_TEXT_Z,
  57598. silent: node.getModel('label').get('silent')
  57599. });
  57600. this.add(sector);
  57601. this.add(text);
  57602. this.updateData(true, node, 'normal', seriesModel, ecModel);
  57603. // Hover to change label and labelLine
  57604. function onEmphasis() {
  57605. text.ignore = text.hoverIgnore;
  57606. }
  57607. function onNormal() {
  57608. text.ignore = text.normalIgnore;
  57609. }
  57610. this.on('emphasis', onEmphasis)
  57611. .on('normal', onNormal)
  57612. .on('mouseover', onEmphasis)
  57613. .on('mouseout', onNormal);
  57614. }
  57615. var SunburstPieceProto = SunburstPiece.prototype;
  57616. SunburstPieceProto.updateData = function (
  57617. firstCreate,
  57618. node,
  57619. state,
  57620. seriesModel,
  57621. ecModel
  57622. ) {
  57623. this.node = node;
  57624. node.piece = this;
  57625. seriesModel = seriesModel || this._seriesModel;
  57626. ecModel = ecModel || this._ecModel;
  57627. var sector = this.childAt(0);
  57628. sector.dataIndex = node.dataIndex;
  57629. var itemModel = node.getModel();
  57630. var layout = node.getLayout();
  57631. if (!layout) {
  57632. console.log(node.getLayout());
  57633. }
  57634. var sectorShape = extend({}, layout);
  57635. sectorShape.label = null;
  57636. var visualColor = getNodeColor(node, seriesModel, ecModel);
  57637. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  57638. var style;
  57639. if (state === 'normal') {
  57640. style = normalStyle;
  57641. }
  57642. else {
  57643. var stateStyle = itemModel.getModel(state + '.itemStyle')
  57644. .getItemStyle();
  57645. style = merge(stateStyle, normalStyle);
  57646. }
  57647. style = defaults(
  57648. {
  57649. lineJoin: 'bevel',
  57650. fill: style.fill || visualColor
  57651. },
  57652. style
  57653. );
  57654. if (firstCreate) {
  57655. sector.setShape(sectorShape);
  57656. sector.shape.r = layout.r0;
  57657. updateProps(
  57658. sector,
  57659. {
  57660. shape: {
  57661. r: layout.r
  57662. }
  57663. },
  57664. seriesModel,
  57665. node.dataIndex
  57666. );
  57667. sector.useStyle(style);
  57668. }
  57669. else if (typeof style.fill === 'object' && style.fill.type
  57670. || typeof sector.style.fill === 'object' && sector.style.fill.type
  57671. ) {
  57672. // Disable animation for gradient since no interpolation method
  57673. // is supported for gradient
  57674. updateProps(sector, {
  57675. shape: sectorShape
  57676. }, seriesModel);
  57677. sector.useStyle(style);
  57678. }
  57679. else {
  57680. updateProps(sector, {
  57681. shape: sectorShape,
  57682. style: style
  57683. }, seriesModel);
  57684. }
  57685. this._updateLabel(seriesModel, visualColor, state);
  57686. var cursorStyle = itemModel.getShallow('cursor');
  57687. cursorStyle && sector.attr('cursor', cursorStyle);
  57688. if (firstCreate) {
  57689. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  57690. this._initEvents(sector, node, seriesModel, highlightPolicy);
  57691. }
  57692. this._seriesModel = seriesModel || this._seriesModel;
  57693. this._ecModel = ecModel || this._ecModel;
  57694. };
  57695. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  57696. var that = this;
  57697. this.node.hostTree.root.eachNode(function (n) {
  57698. if (n.piece) {
  57699. if (that.node === n) {
  57700. n.piece.updateData(false, n, 'emphasis');
  57701. }
  57702. else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  57703. n.piece.childAt(0).trigger('highlight');
  57704. }
  57705. else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  57706. n.piece.childAt(0).trigger('downplay');
  57707. }
  57708. }
  57709. });
  57710. };
  57711. SunburstPieceProto.onNormal = function () {
  57712. this.node.hostTree.root.eachNode(function (n) {
  57713. if (n.piece) {
  57714. n.piece.updateData(false, n, 'normal');
  57715. }
  57716. });
  57717. };
  57718. SunburstPieceProto.onHighlight = function () {
  57719. this.updateData(false, this.node, 'highlight');
  57720. };
  57721. SunburstPieceProto.onDownplay = function () {
  57722. this.updateData(false, this.node, 'downplay');
  57723. };
  57724. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  57725. var itemModel = this.node.getModel();
  57726. var normalModel = itemModel.getModel('label');
  57727. var labelModel = state === 'normal' || state === 'emphasis'
  57728. ? normalModel
  57729. : itemModel.getModel(state + '.label');
  57730. var labelHoverModel = itemModel.getModel('emphasis.label');
  57731. var text = retrieve(
  57732. seriesModel.getFormattedLabel(
  57733. this.node.dataIndex, 'normal', null, null, 'label'
  57734. ),
  57735. this.node.name
  57736. );
  57737. if (getLabelAttr('show') === false) {
  57738. text = '';
  57739. }
  57740. var layout = this.node.getLayout();
  57741. var labelMinAngle = labelModel.get('minAngle');
  57742. if (labelMinAngle == null) {
  57743. labelMinAngle = normalModel.get('minAngle');
  57744. }
  57745. labelMinAngle = labelMinAngle / 180 * Math.PI;
  57746. var angle = layout.endAngle - layout.startAngle;
  57747. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  57748. // Not displaying text when angle is too small
  57749. text = '';
  57750. }
  57751. var label = this.childAt(1);
  57752. setLabelStyle(
  57753. label.style, label.hoverStyle || {}, normalModel, labelHoverModel,
  57754. {
  57755. defaultText: labelModel.getShallow('show') ? text : null,
  57756. autoColor: visualColor,
  57757. useInsideStyle: true
  57758. }
  57759. );
  57760. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  57761. var dx = Math.cos(midAngle);
  57762. var dy = Math.sin(midAngle);
  57763. var r;
  57764. var labelPosition = getLabelAttr('position');
  57765. var labelPadding = getLabelAttr('distance') || 0;
  57766. var textAlign = getLabelAttr('align');
  57767. if (labelPosition === 'outside') {
  57768. r = layout.r + labelPadding;
  57769. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  57770. }
  57771. else {
  57772. if (!textAlign || textAlign === 'center') {
  57773. r = (layout.r + layout.r0) / 2;
  57774. textAlign = 'center';
  57775. }
  57776. else if (textAlign === 'left') {
  57777. r = layout.r0 + labelPadding;
  57778. if (midAngle > Math.PI / 2) {
  57779. textAlign = 'right';
  57780. }
  57781. }
  57782. else if (textAlign === 'right') {
  57783. r = layout.r - labelPadding;
  57784. if (midAngle > Math.PI / 2) {
  57785. textAlign = 'left';
  57786. }
  57787. }
  57788. }
  57789. label.attr('style', {
  57790. text: text,
  57791. textAlign: textAlign,
  57792. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  57793. opacity: getLabelAttr('opacity')
  57794. });
  57795. var textX = r * dx + layout.cx;
  57796. var textY = r * dy + layout.cy;
  57797. label.attr('position', [textX, textY]);
  57798. var rotateType = getLabelAttr('rotate');
  57799. var rotate = 0;
  57800. if (rotateType === 'radial') {
  57801. rotate = -midAngle;
  57802. if (rotate < -Math.PI / 2) {
  57803. rotate += Math.PI;
  57804. }
  57805. }
  57806. else if (rotateType === 'tangential') {
  57807. rotate = Math.PI / 2 - midAngle;
  57808. if (rotate > Math.PI / 2) {
  57809. rotate -= Math.PI;
  57810. }
  57811. else if (rotate < -Math.PI / 2) {
  57812. rotate += Math.PI;
  57813. }
  57814. } else if (typeof rotateType === 'number') {
  57815. rotate = rotateType * Math.PI / 180;
  57816. }
  57817. label.attr('rotation', rotate);
  57818. function getLabelAttr(name) {
  57819. var stateAttr = labelModel.get(name);
  57820. if (stateAttr == null) {
  57821. return normalModel.get(name);
  57822. }
  57823. else {
  57824. return stateAttr;
  57825. }
  57826. }
  57827. };
  57828. SunburstPieceProto._initEvents = function (
  57829. sector,
  57830. node,
  57831. seriesModel,
  57832. highlightPolicy
  57833. ) {
  57834. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  57835. var that = this;
  57836. var onEmphasis = function () {
  57837. that.onEmphasis(highlightPolicy);
  57838. };
  57839. var onNormal = function () {
  57840. that.onNormal();
  57841. };
  57842. var onDownplay = function () {
  57843. that.onDownplay();
  57844. };
  57845. var onHighlight = function () {
  57846. that.onHighlight();
  57847. };
  57848. if (seriesModel.isAnimationEnabled()) {
  57849. sector
  57850. .on('mouseover', onEmphasis)
  57851. .on('mouseout', onNormal)
  57852. .on('emphasis', onEmphasis)
  57853. .on('normal', onNormal)
  57854. .on('downplay', onDownplay)
  57855. .on('highlight', onHighlight);
  57856. }
  57857. };
  57858. inherits(SunburstPiece, Group);
  57859. /**
  57860. * Get node color
  57861. *
  57862. * @param {TreeNode} node the node to get color
  57863. * @param {module:echarts/model/Series} seriesModel series
  57864. * @param {module:echarts/model/Global} ecModel echarts defaults
  57865. */
  57866. function getNodeColor(node, seriesModel, ecModel) {
  57867. // Color from visualMap
  57868. var visualColor = node.getVisual('color');
  57869. var visualMetaList = node.getVisual('visualMeta');
  57870. if (!visualMetaList || visualMetaList.length === 0) {
  57871. // Use first-generation color if has no visualMap
  57872. visualColor = null;
  57873. }
  57874. // Self color or level color
  57875. var color = node.getModel('itemStyle').get('color');
  57876. if (color) {
  57877. return color;
  57878. }
  57879. else if (visualColor) {
  57880. // Color mapping
  57881. return visualColor;
  57882. }
  57883. else if (node.depth === 0) {
  57884. // Virtual root node
  57885. return ecModel.option.color[0];
  57886. }
  57887. else {
  57888. // First-generation color
  57889. var length = ecModel.option.color.length;
  57890. color = ecModel.option.color[getRootId(node) % length];
  57891. }
  57892. return color;
  57893. }
  57894. /**
  57895. * Get index of root in sorted order
  57896. *
  57897. * @param {TreeNode} node current node
  57898. * @return {number} index in root
  57899. */
  57900. function getRootId(node) {
  57901. var ancestor = node;
  57902. while (ancestor.depth > 1) {
  57903. ancestor = ancestor.parentNode;
  57904. }
  57905. var virtualRoot = node.getAncestors()[0];
  57906. return indexOf(virtualRoot.children, ancestor);
  57907. }
  57908. function isNodeHighlighted(node, activeNode, policy) {
  57909. if (policy === NodeHighlightPolicy.NONE) {
  57910. return false;
  57911. }
  57912. else if (policy === NodeHighlightPolicy.SELF) {
  57913. return node === activeNode;
  57914. }
  57915. else if (policy === NodeHighlightPolicy.ANCESTOR) {
  57916. return node === activeNode || node.isAncestorOf(activeNode);
  57917. }
  57918. else {
  57919. return node === activeNode || node.isDescendantOf(activeNode);
  57920. }
  57921. }
  57922. /*
  57923. * Licensed to the Apache Software Foundation (ASF) under one
  57924. * or more contributor license agreements. See the NOTICE file
  57925. * distributed with this work for additional information
  57926. * regarding copyright ownership. The ASF licenses this file
  57927. * to you under the Apache License, Version 2.0 (the
  57928. * "License"); you may not use this file except in compliance
  57929. * with the License. You may obtain a copy of the License at
  57930. *
  57931. * http://www.apache.org/licenses/LICENSE-2.0
  57932. *
  57933. * Unless required by applicable law or agreed to in writing,
  57934. * software distributed under the License is distributed on an
  57935. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57936. * KIND, either express or implied. See the License for the
  57937. * specific language governing permissions and limitations
  57938. * under the License.
  57939. */
  57940. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  57941. var SunburstView = Chart.extend({
  57942. type: 'sunburst',
  57943. init: function () {
  57944. },
  57945. render: function (seriesModel, ecModel, api, payload) {
  57946. var that = this;
  57947. this.seriesModel = seriesModel;
  57948. this.api = api;
  57949. this.ecModel = ecModel;
  57950. var data = seriesModel.getData();
  57951. var virtualRoot = data.tree.root;
  57952. var newRoot = seriesModel.getViewRoot();
  57953. var group = this.group;
  57954. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  57955. var newChildren = [];
  57956. newRoot.eachNode(function (node) {
  57957. newChildren.push(node);
  57958. });
  57959. var oldChildren = this._oldChildren || [];
  57960. dualTravel(newChildren, oldChildren);
  57961. renderRollUp(virtualRoot, newRoot);
  57962. if (payload && payload.highlight && payload.highlight.piece) {
  57963. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  57964. payload.highlight.piece.onEmphasis(highlightPolicy);
  57965. }
  57966. else if (payload && payload.unhighlight) {
  57967. var piece = this.virtualPiece;
  57968. if (!piece && virtualRoot.children.length) {
  57969. piece = virtualRoot.children[0].piece;
  57970. }
  57971. if (piece) {
  57972. piece.onNormal();
  57973. }
  57974. }
  57975. this._initEvents();
  57976. this._oldChildren = newChildren;
  57977. function dualTravel(newChildren, oldChildren) {
  57978. if (newChildren.length === 0 && oldChildren.length === 0) {
  57979. return;
  57980. }
  57981. new DataDiffer(oldChildren, newChildren, getKey, getKey)
  57982. .add(processNode)
  57983. .update(processNode)
  57984. .remove(curry(processNode, null))
  57985. .execute();
  57986. function getKey(node) {
  57987. return node.getId();
  57988. }
  57989. function processNode(newId, oldId) {
  57990. var newNode = newId == null ? null : newChildren[newId];
  57991. var oldNode = oldId == null ? null : oldChildren[oldId];
  57992. doRenderNode(newNode, oldNode);
  57993. }
  57994. }
  57995. function doRenderNode(newNode, oldNode) {
  57996. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  57997. // Not render data with value 0
  57998. newNode = null;
  57999. }
  58000. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  58001. if (oldNode && oldNode.piece) {
  58002. if (newNode) {
  58003. // Update
  58004. oldNode.piece.updateData(
  58005. false, newNode, 'normal', seriesModel, ecModel);
  58006. // For tooltip
  58007. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  58008. }
  58009. else {
  58010. // Remove
  58011. removeNode(oldNode);
  58012. }
  58013. }
  58014. else if (newNode) {
  58015. // Add
  58016. var piece = new SunburstPiece(
  58017. newNode,
  58018. seriesModel,
  58019. ecModel
  58020. );
  58021. group.add(piece);
  58022. // For tooltip
  58023. data.setItemGraphicEl(newNode.dataIndex, piece);
  58024. }
  58025. }
  58026. }
  58027. function removeNode(node) {
  58028. if (!node) {
  58029. return;
  58030. }
  58031. if (node.piece) {
  58032. group.remove(node.piece);
  58033. node.piece = null;
  58034. }
  58035. }
  58036. function renderRollUp(virtualRoot, viewRoot) {
  58037. if (viewRoot.depth > 0) {
  58038. // Render
  58039. if (that.virtualPiece) {
  58040. // Update
  58041. that.virtualPiece.updateData(
  58042. false, virtualRoot, 'normal', seriesModel, ecModel);
  58043. }
  58044. else {
  58045. // Add
  58046. that.virtualPiece = new SunburstPiece(
  58047. virtualRoot,
  58048. seriesModel,
  58049. ecModel
  58050. );
  58051. group.add(that.virtualPiece);
  58052. }
  58053. if (viewRoot.piece._onclickEvent) {
  58054. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  58055. }
  58056. var event = function (e) {
  58057. that._rootToNode(viewRoot.parentNode);
  58058. };
  58059. viewRoot.piece._onclickEvent = event;
  58060. that.virtualPiece.on('click', event);
  58061. }
  58062. else if (that.virtualPiece) {
  58063. // Remove
  58064. group.remove(that.virtualPiece);
  58065. that.virtualPiece = null;
  58066. }
  58067. }
  58068. },
  58069. dispose: function () {
  58070. },
  58071. /**
  58072. * @private
  58073. */
  58074. _initEvents: function () {
  58075. var that = this;
  58076. var event = function (e) {
  58077. var targetFound = false;
  58078. var viewRoot = that.seriesModel.getViewRoot();
  58079. viewRoot.eachNode(function (node) {
  58080. if (!targetFound
  58081. && node.piece && node.piece.childAt(0) === e.target
  58082. ) {
  58083. var nodeClick = node.getModel().get('nodeClick');
  58084. if (nodeClick === 'rootToNode') {
  58085. that._rootToNode(node);
  58086. }
  58087. else if (nodeClick === 'link') {
  58088. var itemModel = node.getModel();
  58089. var link = itemModel.get('link');
  58090. if (link) {
  58091. var linkTarget = itemModel.get('target', true)
  58092. || '_blank';
  58093. window.open(link, linkTarget);
  58094. }
  58095. }
  58096. targetFound = true;
  58097. }
  58098. });
  58099. };
  58100. if (this.group._onclickEvent) {
  58101. this.group.off('click', this.group._onclickEvent);
  58102. }
  58103. this.group.on('click', event);
  58104. this.group._onclickEvent = event;
  58105. },
  58106. /**
  58107. * @private
  58108. */
  58109. _rootToNode: function (node) {
  58110. if (node !== this.seriesModel.getViewRoot()) {
  58111. this.api.dispatchAction({
  58112. type: ROOT_TO_NODE_ACTION,
  58113. from: this.uid,
  58114. seriesId: this.seriesModel.id,
  58115. targetNode: node
  58116. });
  58117. }
  58118. },
  58119. /**
  58120. * @implement
  58121. */
  58122. containPoint: function (point, seriesModel) {
  58123. var treeRoot = seriesModel.getData();
  58124. var itemLayout = treeRoot.getItemLayout(0);
  58125. if (itemLayout) {
  58126. var dx = point[0] - itemLayout.cx;
  58127. var dy = point[1] - itemLayout.cy;
  58128. var radius = Math.sqrt(dx * dx + dy * dy);
  58129. return radius <= itemLayout.r && radius >= itemLayout.r0;
  58130. }
  58131. }
  58132. });
  58133. /*
  58134. * Licensed to the Apache Software Foundation (ASF) under one
  58135. * or more contributor license agreements. See the NOTICE file
  58136. * distributed with this work for additional information
  58137. * regarding copyright ownership. The ASF licenses this file
  58138. * to you under the Apache License, Version 2.0 (the
  58139. * "License"); you may not use this file except in compliance
  58140. * with the License. You may obtain a copy of the License at
  58141. *
  58142. * http://www.apache.org/licenses/LICENSE-2.0
  58143. *
  58144. * Unless required by applicable law or agreed to in writing,
  58145. * software distributed under the License is distributed on an
  58146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58147. * KIND, either express or implied. See the License for the
  58148. * specific language governing permissions and limitations
  58149. * under the License.
  58150. */
  58151. /**
  58152. * @file Sunburst action
  58153. */
  58154. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  58155. registerAction(
  58156. {type: ROOT_TO_NODE_ACTION$1, update: 'updateView'},
  58157. function (payload, ecModel) {
  58158. ecModel.eachComponent(
  58159. {mainType: 'series', subType: 'sunburst', query: payload},
  58160. handleRootToNode
  58161. );
  58162. function handleRootToNode(model, index) {
  58163. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  58164. if (targetInfo) {
  58165. var originViewRoot = model.getViewRoot();
  58166. if (originViewRoot) {
  58167. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node)
  58168. ? 'rollUp' : 'drillDown';
  58169. }
  58170. model.resetViewRoot(targetInfo.node);
  58171. }
  58172. }
  58173. }
  58174. );
  58175. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  58176. registerAction(
  58177. {type: HIGHLIGHT_ACTION, update: 'updateView'},
  58178. function (payload, ecModel) {
  58179. ecModel.eachComponent(
  58180. {mainType: 'series', subType: 'sunburst', query: payload},
  58181. handleHighlight
  58182. );
  58183. function handleHighlight(model, index) {
  58184. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  58185. if (targetInfo) {
  58186. payload.highlight = targetInfo.node;
  58187. }
  58188. }
  58189. }
  58190. );
  58191. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  58192. registerAction(
  58193. {type: UNHIGHLIGHT_ACTION, update: 'updateView'},
  58194. function (payload, ecModel) {
  58195. ecModel.eachComponent(
  58196. {mainType: 'series', subType: 'sunburst', query: payload},
  58197. handleUnhighlight
  58198. );
  58199. function handleUnhighlight(model, index) {
  58200. payload.unhighlight = true;
  58201. }
  58202. }
  58203. );
  58204. /*
  58205. * Licensed to the Apache Software Foundation (ASF) under one
  58206. * or more contributor license agreements. See the NOTICE file
  58207. * distributed with this work for additional information
  58208. * regarding copyright ownership. The ASF licenses this file
  58209. * to you under the Apache License, Version 2.0 (the
  58210. * "License"); you may not use this file except in compliance
  58211. * with the License. You may obtain a copy of the License at
  58212. *
  58213. * http://www.apache.org/licenses/LICENSE-2.0
  58214. *
  58215. * Unless required by applicable law or agreed to in writing,
  58216. * software distributed under the License is distributed on an
  58217. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58218. * KIND, either express or implied. See the License for the
  58219. * specific language governing permissions and limitations
  58220. * under the License.
  58221. */
  58222. var RADIAN$1 = Math.PI / 180;
  58223. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  58224. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  58225. var center = seriesModel.get('center');
  58226. var radius = seriesModel.get('radius');
  58227. if (!isArray(radius)) {
  58228. radius = [0, radius];
  58229. }
  58230. if (!isArray(center)) {
  58231. center = [center, center];
  58232. }
  58233. var width = api.getWidth();
  58234. var height = api.getHeight();
  58235. var size = Math.min(width, height);
  58236. var cx = parsePercent$1(center[0], width);
  58237. var cy = parsePercent$1(center[1], height);
  58238. var r0 = parsePercent$1(radius[0], size / 2);
  58239. var r = parsePercent$1(radius[1], size / 2);
  58240. var startAngle = -seriesModel.get('startAngle') * RADIAN$1;
  58241. var minAngle = seriesModel.get('minAngle') * RADIAN$1;
  58242. var virtualRoot = seriesModel.getData().tree.root;
  58243. var treeRoot = seriesModel.getViewRoot();
  58244. var rootDepth = treeRoot.depth;
  58245. var sort = seriesModel.get('sort');
  58246. if (sort != null) {
  58247. initChildren$1(treeRoot, sort);
  58248. }
  58249. var validDataCount = 0;
  58250. each$1(treeRoot.children, function (child) {
  58251. !isNaN(child.getValue()) && validDataCount++;
  58252. });
  58253. var sum = treeRoot.getValue();
  58254. // Sum may be 0
  58255. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  58256. var renderRollupNode = treeRoot.depth > 0;
  58257. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  58258. var rPerLevel = (r - r0) / (levels || 1);
  58259. var clockwise = seriesModel.get('clockwise');
  58260. var stillShowZeroSum = seriesModel.get('stillShowZeroSum');
  58261. // In the case some sector angle is smaller than minAngle
  58262. var dir = clockwise ? 1 : -1;
  58263. /**
  58264. * Render a tree
  58265. * @return increased angle
  58266. */
  58267. var renderNode = function (node, startAngle) {
  58268. if (!node) {
  58269. return;
  58270. }
  58271. var endAngle = startAngle;
  58272. // Render self
  58273. if (node !== virtualRoot) {
  58274. // Tree node is virtual, so it doesn't need to be drawn
  58275. var value = node.getValue();
  58276. var angle = (sum === 0 && stillShowZeroSum)
  58277. ? unitRadian : (value * unitRadian);
  58278. if (angle < minAngle) {
  58279. angle = minAngle;
  58280. }
  58281. else {
  58282. }
  58283. endAngle = startAngle + dir * angle;
  58284. var depth = node.depth - rootDepth
  58285. - (renderRollupNode ? -1 : 1);
  58286. var rStart = r0 + rPerLevel * depth;
  58287. var rEnd = r0 + rPerLevel * (depth + 1);
  58288. var itemModel = node.getModel();
  58289. if (itemModel.get('r0') != null) {
  58290. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  58291. }
  58292. if (itemModel.get('r') != null) {
  58293. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  58294. }
  58295. node.setLayout({
  58296. angle: angle,
  58297. startAngle: startAngle,
  58298. endAngle: endAngle,
  58299. clockwise: clockwise,
  58300. cx: cx,
  58301. cy: cy,
  58302. r0: rStart,
  58303. r: rEnd
  58304. });
  58305. }
  58306. // Render children
  58307. if (node.children && node.children.length) {
  58308. // currentAngle = startAngle;
  58309. var siblingAngle = 0;
  58310. each$1(node.children, function (node) {
  58311. siblingAngle += renderNode(node, startAngle + siblingAngle);
  58312. });
  58313. }
  58314. return endAngle - startAngle;
  58315. };
  58316. // Virtual root node for roll up
  58317. if (renderRollupNode) {
  58318. var rStart = r0;
  58319. var rEnd = r0 + rPerLevel;
  58320. var angle = Math.PI * 2;
  58321. virtualRoot.setLayout({
  58322. angle: angle,
  58323. startAngle: startAngle,
  58324. endAngle: startAngle + angle,
  58325. clockwise: clockwise,
  58326. cx: cx,
  58327. cy: cy,
  58328. r0: rStart,
  58329. r: rEnd
  58330. });
  58331. }
  58332. renderNode(treeRoot, startAngle);
  58333. });
  58334. };
  58335. /**
  58336. * Init node children by order and update visual
  58337. *
  58338. * @param {TreeNode} node root node
  58339. * @param {boolean} isAsc if is in ascendant order
  58340. */
  58341. function initChildren$1(node, isAsc) {
  58342. var children = node.children || [];
  58343. node.children = sort$2(children, isAsc);
  58344. // Init children recursively
  58345. if (children.length) {
  58346. each$1(node.children, function (child) {
  58347. initChildren$1(child, isAsc);
  58348. });
  58349. }
  58350. }
  58351. /**
  58352. * Sort children nodes
  58353. *
  58354. * @param {TreeNode[]} children children of node to be sorted
  58355. * @param {string | function | null} sort sort method
  58356. * See SunburstSeries.js for details.
  58357. */
  58358. function sort$2(children, sortOrder) {
  58359. if (typeof sortOrder === 'function') {
  58360. return children.sort(sortOrder);
  58361. }
  58362. else {
  58363. var isAsc = sortOrder === 'asc';
  58364. return children.sort(function (a, b) {
  58365. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  58366. return diff === 0
  58367. ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1)
  58368. : diff;
  58369. });
  58370. }
  58371. }
  58372. /*
  58373. * Licensed to the Apache Software Foundation (ASF) under one
  58374. * or more contributor license agreements. See the NOTICE file
  58375. * distributed with this work for additional information
  58376. * regarding copyright ownership. The ASF licenses this file
  58377. * to you under the Apache License, Version 2.0 (the
  58378. * "License"); you may not use this file except in compliance
  58379. * with the License. You may obtain a copy of the License at
  58380. *
  58381. * http://www.apache.org/licenses/LICENSE-2.0
  58382. *
  58383. * Unless required by applicable law or agreed to in writing,
  58384. * software distributed under the License is distributed on an
  58385. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58386. * KIND, either express or implied. See the License for the
  58387. * specific language governing permissions and limitations
  58388. * under the License.
  58389. */
  58390. registerVisual(curry(dataColor, 'sunburst'));
  58391. registerLayout(curry(sunburstLayout, 'sunburst'));
  58392. registerProcessor(curry(dataFilter, 'sunburst'));
  58393. /*
  58394. * Licensed to the Apache Software Foundation (ASF) under one
  58395. * or more contributor license agreements. See the NOTICE file
  58396. * distributed with this work for additional information
  58397. * regarding copyright ownership. The ASF licenses this file
  58398. * to you under the Apache License, Version 2.0 (the
  58399. * "License"); you may not use this file except in compliance
  58400. * with the License. You may obtain a copy of the License at
  58401. *
  58402. * http://www.apache.org/licenses/LICENSE-2.0
  58403. *
  58404. * Unless required by applicable law or agreed to in writing,
  58405. * software distributed under the License is distributed on an
  58406. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58407. * KIND, either express or implied. See the License for the
  58408. * specific language governing permissions and limitations
  58409. * under the License.
  58410. */
  58411. function dataToCoordSize(dataSize, dataItem) {
  58412. // dataItem is necessary in log axis.
  58413. dataItem = dataItem || [0, 0];
  58414. return map(['x', 'y'], function (dim, dimIdx) {
  58415. var axis = this.getAxis(dim);
  58416. var val = dataItem[dimIdx];
  58417. var halfSize = dataSize[dimIdx] / 2;
  58418. return axis.type === 'category'
  58419. ? axis.getBandWidth()
  58420. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  58421. }, this);
  58422. }
  58423. var prepareCartesian2d = function (coordSys) {
  58424. var rect = coordSys.grid.getRect();
  58425. return {
  58426. coordSys: {
  58427. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  58428. type: 'cartesian2d',
  58429. x: rect.x,
  58430. y: rect.y,
  58431. width: rect.width,
  58432. height: rect.height
  58433. },
  58434. api: {
  58435. coord: function (data) {
  58436. // do not provide "out" param
  58437. return coordSys.dataToPoint(data);
  58438. },
  58439. size: bind(dataToCoordSize, coordSys)
  58440. }
  58441. };
  58442. };
  58443. /*
  58444. * Licensed to the Apache Software Foundation (ASF) under one
  58445. * or more contributor license agreements. See the NOTICE file
  58446. * distributed with this work for additional information
  58447. * regarding copyright ownership. The ASF licenses this file
  58448. * to you under the Apache License, Version 2.0 (the
  58449. * "License"); you may not use this file except in compliance
  58450. * with the License. You may obtain a copy of the License at
  58451. *
  58452. * http://www.apache.org/licenses/LICENSE-2.0
  58453. *
  58454. * Unless required by applicable law or agreed to in writing,
  58455. * software distributed under the License is distributed on an
  58456. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58457. * KIND, either express or implied. See the License for the
  58458. * specific language governing permissions and limitations
  58459. * under the License.
  58460. */
  58461. function dataToCoordSize$1(dataSize, dataItem) {
  58462. dataItem = dataItem || [0, 0];
  58463. return map([0, 1], function (dimIdx) {
  58464. var val = dataItem[dimIdx];
  58465. var halfSize = dataSize[dimIdx] / 2;
  58466. var p1 = [];
  58467. var p2 = [];
  58468. p1[dimIdx] = val - halfSize;
  58469. p2[dimIdx] = val + halfSize;
  58470. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  58471. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  58472. }, this);
  58473. }
  58474. var prepareGeo = function (coordSys) {
  58475. var rect = coordSys.getBoundingRect();
  58476. return {
  58477. coordSys: {
  58478. type: 'geo',
  58479. x: rect.x,
  58480. y: rect.y,
  58481. width: rect.width,
  58482. height: rect.height
  58483. },
  58484. api: {
  58485. coord: function (data) {
  58486. // do not provide "out" and noRoam param,
  58487. // Compatible with this usage:
  58488. // echarts.util.map(item.points, api.coord)
  58489. return coordSys.dataToPoint(data);
  58490. },
  58491. size: bind(dataToCoordSize$1, coordSys)
  58492. }
  58493. };
  58494. };
  58495. /*
  58496. * Licensed to the Apache Software Foundation (ASF) under one
  58497. * or more contributor license agreements. See the NOTICE file
  58498. * distributed with this work for additional information
  58499. * regarding copyright ownership. The ASF licenses this file
  58500. * to you under the Apache License, Version 2.0 (the
  58501. * "License"); you may not use this file except in compliance
  58502. * with the License. You may obtain a copy of the License at
  58503. *
  58504. * http://www.apache.org/licenses/LICENSE-2.0
  58505. *
  58506. * Unless required by applicable law or agreed to in writing,
  58507. * software distributed under the License is distributed on an
  58508. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58509. * KIND, either express or implied. See the License for the
  58510. * specific language governing permissions and limitations
  58511. * under the License.
  58512. */
  58513. function dataToCoordSize$2(dataSize, dataItem) {
  58514. // dataItem is necessary in log axis.
  58515. var axis = this.getAxis();
  58516. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  58517. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  58518. return axis.type === 'category'
  58519. ? axis.getBandWidth()
  58520. : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  58521. }
  58522. var prepareSingleAxis = function (coordSys) {
  58523. var rect = coordSys.getRect();
  58524. return {
  58525. coordSys: {
  58526. type: 'singleAxis',
  58527. x: rect.x,
  58528. y: rect.y,
  58529. width: rect.width,
  58530. height: rect.height
  58531. },
  58532. api: {
  58533. coord: function (val) {
  58534. // do not provide "out" param
  58535. return coordSys.dataToPoint(val);
  58536. },
  58537. size: bind(dataToCoordSize$2, coordSys)
  58538. }
  58539. };
  58540. };
  58541. /*
  58542. * Licensed to the Apache Software Foundation (ASF) under one
  58543. * or more contributor license agreements. See the NOTICE file
  58544. * distributed with this work for additional information
  58545. * regarding copyright ownership. The ASF licenses this file
  58546. * to you under the Apache License, Version 2.0 (the
  58547. * "License"); you may not use this file except in compliance
  58548. * with the License. You may obtain a copy of the License at
  58549. *
  58550. * http://www.apache.org/licenses/LICENSE-2.0
  58551. *
  58552. * Unless required by applicable law or agreed to in writing,
  58553. * software distributed under the License is distributed on an
  58554. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58555. * KIND, either express or implied. See the License for the
  58556. * specific language governing permissions and limitations
  58557. * under the License.
  58558. */
  58559. function dataToCoordSize$3(dataSize, dataItem) {
  58560. // dataItem is necessary in log axis.
  58561. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  58562. var axis = this['get' + dim + 'Axis']();
  58563. var val = dataItem[dimIdx];
  58564. var halfSize = dataSize[dimIdx] / 2;
  58565. var method = 'dataTo' + dim;
  58566. var result = axis.type === 'category'
  58567. ? axis.getBandWidth()
  58568. : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  58569. if (dim === 'Angle') {
  58570. result = result * Math.PI / 180;
  58571. }
  58572. return result;
  58573. }, this);
  58574. }
  58575. var preparePolar = function (coordSys) {
  58576. var radiusAxis = coordSys.getRadiusAxis();
  58577. var angleAxis = coordSys.getAngleAxis();
  58578. var radius = radiusAxis.getExtent();
  58579. radius[0] > radius[1] && radius.reverse();
  58580. return {
  58581. coordSys: {
  58582. type: 'polar',
  58583. cx: coordSys.cx,
  58584. cy: coordSys.cy,
  58585. r: radius[1],
  58586. r0: radius[0]
  58587. },
  58588. api: {
  58589. coord: bind(function (data) {
  58590. var radius = radiusAxis.dataToRadius(data[0]);
  58591. var angle = angleAxis.dataToAngle(data[1]);
  58592. var coord = coordSys.coordToPoint([radius, angle]);
  58593. coord.push(radius, angle * Math.PI / 180);
  58594. return coord;
  58595. }),
  58596. size: bind(dataToCoordSize$3, coordSys)
  58597. }
  58598. };
  58599. };
  58600. /*
  58601. * Licensed to the Apache Software Foundation (ASF) under one
  58602. * or more contributor license agreements. See the NOTICE file
  58603. * distributed with this work for additional information
  58604. * regarding copyright ownership. The ASF licenses this file
  58605. * to you under the Apache License, Version 2.0 (the
  58606. * "License"); you may not use this file except in compliance
  58607. * with the License. You may obtain a copy of the License at
  58608. *
  58609. * http://www.apache.org/licenses/LICENSE-2.0
  58610. *
  58611. * Unless required by applicable law or agreed to in writing,
  58612. * software distributed under the License is distributed on an
  58613. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58614. * KIND, either express or implied. See the License for the
  58615. * specific language governing permissions and limitations
  58616. * under the License.
  58617. */
  58618. var prepareCalendar = function (coordSys) {
  58619. var rect = coordSys.getRect();
  58620. var rangeInfo = coordSys.getRangeInfo();
  58621. return {
  58622. coordSys: {
  58623. type: 'calendar',
  58624. x: rect.x,
  58625. y: rect.y,
  58626. width: rect.width,
  58627. height: rect.height,
  58628. cellWidth: coordSys.getCellWidth(),
  58629. cellHeight: coordSys.getCellHeight(),
  58630. rangeInfo: {
  58631. start: rangeInfo.start,
  58632. end: rangeInfo.end,
  58633. weeks: rangeInfo.weeks,
  58634. dayCount: rangeInfo.allDay
  58635. }
  58636. },
  58637. api: {
  58638. coord: function (data, clamp) {
  58639. return coordSys.dataToPoint(data, clamp);
  58640. }
  58641. }
  58642. };
  58643. };
  58644. /*
  58645. * Licensed to the Apache Software Foundation (ASF) under one
  58646. * or more contributor license agreements. See the NOTICE file
  58647. * distributed with this work for additional information
  58648. * regarding copyright ownership. The ASF licenses this file
  58649. * to you under the Apache License, Version 2.0 (the
  58650. * "License"); you may not use this file except in compliance
  58651. * with the License. You may obtain a copy of the License at
  58652. *
  58653. * http://www.apache.org/licenses/LICENSE-2.0
  58654. *
  58655. * Unless required by applicable law or agreed to in writing,
  58656. * software distributed under the License is distributed on an
  58657. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58658. * KIND, either express or implied. See the License for the
  58659. * specific language governing permissions and limitations
  58660. * under the License.
  58661. */
  58662. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  58663. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  58664. var LABEL_NORMAL = ['label'];
  58665. var LABEL_EMPHASIS = ['emphasis', 'label'];
  58666. // Use prefix to avoid index to be the same as el.name,
  58667. // which will cause weird update animation.
  58668. var GROUP_DIFF_PREFIX = 'e\0\0';
  58669. /**
  58670. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  58671. * of each coordinate systems are not required by each coordinate systems directly, but
  58672. * required by the module `custom`.
  58673. *
  58674. * prepareInfoForCustomSeries {Function}: optional
  58675. * @return {Object} {coordSys: {...}, api: {
  58676. * coord: function (data, clamp) {}, // return point in global.
  58677. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  58678. * }}
  58679. */
  58680. var prepareCustoms = {
  58681. cartesian2d: prepareCartesian2d,
  58682. geo: prepareGeo,
  58683. singleAxis: prepareSingleAxis,
  58684. polar: preparePolar,
  58685. calendar: prepareCalendar
  58686. };
  58687. // ------
  58688. // Model
  58689. // ------
  58690. extendSeriesModel({
  58691. type: 'series.custom',
  58692. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  58693. defaultOption: {
  58694. coordinateSystem: 'cartesian2d', // Can be set as 'none'
  58695. zlevel: 0,
  58696. z: 2,
  58697. legendHoverLink: true
  58698. // Cartesian coordinate system
  58699. // xAxisIndex: 0,
  58700. // yAxisIndex: 0,
  58701. // Polar coordinate system
  58702. // polarIndex: 0,
  58703. // Geo coordinate system
  58704. // geoIndex: 0,
  58705. // label: {}
  58706. // itemStyle: {}
  58707. },
  58708. getInitialData: function (option, ecModel) {
  58709. return createListFromArray(this.getSource(), this);
  58710. }
  58711. });
  58712. // -----
  58713. // View
  58714. // -----
  58715. extendChartView({
  58716. type: 'custom',
  58717. /**
  58718. * @private
  58719. * @type {module:echarts/data/List}
  58720. */
  58721. _data: null,
  58722. /**
  58723. * @override
  58724. */
  58725. render: function (customSeries, ecModel, api) {
  58726. var oldData = this._data;
  58727. var data = customSeries.getData();
  58728. var group = this.group;
  58729. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  58730. this.group.removeAll();
  58731. data.diff(oldData)
  58732. .add(function (newIdx) {
  58733. createOrUpdate$1(
  58734. null, newIdx, renderItem(newIdx), customSeries, group, data
  58735. );
  58736. })
  58737. .update(function (newIdx, oldIdx) {
  58738. var el = oldData.getItemGraphicEl(oldIdx);
  58739. createOrUpdate$1(
  58740. el, newIdx, renderItem(newIdx), customSeries, group, data
  58741. );
  58742. })
  58743. .remove(function (oldIdx) {
  58744. var el = oldData.getItemGraphicEl(oldIdx);
  58745. el && group.remove(el);
  58746. })
  58747. .execute();
  58748. this._data = data;
  58749. },
  58750. incrementalPrepareRender: function (customSeries, ecModel, api) {
  58751. this.group.removeAll();
  58752. this._data = null;
  58753. },
  58754. incrementalRender: function (params, customSeries, ecModel, api) {
  58755. var data = customSeries.getData();
  58756. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  58757. function setIncrementalAndHoverLayer(el) {
  58758. if (!el.isGroup) {
  58759. el.incremental = true;
  58760. el.useHoverLayer = true;
  58761. }
  58762. }
  58763. for (var idx = params.start; idx < params.end; idx++) {
  58764. var el = createOrUpdate$1(null, idx, renderItem(idx), customSeries, this.group, data);
  58765. el.traverse(setIncrementalAndHoverLayer);
  58766. }
  58767. },
  58768. /**
  58769. * @override
  58770. */
  58771. dispose: noop
  58772. });
  58773. function createEl(elOption) {
  58774. var graphicType = elOption.type;
  58775. var el;
  58776. if (graphicType === 'path') {
  58777. var shape = elOption.shape;
  58778. el = makePath(
  58779. shape.pathData,
  58780. null,
  58781. {
  58782. x: shape.x || 0,
  58783. y: shape.y || 0,
  58784. width: shape.width || 0,
  58785. height: shape.height || 0
  58786. },
  58787. 'center'
  58788. );
  58789. el.__customPathData = elOption.pathData;
  58790. }
  58791. else if (graphicType === 'image') {
  58792. el = new ZImage({
  58793. });
  58794. el.__customImagePath = elOption.style.image;
  58795. }
  58796. else if (graphicType === 'text') {
  58797. el = new Text({
  58798. });
  58799. el.__customText = elOption.style.text;
  58800. }
  58801. else {
  58802. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  58803. if (__DEV__) {
  58804. assert$1(Clz, 'graphic type "' + graphicType + '" can not be found.');
  58805. }
  58806. el = new Clz();
  58807. }
  58808. el.__customGraphicType = graphicType;
  58809. el.name = elOption.name;
  58810. return el;
  58811. }
  58812. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit) {
  58813. var targetProps = {};
  58814. var elOptionStyle = elOption.style || {};
  58815. elOption.shape && (targetProps.shape = clone(elOption.shape));
  58816. elOption.position && (targetProps.position = elOption.position.slice());
  58817. elOption.scale && (targetProps.scale = elOption.scale.slice());
  58818. elOption.origin && (targetProps.origin = elOption.origin.slice());
  58819. elOption.rotation && (targetProps.rotation = elOption.rotation);
  58820. if (el.type === 'image' && elOption.style) {
  58821. var targetStyle = targetProps.style = {};
  58822. each$1(['x', 'y', 'width', 'height'], function (prop) {
  58823. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  58824. });
  58825. }
  58826. if (el.type === 'text' && elOption.style) {
  58827. var targetStyle = targetProps.style = {};
  58828. each$1(['x', 'y'], function (prop) {
  58829. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  58830. });
  58831. // Compatible with previous: both support
  58832. // textFill and fill, textStroke and stroke in 'text' element.
  58833. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  58834. elOptionStyle.textFill = elOptionStyle.fill
  58835. );
  58836. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  58837. elOptionStyle.textStroke = elOptionStyle.stroke
  58838. );
  58839. }
  58840. if (el.type !== 'group') {
  58841. el.useStyle(elOptionStyle);
  58842. // Init animation.
  58843. if (isInit) {
  58844. el.style.opacity = 0;
  58845. var targetOpacity = elOptionStyle.opacity;
  58846. targetOpacity == null && (targetOpacity = 1);
  58847. initProps(el, {style: {opacity: targetOpacity}}, animatableModel, dataIndex);
  58848. }
  58849. }
  58850. if (isInit) {
  58851. el.attr(targetProps);
  58852. }
  58853. else {
  58854. updateProps(el, targetProps, animatableModel, dataIndex);
  58855. }
  58856. // z2 must not be null/undefined, otherwise sort error may occur.
  58857. el.attr({z2: elOption.z2 || 0, silent: elOption.silent});
  58858. elOption.styleEmphasis !== false && setHoverStyle(el, elOption.styleEmphasis);
  58859. }
  58860. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  58861. if (elOptionStyle[prop] != null && !isInit) {
  58862. targetStyle[prop] = elOptionStyle[prop];
  58863. elOptionStyle[prop] = oldElStyle[prop];
  58864. }
  58865. }
  58866. function makeRenderItem(customSeries, data, ecModel, api) {
  58867. var renderItem = customSeries.get('renderItem');
  58868. var coordSys = customSeries.coordinateSystem;
  58869. var prepareResult = {};
  58870. if (coordSys) {
  58871. if (__DEV__) {
  58872. assert$1(renderItem, 'series.render is required.');
  58873. assert$1(
  58874. coordSys.prepareCustoms || prepareCustoms[coordSys.type],
  58875. 'This coordSys does not support custom series.'
  58876. );
  58877. }
  58878. prepareResult = coordSys.prepareCustoms
  58879. ? coordSys.prepareCustoms()
  58880. : prepareCustoms[coordSys.type](coordSys);
  58881. }
  58882. var userAPI = defaults({
  58883. getWidth: api.getWidth,
  58884. getHeight: api.getHeight,
  58885. getZr: api.getZr,
  58886. getDevicePixelRatio: api.getDevicePixelRatio,
  58887. value: value,
  58888. style: style,
  58889. styleEmphasis: styleEmphasis,
  58890. visual: visual,
  58891. barLayout: barLayout,
  58892. currentSeriesIndices: currentSeriesIndices,
  58893. font: font
  58894. }, prepareResult.api || {});
  58895. var userParams = {
  58896. context: {},
  58897. seriesId: customSeries.id,
  58898. seriesName: customSeries.name,
  58899. seriesIndex: customSeries.seriesIndex,
  58900. coordSys: prepareResult.coordSys,
  58901. dataInsideLength: data.count(),
  58902. encode: wrapEncodeDef(customSeries.getData())
  58903. };
  58904. // Do not support call `api` asynchronously without dataIndexInside input.
  58905. var currDataIndexInside;
  58906. var currDirty = true;
  58907. var currItemModel;
  58908. var currLabelNormalModel;
  58909. var currLabelEmphasisModel;
  58910. var currVisualColor;
  58911. return function (dataIndexInside) {
  58912. currDataIndexInside = dataIndexInside;
  58913. currDirty = true;
  58914. return renderItem && renderItem(
  58915. defaults({
  58916. dataIndexInside: dataIndexInside,
  58917. dataIndex: data.getRawIndex(dataIndexInside)
  58918. }, userParams),
  58919. userAPI
  58920. ) || {};
  58921. };
  58922. // Do not update cache until api called.
  58923. function updateCache(dataIndexInside) {
  58924. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58925. if (currDirty) {
  58926. currItemModel = data.getItemModel(dataIndexInside);
  58927. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  58928. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  58929. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  58930. currDirty = false;
  58931. }
  58932. }
  58933. /**
  58934. * @public
  58935. * @param {number|string} dim
  58936. * @param {number} [dataIndexInside=currDataIndexInside]
  58937. * @return {number|string} value
  58938. */
  58939. function value(dim, dataIndexInside) {
  58940. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58941. return data.get(data.getDimension(dim || 0), dataIndexInside);
  58942. }
  58943. /**
  58944. * By default, `visual` is applied to style (to support visualMap).
  58945. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  58946. * it can be implemented as:
  58947. * `api.style({stroke: api.visual('color'), fill: null})`;
  58948. * @public
  58949. * @param {Object} [extra]
  58950. * @param {number} [dataIndexInside=currDataIndexInside]
  58951. */
  58952. function style(extra, dataIndexInside) {
  58953. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58954. updateCache(dataIndexInside);
  58955. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  58956. currVisualColor != null && (itemStyle.fill = currVisualColor);
  58957. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  58958. opacity != null && (itemStyle.opacity = opacity);
  58959. setTextStyle(itemStyle, currLabelNormalModel, null, {
  58960. autoColor: currVisualColor,
  58961. isRectText: true
  58962. });
  58963. itemStyle.text = currLabelNormalModel.getShallow('show')
  58964. ? retrieve2(
  58965. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  58966. getDefaultLabel(data, dataIndexInside)
  58967. )
  58968. : null;
  58969. extra && extend(itemStyle, extra);
  58970. return itemStyle;
  58971. }
  58972. /**
  58973. * @public
  58974. * @param {Object} [extra]
  58975. * @param {number} [dataIndexInside=currDataIndexInside]
  58976. */
  58977. function styleEmphasis(extra, dataIndexInside) {
  58978. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  58979. updateCache(dataIndexInside);
  58980. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  58981. setTextStyle(itemStyle, currLabelEmphasisModel, null, {
  58982. isRectText: true
  58983. }, true);
  58984. itemStyle.text = currLabelEmphasisModel.getShallow('show')
  58985. ? retrieve3(
  58986. customSeries.getFormattedLabel(dataIndexInside, 'emphasis'),
  58987. customSeries.getFormattedLabel(dataIndexInside, 'normal'),
  58988. getDefaultLabel(data, dataIndexInside)
  58989. )
  58990. : null;
  58991. extra && extend(itemStyle, extra);
  58992. return itemStyle;
  58993. }
  58994. /**
  58995. * @public
  58996. * @param {string} visualType
  58997. * @param {number} [dataIndexInside=currDataIndexInside]
  58998. */
  58999. function visual(visualType, dataIndexInside) {
  59000. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  59001. return data.getItemVisual(dataIndexInside, visualType);
  59002. }
  59003. /**
  59004. * @public
  59005. * @param {number} opt.count Positive interger.
  59006. * @param {number} [opt.barWidth]
  59007. * @param {number} [opt.barMaxWidth]
  59008. * @param {number} [opt.barGap]
  59009. * @param {number} [opt.barCategoryGap]
  59010. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  59011. */
  59012. function barLayout(opt) {
  59013. if (coordSys.getBaseAxis) {
  59014. var baseAxis = coordSys.getBaseAxis();
  59015. return getLayoutOnAxis(defaults({axis: baseAxis}, opt), api);
  59016. }
  59017. }
  59018. /**
  59019. * @public
  59020. * @return {Array.<number>}
  59021. */
  59022. function currentSeriesIndices() {
  59023. return ecModel.getCurrentSeriesIndices();
  59024. }
  59025. /**
  59026. * @public
  59027. * @param {Object} opt
  59028. * @param {string} [opt.fontStyle]
  59029. * @param {number} [opt.fontWeight]
  59030. * @param {number} [opt.fontSize]
  59031. * @param {string} [opt.fontFamily]
  59032. * @return {string} font string
  59033. */
  59034. function font(opt) {
  59035. return getFont(opt, ecModel);
  59036. }
  59037. }
  59038. function wrapEncodeDef(data) {
  59039. var encodeDef = {};
  59040. each$1(data.dimensions, function (dimName, dataDimIndex) {
  59041. var dimInfo = data.getDimensionInfo(dimName);
  59042. if (!dimInfo.isExtraCoord) {
  59043. var coordDim = dimInfo.coordDim;
  59044. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  59045. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  59046. }
  59047. });
  59048. return encodeDef;
  59049. }
  59050. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  59051. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data);
  59052. el && data.setItemGraphicEl(dataIndex, el);
  59053. return el;
  59054. }
  59055. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data) {
  59056. var elOptionType = elOption.type;
  59057. if (el
  59058. && elOptionType !== el.__customGraphicType
  59059. && (elOptionType !== 'path' || elOption.pathData !== el.__customPathData)
  59060. && (elOptionType !== 'image' || elOption.style.image !== el.__customImagePath)
  59061. && (elOptionType !== 'text' || elOption.style.text !== el.__customText)
  59062. ) {
  59063. group.remove(el);
  59064. el = null;
  59065. }
  59066. // `elOption.type` is undefined when `renderItem` returns nothing.
  59067. if (elOptionType == null) {
  59068. return;
  59069. }
  59070. var isInit = !el;
  59071. !el && (el = createEl(elOption));
  59072. updateEl(el, dataIndex, elOption, animatableModel, data, isInit);
  59073. if (elOptionType === 'group') {
  59074. var oldChildren = el.children() || [];
  59075. var newChildren = elOption.children || [];
  59076. if (elOption.diffChildrenByName) {
  59077. // lower performance.
  59078. diffGroupChildren({
  59079. oldChildren: oldChildren,
  59080. newChildren: newChildren,
  59081. dataIndex: dataIndex,
  59082. animatableModel: animatableModel,
  59083. group: el,
  59084. data: data
  59085. });
  59086. }
  59087. else {
  59088. // better performance.
  59089. var index = 0;
  59090. for (; index < newChildren.length; index++) {
  59091. doCreateOrUpdate(
  59092. el.childAt(index),
  59093. dataIndex,
  59094. newChildren[index],
  59095. animatableModel,
  59096. el,
  59097. data
  59098. );
  59099. }
  59100. for (; index < oldChildren.length; index++) {
  59101. oldChildren[index] && el.remove(oldChildren[index]);
  59102. }
  59103. }
  59104. }
  59105. group.add(el);
  59106. return el;
  59107. }
  59108. function diffGroupChildren(context) {
  59109. (new DataDiffer(
  59110. context.oldChildren,
  59111. context.newChildren,
  59112. getKey,
  59113. getKey,
  59114. context
  59115. ))
  59116. .add(processAddUpdate)
  59117. .update(processAddUpdate)
  59118. .remove(processRemove)
  59119. .execute();
  59120. }
  59121. function getKey(item, idx) {
  59122. var name = item && item.name;
  59123. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  59124. }
  59125. function processAddUpdate(newIndex, oldIndex) {
  59126. var context = this.context;
  59127. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  59128. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  59129. doCreateOrUpdate(
  59130. child,
  59131. context.dataIndex,
  59132. childOption,
  59133. context.animatableModel,
  59134. context.group,
  59135. context.data
  59136. );
  59137. }
  59138. function processRemove(oldIndex) {
  59139. var context = this.context;
  59140. var child = context.oldChildren[oldIndex];
  59141. child && context.group.remove(child);
  59142. }
  59143. /*
  59144. * Licensed to the Apache Software Foundation (ASF) under one
  59145. * or more contributor license agreements. See the NOTICE file
  59146. * distributed with this work for additional information
  59147. * regarding copyright ownership. The ASF licenses this file
  59148. * to you under the Apache License, Version 2.0 (the
  59149. * "License"); you may not use this file except in compliance
  59150. * with the License. You may obtain a copy of the License at
  59151. *
  59152. * http://www.apache.org/licenses/LICENSE-2.0
  59153. *
  59154. * Unless required by applicable law or agreed to in writing,
  59155. * software distributed under the License is distributed on an
  59156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59157. * KIND, either express or implied. See the License for the
  59158. * specific language governing permissions and limitations
  59159. * under the License.
  59160. */
  59161. // -------------
  59162. // Preprocessor
  59163. // -------------
  59164. registerPreprocessor(function (option) {
  59165. var graphicOption = option.graphic;
  59166. // Convert
  59167. // {graphic: [{left: 10, type: 'circle'}, ...]}
  59168. // or
  59169. // {graphic: {left: 10, type: 'circle'}}
  59170. // to
  59171. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  59172. if (isArray(graphicOption)) {
  59173. if (!graphicOption[0] || !graphicOption[0].elements) {
  59174. option.graphic = [{elements: graphicOption}];
  59175. }
  59176. else {
  59177. // Only one graphic instance can be instantiated. (We dont
  59178. // want that too many views are created in echarts._viewMap)
  59179. option.graphic = [option.graphic[0]];
  59180. }
  59181. }
  59182. else if (graphicOption && !graphicOption.elements) {
  59183. option.graphic = [{elements: [graphicOption]}];
  59184. }
  59185. });
  59186. // ------
  59187. // Model
  59188. // ------
  59189. var GraphicModel = extendComponentModel({
  59190. type: 'graphic',
  59191. defaultOption: {
  59192. // Extra properties for each elements:
  59193. //
  59194. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  59195. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  59196. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  59197. // This mechanism is useful when you want to position a group/element
  59198. // against the right side or the center of this container.
  59199. //
  59200. // width/height: (can only be pixel value, default 0)
  59201. // Only be used to specify contianer(group) size, if needed. And
  59202. // can not be percentage value (like '33%'). See the reason in the
  59203. // layout algorithm below.
  59204. //
  59205. // bounding: (enum: 'all' (default) | 'raw')
  59206. // Specify how to calculate boundingRect when locating.
  59207. // 'all': Get uioned and transformed boundingRect
  59208. // from both itself and its descendants.
  59209. // This mode simplies confining a group of elements in the bounding
  59210. // of their ancester container (e.g., using 'right: 0').
  59211. // 'raw': Only use the boundingRect of itself and before transformed.
  59212. // This mode is similar to css behavior, which is useful when you
  59213. // want an element to be able to overflow its container. (Consider
  59214. // a rotated circle needs to be located in a corner.)
  59215. // Note: elements is always behind its ancestors in this elements array.
  59216. elements: [],
  59217. parentId: null
  59218. },
  59219. /**
  59220. * Save el options for the sake of the performance (only update modified graphics).
  59221. * The order is the same as those in option. (ancesters -> descendants)
  59222. *
  59223. * @private
  59224. * @type {Array.<Object>}
  59225. */
  59226. _elOptionsToUpdate: null,
  59227. /**
  59228. * @override
  59229. */
  59230. mergeOption: function (option) {
  59231. // Prevent default merge to elements
  59232. var elements = this.option.elements;
  59233. this.option.elements = null;
  59234. GraphicModel.superApply(this, 'mergeOption', arguments);
  59235. this.option.elements = elements;
  59236. },
  59237. /**
  59238. * @override
  59239. */
  59240. optionUpdated: function (newOption, isInit) {
  59241. var thisOption = this.option;
  59242. var newList = (isInit ? thisOption : newOption).elements;
  59243. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  59244. var flattenedList = [];
  59245. this._flatten(newList, flattenedList);
  59246. var mappingResult = mappingToExists(existList, flattenedList);
  59247. makeIdAndName(mappingResult);
  59248. // Clear elOptionsToUpdate
  59249. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  59250. each$1(mappingResult, function (resultItem, index) {
  59251. var newElOption = resultItem.option;
  59252. if (__DEV__) {
  59253. assert$1(
  59254. isObject$1(newElOption) || resultItem.exist,
  59255. 'Empty graphic option definition'
  59256. );
  59257. }
  59258. if (!newElOption) {
  59259. return;
  59260. }
  59261. elOptionsToUpdate.push(newElOption);
  59262. setKeyInfoToNewElOption(resultItem, newElOption);
  59263. mergeNewElOptionToExist(existList, index, newElOption);
  59264. setLayoutInfoToExist(existList[index], newElOption);
  59265. }, this);
  59266. // Clean
  59267. for (var i = existList.length - 1; i >= 0; i--) {
  59268. if (existList[i] == null) {
  59269. existList.splice(i, 1);
  59270. }
  59271. else {
  59272. // $action should be volatile, otherwise option gotten from
  59273. // `getOption` will contain unexpected $action.
  59274. delete existList[i].$action;
  59275. }
  59276. }
  59277. },
  59278. /**
  59279. * Convert
  59280. * [{
  59281. * type: 'group',
  59282. * id: 'xx',
  59283. * children: [{type: 'circle'}, {type: 'polygon'}]
  59284. * }]
  59285. * to
  59286. * [
  59287. * {type: 'group', id: 'xx'},
  59288. * {type: 'circle', parentId: 'xx'},
  59289. * {type: 'polygon', parentId: 'xx'}
  59290. * ]
  59291. *
  59292. * @private
  59293. * @param {Array.<Object>} optionList option list
  59294. * @param {Array.<Object>} result result of flatten
  59295. * @param {Object} parentOption parent option
  59296. */
  59297. _flatten: function (optionList, result, parentOption) {
  59298. each$1(optionList, function (option) {
  59299. if (!option) {
  59300. return;
  59301. }
  59302. if (parentOption) {
  59303. option.parentOption = parentOption;
  59304. }
  59305. result.push(option);
  59306. var children = option.children;
  59307. if (option.type === 'group' && children) {
  59308. this._flatten(children, result, option);
  59309. }
  59310. // Deleting for JSON output, and for not affecting group creation.
  59311. delete option.children;
  59312. }, this);
  59313. },
  59314. // FIXME
  59315. // Pass to view using payload? setOption has a payload?
  59316. useElOptionsToUpdate: function () {
  59317. var els = this._elOptionsToUpdate;
  59318. // Clear to avoid render duplicately when zooming.
  59319. this._elOptionsToUpdate = null;
  59320. return els;
  59321. }
  59322. });
  59323. // -----
  59324. // View
  59325. // -----
  59326. extendComponentView({
  59327. type: 'graphic',
  59328. /**
  59329. * @override
  59330. */
  59331. init: function (ecModel, api) {
  59332. /**
  59333. * @private
  59334. * @type {module:zrender/core/util.HashMap}
  59335. */
  59336. this._elMap = createHashMap();
  59337. /**
  59338. * @private
  59339. * @type {module:echarts/graphic/GraphicModel}
  59340. */
  59341. this._lastGraphicModel;
  59342. },
  59343. /**
  59344. * @override
  59345. */
  59346. render: function (graphicModel, ecModel, api) {
  59347. // Having leveraged between use cases and algorithm complexity, a very
  59348. // simple layout mechanism is used:
  59349. // The size(width/height) can be determined by itself or its parent (not
  59350. // implemented yet), but can not by its children. (Top-down travel)
  59351. // The location(x/y) can be determined by the bounding rect of itself
  59352. // (can including its descendants or not) and the size of its parent.
  59353. // (Bottom-up travel)
  59354. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  59355. // view will be reused.
  59356. if (graphicModel !== this._lastGraphicModel) {
  59357. this._clear();
  59358. }
  59359. this._lastGraphicModel = graphicModel;
  59360. this._updateElements(graphicModel, api);
  59361. this._relocate(graphicModel, api);
  59362. },
  59363. /**
  59364. * Update graphic elements.
  59365. *
  59366. * @private
  59367. * @param {Object} graphicModel graphic model
  59368. * @param {module:echarts/ExtensionAPI} api extension API
  59369. */
  59370. _updateElements: function (graphicModel, api) {
  59371. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  59372. if (!elOptionsToUpdate) {
  59373. return;
  59374. }
  59375. var elMap = this._elMap;
  59376. var rootGroup = this.group;
  59377. // Top-down tranverse to assign graphic settings to each elements.
  59378. each$1(elOptionsToUpdate, function (elOption) {
  59379. var $action = elOption.$action;
  59380. var id = elOption.id;
  59381. var existEl = elMap.get(id);
  59382. var parentId = elOption.parentId;
  59383. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  59384. if (elOption.type === 'text') {
  59385. var elOptionStyle = elOption.style;
  59386. // In top/bottom mode, textVerticalAlign should not be used, which cause
  59387. // inaccurately locating.
  59388. if (elOption.hv && elOption.hv[1]) {
  59389. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  59390. }
  59391. // Compatible with previous setting: both support fill and textFill,
  59392. // stroke and textStroke.
  59393. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (
  59394. elOptionStyle.textFill = elOptionStyle.fill
  59395. );
  59396. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (
  59397. elOptionStyle.textStroke = elOptionStyle.stroke
  59398. );
  59399. }
  59400. // Remove unnecessary props to avoid potential problems.
  59401. var elOptionCleaned = getCleanedElOption(elOption);
  59402. // For simple, do not support parent change, otherwise reorder is needed.
  59403. if (__DEV__) {
  59404. existEl && assert$1(
  59405. targetElParent === existEl.parent,
  59406. 'Changing parent is not supported.'
  59407. );
  59408. }
  59409. if (!$action || $action === 'merge') {
  59410. existEl
  59411. ? existEl.attr(elOptionCleaned)
  59412. : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  59413. }
  59414. else if ($action === 'replace') {
  59415. removeEl(existEl, elMap);
  59416. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  59417. }
  59418. else if ($action === 'remove') {
  59419. removeEl(existEl, elMap);
  59420. }
  59421. var el = elMap.get(id);
  59422. if (el) {
  59423. el.__ecGraphicWidth = elOption.width;
  59424. el.__ecGraphicHeight = elOption.height;
  59425. }
  59426. });
  59427. },
  59428. /**
  59429. * Locate graphic elements.
  59430. *
  59431. * @private
  59432. * @param {Object} graphicModel graphic model
  59433. * @param {module:echarts/ExtensionAPI} api extension API
  59434. */
  59435. _relocate: function (graphicModel, api) {
  59436. var elOptions = graphicModel.option.elements;
  59437. var rootGroup = this.group;
  59438. var elMap = this._elMap;
  59439. // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  59440. for (var i = elOptions.length - 1; i >= 0; i--) {
  59441. var elOption = elOptions[i];
  59442. var el = elMap.get(elOption.id);
  59443. if (!el) {
  59444. continue;
  59445. }
  59446. var parentEl = el.parent;
  59447. var containerInfo = parentEl === rootGroup
  59448. ? {
  59449. width: api.getWidth(),
  59450. height: api.getHeight()
  59451. }
  59452. : { // Like 'position:absolut' in css, default 0.
  59453. width: parentEl.__ecGraphicWidth || 0,
  59454. height: parentEl.__ecGraphicHeight || 0
  59455. };
  59456. positionElement(
  59457. el, elOption, containerInfo, null,
  59458. {hv: elOption.hv, boundingMode: elOption.bounding}
  59459. );
  59460. }
  59461. },
  59462. /**
  59463. * Clear all elements.
  59464. *
  59465. * @private
  59466. */
  59467. _clear: function () {
  59468. var elMap = this._elMap;
  59469. elMap.each(function (el) {
  59470. removeEl(el, elMap);
  59471. });
  59472. this._elMap = createHashMap();
  59473. },
  59474. /**
  59475. * @override
  59476. */
  59477. dispose: function () {
  59478. this._clear();
  59479. }
  59480. });
  59481. function createEl$1(id, targetElParent, elOption, elMap) {
  59482. var graphicType = elOption.type;
  59483. if (__DEV__) {
  59484. assert$1(graphicType, 'graphic type MUST be set');
  59485. }
  59486. var Clz = graphic[graphicType.charAt(0).toUpperCase() + graphicType.slice(1)];
  59487. if (__DEV__) {
  59488. assert$1(Clz, 'graphic type can not be found');
  59489. }
  59490. var el = new Clz(elOption);
  59491. targetElParent.add(el);
  59492. elMap.set(id, el);
  59493. el.__ecGraphicId = id;
  59494. }
  59495. function removeEl(existEl, elMap) {
  59496. var existElParent = existEl && existEl.parent;
  59497. if (existElParent) {
  59498. existEl.type === 'group' && existEl.traverse(function (el) {
  59499. removeEl(el, elMap);
  59500. });
  59501. elMap.removeKey(existEl.__ecGraphicId);
  59502. existElParent.remove(existEl);
  59503. }
  59504. }
  59505. // Remove unnecessary props to avoid potential problems.
  59506. function getCleanedElOption(elOption) {
  59507. elOption = extend({}, elOption);
  59508. each$1(
  59509. ['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS),
  59510. function (name) {
  59511. delete elOption[name];
  59512. }
  59513. );
  59514. return elOption;
  59515. }
  59516. function isSetLoc(obj, props) {
  59517. var isSet;
  59518. each$1(props, function (prop) {
  59519. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  59520. });
  59521. return isSet;
  59522. }
  59523. function setKeyInfoToNewElOption(resultItem, newElOption) {
  59524. var existElOption = resultItem.exist;
  59525. // Set id and type after id assigned.
  59526. newElOption.id = resultItem.keyInfo.id;
  59527. !newElOption.type && existElOption && (newElOption.type = existElOption.type);
  59528. // Set parent id if not specified
  59529. if (newElOption.parentId == null) {
  59530. var newElParentOption = newElOption.parentOption;
  59531. if (newElParentOption) {
  59532. newElOption.parentId = newElParentOption.id;
  59533. }
  59534. else if (existElOption) {
  59535. newElOption.parentId = existElOption.parentId;
  59536. }
  59537. }
  59538. // Clear
  59539. newElOption.parentOption = null;
  59540. }
  59541. function mergeNewElOptionToExist(existList, index, newElOption) {
  59542. // Update existing options, for `getOption` feature.
  59543. var newElOptCopy = extend({}, newElOption);
  59544. var existElOption = existList[index];
  59545. var $action = newElOption.$action || 'merge';
  59546. if ($action === 'merge') {
  59547. if (existElOption) {
  59548. if (__DEV__) {
  59549. var newType = newElOption.type;
  59550. assert$1(
  59551. !newType || existElOption.type === newType,
  59552. 'Please set $action: "replace" to change `type`'
  59553. );
  59554. }
  59555. // We can ensure that newElOptCopy and existElOption are not
  59556. // the same object, so `merge` will not change newElOptCopy.
  59557. merge(existElOption, newElOptCopy, true);
  59558. // Rigid body, use ignoreSize.
  59559. mergeLayoutParam(existElOption, newElOptCopy, {ignoreSize: true});
  59560. // Will be used in render.
  59561. copyLayoutParams(newElOption, existElOption);
  59562. }
  59563. else {
  59564. existList[index] = newElOptCopy;
  59565. }
  59566. }
  59567. else if ($action === 'replace') {
  59568. existList[index] = newElOptCopy;
  59569. }
  59570. else if ($action === 'remove') {
  59571. // null will be cleaned later.
  59572. existElOption && (existList[index] = null);
  59573. }
  59574. }
  59575. function setLayoutInfoToExist(existItem, newElOption) {
  59576. if (!existItem) {
  59577. return;
  59578. }
  59579. existItem.hv = newElOption.hv = [
  59580. // Rigid body, dont care `width`.
  59581. isSetLoc(newElOption, ['left', 'right']),
  59582. // Rigid body, dont care `height`.
  59583. isSetLoc(newElOption, ['top', 'bottom'])
  59584. ];
  59585. // Give default group size. Otherwise layout error may occur.
  59586. if (existItem.type === 'group') {
  59587. existItem.width == null && (existItem.width = newElOption.width = 0);
  59588. existItem.height == null && (existItem.height = newElOption.height = 0);
  59589. }
  59590. }
  59591. /*
  59592. * Licensed to the Apache Software Foundation (ASF) under one
  59593. * or more contributor license agreements. See the NOTICE file
  59594. * distributed with this work for additional information
  59595. * regarding copyright ownership. The ASF licenses this file
  59596. * to you under the Apache License, Version 2.0 (the
  59597. * "License"); you may not use this file except in compliance
  59598. * with the License. You may obtain a copy of the License at
  59599. *
  59600. * http://www.apache.org/licenses/LICENSE-2.0
  59601. *
  59602. * Unless required by applicable law or agreed to in writing,
  59603. * software distributed under the License is distributed on an
  59604. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59605. * KIND, either express or implied. See the License for the
  59606. * specific language governing permissions and limitations
  59607. * under the License.
  59608. */
  59609. /*
  59610. * Licensed to the Apache Software Foundation (ASF) under one
  59611. * or more contributor license agreements. See the NOTICE file
  59612. * distributed with this work for additional information
  59613. * regarding copyright ownership. The ASF licenses this file
  59614. * to you under the Apache License, Version 2.0 (the
  59615. * "License"); you may not use this file except in compliance
  59616. * with the License. You may obtain a copy of the License at
  59617. *
  59618. * http://www.apache.org/licenses/LICENSE-2.0
  59619. *
  59620. * Unless required by applicable law or agreed to in writing,
  59621. * software distributed under the License is distributed on an
  59622. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59623. * KIND, either express or implied. See the License for the
  59624. * specific language governing permissions and limitations
  59625. * under the License.
  59626. */
  59627. var LegendModel = extendComponentModel({
  59628. type: 'legend.plain',
  59629. dependencies: ['series'],
  59630. layoutMode: {
  59631. type: 'box',
  59632. // legend.width/height are maxWidth/maxHeight actually,
  59633. // whereas realy width/height is calculated by its content.
  59634. // (Setting {left: 10, right: 10} does not make sense).
  59635. // So consider the case:
  59636. // `setOption({legend: {left: 10});`
  59637. // then `setOption({legend: {right: 10});`
  59638. // The previous `left` should be cleared by setting `ignoreSize`.
  59639. ignoreSize: true
  59640. },
  59641. init: function (option, parentModel, ecModel) {
  59642. this.mergeDefaultAndTheme(option, ecModel);
  59643. option.selected = option.selected || {};
  59644. },
  59645. mergeOption: function (option) {
  59646. LegendModel.superCall(this, 'mergeOption', option);
  59647. },
  59648. optionUpdated: function () {
  59649. this._updateData(this.ecModel);
  59650. var legendData = this._data;
  59651. // If selectedMode is single, try to select one
  59652. if (legendData[0] && this.get('selectedMode') === 'single') {
  59653. var hasSelected = false;
  59654. // If has any selected in option.selected
  59655. for (var i = 0; i < legendData.length; i++) {
  59656. var name = legendData[i].get('name');
  59657. if (this.isSelected(name)) {
  59658. // Force to unselect others
  59659. this.select(name);
  59660. hasSelected = true;
  59661. break;
  59662. }
  59663. }
  59664. // Try select the first if selectedMode is single
  59665. !hasSelected && this.select(legendData[0].get('name'));
  59666. }
  59667. },
  59668. _updateData: function (ecModel) {
  59669. var potentialData = [];
  59670. var availableNames = [];
  59671. ecModel.eachRawSeries(function (seriesModel) {
  59672. var seriesName = seriesModel.name;
  59673. availableNames.push(seriesName);
  59674. var isPotential;
  59675. if (seriesModel.legendDataProvider) {
  59676. var data = seriesModel.legendDataProvider();
  59677. var names = data.mapArray(data.getName);
  59678. if (!ecModel.isSeriesFiltered(seriesModel)) {
  59679. availableNames = availableNames.concat(names);
  59680. }
  59681. if (names.length) {
  59682. potentialData = potentialData.concat(names);
  59683. }
  59684. else {
  59685. isPotential = true;
  59686. }
  59687. }
  59688. else {
  59689. isPotential = true;
  59690. }
  59691. if (isPotential && isNameSpecified(seriesModel)) {
  59692. potentialData.push(seriesModel.name);
  59693. }
  59694. });
  59695. /**
  59696. * @type {Array.<string>}
  59697. * @private
  59698. */
  59699. this._availableNames = availableNames;
  59700. // If legend.data not specified in option, use availableNames as data,
  59701. // which is convinient for user preparing option.
  59702. var rawData = this.get('data') || potentialData;
  59703. var legendData = map(rawData, function (dataItem) {
  59704. // Can be string or number
  59705. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  59706. dataItem = {
  59707. name: dataItem
  59708. };
  59709. }
  59710. return new Model(dataItem, this, this.ecModel);
  59711. }, this);
  59712. /**
  59713. * @type {Array.<module:echarts/model/Model>}
  59714. * @private
  59715. */
  59716. this._data = legendData;
  59717. },
  59718. /**
  59719. * @return {Array.<module:echarts/model/Model>}
  59720. */
  59721. getData: function () {
  59722. return this._data;
  59723. },
  59724. /**
  59725. * @param {string} name
  59726. */
  59727. select: function (name) {
  59728. var selected = this.option.selected;
  59729. var selectedMode = this.get('selectedMode');
  59730. if (selectedMode === 'single') {
  59731. var data = this._data;
  59732. each$1(data, function (dataItem) {
  59733. selected[dataItem.get('name')] = false;
  59734. });
  59735. }
  59736. selected[name] = true;
  59737. },
  59738. /**
  59739. * @param {string} name
  59740. */
  59741. unSelect: function (name) {
  59742. if (this.get('selectedMode') !== 'single') {
  59743. this.option.selected[name] = false;
  59744. }
  59745. },
  59746. /**
  59747. * @param {string} name
  59748. */
  59749. toggleSelected: function (name) {
  59750. var selected = this.option.selected;
  59751. // Default is true
  59752. if (!selected.hasOwnProperty(name)) {
  59753. selected[name] = true;
  59754. }
  59755. this[selected[name] ? 'unSelect' : 'select'](name);
  59756. },
  59757. /**
  59758. * @param {string} name
  59759. */
  59760. isSelected: function (name) {
  59761. var selected = this.option.selected;
  59762. return !(selected.hasOwnProperty(name) && !selected[name])
  59763. && indexOf(this._availableNames, name) >= 0;
  59764. },
  59765. defaultOption: {
  59766. // 一级层叠
  59767. zlevel: 0,
  59768. // 二级层叠
  59769. z: 4,
  59770. show: true,
  59771. // 布局方式,默认为水平布局,可选为:
  59772. // 'horizontal' | 'vertical'
  59773. orient: 'horizontal',
  59774. left: 'center',
  59775. // right: 'center',
  59776. top: 40,
  59777. // bottom: null,
  59778. // 水平对齐
  59779. // 'auto' | 'left' | 'right'
  59780. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  59781. align: 'auto',
  59782. backgroundColor: 'rgba(0,0,0,0)',
  59783. // 图例边框颜色
  59784. borderColor: '#ccc',
  59785. borderRadius: 0,
  59786. // 图例边框线宽,单位px,默认为0(无边框)
  59787. borderWidth: 0,
  59788. // 图例内边距,单位px,默认各方向内边距为5,
  59789. // 接受数组分别设定上右下左边距,同css
  59790. padding: 5,
  59791. // 各个item之间的间隔,单位px,默认为10,
  59792. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  59793. itemGap: 10,
  59794. // 图例图形宽度
  59795. itemWidth: 25,
  59796. // 图例图形高度
  59797. itemHeight: 14,
  59798. // 图例关闭时候的颜色
  59799. inactiveColor: '#ccc',
  59800. textStyle: {
  59801. // 图例文字颜色
  59802. color: '#333'
  59803. },
  59804. // formatter: '',
  59805. // 选择模式,默认开启图例开关
  59806. selectedMode: true,
  59807. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  59808. // selected: null,
  59809. // 图例内容(详见legend.data,数组中每一项代表一个item
  59810. // data: [],
  59811. // Tooltip 相关配置
  59812. tooltip: {
  59813. show: false
  59814. }
  59815. }
  59816. });
  59817. /*
  59818. * Licensed to the Apache Software Foundation (ASF) under one
  59819. * or more contributor license agreements. See the NOTICE file
  59820. * distributed with this work for additional information
  59821. * regarding copyright ownership. The ASF licenses this file
  59822. * to you under the Apache License, Version 2.0 (the
  59823. * "License"); you may not use this file except in compliance
  59824. * with the License. You may obtain a copy of the License at
  59825. *
  59826. * http://www.apache.org/licenses/LICENSE-2.0
  59827. *
  59828. * Unless required by applicable law or agreed to in writing,
  59829. * software distributed under the License is distributed on an
  59830. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59831. * KIND, either express or implied. See the License for the
  59832. * specific language governing permissions and limitations
  59833. * under the License.
  59834. */
  59835. function legendSelectActionHandler(methodName, payload, ecModel) {
  59836. var selectedMap = {};
  59837. var isToggleSelect = methodName === 'toggleSelected';
  59838. var isSelected;
  59839. // Update all legend components
  59840. ecModel.eachComponent('legend', function (legendModel) {
  59841. if (isToggleSelect && isSelected != null) {
  59842. // Force other legend has same selected status
  59843. // Or the first is toggled to true and other are toggled to false
  59844. // In the case one legend has some item unSelected in option. And if other legend
  59845. // doesn't has the item, they will assume it is selected.
  59846. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  59847. }
  59848. else {
  59849. legendModel[methodName](payload.name);
  59850. isSelected = legendModel.isSelected(payload.name);
  59851. }
  59852. var legendData = legendModel.getData();
  59853. each$1(legendData, function (model) {
  59854. var name = model.get('name');
  59855. // Wrap element
  59856. if (name === '\n' || name === '') {
  59857. return;
  59858. }
  59859. var isItemSelected = legendModel.isSelected(name);
  59860. if (selectedMap.hasOwnProperty(name)) {
  59861. // Unselected if any legend is unselected
  59862. selectedMap[name] = selectedMap[name] && isItemSelected;
  59863. }
  59864. else {
  59865. selectedMap[name] = isItemSelected;
  59866. }
  59867. });
  59868. });
  59869. // Return the event explicitly
  59870. return {
  59871. name: payload.name,
  59872. selected: selectedMap
  59873. };
  59874. }
  59875. /**
  59876. * @event legendToggleSelect
  59877. * @type {Object}
  59878. * @property {string} type 'legendToggleSelect'
  59879. * @property {string} [from]
  59880. * @property {string} name Series name or data item name
  59881. */
  59882. registerAction(
  59883. 'legendToggleSelect', 'legendselectchanged',
  59884. curry(legendSelectActionHandler, 'toggleSelected')
  59885. );
  59886. /**
  59887. * @event legendSelect
  59888. * @type {Object}
  59889. * @property {string} type 'legendSelect'
  59890. * @property {string} name Series name or data item name
  59891. */
  59892. registerAction(
  59893. 'legendSelect', 'legendselected',
  59894. curry(legendSelectActionHandler, 'select')
  59895. );
  59896. /**
  59897. * @event legendUnSelect
  59898. * @type {Object}
  59899. * @property {string} type 'legendUnSelect'
  59900. * @property {string} name Series name or data item name
  59901. */
  59902. registerAction(
  59903. 'legendUnSelect', 'legendunselected',
  59904. curry(legendSelectActionHandler, 'unSelect')
  59905. );
  59906. /*
  59907. * Licensed to the Apache Software Foundation (ASF) under one
  59908. * or more contributor license agreements. See the NOTICE file
  59909. * distributed with this work for additional information
  59910. * regarding copyright ownership. The ASF licenses this file
  59911. * to you under the Apache License, Version 2.0 (the
  59912. * "License"); you may not use this file except in compliance
  59913. * with the License. You may obtain a copy of the License at
  59914. *
  59915. * http://www.apache.org/licenses/LICENSE-2.0
  59916. *
  59917. * Unless required by applicable law or agreed to in writing,
  59918. * software distributed under the License is distributed on an
  59919. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59920. * KIND, either express or implied. See the License for the
  59921. * specific language governing permissions and limitations
  59922. * under the License.
  59923. */
  59924. /**
  59925. * Layout list like component.
  59926. * It will box layout each items in group of component and then position the whole group in the viewport
  59927. * @param {module:zrender/group/Group} group
  59928. * @param {module:echarts/model/Component} componentModel
  59929. * @param {module:echarts/ExtensionAPI}
  59930. */
  59931. function layout$3(group, componentModel, api) {
  59932. var boxLayoutParams = componentModel.getBoxLayoutParams();
  59933. var padding = componentModel.get('padding');
  59934. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  59935. var rect = getLayoutRect(
  59936. boxLayoutParams,
  59937. viewportSize,
  59938. padding
  59939. );
  59940. box(
  59941. componentModel.get('orient'),
  59942. group,
  59943. componentModel.get('itemGap'),
  59944. rect.width,
  59945. rect.height
  59946. );
  59947. positionElement(
  59948. group,
  59949. boxLayoutParams,
  59950. viewportSize,
  59951. padding
  59952. );
  59953. }
  59954. function makeBackground(rect, componentModel) {
  59955. var padding = normalizeCssArray$1(
  59956. componentModel.get('padding')
  59957. );
  59958. var style = componentModel.getItemStyle(['color', 'opacity']);
  59959. style.fill = componentModel.get('backgroundColor');
  59960. var rect = new Rect({
  59961. shape: {
  59962. x: rect.x - padding[3],
  59963. y: rect.y - padding[0],
  59964. width: rect.width + padding[1] + padding[3],
  59965. height: rect.height + padding[0] + padding[2],
  59966. r: componentModel.get('borderRadius')
  59967. },
  59968. style: style,
  59969. silent: true,
  59970. z2: -1
  59971. });
  59972. // FIXME
  59973. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  59974. // and background rect when setting like `left: 0`, `top: 0`.
  59975. // graphic.subPixelOptimizeRect(rect);
  59976. return rect;
  59977. }
  59978. /*
  59979. * Licensed to the Apache Software Foundation (ASF) under one
  59980. * or more contributor license agreements. See the NOTICE file
  59981. * distributed with this work for additional information
  59982. * regarding copyright ownership. The ASF licenses this file
  59983. * to you under the Apache License, Version 2.0 (the
  59984. * "License"); you may not use this file except in compliance
  59985. * with the License. You may obtain a copy of the License at
  59986. *
  59987. * http://www.apache.org/licenses/LICENSE-2.0
  59988. *
  59989. * Unless required by applicable law or agreed to in writing,
  59990. * software distributed under the License is distributed on an
  59991. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59992. * KIND, either express or implied. See the License for the
  59993. * specific language governing permissions and limitations
  59994. * under the License.
  59995. */
  59996. var curry$4 = curry;
  59997. var each$16 = each$1;
  59998. var Group$3 = Group;
  59999. var LegendView = extendComponentView({
  60000. type: 'legend.plain',
  60001. newlineDisabled: false,
  60002. /**
  60003. * @override
  60004. */
  60005. init: function () {
  60006. /**
  60007. * @private
  60008. * @type {module:zrender/container/Group}
  60009. */
  60010. this.group.add(this._contentGroup = new Group$3());
  60011. /**
  60012. * @private
  60013. * @type {module:zrender/Element}
  60014. */
  60015. this._backgroundEl;
  60016. },
  60017. /**
  60018. * @protected
  60019. */
  60020. getContentGroup: function () {
  60021. return this._contentGroup;
  60022. },
  60023. /**
  60024. * @override
  60025. */
  60026. render: function (legendModel, ecModel, api) {
  60027. this.resetInner();
  60028. if (!legendModel.get('show', true)) {
  60029. return;
  60030. }
  60031. var itemAlign = legendModel.get('align');
  60032. if (!itemAlign || itemAlign === 'auto') {
  60033. itemAlign = (
  60034. legendModel.get('left') === 'right'
  60035. && legendModel.get('orient') === 'vertical'
  60036. ) ? 'right' : 'left';
  60037. }
  60038. this.renderInner(itemAlign, legendModel, ecModel, api);
  60039. // Perform layout.
  60040. var positionInfo = legendModel.getBoxLayoutParams();
  60041. var viewportSize = {width: api.getWidth(), height: api.getHeight()};
  60042. var padding = legendModel.get('padding');
  60043. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  60044. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize);
  60045. // Place mainGroup, based on the calculated `mainRect`.
  60046. var layoutRect = getLayoutRect(
  60047. defaults({width: mainRect.width, height: mainRect.height}, positionInfo),
  60048. viewportSize,
  60049. padding
  60050. );
  60051. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]);
  60052. // Render background after group is layout.
  60053. this.group.add(
  60054. this._backgroundEl = makeBackground(mainRect, legendModel)
  60055. );
  60056. },
  60057. /**
  60058. * @protected
  60059. */
  60060. resetInner: function () {
  60061. this.getContentGroup().removeAll();
  60062. this._backgroundEl && this.group.remove(this._backgroundEl);
  60063. },
  60064. /**
  60065. * @protected
  60066. */
  60067. renderInner: function (itemAlign, legendModel, ecModel, api) {
  60068. var contentGroup = this.getContentGroup();
  60069. var legendDrawnMap = createHashMap();
  60070. var selectMode = legendModel.get('selectedMode');
  60071. var excludeSeriesId = [];
  60072. ecModel.eachRawSeries(function (seriesModel) {
  60073. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  60074. });
  60075. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  60076. var name = itemModel.get('name');
  60077. // Use empty string or \n as a newline string
  60078. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  60079. contentGroup.add(new Group$3({
  60080. newline: true
  60081. }));
  60082. return;
  60083. }
  60084. // Representitive series.
  60085. var seriesModel = ecModel.getSeriesByName(name)[0];
  60086. if (legendDrawnMap.get(name)) {
  60087. // Have been drawed
  60088. return;
  60089. }
  60090. // Series legend
  60091. if (seriesModel) {
  60092. var data = seriesModel.getData();
  60093. var color = data.getVisual('color');
  60094. // If color is a callback function
  60095. if (typeof color === 'function') {
  60096. // Use the first data
  60097. color = color(seriesModel.getDataParams(0));
  60098. }
  60099. // Using rect symbol defaultly
  60100. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  60101. var symbolType = data.getVisual('symbol');
  60102. var itemGroup = this._createItem(
  60103. name, dataIndex, itemModel, legendModel,
  60104. legendSymbolType, symbolType,
  60105. itemAlign, color,
  60106. selectMode
  60107. );
  60108. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  60109. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, null, api, excludeSeriesId))
  60110. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, null, api, excludeSeriesId));
  60111. legendDrawnMap.set(name, true);
  60112. }
  60113. else {
  60114. // Data legend of pie, funnel
  60115. ecModel.eachRawSeries(function (seriesModel) {
  60116. // In case multiple series has same data name
  60117. if (legendDrawnMap.get(name)) {
  60118. return;
  60119. }
  60120. if (seriesModel.legendDataProvider) {
  60121. var data = seriesModel.legendDataProvider();
  60122. var idx = data.indexOfName(name);
  60123. if (idx < 0) {
  60124. return;
  60125. }
  60126. var color = data.getItemVisual(idx, 'color');
  60127. var legendSymbolType = 'roundRect';
  60128. var itemGroup = this._createItem(
  60129. name, dataIndex, itemModel, legendModel,
  60130. legendSymbolType, null,
  60131. itemAlign, color,
  60132. selectMode
  60133. );
  60134. // FIXME: consider different series has items with the same name.
  60135. itemGroup.on('click', curry$4(dispatchSelectAction, name, api))
  60136. // FIXME Should not specify the series name
  60137. .on('mouseover', curry$4(dispatchHighlightAction, seriesModel, name, api, excludeSeriesId))
  60138. .on('mouseout', curry$4(dispatchDownplayAction, seriesModel, name, api, excludeSeriesId));
  60139. legendDrawnMap.set(name, true);
  60140. }
  60141. }, this);
  60142. }
  60143. if (__DEV__) {
  60144. if (!legendDrawnMap.get(name)) {
  60145. console.warn(name + ' series not exists. Legend data should be same with series name or data name.');
  60146. }
  60147. }
  60148. }, this);
  60149. },
  60150. _createItem: function (
  60151. name, dataIndex, itemModel, legendModel,
  60152. legendSymbolType, symbolType,
  60153. itemAlign, color, selectMode
  60154. ) {
  60155. var itemWidth = legendModel.get('itemWidth');
  60156. var itemHeight = legendModel.get('itemHeight');
  60157. var inactiveColor = legendModel.get('inactiveColor');
  60158. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  60159. var isSelected = legendModel.isSelected(name);
  60160. var itemGroup = new Group$3();
  60161. var textStyleModel = itemModel.getModel('textStyle');
  60162. var itemIcon = itemModel.get('icon');
  60163. var tooltipModel = itemModel.getModel('tooltip');
  60164. var legendGlobalTooltipModel = tooltipModel.parentModel;
  60165. // Use user given icon first
  60166. legendSymbolType = itemIcon || legendSymbolType;
  60167. itemGroup.add(createSymbol(
  60168. legendSymbolType,
  60169. 0,
  60170. 0,
  60171. itemWidth,
  60172. itemHeight,
  60173. isSelected ? color : inactiveColor,
  60174. // symbolKeepAspect default true for legend
  60175. symbolKeepAspect == null ? true : symbolKeepAspect
  60176. ));
  60177. // Compose symbols
  60178. // PENDING
  60179. if (!itemIcon && symbolType
  60180. // At least show one symbol, can't be all none
  60181. && ((symbolType !== legendSymbolType) || symbolType == 'none')
  60182. ) {
  60183. var size = itemHeight * 0.8;
  60184. if (symbolType === 'none') {
  60185. symbolType = 'circle';
  60186. }
  60187. // Put symbol in the center
  60188. itemGroup.add(createSymbol(
  60189. symbolType,
  60190. (itemWidth - size) / 2,
  60191. (itemHeight - size) / 2,
  60192. size,
  60193. size,
  60194. isSelected ? color : inactiveColor,
  60195. // symbolKeepAspect default true for legend
  60196. symbolKeepAspect == null ? true : symbolKeepAspect
  60197. ));
  60198. }
  60199. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  60200. var textAlign = itemAlign;
  60201. var formatter = legendModel.get('formatter');
  60202. var content = name;
  60203. if (typeof formatter === 'string' && formatter) {
  60204. content = formatter.replace('{name}', name != null ? name : '');
  60205. }
  60206. else if (typeof formatter === 'function') {
  60207. content = formatter(name);
  60208. }
  60209. itemGroup.add(new Text({
  60210. style: setTextStyle({}, textStyleModel, {
  60211. text: content,
  60212. x: textX,
  60213. y: itemHeight / 2,
  60214. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  60215. textAlign: textAlign,
  60216. textVerticalAlign: 'middle'
  60217. })
  60218. }));
  60219. // Add a invisible rect to increase the area of mouse hover
  60220. var hitRect = new Rect({
  60221. shape: itemGroup.getBoundingRect(),
  60222. invisible: true,
  60223. tooltip: tooltipModel.get('show') ? extend({
  60224. content: name,
  60225. // Defaul formatter
  60226. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  60227. return name;
  60228. },
  60229. formatterParams: {
  60230. componentType: 'legend',
  60231. legendIndex: legendModel.componentIndex,
  60232. name: name,
  60233. $vars: ['name']
  60234. }
  60235. }, tooltipModel.option) : null
  60236. });
  60237. itemGroup.add(hitRect);
  60238. itemGroup.eachChild(function (child) {
  60239. child.silent = true;
  60240. });
  60241. hitRect.silent = !selectMode;
  60242. this.getContentGroup().add(itemGroup);
  60243. setHoverStyle(itemGroup);
  60244. itemGroup.__legendDataIndex = dataIndex;
  60245. return itemGroup;
  60246. },
  60247. /**
  60248. * @protected
  60249. */
  60250. layoutInner: function (legendModel, itemAlign, maxSize) {
  60251. var contentGroup = this.getContentGroup();
  60252. // Place items in contentGroup.
  60253. box(
  60254. legendModel.get('orient'),
  60255. contentGroup,
  60256. legendModel.get('itemGap'),
  60257. maxSize.width,
  60258. maxSize.height
  60259. );
  60260. var contentRect = contentGroup.getBoundingRect();
  60261. contentGroup.attr('position', [-contentRect.x, -contentRect.y]);
  60262. return this.group.getBoundingRect();
  60263. }
  60264. });
  60265. function dispatchSelectAction(name, api) {
  60266. api.dispatchAction({
  60267. type: 'legendToggleSelect',
  60268. name: name
  60269. });
  60270. }
  60271. function dispatchHighlightAction(seriesModel, dataName, api, excludeSeriesId) {
  60272. // If element hover will move to a hoverLayer.
  60273. var el = api.getZr().storage.getDisplayList()[0];
  60274. if (!(el && el.useHoverLayer)) {
  60275. api.dispatchAction({
  60276. type: 'highlight',
  60277. seriesName: seriesModel.name,
  60278. name: dataName,
  60279. excludeSeriesId: excludeSeriesId
  60280. });
  60281. }
  60282. }
  60283. function dispatchDownplayAction(seriesModel, dataName, api, excludeSeriesId) {
  60284. // If element hover will move to a hoverLayer.
  60285. var el = api.getZr().storage.getDisplayList()[0];
  60286. if (!(el && el.useHoverLayer)) {
  60287. api.dispatchAction({
  60288. type: 'downplay',
  60289. seriesName: seriesModel.name,
  60290. name: dataName,
  60291. excludeSeriesId: excludeSeriesId
  60292. });
  60293. }
  60294. }
  60295. /*
  60296. * Licensed to the Apache Software Foundation (ASF) under one
  60297. * or more contributor license agreements. See the NOTICE file
  60298. * distributed with this work for additional information
  60299. * regarding copyright ownership. The ASF licenses this file
  60300. * to you under the Apache License, Version 2.0 (the
  60301. * "License"); you may not use this file except in compliance
  60302. * with the License. You may obtain a copy of the License at
  60303. *
  60304. * http://www.apache.org/licenses/LICENSE-2.0
  60305. *
  60306. * Unless required by applicable law or agreed to in writing,
  60307. * software distributed under the License is distributed on an
  60308. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60309. * KIND, either express or implied. See the License for the
  60310. * specific language governing permissions and limitations
  60311. * under the License.
  60312. */
  60313. var legendFilter = function (ecModel) {
  60314. var legendModels = ecModel.findComponents({
  60315. mainType: 'legend'
  60316. });
  60317. if (legendModels && legendModels.length) {
  60318. ecModel.filterSeries(function (series) {
  60319. // If in any legend component the status is not selected.
  60320. // Because in legend series is assumed selected when it is not in the legend data.
  60321. for (var i = 0; i < legendModels.length; i++) {
  60322. if (!legendModels[i].isSelected(series.name)) {
  60323. return false;
  60324. }
  60325. }
  60326. return true;
  60327. });
  60328. }
  60329. };
  60330. /*
  60331. * Licensed to the Apache Software Foundation (ASF) under one
  60332. * or more contributor license agreements. See the NOTICE file
  60333. * distributed with this work for additional information
  60334. * regarding copyright ownership. The ASF licenses this file
  60335. * to you under the Apache License, Version 2.0 (the
  60336. * "License"); you may not use this file except in compliance
  60337. * with the License. You may obtain a copy of the License at
  60338. *
  60339. * http://www.apache.org/licenses/LICENSE-2.0
  60340. *
  60341. * Unless required by applicable law or agreed to in writing,
  60342. * software distributed under the License is distributed on an
  60343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60344. * KIND, either express or implied. See the License for the
  60345. * specific language governing permissions and limitations
  60346. * under the License.
  60347. */
  60348. // Do not contain scrollable legend, for sake of file size.
  60349. // Series Filter
  60350. registerProcessor(legendFilter);
  60351. ComponentModel.registerSubTypeDefaulter('legend', function () {
  60352. // Default 'plain' when no type specified.
  60353. return 'plain';
  60354. });
  60355. /*
  60356. * Licensed to the Apache Software Foundation (ASF) under one
  60357. * or more contributor license agreements. See the NOTICE file
  60358. * distributed with this work for additional information
  60359. * regarding copyright ownership. The ASF licenses this file
  60360. * to you under the Apache License, Version 2.0 (the
  60361. * "License"); you may not use this file except in compliance
  60362. * with the License. You may obtain a copy of the License at
  60363. *
  60364. * http://www.apache.org/licenses/LICENSE-2.0
  60365. *
  60366. * Unless required by applicable law or agreed to in writing,
  60367. * software distributed under the License is distributed on an
  60368. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60369. * KIND, either express or implied. See the License for the
  60370. * specific language governing permissions and limitations
  60371. * under the License.
  60372. */
  60373. var ScrollableLegendModel = LegendModel.extend({
  60374. type: 'legend.scroll',
  60375. /**
  60376. * @param {number} scrollDataIndex
  60377. */
  60378. setScrollDataIndex: function (scrollDataIndex) {
  60379. this.option.scrollDataIndex = scrollDataIndex;
  60380. },
  60381. defaultOption: {
  60382. scrollDataIndex: 0,
  60383. pageButtonItemGap: 5,
  60384. pageButtonGap: null,
  60385. pageButtonPosition: 'end', // 'start' or 'end'
  60386. pageFormatter: '{current}/{total}', // If null/undefined, do not show page.
  60387. pageIcons: {
  60388. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  60389. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  60390. },
  60391. pageIconColor: '#2f4554',
  60392. pageIconInactiveColor: '#aaa',
  60393. pageIconSize: 15, // Can be [10, 3], which represents [width, height]
  60394. pageTextStyle: {
  60395. color: '#333'
  60396. },
  60397. animationDurationUpdate: 800
  60398. },
  60399. /**
  60400. * @override
  60401. */
  60402. init: function (option, parentModel, ecModel, extraOpt) {
  60403. var inputPositionParams = getLayoutParams(option);
  60404. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  60405. mergeAndNormalizeLayoutParams(this, option, inputPositionParams);
  60406. },
  60407. /**
  60408. * @override
  60409. */
  60410. mergeOption: function (option, extraOpt) {
  60411. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  60412. mergeAndNormalizeLayoutParams(this, this.option, option);
  60413. },
  60414. getOrient: function () {
  60415. return this.get('orient') === 'vertical'
  60416. ? {index: 1, name: 'vertical'}
  60417. : {index: 0, name: 'horizontal'};
  60418. }
  60419. });
  60420. // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  60421. function mergeAndNormalizeLayoutParams(legendModel, target, raw) {
  60422. var orient = legendModel.getOrient();
  60423. var ignoreSize = [1, 1];
  60424. ignoreSize[orient.index] = 0;
  60425. mergeLayoutParam(target, raw, {
  60426. type: 'box', ignoreSize: ignoreSize
  60427. });
  60428. }
  60429. /*
  60430. * Licensed to the Apache Software Foundation (ASF) under one
  60431. * or more contributor license agreements. See the NOTICE file
  60432. * distributed with this work for additional information
  60433. * regarding copyright ownership. The ASF licenses this file
  60434. * to you under the Apache License, Version 2.0 (the
  60435. * "License"); you may not use this file except in compliance
  60436. * with the License. You may obtain a copy of the License at
  60437. *
  60438. * http://www.apache.org/licenses/LICENSE-2.0
  60439. *
  60440. * Unless required by applicable law or agreed to in writing,
  60441. * software distributed under the License is distributed on an
  60442. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60443. * KIND, either express or implied. See the License for the
  60444. * specific language governing permissions and limitations
  60445. * under the License.
  60446. */
  60447. /**
  60448. * Separate legend and scrollable legend to reduce package size.
  60449. */
  60450. var Group$4 = Group;
  60451. var WH$1 = ['width', 'height'];
  60452. var XY$1 = ['x', 'y'];
  60453. var ScrollableLegendView = LegendView.extend({
  60454. type: 'legend.scroll',
  60455. newlineDisabled: true,
  60456. init: function () {
  60457. ScrollableLegendView.superCall(this, 'init');
  60458. /**
  60459. * @private
  60460. * @type {number} For `scroll`.
  60461. */
  60462. this._currentIndex = 0;
  60463. /**
  60464. * @private
  60465. * @type {module:zrender/container/Group}
  60466. */
  60467. this.group.add(this._containerGroup = new Group$4());
  60468. this._containerGroup.add(this.getContentGroup());
  60469. /**
  60470. * @private
  60471. * @type {module:zrender/container/Group}
  60472. */
  60473. this.group.add(this._controllerGroup = new Group$4());
  60474. /**
  60475. *
  60476. * @private
  60477. */
  60478. this._showController;
  60479. },
  60480. /**
  60481. * @override
  60482. */
  60483. resetInner: function () {
  60484. ScrollableLegendView.superCall(this, 'resetInner');
  60485. this._controllerGroup.removeAll();
  60486. this._containerGroup.removeClipPath();
  60487. this._containerGroup.__rectSize = null;
  60488. },
  60489. /**
  60490. * @override
  60491. */
  60492. renderInner: function (itemAlign, legendModel, ecModel, api) {
  60493. var me = this;
  60494. // Render content items.
  60495. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api);
  60496. var controllerGroup = this._controllerGroup;
  60497. var pageIconSize = legendModel.get('pageIconSize', true);
  60498. if (!isArray(pageIconSize)) {
  60499. pageIconSize = [pageIconSize, pageIconSize];
  60500. }
  60501. createPageButton('pagePrev', 0);
  60502. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  60503. controllerGroup.add(new Text({
  60504. name: 'pageText',
  60505. style: {
  60506. textFill: pageTextStyleModel.getTextColor(),
  60507. font: pageTextStyleModel.getFont(),
  60508. textVerticalAlign: 'middle',
  60509. textAlign: 'center'
  60510. },
  60511. silent: true
  60512. }));
  60513. createPageButton('pageNext', 1);
  60514. function createPageButton(name, iconIdx) {
  60515. var pageDataIndexName = name + 'DataIndex';
  60516. var icon = createIcon(
  60517. legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx],
  60518. {
  60519. // Buttons will be created in each render, so we do not need
  60520. // to worry about avoiding using legendModel kept in scope.
  60521. onclick: bind(
  60522. me._pageGo, me, pageDataIndexName, legendModel, api
  60523. )
  60524. },
  60525. {
  60526. x: -pageIconSize[0] / 2,
  60527. y: -pageIconSize[1] / 2,
  60528. width: pageIconSize[0],
  60529. height: pageIconSize[1]
  60530. }
  60531. );
  60532. icon.name = name;
  60533. controllerGroup.add(icon);
  60534. }
  60535. },
  60536. /**
  60537. * @override
  60538. */
  60539. layoutInner: function (legendModel, itemAlign, maxSize) {
  60540. var contentGroup = this.getContentGroup();
  60541. var containerGroup = this._containerGroup;
  60542. var controllerGroup = this._controllerGroup;
  60543. var orientIdx = legendModel.getOrient().index;
  60544. var wh = WH$1[orientIdx];
  60545. var hw = WH$1[1 - orientIdx];
  60546. var yx = XY$1[1 - orientIdx];
  60547. // Place items in contentGroup.
  60548. box(
  60549. legendModel.get('orient'),
  60550. contentGroup,
  60551. legendModel.get('itemGap'),
  60552. !orientIdx ? null : maxSize.width,
  60553. orientIdx ? null : maxSize.height
  60554. );
  60555. box(
  60556. // Buttons in controller are layout always horizontally.
  60557. 'horizontal',
  60558. controllerGroup,
  60559. legendModel.get('pageButtonItemGap', true)
  60560. );
  60561. var contentRect = contentGroup.getBoundingRect();
  60562. var controllerRect = controllerGroup.getBoundingRect();
  60563. var showController = this._showController = contentRect[wh] > maxSize[wh];
  60564. var contentPos = [-contentRect.x, -contentRect.y];
  60565. // Remain contentPos when scroll animation perfroming.
  60566. contentPos[orientIdx] = contentGroup.position[orientIdx];
  60567. // Layout container group based on 0.
  60568. var containerPos = [0, 0];
  60569. var controllerPos = [-controllerRect.x, -controllerRect.y];
  60570. var pageButtonGap = retrieve2(
  60571. legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)
  60572. );
  60573. // Place containerGroup and controllerGroup and contentGroup.
  60574. if (showController) {
  60575. var pageButtonPosition = legendModel.get('pageButtonPosition', true);
  60576. // controller is on the right / bottom.
  60577. if (pageButtonPosition === 'end') {
  60578. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  60579. }
  60580. // controller is on the left / top.
  60581. else {
  60582. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  60583. }
  60584. }
  60585. // Always align controller to content as 'middle'.
  60586. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  60587. contentGroup.attr('position', contentPos);
  60588. containerGroup.attr('position', containerPos);
  60589. controllerGroup.attr('position', controllerPos);
  60590. // Calculate `mainRect` and set `clipPath`.
  60591. // mainRect should not be calculated by `this.group.getBoundingRect()`
  60592. // for sake of the overflow.
  60593. var mainRect = this.group.getBoundingRect();
  60594. var mainRect = {x: 0, y: 0};
  60595. // Consider content may be overflow (should be clipped).
  60596. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  60597. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]);
  60598. // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  60599. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  60600. containerGroup.__rectSize = maxSize[wh];
  60601. if (showController) {
  60602. var clipShape = {x: 0, y: 0};
  60603. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  60604. clipShape[hw] = mainRect[hw];
  60605. containerGroup.setClipPath(new Rect({shape: clipShape}));
  60606. // Consider content may be larger than container, container rect
  60607. // can not be obtained from `containerGroup.getBoundingRect()`.
  60608. containerGroup.__rectSize = clipShape[wh];
  60609. }
  60610. else {
  60611. // Do not remove or ignore controller. Keep them set as place holders.
  60612. controllerGroup.eachChild(function (child) {
  60613. child.attr({invisible: true, silent: true});
  60614. });
  60615. }
  60616. // Content translate animation.
  60617. var pageInfo = this._getPageInfo(legendModel);
  60618. pageInfo.pageIndex != null && updateProps(
  60619. contentGroup,
  60620. {position: pageInfo.contentPosition},
  60621. // When switch from "show controller" to "not show controller", view should be
  60622. // updated immediately without animation, otherwise causes weird efffect.
  60623. showController ? legendModel : false
  60624. );
  60625. this._updatePageInfoView(legendModel, pageInfo);
  60626. return mainRect;
  60627. },
  60628. _pageGo: function (to, legendModel, api) {
  60629. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  60630. scrollDataIndex != null && api.dispatchAction({
  60631. type: 'legendScroll',
  60632. scrollDataIndex: scrollDataIndex,
  60633. legendId: legendModel.id
  60634. });
  60635. },
  60636. _updatePageInfoView: function (legendModel, pageInfo) {
  60637. var controllerGroup = this._controllerGroup;
  60638. each$1(['pagePrev', 'pageNext'], function (name) {
  60639. var canJump = pageInfo[name + 'DataIndex'] != null;
  60640. var icon = controllerGroup.childOfName(name);
  60641. if (icon) {
  60642. icon.setStyle(
  60643. 'fill',
  60644. canJump
  60645. ? legendModel.get('pageIconColor', true)
  60646. : legendModel.get('pageIconInactiveColor', true)
  60647. );
  60648. icon.cursor = canJump ? 'pointer' : 'default';
  60649. }
  60650. });
  60651. var pageText = controllerGroup.childOfName('pageText');
  60652. var pageFormatter = legendModel.get('pageFormatter');
  60653. var pageIndex = pageInfo.pageIndex;
  60654. var current = pageIndex != null ? pageIndex + 1 : 0;
  60655. var total = pageInfo.pageCount;
  60656. pageText && pageFormatter && pageText.setStyle(
  60657. 'text',
  60658. isString(pageFormatter)
  60659. ? pageFormatter.replace('{current}', current).replace('{total}', total)
  60660. : pageFormatter({current: current, total: total})
  60661. );
  60662. },
  60663. /**
  60664. * @param {module:echarts/model/Model} legendModel
  60665. * @return {Object} {
  60666. * contentPosition: Array.<number>, null when data item not found.
  60667. * pageIndex: number, null when data item not found.
  60668. * pageCount: number, always be a number, can be 0.
  60669. * pagePrevDataIndex: number, null when no next page.
  60670. * pageNextDataIndex: number, null when no previous page.
  60671. * }
  60672. */
  60673. _getPageInfo: function (legendModel) {
  60674. // Align left or top by the current dataIndex.
  60675. var currDataIndex = legendModel.get('scrollDataIndex', true);
  60676. var contentGroup = this.getContentGroup();
  60677. var contentRect = contentGroup.getBoundingRect();
  60678. var containerRectSize = this._containerGroup.__rectSize;
  60679. var orientIdx = legendModel.getOrient().index;
  60680. var wh = WH$1[orientIdx];
  60681. var hw = WH$1[1 - orientIdx];
  60682. var xy = XY$1[orientIdx];
  60683. var contentPos = contentGroup.position.slice();
  60684. var pageIndex;
  60685. var pagePrevDataIndex;
  60686. var pageNextDataIndex;
  60687. var targetItemGroup;
  60688. if (this._showController) {
  60689. contentGroup.eachChild(function (child) {
  60690. if (child.__legendDataIndex === currDataIndex) {
  60691. targetItemGroup = child;
  60692. }
  60693. });
  60694. }
  60695. else {
  60696. targetItemGroup = contentGroup.childAt(0);
  60697. }
  60698. var pageCount = containerRectSize ? Math.ceil(contentRect[wh] / containerRectSize) : 0;
  60699. if (targetItemGroup) {
  60700. var itemRect = targetItemGroup.getBoundingRect();
  60701. var itemLoc = targetItemGroup.position[orientIdx] + itemRect[xy];
  60702. contentPos[orientIdx] = -itemLoc - contentRect[xy];
  60703. pageIndex = Math.floor(
  60704. pageCount * (itemLoc + itemRect[xy] + containerRectSize / 2) / contentRect[wh]
  60705. );
  60706. pageIndex = (contentRect[wh] && pageCount)
  60707. ? Math.max(0, Math.min(pageCount - 1, pageIndex))
  60708. : -1;
  60709. var winRect = {x: 0, y: 0};
  60710. winRect[wh] = containerRectSize;
  60711. winRect[hw] = contentRect[hw];
  60712. winRect[xy] = -contentPos[orientIdx] - contentRect[xy];
  60713. var startIdx;
  60714. var children = contentGroup.children();
  60715. contentGroup.eachChild(function (child, index) {
  60716. var itemRect = getItemRect(child);
  60717. if (itemRect.intersect(winRect)) {
  60718. startIdx == null && (startIdx = index);
  60719. // It is user-friendly that the last item shown in the
  60720. // current window is shown at the begining of next window.
  60721. pageNextDataIndex = child.__legendDataIndex;
  60722. }
  60723. // If the last item is shown entirely, no next page.
  60724. if (index === children.length - 1
  60725. && itemRect[xy] + itemRect[wh] <= winRect[xy] + winRect[wh]
  60726. ) {
  60727. pageNextDataIndex = null;
  60728. }
  60729. });
  60730. // Always align based on the left/top most item, so the left/top most
  60731. // item in the previous window is needed to be found here.
  60732. if (startIdx != null) {
  60733. var startItem = children[startIdx];
  60734. var startRect = getItemRect(startItem);
  60735. winRect[xy] = startRect[xy] + startRect[wh] - winRect[wh];
  60736. // If the first item is shown entirely, no previous page.
  60737. if (startIdx <= 0 && startRect[xy] >= winRect[xy]) {
  60738. pagePrevDataIndex = null;
  60739. }
  60740. else {
  60741. while (startIdx > 0 && getItemRect(children[startIdx - 1]).intersect(winRect)) {
  60742. startIdx--;
  60743. }
  60744. pagePrevDataIndex = children[startIdx].__legendDataIndex;
  60745. }
  60746. }
  60747. }
  60748. return {
  60749. contentPosition: contentPos,
  60750. pageIndex: pageIndex,
  60751. pageCount: pageCount,
  60752. pagePrevDataIndex: pagePrevDataIndex,
  60753. pageNextDataIndex: pageNextDataIndex
  60754. };
  60755. function getItemRect(el) {
  60756. var itemRect = el.getBoundingRect().clone();
  60757. itemRect[xy] += el.position[orientIdx];
  60758. return itemRect;
  60759. }
  60760. }
  60761. });
  60762. /*
  60763. * Licensed to the Apache Software Foundation (ASF) under one
  60764. * or more contributor license agreements. See the NOTICE file
  60765. * distributed with this work for additional information
  60766. * regarding copyright ownership. The ASF licenses this file
  60767. * to you under the Apache License, Version 2.0 (the
  60768. * "License"); you may not use this file except in compliance
  60769. * with the License. You may obtain a copy of the License at
  60770. *
  60771. * http://www.apache.org/licenses/LICENSE-2.0
  60772. *
  60773. * Unless required by applicable law or agreed to in writing,
  60774. * software distributed under the License is distributed on an
  60775. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60776. * KIND, either express or implied. See the License for the
  60777. * specific language governing permissions and limitations
  60778. * under the License.
  60779. */
  60780. /**
  60781. * @event legendScroll
  60782. * @type {Object}
  60783. * @property {string} type 'legendScroll'
  60784. * @property {string} scrollDataIndex
  60785. */
  60786. registerAction(
  60787. 'legendScroll', 'legendscroll',
  60788. function (payload, ecModel) {
  60789. var scrollDataIndex = payload.scrollDataIndex;
  60790. scrollDataIndex != null && ecModel.eachComponent(
  60791. {mainType: 'legend', subType: 'scroll', query: payload},
  60792. function (legendModel) {
  60793. legendModel.setScrollDataIndex(scrollDataIndex);
  60794. }
  60795. );
  60796. }
  60797. );
  60798. /*
  60799. * Licensed to the Apache Software Foundation (ASF) under one
  60800. * or more contributor license agreements. See the NOTICE file
  60801. * distributed with this work for additional information
  60802. * regarding copyright ownership. The ASF licenses this file
  60803. * to you under the Apache License, Version 2.0 (the
  60804. * "License"); you may not use this file except in compliance
  60805. * with the License. You may obtain a copy of the License at
  60806. *
  60807. * http://www.apache.org/licenses/LICENSE-2.0
  60808. *
  60809. * Unless required by applicable law or agreed to in writing,
  60810. * software distributed under the License is distributed on an
  60811. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60812. * KIND, either express or implied. See the License for the
  60813. * specific language governing permissions and limitations
  60814. * under the License.
  60815. */
  60816. /**
  60817. * Legend component entry file8
  60818. */
  60819. /*
  60820. * Licensed to the Apache Software Foundation (ASF) under one
  60821. * or more contributor license agreements. See the NOTICE file
  60822. * distributed with this work for additional information
  60823. * regarding copyright ownership. The ASF licenses this file
  60824. * to you under the Apache License, Version 2.0 (the
  60825. * "License"); you may not use this file except in compliance
  60826. * with the License. You may obtain a copy of the License at
  60827. *
  60828. * http://www.apache.org/licenses/LICENSE-2.0
  60829. *
  60830. * Unless required by applicable law or agreed to in writing,
  60831. * software distributed under the License is distributed on an
  60832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60833. * KIND, either express or implied. See the License for the
  60834. * specific language governing permissions and limitations
  60835. * under the License.
  60836. */
  60837. extendComponentModel({
  60838. type: 'tooltip',
  60839. dependencies: ['axisPointer'],
  60840. defaultOption: {
  60841. zlevel: 0,
  60842. z: 8,
  60843. show: true,
  60844. // tooltip主体内容
  60845. showContent: true,
  60846. // 'trigger' only works on coordinate system.
  60847. // 'item' | 'axis' | 'none'
  60848. trigger: 'item',
  60849. // 'click' | 'mousemove' | 'none'
  60850. triggerOn: 'mousemove|click',
  60851. alwaysShowContent: false,
  60852. displayMode: 'single', // 'single' | 'multipleByCoordSys'
  60853. // 位置 {Array} | {Function}
  60854. // position: null
  60855. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  60856. // align: null,
  60857. // verticalAlign: null,
  60858. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  60859. confine: false,
  60860. // 内容格式器:{string}(Template) ¦ {Function}
  60861. // formatter: null
  60862. showDelay: 0,
  60863. // 隐藏延迟,单位ms
  60864. hideDelay: 100,
  60865. // 动画变换时间,单位s
  60866. transitionDuration: 0.4,
  60867. enterable: false,
  60868. // 提示背景颜色,默认为透明度为0.7的黑色
  60869. backgroundColor: 'rgba(50,50,50,0.7)',
  60870. // 提示边框颜色
  60871. borderColor: '#333',
  60872. // 提示边框圆角,单位px,默认为4
  60873. borderRadius: 4,
  60874. // 提示边框线宽,单位px,默认为0(无边框)
  60875. borderWidth: 0,
  60876. // 提示内边距,单位px,默认各方向内边距为5,
  60877. // 接受数组分别设定上右下左边距,同css
  60878. padding: 5,
  60879. // Extra css text
  60880. extraCssText: '',
  60881. // 坐标轴指示器,坐标轴触发有效
  60882. axisPointer: {
  60883. // 默认为直线
  60884. // 可选为:'line' | 'shadow' | 'cross'
  60885. type: 'line',
  60886. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  60887. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  60888. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  60889. // 极坐标系会默认选择 angle 轴
  60890. axis: 'auto',
  60891. animation: 'auto',
  60892. animationDurationUpdate: 200,
  60893. animationEasingUpdate: 'exponentialOut',
  60894. crossStyle: {
  60895. color: '#999',
  60896. width: 1,
  60897. type: 'dashed',
  60898. // TODO formatter
  60899. textStyle: {}
  60900. }
  60901. // lineStyle and shadowStyle should not be specified here,
  60902. // otherwise it will always override those styles on option.axisPointer.
  60903. },
  60904. textStyle: {
  60905. color: '#fff',
  60906. fontSize: 14
  60907. }
  60908. }
  60909. });
  60910. /*
  60911. * Licensed to the Apache Software Foundation (ASF) under one
  60912. * or more contributor license agreements. See the NOTICE file
  60913. * distributed with this work for additional information
  60914. * regarding copyright ownership. The ASF licenses this file
  60915. * to you under the Apache License, Version 2.0 (the
  60916. * "License"); you may not use this file except in compliance
  60917. * with the License. You may obtain a copy of the License at
  60918. *
  60919. * http://www.apache.org/licenses/LICENSE-2.0
  60920. *
  60921. * Unless required by applicable law or agreed to in writing,
  60922. * software distributed under the License is distributed on an
  60923. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60924. * KIND, either express or implied. See the License for the
  60925. * specific language governing permissions and limitations
  60926. * under the License.
  60927. */
  60928. var each$18 = each$1;
  60929. var toCamelCase$1 = toCamelCase;
  60930. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  60931. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  60932. /**
  60933. * @param {number} duration
  60934. * @return {string}
  60935. * @inner
  60936. */
  60937. function assembleTransition(duration) {
  60938. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  60939. var transitionText = 'left ' + duration + 's ' + transitionCurve + ','
  60940. + 'top ' + duration + 's ' + transitionCurve;
  60941. return map(vendors, function (vendorPrefix) {
  60942. return vendorPrefix + 'transition:' + transitionText;
  60943. }).join(';');
  60944. }
  60945. /**
  60946. * @param {Object} textStyle
  60947. * @return {string}
  60948. * @inner
  60949. */
  60950. function assembleFont(textStyleModel) {
  60951. var cssText = [];
  60952. var fontSize = textStyleModel.get('fontSize');
  60953. var color = textStyleModel.getTextColor();
  60954. color && cssText.push('color:' + color);
  60955. cssText.push('font:' + textStyleModel.getFont());
  60956. fontSize &&
  60957. cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  60958. each$18(['decoration', 'align'], function (name) {
  60959. var val = textStyleModel.get(name);
  60960. val && cssText.push('text-' + name + ':' + val);
  60961. });
  60962. return cssText.join(';');
  60963. }
  60964. /**
  60965. * @param {Object} tooltipModel
  60966. * @return {string}
  60967. * @inner
  60968. */
  60969. function assembleCssText(tooltipModel) {
  60970. var cssText = [];
  60971. var transitionDuration = tooltipModel.get('transitionDuration');
  60972. var backgroundColor = tooltipModel.get('backgroundColor');
  60973. var textStyleModel = tooltipModel.getModel('textStyle');
  60974. var padding = tooltipModel.get('padding');
  60975. // Animation transition. Do not animate when transitionDuration is 0.
  60976. transitionDuration &&
  60977. cssText.push(assembleTransition(transitionDuration));
  60978. if (backgroundColor) {
  60979. if (env$1.canvasSupported) {
  60980. cssText.push('background-Color:' + backgroundColor);
  60981. }
  60982. else {
  60983. // for ie
  60984. cssText.push(
  60985. 'background-Color:#' + toHex(backgroundColor)
  60986. );
  60987. cssText.push('filter:alpha(opacity=70)');
  60988. }
  60989. }
  60990. // Border style
  60991. each$18(['width', 'color', 'radius'], function (name) {
  60992. var borderName = 'border-' + name;
  60993. var camelCase = toCamelCase$1(borderName);
  60994. var val = tooltipModel.get(camelCase);
  60995. val != null &&
  60996. cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  60997. });
  60998. // Text style
  60999. cssText.push(assembleFont(textStyleModel));
  61000. // Padding
  61001. if (padding != null) {
  61002. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  61003. }
  61004. return cssText.join(';') + ';';
  61005. }
  61006. /**
  61007. * @alias module:echarts/component/tooltip/TooltipContent
  61008. * @constructor
  61009. */
  61010. function TooltipContent(container, api) {
  61011. if (env$1.wxa) {
  61012. return null;
  61013. }
  61014. var el = document.createElement('div');
  61015. var zr = this._zr = api.getZr();
  61016. this.el = el;
  61017. this._x = api.getWidth() / 2;
  61018. this._y = api.getHeight() / 2;
  61019. container.appendChild(el);
  61020. this._container = container;
  61021. this._show = false;
  61022. /**
  61023. * @private
  61024. */
  61025. this._hideTimeout;
  61026. var self = this;
  61027. el.onmouseenter = function () {
  61028. // clear the timeout in hideLater and keep showing tooltip
  61029. if (self._enterable) {
  61030. clearTimeout(self._hideTimeout);
  61031. self._show = true;
  61032. }
  61033. self._inContent = true;
  61034. };
  61035. el.onmousemove = function (e) {
  61036. e = e || window.event;
  61037. if (!self._enterable) {
  61038. // Try trigger zrender event to avoid mouse
  61039. // in and out shape too frequently
  61040. var handler = zr.handler;
  61041. normalizeEvent(container, e, true);
  61042. handler.dispatch('mousemove', e);
  61043. }
  61044. };
  61045. el.onmouseleave = function () {
  61046. if (self._enterable) {
  61047. if (self._show) {
  61048. self.hideLater(self._hideDelay);
  61049. }
  61050. }
  61051. self._inContent = false;
  61052. };
  61053. }
  61054. TooltipContent.prototype = {
  61055. constructor: TooltipContent,
  61056. /**
  61057. * @private
  61058. * @type {boolean}
  61059. */
  61060. _enterable: true,
  61061. /**
  61062. * Update when tooltip is rendered
  61063. */
  61064. update: function () {
  61065. // FIXME
  61066. // Move this logic to ec main?
  61067. var container = this._container;
  61068. var stl = container.currentStyle
  61069. || document.defaultView.getComputedStyle(container);
  61070. var domStyle = container.style;
  61071. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  61072. domStyle.position = 'relative';
  61073. }
  61074. // Hide the tooltip
  61075. // PENDING
  61076. // this.hide();
  61077. },
  61078. show: function (tooltipModel) {
  61079. clearTimeout(this._hideTimeout);
  61080. var el = this.el;
  61081. el.style.cssText = gCssText + assembleCssText(tooltipModel)
  61082. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  61083. + ';left:' + this._x + 'px;top:' + this._y + 'px;'
  61084. + (tooltipModel.get('extraCssText') || '');
  61085. el.style.display = el.innerHTML ? 'block' : 'none';
  61086. this._show = true;
  61087. },
  61088. setContent: function (content) {
  61089. this.el.innerHTML = content == null ? '' : content;
  61090. },
  61091. setEnterable: function (enterable) {
  61092. this._enterable = enterable;
  61093. },
  61094. getSize: function () {
  61095. var el = this.el;
  61096. return [el.clientWidth, el.clientHeight];
  61097. },
  61098. moveTo: function (x, y) {
  61099. // xy should be based on canvas root. But tooltipContent is
  61100. // the sibling of canvas root. So padding of ec container
  61101. // should be considered here.
  61102. var zr = this._zr;
  61103. var viewportRootOffset;
  61104. if (zr && zr.painter && (viewportRootOffset = zr.painter.getViewportRootOffset())) {
  61105. x += viewportRootOffset.offsetLeft;
  61106. y += viewportRootOffset.offsetTop;
  61107. }
  61108. var style = this.el.style;
  61109. style.left = x + 'px';
  61110. style.top = y + 'px';
  61111. this._x = x;
  61112. this._y = y;
  61113. },
  61114. hide: function () {
  61115. this.el.style.display = 'none';
  61116. this._show = false;
  61117. },
  61118. hideLater: function (time) {
  61119. if (this._show && !(this._inContent && this._enterable)) {
  61120. if (time) {
  61121. this._hideDelay = time;
  61122. // Set show false to avoid invoke hideLater mutiple times
  61123. this._show = false;
  61124. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  61125. }
  61126. else {
  61127. this.hide();
  61128. }
  61129. }
  61130. },
  61131. isShow: function () {
  61132. return this._show;
  61133. }
  61134. };
  61135. /*
  61136. * Licensed to the Apache Software Foundation (ASF) under one
  61137. * or more contributor license agreements. See the NOTICE file
  61138. * distributed with this work for additional information
  61139. * regarding copyright ownership. The ASF licenses this file
  61140. * to you under the Apache License, Version 2.0 (the
  61141. * "License"); you may not use this file except in compliance
  61142. * with the License. You may obtain a copy of the License at
  61143. *
  61144. * http://www.apache.org/licenses/LICENSE-2.0
  61145. *
  61146. * Unless required by applicable law or agreed to in writing,
  61147. * software distributed under the License is distributed on an
  61148. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61149. * KIND, either express or implied. See the License for the
  61150. * specific language governing permissions and limitations
  61151. * under the License.
  61152. */
  61153. var bind$3 = bind;
  61154. var each$17 = each$1;
  61155. var parsePercent$2 = parsePercent$1;
  61156. var proxyRect = new Rect({
  61157. shape: {x: -1, y: -1, width: 2, height: 2}
  61158. });
  61159. extendComponentView({
  61160. type: 'tooltip',
  61161. init: function (ecModel, api) {
  61162. if (env$1.node) {
  61163. return;
  61164. }
  61165. var tooltipContent = new TooltipContent(api.getDom(), api);
  61166. this._tooltipContent = tooltipContent;
  61167. },
  61168. render: function (tooltipModel, ecModel, api) {
  61169. if (env$1.node || env$1.wxa) {
  61170. return;
  61171. }
  61172. // Reset
  61173. this.group.removeAll();
  61174. /**
  61175. * @private
  61176. * @type {module:echarts/component/tooltip/TooltipModel}
  61177. */
  61178. this._tooltipModel = tooltipModel;
  61179. /**
  61180. * @private
  61181. * @type {module:echarts/model/Global}
  61182. */
  61183. this._ecModel = ecModel;
  61184. /**
  61185. * @private
  61186. * @type {module:echarts/ExtensionAPI}
  61187. */
  61188. this._api = api;
  61189. /**
  61190. * Should be cleaned when render.
  61191. * @private
  61192. * @type {Array.<Array.<Object>>}
  61193. */
  61194. this._lastDataByCoordSys = null;
  61195. /**
  61196. * @private
  61197. * @type {boolean}
  61198. */
  61199. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  61200. var tooltipContent = this._tooltipContent;
  61201. tooltipContent.update();
  61202. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  61203. this._initGlobalListener();
  61204. this._keepShow();
  61205. },
  61206. _initGlobalListener: function () {
  61207. var tooltipModel = this._tooltipModel;
  61208. var triggerOn = tooltipModel.get('triggerOn');
  61209. register(
  61210. 'itemTooltip',
  61211. this._api,
  61212. bind$3(function (currTrigger, e, dispatchAction) {
  61213. // If 'none', it is not controlled by mouse totally.
  61214. if (triggerOn !== 'none') {
  61215. if (triggerOn.indexOf(currTrigger) >= 0) {
  61216. this._tryShow(e, dispatchAction);
  61217. }
  61218. else if (currTrigger === 'leave') {
  61219. this._hide(dispatchAction);
  61220. }
  61221. }
  61222. }, this)
  61223. );
  61224. },
  61225. _keepShow: function () {
  61226. var tooltipModel = this._tooltipModel;
  61227. var ecModel = this._ecModel;
  61228. var api = this._api;
  61229. // Try to keep the tooltip show when refreshing
  61230. if (this._lastX != null
  61231. && this._lastY != null
  61232. // When user is willing to control tooltip totally using API,
  61233. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  61234. // which is not expected.
  61235. && tooltipModel.get('triggerOn') !== 'none'
  61236. ) {
  61237. var self = this;
  61238. clearTimeout(this._refreshUpdateTimeout);
  61239. this._refreshUpdateTimeout = setTimeout(function () {
  61240. // Show tip next tick after other charts are rendered
  61241. // In case highlight action has wrong result
  61242. // FIXME
  61243. self.manuallyShowTip(tooltipModel, ecModel, api, {
  61244. x: self._lastX,
  61245. y: self._lastY
  61246. });
  61247. });
  61248. }
  61249. },
  61250. /**
  61251. * Show tip manually by
  61252. * dispatchAction({
  61253. * type: 'showTip',
  61254. * x: 10,
  61255. * y: 10
  61256. * });
  61257. * Or
  61258. * dispatchAction({
  61259. * type: 'showTip',
  61260. * seriesIndex: 0,
  61261. * dataIndex or dataIndexInside or name
  61262. * });
  61263. *
  61264. * TODO Batch
  61265. */
  61266. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  61267. if (payload.from === this.uid || env$1.node) {
  61268. return;
  61269. }
  61270. var dispatchAction = makeDispatchAction$1(payload, api);
  61271. // Reset ticket
  61272. this._ticket = '';
  61273. // When triggered from axisPointer.
  61274. var dataByCoordSys = payload.dataByCoordSys;
  61275. if (payload.tooltip && payload.x != null && payload.y != null) {
  61276. var el = proxyRect;
  61277. el.position = [payload.x, payload.y];
  61278. el.update();
  61279. el.tooltip = payload.tooltip;
  61280. // Manually show tooltip while view is not using zrender elements.
  61281. this._tryShow({
  61282. offsetX: payload.x,
  61283. offsetY: payload.y,
  61284. target: el
  61285. }, dispatchAction);
  61286. }
  61287. else if (dataByCoordSys) {
  61288. this._tryShow({
  61289. offsetX: payload.x,
  61290. offsetY: payload.y,
  61291. position: payload.position,
  61292. event: {},
  61293. dataByCoordSys: payload.dataByCoordSys,
  61294. tooltipOption: payload.tooltipOption
  61295. }, dispatchAction);
  61296. }
  61297. else if (payload.seriesIndex != null) {
  61298. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  61299. return;
  61300. }
  61301. var pointInfo = findPointFromSeries(payload, ecModel);
  61302. var cx = pointInfo.point[0];
  61303. var cy = pointInfo.point[1];
  61304. if (cx != null && cy != null) {
  61305. this._tryShow({
  61306. offsetX: cx,
  61307. offsetY: cy,
  61308. position: payload.position,
  61309. target: pointInfo.el,
  61310. event: {}
  61311. }, dispatchAction);
  61312. }
  61313. }
  61314. else if (payload.x != null && payload.y != null) {
  61315. // FIXME
  61316. // should wrap dispatchAction like `axisPointer/globalListener` ?
  61317. api.dispatchAction({
  61318. type: 'updateAxisPointer',
  61319. x: payload.x,
  61320. y: payload.y
  61321. });
  61322. this._tryShow({
  61323. offsetX: payload.x,
  61324. offsetY: payload.y,
  61325. position: payload.position,
  61326. target: api.getZr().findHover(payload.x, payload.y).target,
  61327. event: {}
  61328. }, dispatchAction);
  61329. }
  61330. },
  61331. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  61332. var tooltipContent = this._tooltipContent;
  61333. if (!this._alwaysShowContent && this._tooltipModel) {
  61334. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  61335. }
  61336. this._lastX = this._lastY = null;
  61337. if (payload.from !== this.uid) {
  61338. this._hide(makeDispatchAction$1(payload, api));
  61339. }
  61340. },
  61341. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  61342. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  61343. // and tooltip.
  61344. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  61345. var seriesIndex = payload.seriesIndex;
  61346. var dataIndex = payload.dataIndex;
  61347. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  61348. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  61349. return;
  61350. }
  61351. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  61352. if (!seriesModel) {
  61353. return;
  61354. }
  61355. var data = seriesModel.getData();
  61356. var tooltipModel = buildTooltipModel([
  61357. data.getItemModel(dataIndex),
  61358. seriesModel,
  61359. (seriesModel.coordinateSystem || {}).model,
  61360. tooltipModel
  61361. ]);
  61362. if (tooltipModel.get('trigger') !== 'axis') {
  61363. return;
  61364. }
  61365. api.dispatchAction({
  61366. type: 'updateAxisPointer',
  61367. seriesIndex: seriesIndex,
  61368. dataIndex: dataIndex,
  61369. position: payload.position
  61370. });
  61371. return true;
  61372. },
  61373. _tryShow: function (e, dispatchAction) {
  61374. var el = e.target;
  61375. var tooltipModel = this._tooltipModel;
  61376. if (!tooltipModel) {
  61377. return;
  61378. }
  61379. // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  61380. this._lastX = e.offsetX;
  61381. this._lastY = e.offsetY;
  61382. var dataByCoordSys = e.dataByCoordSys;
  61383. if (dataByCoordSys && dataByCoordSys.length) {
  61384. this._showAxisTooltip(dataByCoordSys, e);
  61385. }
  61386. // Always show item tooltip if mouse is on the element with dataIndex
  61387. else if (el && el.dataIndex != null) {
  61388. this._lastDataByCoordSys = null;
  61389. this._showSeriesItemTooltip(e, el, dispatchAction);
  61390. }
  61391. // Tooltip provided directly. Like legend.
  61392. else if (el && el.tooltip) {
  61393. this._lastDataByCoordSys = null;
  61394. this._showComponentItemTooltip(e, el, dispatchAction);
  61395. }
  61396. else {
  61397. this._lastDataByCoordSys = null;
  61398. this._hide(dispatchAction);
  61399. }
  61400. },
  61401. _showOrMove: function (tooltipModel, cb) {
  61402. // showDelay is used in this case: tooltip.enterable is set
  61403. // as true. User intent to move mouse into tooltip and click
  61404. // something. `showDelay` makes it easyer to enter the content
  61405. // but tooltip do not move immediately.
  61406. var delay = tooltipModel.get('showDelay');
  61407. cb = bind(cb, this);
  61408. clearTimeout(this._showTimout);
  61409. delay > 0
  61410. ? (this._showTimout = setTimeout(cb, delay))
  61411. : cb();
  61412. },
  61413. _showAxisTooltip: function (dataByCoordSys, e) {
  61414. var ecModel = this._ecModel;
  61415. var globalTooltipModel = this._tooltipModel;
  61416. var point = [e.offsetX, e.offsetY];
  61417. var singleDefaultHTML = [];
  61418. var singleParamsList = [];
  61419. var singleTooltipModel = buildTooltipModel([
  61420. e.tooltipOption,
  61421. globalTooltipModel
  61422. ]);
  61423. each$17(dataByCoordSys, function (itemCoordSys) {
  61424. // var coordParamList = [];
  61425. // var coordDefaultHTML = [];
  61426. // var coordTooltipModel = buildTooltipModel([
  61427. // e.tooltipOption,
  61428. // itemCoordSys.tooltipOption,
  61429. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  61430. // globalTooltipModel
  61431. // ]);
  61432. // var displayMode = coordTooltipModel.get('displayMode');
  61433. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  61434. each$17(itemCoordSys.dataByAxis, function (item) {
  61435. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  61436. var axisValue = item.value;
  61437. var seriesDefaultHTML = [];
  61438. if (!axisModel || axisValue == null) {
  61439. return;
  61440. }
  61441. var valueLabel = getValueLabel(
  61442. axisValue, axisModel.axis, ecModel,
  61443. item.seriesDataIndices,
  61444. item.valueLabelOpt
  61445. );
  61446. each$1(item.seriesDataIndices, function (idxItem) {
  61447. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  61448. var dataIndex = idxItem.dataIndexInside;
  61449. var dataParams = series && series.getDataParams(dataIndex);
  61450. dataParams.axisDim = item.axisDim;
  61451. dataParams.axisIndex = item.axisIndex;
  61452. dataParams.axisType = item.axisType;
  61453. dataParams.axisId = item.axisId;
  61454. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  61455. dataParams.axisValueLabel = valueLabel;
  61456. if (dataParams) {
  61457. singleParamsList.push(dataParams);
  61458. seriesDefaultHTML.push(series.formatTooltip(dataIndex, true));
  61459. }
  61460. });
  61461. // Default tooltip content
  61462. // FIXME
  61463. // (1) shold be the first data which has name?
  61464. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  61465. var firstLine = valueLabel;
  61466. singleDefaultHTML.push(
  61467. (firstLine ? encodeHTML(firstLine) + '<br />' : '')
  61468. + seriesDefaultHTML.join('<br />')
  61469. );
  61470. });
  61471. }, this);
  61472. // In most case, the second axis is shown upper than the first one.
  61473. singleDefaultHTML.reverse();
  61474. singleDefaultHTML = singleDefaultHTML.join('<br /><br />');
  61475. var positionExpr = e.position;
  61476. this._showOrMove(singleTooltipModel, function () {
  61477. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  61478. this._updatePosition(
  61479. singleTooltipModel,
  61480. positionExpr,
  61481. point[0], point[1],
  61482. this._tooltipContent,
  61483. singleParamsList
  61484. );
  61485. }
  61486. else {
  61487. this._showTooltipContent(
  61488. singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(),
  61489. point[0], point[1], positionExpr
  61490. );
  61491. }
  61492. });
  61493. // Do not trigger events here, because this branch only be entered
  61494. // from dispatchAction.
  61495. },
  61496. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  61497. var ecModel = this._ecModel;
  61498. // Use dataModel in element if possible
  61499. // Used when mouseover on a element like markPoint or edge
  61500. // In which case, the data is not main data in series.
  61501. var seriesIndex = el.seriesIndex;
  61502. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  61503. // For example, graph link.
  61504. var dataModel = el.dataModel || seriesModel;
  61505. var dataIndex = el.dataIndex;
  61506. var dataType = el.dataType;
  61507. var data = dataModel.getData();
  61508. var tooltipModel = buildTooltipModel([
  61509. data.getItemModel(dataIndex),
  61510. dataModel,
  61511. seriesModel && (seriesModel.coordinateSystem || {}).model,
  61512. this._tooltipModel
  61513. ]);
  61514. var tooltipTrigger = tooltipModel.get('trigger');
  61515. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  61516. return;
  61517. }
  61518. var params = dataModel.getDataParams(dataIndex, dataType);
  61519. var defaultHtml = dataModel.formatTooltip(dataIndex, false, dataType);
  61520. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  61521. this._showOrMove(tooltipModel, function () {
  61522. this._showTooltipContent(
  61523. tooltipModel, defaultHtml, params, asyncTicket,
  61524. e.offsetX, e.offsetY, e.position, e.target
  61525. );
  61526. });
  61527. // FIXME
  61528. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  61529. dispatchAction({
  61530. type: 'showTip',
  61531. dataIndexInside: dataIndex,
  61532. dataIndex: data.getRawIndex(dataIndex),
  61533. seriesIndex: seriesIndex,
  61534. from: this.uid
  61535. });
  61536. },
  61537. _showComponentItemTooltip: function (e, el, dispatchAction) {
  61538. var tooltipOpt = el.tooltip;
  61539. if (typeof tooltipOpt === 'string') {
  61540. var content = tooltipOpt;
  61541. tooltipOpt = {
  61542. content: content,
  61543. // Fixed formatter
  61544. formatter: content
  61545. };
  61546. }
  61547. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  61548. var defaultHtml = subTooltipModel.get('content');
  61549. var asyncTicket = Math.random();
  61550. // Do not check whether `trigger` is 'none' here, because `trigger`
  61551. // only works on cooridinate system. In fact, we have not found case
  61552. // that requires setting `trigger` nothing on component yet.
  61553. this._showOrMove(subTooltipModel, function () {
  61554. this._showTooltipContent(
  61555. subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {},
  61556. asyncTicket, e.offsetX, e.offsetY, e.position, el
  61557. );
  61558. });
  61559. // If not dispatch showTip, tip may be hide triggered by axis.
  61560. dispatchAction({
  61561. type: 'showTip',
  61562. from: this.uid
  61563. });
  61564. },
  61565. _showTooltipContent: function (
  61566. tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el
  61567. ) {
  61568. // Reset ticket
  61569. this._ticket = '';
  61570. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  61571. return;
  61572. }
  61573. var tooltipContent = this._tooltipContent;
  61574. var formatter = tooltipModel.get('formatter');
  61575. positionExpr = positionExpr || tooltipModel.get('position');
  61576. var html = defaultHtml;
  61577. if (formatter && typeof formatter === 'string') {
  61578. html = formatTpl(formatter, params, true);
  61579. }
  61580. else if (typeof formatter === 'function') {
  61581. var callback = bind$3(function (cbTicket, html) {
  61582. if (cbTicket === this._ticket) {
  61583. tooltipContent.setContent(html);
  61584. this._updatePosition(
  61585. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  61586. );
  61587. }
  61588. }, this);
  61589. this._ticket = asyncTicket;
  61590. html = formatter(params, asyncTicket, callback);
  61591. }
  61592. tooltipContent.setContent(html);
  61593. tooltipContent.show(tooltipModel);
  61594. this._updatePosition(
  61595. tooltipModel, positionExpr, x, y, tooltipContent, params, el
  61596. );
  61597. },
  61598. /**
  61599. * @param {string|Function|Array.<number>|Object} positionExpr
  61600. * @param {number} x Mouse x
  61601. * @param {number} y Mouse y
  61602. * @param {boolean} confine Whether confine tooltip content in view rect.
  61603. * @param {Object|<Array.<Object>} params
  61604. * @param {module:zrender/Element} el target element
  61605. * @param {module:echarts/ExtensionAPI} api
  61606. * @return {Array.<number>}
  61607. */
  61608. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  61609. var viewWidth = this._api.getWidth();
  61610. var viewHeight = this._api.getHeight();
  61611. positionExpr = positionExpr || tooltipModel.get('position');
  61612. var contentSize = content.getSize();
  61613. var align = tooltipModel.get('align');
  61614. var vAlign = tooltipModel.get('verticalAlign');
  61615. var rect = el && el.getBoundingRect().clone();
  61616. el && rect.applyTransform(el.transform);
  61617. if (typeof positionExpr === 'function') {
  61618. // Callback of position can be an array or a string specify the position
  61619. positionExpr = positionExpr([x, y], params, content.el, rect, {
  61620. viewSize: [viewWidth, viewHeight],
  61621. contentSize: contentSize.slice()
  61622. });
  61623. }
  61624. if (isArray(positionExpr)) {
  61625. x = parsePercent$2(positionExpr[0], viewWidth);
  61626. y = parsePercent$2(positionExpr[1], viewHeight);
  61627. }
  61628. else if (isObject$1(positionExpr)) {
  61629. positionExpr.width = contentSize[0];
  61630. positionExpr.height = contentSize[1];
  61631. var layoutRect = getLayoutRect(
  61632. positionExpr, {width: viewWidth, height: viewHeight}
  61633. );
  61634. x = layoutRect.x;
  61635. y = layoutRect.y;
  61636. align = null;
  61637. // When positionExpr is left/top/right/bottom,
  61638. // align and verticalAlign will not work.
  61639. vAlign = null;
  61640. }
  61641. // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  61642. else if (typeof positionExpr === 'string' && el) {
  61643. var pos = calcTooltipPosition(
  61644. positionExpr, rect, contentSize
  61645. );
  61646. x = pos[0];
  61647. y = pos[1];
  61648. }
  61649. else {
  61650. var pos = refixTooltipPosition(
  61651. x, y, content.el, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20
  61652. );
  61653. x = pos[0];
  61654. y = pos[1];
  61655. }
  61656. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  61657. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  61658. if (tooltipModel.get('confine')) {
  61659. var pos = confineTooltipPosition(
  61660. x, y, content.el, viewWidth, viewHeight
  61661. );
  61662. x = pos[0];
  61663. y = pos[1];
  61664. }
  61665. content.moveTo(x, y);
  61666. },
  61667. // FIXME
  61668. // Should we remove this but leave this to user?
  61669. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  61670. var lastCoordSys = this._lastDataByCoordSys;
  61671. var contentNotChanged = !!lastCoordSys
  61672. && lastCoordSys.length === dataByCoordSys.length;
  61673. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  61674. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  61675. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  61676. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  61677. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  61678. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  61679. var thisItem = thisDataByAxis[indexAxis] || {};
  61680. var lastIndices = lastItem.seriesDataIndices || [];
  61681. var newIndices = thisItem.seriesDataIndices || [];
  61682. contentNotChanged &=
  61683. lastItem.value === thisItem.value
  61684. && lastItem.axisType === thisItem.axisType
  61685. && lastItem.axisId === thisItem.axisId
  61686. && lastIndices.length === newIndices.length;
  61687. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  61688. var newIdxItem = newIndices[j];
  61689. contentNotChanged &=
  61690. lastIdxItem.seriesIndex === newIdxItem.seriesIndex
  61691. && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  61692. });
  61693. });
  61694. });
  61695. this._lastDataByCoordSys = dataByCoordSys;
  61696. return !!contentNotChanged;
  61697. },
  61698. _hide: function (dispatchAction) {
  61699. // Do not directly hideLater here, because this behavior may be prevented
  61700. // in dispatchAction when showTip is dispatched.
  61701. // FIXME
  61702. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  61703. this._lastDataByCoordSys = null;
  61704. dispatchAction({
  61705. type: 'hideTip',
  61706. from: this.uid
  61707. });
  61708. },
  61709. dispose: function (ecModel, api) {
  61710. if (env$1.node || env$1.wxa) {
  61711. return;
  61712. }
  61713. this._tooltipContent.hide();
  61714. unregister('itemTooltip', api);
  61715. }
  61716. });
  61717. /**
  61718. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  61719. * From top to bottom. (the last one should be globalTooltipModel);
  61720. */
  61721. function buildTooltipModel(modelCascade) {
  61722. var resultModel = modelCascade.pop();
  61723. while (modelCascade.length) {
  61724. var tooltipOpt = modelCascade.pop();
  61725. if (tooltipOpt) {
  61726. if (Model.isInstance(tooltipOpt)) {
  61727. tooltipOpt = tooltipOpt.get('tooltip', true);
  61728. }
  61729. // In each data item tooltip can be simply write:
  61730. // {
  61731. // value: 10,
  61732. // tooltip: 'Something you need to know'
  61733. // }
  61734. if (typeof tooltipOpt === 'string') {
  61735. tooltipOpt = {formatter: tooltipOpt};
  61736. }
  61737. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  61738. }
  61739. }
  61740. return resultModel;
  61741. }
  61742. function makeDispatchAction$1(payload, api) {
  61743. return payload.dispatchAction || bind(api.dispatchAction, api);
  61744. }
  61745. function refixTooltipPosition(x, y, el, viewWidth, viewHeight, gapH, gapV) {
  61746. var size = getOuterSize(el);
  61747. var width = size.width;
  61748. var height = size.height;
  61749. if (gapH != null) {
  61750. if (x + width + gapH > viewWidth) {
  61751. x -= width + gapH;
  61752. }
  61753. else {
  61754. x += gapH;
  61755. }
  61756. }
  61757. if (gapV != null) {
  61758. if (y + height + gapV > viewHeight) {
  61759. y -= height + gapV;
  61760. }
  61761. else {
  61762. y += gapV;
  61763. }
  61764. }
  61765. return [x, y];
  61766. }
  61767. function confineTooltipPosition(x, y, el, viewWidth, viewHeight) {
  61768. var size = getOuterSize(el);
  61769. var width = size.width;
  61770. var height = size.height;
  61771. x = Math.min(x + width, viewWidth) - width;
  61772. y = Math.min(y + height, viewHeight) - height;
  61773. x = Math.max(x, 0);
  61774. y = Math.max(y, 0);
  61775. return [x, y];
  61776. }
  61777. function getOuterSize(el) {
  61778. var width = el.clientWidth;
  61779. var height = el.clientHeight;
  61780. // Consider browser compatibility.
  61781. // IE8 does not support getComputedStyle.
  61782. if (document.defaultView && document.defaultView.getComputedStyle) {
  61783. var stl = document.defaultView.getComputedStyle(el);
  61784. if (stl) {
  61785. width += parseInt(stl.paddingLeft, 10) + parseInt(stl.paddingRight, 10)
  61786. + parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  61787. height += parseInt(stl.paddingTop, 10) + parseInt(stl.paddingBottom, 10)
  61788. + parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  61789. }
  61790. }
  61791. return {width: width, height: height};
  61792. }
  61793. function calcTooltipPosition(position, rect, contentSize) {
  61794. var domWidth = contentSize[0];
  61795. var domHeight = contentSize[1];
  61796. var gap = 5;
  61797. var x = 0;
  61798. var y = 0;
  61799. var rectWidth = rect.width;
  61800. var rectHeight = rect.height;
  61801. switch (position) {
  61802. case 'inside':
  61803. x = rect.x + rectWidth / 2 - domWidth / 2;
  61804. y = rect.y + rectHeight / 2 - domHeight / 2;
  61805. break;
  61806. case 'top':
  61807. x = rect.x + rectWidth / 2 - domWidth / 2;
  61808. y = rect.y - domHeight - gap;
  61809. break;
  61810. case 'bottom':
  61811. x = rect.x + rectWidth / 2 - domWidth / 2;
  61812. y = rect.y + rectHeight + gap;
  61813. break;
  61814. case 'left':
  61815. x = rect.x - domWidth - gap;
  61816. y = rect.y + rectHeight / 2 - domHeight / 2;
  61817. break;
  61818. case 'right':
  61819. x = rect.x + rectWidth + gap;
  61820. y = rect.y + rectHeight / 2 - domHeight / 2;
  61821. }
  61822. return [x, y];
  61823. }
  61824. function isCenterAlign(align) {
  61825. return align === 'center' || align === 'middle';
  61826. }
  61827. /*
  61828. * Licensed to the Apache Software Foundation (ASF) under one
  61829. * or more contributor license agreements. See the NOTICE file
  61830. * distributed with this work for additional information
  61831. * regarding copyright ownership. The ASF licenses this file
  61832. * to you under the Apache License, Version 2.0 (the
  61833. * "License"); you may not use this file except in compliance
  61834. * with the License. You may obtain a copy of the License at
  61835. *
  61836. * http://www.apache.org/licenses/LICENSE-2.0
  61837. *
  61838. * Unless required by applicable law or agreed to in writing,
  61839. * software distributed under the License is distributed on an
  61840. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61841. * KIND, either express or implied. See the License for the
  61842. * specific language governing permissions and limitations
  61843. * under the License.
  61844. */
  61845. // FIXME Better way to pack data in graphic element
  61846. /**
  61847. * @action
  61848. * @property {string} type
  61849. * @property {number} seriesIndex
  61850. * @property {number} dataIndex
  61851. * @property {number} [x]
  61852. * @property {number} [y]
  61853. */
  61854. registerAction(
  61855. {
  61856. type: 'showTip',
  61857. event: 'showTip',
  61858. update: 'tooltip:manuallyShowTip'
  61859. },
  61860. // noop
  61861. function () {}
  61862. );
  61863. registerAction(
  61864. {
  61865. type: 'hideTip',
  61866. event: 'hideTip',
  61867. update: 'tooltip:manuallyHideTip'
  61868. },
  61869. // noop
  61870. function () {}
  61871. );
  61872. /*
  61873. * Licensed to the Apache Software Foundation (ASF) under one
  61874. * or more contributor license agreements. See the NOTICE file
  61875. * distributed with this work for additional information
  61876. * regarding copyright ownership. The ASF licenses this file
  61877. * to you under the Apache License, Version 2.0 (the
  61878. * "License"); you may not use this file except in compliance
  61879. * with the License. You may obtain a copy of the License at
  61880. *
  61881. * http://www.apache.org/licenses/LICENSE-2.0
  61882. *
  61883. * Unless required by applicable law or agreed to in writing,
  61884. * software distributed under the License is distributed on an
  61885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61886. * KIND, either express or implied. See the License for the
  61887. * specific language governing permissions and limitations
  61888. * under the License.
  61889. */
  61890. function getSeriesStackId$1(seriesModel) {
  61891. return seriesModel.get('stack')
  61892. || '__ec_stack_' + seriesModel.seriesIndex;
  61893. }
  61894. function getAxisKey$1(axis) {
  61895. return axis.dim;
  61896. }
  61897. /**
  61898. * @param {string} seriesType
  61899. * @param {module:echarts/model/Global} ecModel
  61900. * @param {module:echarts/ExtensionAPI} api
  61901. */
  61902. function barLayoutPolar(seriesType, ecModel, api) {
  61903. var width = api.getWidth();
  61904. var height = api.getHeight();
  61905. var lastStackCoords = {};
  61906. var barWidthAndOffset = calRadialBar(
  61907. filter(
  61908. ecModel.getSeriesByType(seriesType),
  61909. function (seriesModel) {
  61910. return !ecModel.isSeriesFiltered(seriesModel)
  61911. && seriesModel.coordinateSystem
  61912. && seriesModel.coordinateSystem.type === 'polar';
  61913. }
  61914. )
  61915. );
  61916. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  61917. // Check series coordinate, do layout for polar only
  61918. if (seriesModel.coordinateSystem.type !== 'polar') {
  61919. return;
  61920. }
  61921. var data = seriesModel.getData();
  61922. var polar = seriesModel.coordinateSystem;
  61923. var baseAxis = polar.getBaseAxis();
  61924. var stackId = getSeriesStackId$1(seriesModel);
  61925. var columnLayoutInfo
  61926. = barWidthAndOffset[getAxisKey$1(baseAxis)][stackId];
  61927. var columnOffset = columnLayoutInfo.offset;
  61928. var columnWidth = columnLayoutInfo.width;
  61929. var valueAxis = polar.getOtherAxis(baseAxis);
  61930. var center = seriesModel.get('center') || ['50%', '50%'];
  61931. var cx = parsePercent$1(center[0], width);
  61932. var cy = parsePercent$1(center[1], height);
  61933. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  61934. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  61935. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  61936. var valueDim = data.mapDimension(valueAxis.dim);
  61937. var baseDim = data.mapDimension(baseAxis.dim);
  61938. var stacked = isDimensionStacked(data, valueDim /*, baseDim*/);
  61939. var valueAxisStart = valueAxis.getExtent()[0];
  61940. for (var idx = 0, len = data.count(); idx < len; idx++) {
  61941. var value = data.get(valueDim, idx);
  61942. var baseValue = data.get(baseDim, idx);
  61943. if (isNaN(value)) {
  61944. continue;
  61945. }
  61946. var sign = value >= 0 ? 'p' : 'n';
  61947. var baseCoord = valueAxisStart;
  61948. // Because of the barMinHeight, we can not use the value in
  61949. // stackResultDimension directly.
  61950. // Only ordinal axis can be stacked.
  61951. if (stacked) {
  61952. if (!lastStackCoords[stackId][baseValue]) {
  61953. lastStackCoords[stackId][baseValue] = {
  61954. p: valueAxisStart, // Positive stack
  61955. n: valueAxisStart // Negative stack
  61956. };
  61957. }
  61958. // Should also consider #4243
  61959. baseCoord = lastStackCoords[stackId][baseValue][sign];
  61960. }
  61961. var r0;
  61962. var r;
  61963. var startAngle;
  61964. var endAngle;
  61965. // radial sector
  61966. if (valueAxis.dim === 'radius') {
  61967. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  61968. var angle = baseAxis.dataToAngle(baseValue);
  61969. if (Math.abs(radiusSpan) < barMinHeight) {
  61970. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  61971. }
  61972. r0 = baseCoord;
  61973. r = baseCoord + radiusSpan;
  61974. startAngle = angle - columnOffset;
  61975. endAngle = startAngle - columnWidth;
  61976. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  61977. }
  61978. // tangential sector
  61979. else {
  61980. // angleAxis must be clamped.
  61981. var angleSpan = valueAxis.dataToAngle(value, true) - valueAxisStart;
  61982. var radius = baseAxis.dataToRadius(baseValue);
  61983. if (Math.abs(angleSpan) < barMinAngle) {
  61984. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  61985. }
  61986. r0 = radius + columnOffset;
  61987. r = r0 + columnWidth;
  61988. startAngle = baseCoord;
  61989. endAngle = baseCoord + angleSpan;
  61990. // if the previous stack is at the end of the ring,
  61991. // add a round to differentiate it from origin
  61992. // var extent = angleAxis.getExtent();
  61993. // var stackCoord = angle;
  61994. // if (stackCoord === extent[0] && value > 0) {
  61995. // stackCoord = extent[1];
  61996. // }
  61997. // else if (stackCoord === extent[1] && value < 0) {
  61998. // stackCoord = extent[0];
  61999. // }
  62000. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  62001. }
  62002. data.setItemLayout(idx, {
  62003. cx: cx,
  62004. cy: cy,
  62005. r0: r0,
  62006. r: r,
  62007. // Consider that positive angle is anti-clockwise,
  62008. // while positive radian of sector is clockwise
  62009. startAngle: -startAngle * Math.PI / 180,
  62010. endAngle: -endAngle * Math.PI / 180
  62011. });
  62012. }
  62013. }, this);
  62014. }
  62015. /**
  62016. * Calculate bar width and offset for radial bar charts
  62017. */
  62018. function calRadialBar(barSeries, api) {
  62019. // Columns info on each category axis. Key is polar name
  62020. var columnsMap = {};
  62021. each$1(barSeries, function (seriesModel, idx) {
  62022. var data = seriesModel.getData();
  62023. var polar = seriesModel.coordinateSystem;
  62024. var baseAxis = polar.getBaseAxis();
  62025. var axisExtent = baseAxis.getExtent();
  62026. var bandWidth = baseAxis.type === 'category'
  62027. ? baseAxis.getBandWidth()
  62028. : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count());
  62029. var columnsOnAxis = columnsMap[getAxisKey$1(baseAxis)] || {
  62030. bandWidth: bandWidth,
  62031. remainedWidth: bandWidth,
  62032. autoWidthCount: 0,
  62033. categoryGap: '20%',
  62034. gap: '30%',
  62035. stacks: {}
  62036. };
  62037. var stacks = columnsOnAxis.stacks;
  62038. columnsMap[getAxisKey$1(baseAxis)] = columnsOnAxis;
  62039. var stackId = getSeriesStackId$1(seriesModel);
  62040. if (!stacks[stackId]) {
  62041. columnsOnAxis.autoWidthCount++;
  62042. }
  62043. stacks[stackId] = stacks[stackId] || {
  62044. width: 0,
  62045. maxWidth: 0
  62046. };
  62047. var barWidth = parsePercent$1(
  62048. seriesModel.get('barWidth'),
  62049. bandWidth
  62050. );
  62051. var barMaxWidth = parsePercent$1(
  62052. seriesModel.get('barMaxWidth'),
  62053. bandWidth
  62054. );
  62055. var barGap = seriesModel.get('barGap');
  62056. var barCategoryGap = seriesModel.get('barCategoryGap');
  62057. if (barWidth && !stacks[stackId].width) {
  62058. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  62059. stacks[stackId].width = barWidth;
  62060. columnsOnAxis.remainedWidth -= barWidth;
  62061. }
  62062. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  62063. (barGap != null) && (columnsOnAxis.gap = barGap);
  62064. (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap);
  62065. });
  62066. var result = {};
  62067. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  62068. result[coordSysName] = {};
  62069. var stacks = columnsOnAxis.stacks;
  62070. var bandWidth = columnsOnAxis.bandWidth;
  62071. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  62072. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  62073. var remainedWidth = columnsOnAxis.remainedWidth;
  62074. var autoWidthCount = columnsOnAxis.autoWidthCount;
  62075. var autoWidth = (remainedWidth - categoryGap)
  62076. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  62077. autoWidth = Math.max(autoWidth, 0);
  62078. // Find if any auto calculated bar exceeded maxBarWidth
  62079. each$1(stacks, function (column, stack) {
  62080. var maxWidth = column.maxWidth;
  62081. if (maxWidth && maxWidth < autoWidth) {
  62082. maxWidth = Math.min(maxWidth, remainedWidth);
  62083. if (column.width) {
  62084. maxWidth = Math.min(maxWidth, column.width);
  62085. }
  62086. remainedWidth -= maxWidth;
  62087. column.width = maxWidth;
  62088. autoWidthCount--;
  62089. }
  62090. });
  62091. // Recalculate width again
  62092. autoWidth = (remainedWidth - categoryGap)
  62093. / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  62094. autoWidth = Math.max(autoWidth, 0);
  62095. var widthSum = 0;
  62096. var lastColumn;
  62097. each$1(stacks, function (column, idx) {
  62098. if (!column.width) {
  62099. column.width = autoWidth;
  62100. }
  62101. lastColumn = column;
  62102. widthSum += column.width * (1 + barGapPercent);
  62103. });
  62104. if (lastColumn) {
  62105. widthSum -= lastColumn.width * barGapPercent;
  62106. }
  62107. var offset = -widthSum / 2;
  62108. each$1(stacks, function (column, stackId) {
  62109. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  62110. offset: offset,
  62111. width: column.width
  62112. };
  62113. offset += column.width * (1 + barGapPercent);
  62114. });
  62115. });
  62116. return result;
  62117. }
  62118. /*
  62119. * Licensed to the Apache Software Foundation (ASF) under one
  62120. * or more contributor license agreements. See the NOTICE file
  62121. * distributed with this work for additional information
  62122. * regarding copyright ownership. The ASF licenses this file
  62123. * to you under the Apache License, Version 2.0 (the
  62124. * "License"); you may not use this file except in compliance
  62125. * with the License. You may obtain a copy of the License at
  62126. *
  62127. * http://www.apache.org/licenses/LICENSE-2.0
  62128. *
  62129. * Unless required by applicable law or agreed to in writing,
  62130. * software distributed under the License is distributed on an
  62131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62132. * KIND, either express or implied. See the License for the
  62133. * specific language governing permissions and limitations
  62134. * under the License.
  62135. */
  62136. function RadiusAxis(scale, radiusExtent) {
  62137. Axis.call(this, 'radius', scale, radiusExtent);
  62138. /**
  62139. * Axis type
  62140. * - 'category'
  62141. * - 'value'
  62142. * - 'time'
  62143. * - 'log'
  62144. * @type {string}
  62145. */
  62146. this.type = 'category';
  62147. }
  62148. RadiusAxis.prototype = {
  62149. constructor: RadiusAxis,
  62150. /**
  62151. * @override
  62152. */
  62153. pointToData: function (point, clamp) {
  62154. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  62155. },
  62156. dataToRadius: Axis.prototype.dataToCoord,
  62157. radiusToData: Axis.prototype.coordToData
  62158. };
  62159. inherits(RadiusAxis, Axis);
  62160. /*
  62161. * Licensed to the Apache Software Foundation (ASF) under one
  62162. * or more contributor license agreements. See the NOTICE file
  62163. * distributed with this work for additional information
  62164. * regarding copyright ownership. The ASF licenses this file
  62165. * to you under the Apache License, Version 2.0 (the
  62166. * "License"); you may not use this file except in compliance
  62167. * with the License. You may obtain a copy of the License at
  62168. *
  62169. * http://www.apache.org/licenses/LICENSE-2.0
  62170. *
  62171. * Unless required by applicable law or agreed to in writing,
  62172. * software distributed under the License is distributed on an
  62173. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62174. * KIND, either express or implied. See the License for the
  62175. * specific language governing permissions and limitations
  62176. * under the License.
  62177. */
  62178. function AngleAxis(scale, angleExtent) {
  62179. angleExtent = angleExtent || [0, 360];
  62180. Axis.call(this, 'angle', scale, angleExtent);
  62181. /**
  62182. * Axis type
  62183. * - 'category'
  62184. * - 'value'
  62185. * - 'time'
  62186. * - 'log'
  62187. * @type {string}
  62188. */
  62189. this.type = 'category';
  62190. }
  62191. AngleAxis.prototype = {
  62192. constructor: AngleAxis,
  62193. /**
  62194. * @override
  62195. */
  62196. pointToData: function (point, clamp) {
  62197. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  62198. },
  62199. dataToAngle: Axis.prototype.dataToCoord,
  62200. angleToData: Axis.prototype.coordToData
  62201. };
  62202. inherits(AngleAxis, Axis);
  62203. /*
  62204. * Licensed to the Apache Software Foundation (ASF) under one
  62205. * or more contributor license agreements. See the NOTICE file
  62206. * distributed with this work for additional information
  62207. * regarding copyright ownership. The ASF licenses this file
  62208. * to you under the Apache License, Version 2.0 (the
  62209. * "License"); you may not use this file except in compliance
  62210. * with the License. You may obtain a copy of the License at
  62211. *
  62212. * http://www.apache.org/licenses/LICENSE-2.0
  62213. *
  62214. * Unless required by applicable law or agreed to in writing,
  62215. * software distributed under the License is distributed on an
  62216. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62217. * KIND, either express or implied. See the License for the
  62218. * specific language governing permissions and limitations
  62219. * under the License.
  62220. */
  62221. /**
  62222. * @module echarts/coord/polar/Polar
  62223. */
  62224. /**
  62225. * @alias {module:echarts/coord/polar/Polar}
  62226. * @constructor
  62227. * @param {string} name
  62228. */
  62229. var Polar = function (name) {
  62230. /**
  62231. * @type {string}
  62232. */
  62233. this.name = name || '';
  62234. /**
  62235. * x of polar center
  62236. * @type {number}
  62237. */
  62238. this.cx = 0;
  62239. /**
  62240. * y of polar center
  62241. * @type {number}
  62242. */
  62243. this.cy = 0;
  62244. /**
  62245. * @type {module:echarts/coord/polar/RadiusAxis}
  62246. * @private
  62247. */
  62248. this._radiusAxis = new RadiusAxis();
  62249. /**
  62250. * @type {module:echarts/coord/polar/AngleAxis}
  62251. * @private
  62252. */
  62253. this._angleAxis = new AngleAxis();
  62254. this._radiusAxis.polar = this._angleAxis.polar = this;
  62255. };
  62256. Polar.prototype = {
  62257. type: 'polar',
  62258. axisPointerEnabled: true,
  62259. constructor: Polar,
  62260. /**
  62261. * @param {Array.<string>}
  62262. * @readOnly
  62263. */
  62264. dimensions: ['radius', 'angle'],
  62265. /**
  62266. * @type {module:echarts/coord/PolarModel}
  62267. */
  62268. model: null,
  62269. /**
  62270. * If contain coord
  62271. * @param {Array.<number>} point
  62272. * @return {boolean}
  62273. */
  62274. containPoint: function (point) {
  62275. var coord = this.pointToCoord(point);
  62276. return this._radiusAxis.contain(coord[0])
  62277. && this._angleAxis.contain(coord[1]);
  62278. },
  62279. /**
  62280. * If contain data
  62281. * @param {Array.<number>} data
  62282. * @return {boolean}
  62283. */
  62284. containData: function (data) {
  62285. return this._radiusAxis.containData(data[0])
  62286. && this._angleAxis.containData(data[1]);
  62287. },
  62288. /**
  62289. * @param {string} dim
  62290. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62291. */
  62292. getAxis: function (dim) {
  62293. return this['_' + dim + 'Axis'];
  62294. },
  62295. /**
  62296. * @return {Array.<module:echarts/coord/Axis>}
  62297. */
  62298. getAxes: function () {
  62299. return [this._radiusAxis, this._angleAxis];
  62300. },
  62301. /**
  62302. * Get axes by type of scale
  62303. * @param {string} scaleType
  62304. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62305. */
  62306. getAxesByScale: function (scaleType) {
  62307. var axes = [];
  62308. var angleAxis = this._angleAxis;
  62309. var radiusAxis = this._radiusAxis;
  62310. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  62311. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  62312. return axes;
  62313. },
  62314. /**
  62315. * @return {module:echarts/coord/polar/AngleAxis}
  62316. */
  62317. getAngleAxis: function () {
  62318. return this._angleAxis;
  62319. },
  62320. /**
  62321. * @return {module:echarts/coord/polar/RadiusAxis}
  62322. */
  62323. getRadiusAxis: function () {
  62324. return this._radiusAxis;
  62325. },
  62326. /**
  62327. * @param {module:echarts/coord/polar/Axis}
  62328. * @return {module:echarts/coord/polar/Axis}
  62329. */
  62330. getOtherAxis: function (axis) {
  62331. var angleAxis = this._angleAxis;
  62332. return axis === angleAxis ? this._radiusAxis : angleAxis;
  62333. },
  62334. /**
  62335. * Base axis will be used on stacking.
  62336. *
  62337. * @return {module:echarts/coord/polar/Axis}
  62338. */
  62339. getBaseAxis: function () {
  62340. return this.getAxesByScale('ordinal')[0]
  62341. || this.getAxesByScale('time')[0]
  62342. || this.getAngleAxis();
  62343. },
  62344. /**
  62345. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  62346. * @return {Object} {baseAxes: [], otherAxes: []}
  62347. */
  62348. getTooltipAxes: function (dim) {
  62349. var baseAxis = (dim != null && dim !== 'auto')
  62350. ? this.getAxis(dim) : this.getBaseAxis();
  62351. return {
  62352. baseAxes: [baseAxis],
  62353. otherAxes: [this.getOtherAxis(baseAxis)]
  62354. };
  62355. },
  62356. /**
  62357. * Convert a single data item to (x, y) point.
  62358. * Parameter data is an array which the first element is radius and the second is angle
  62359. * @param {Array.<number>} data
  62360. * @param {boolean} [clamp=false]
  62361. * @return {Array.<number>}
  62362. */
  62363. dataToPoint: function (data, clamp) {
  62364. return this.coordToPoint([
  62365. this._radiusAxis.dataToRadius(data[0], clamp),
  62366. this._angleAxis.dataToAngle(data[1], clamp)
  62367. ]);
  62368. },
  62369. /**
  62370. * Convert a (x, y) point to data
  62371. * @param {Array.<number>} point
  62372. * @param {boolean} [clamp=false]
  62373. * @return {Array.<number>}
  62374. */
  62375. pointToData: function (point, clamp) {
  62376. var coord = this.pointToCoord(point);
  62377. return [
  62378. this._radiusAxis.radiusToData(coord[0], clamp),
  62379. this._angleAxis.angleToData(coord[1], clamp)
  62380. ];
  62381. },
  62382. /**
  62383. * Convert a (x, y) point to (radius, angle) coord
  62384. * @param {Array.<number>} point
  62385. * @return {Array.<number>}
  62386. */
  62387. pointToCoord: function (point) {
  62388. var dx = point[0] - this.cx;
  62389. var dy = point[1] - this.cy;
  62390. var angleAxis = this.getAngleAxis();
  62391. var extent = angleAxis.getExtent();
  62392. var minAngle = Math.min(extent[0], extent[1]);
  62393. var maxAngle = Math.max(extent[0], extent[1]);
  62394. // Fix fixed extent in polarCreator
  62395. // FIXME
  62396. angleAxis.inverse
  62397. ? (minAngle = maxAngle - 360)
  62398. : (maxAngle = minAngle + 360);
  62399. var radius = Math.sqrt(dx * dx + dy * dy);
  62400. dx /= radius;
  62401. dy /= radius;
  62402. var radian = Math.atan2(-dy, dx) / Math.PI * 180;
  62403. // move to angleExtent
  62404. var dir = radian < minAngle ? 1 : -1;
  62405. while (radian < minAngle || radian > maxAngle) {
  62406. radian += dir * 360;
  62407. }
  62408. return [radius, radian];
  62409. },
  62410. /**
  62411. * Convert a (radius, angle) coord to (x, y) point
  62412. * @param {Array.<number>} coord
  62413. * @return {Array.<number>}
  62414. */
  62415. coordToPoint: function (coord) {
  62416. var radius = coord[0];
  62417. var radian = coord[1] / 180 * Math.PI;
  62418. var x = Math.cos(radian) * radius + this.cx;
  62419. // Inverse the y
  62420. var y = -Math.sin(radian) * radius + this.cy;
  62421. return [x, y];
  62422. }
  62423. };
  62424. /*
  62425. * Licensed to the Apache Software Foundation (ASF) under one
  62426. * or more contributor license agreements. See the NOTICE file
  62427. * distributed with this work for additional information
  62428. * regarding copyright ownership. The ASF licenses this file
  62429. * to you under the Apache License, Version 2.0 (the
  62430. * "License"); you may not use this file except in compliance
  62431. * with the License. You may obtain a copy of the License at
  62432. *
  62433. * http://www.apache.org/licenses/LICENSE-2.0
  62434. *
  62435. * Unless required by applicable law or agreed to in writing,
  62436. * software distributed under the License is distributed on an
  62437. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62438. * KIND, either express or implied. See the License for the
  62439. * specific language governing permissions and limitations
  62440. * under the License.
  62441. */
  62442. var PolarAxisModel = ComponentModel.extend({
  62443. type: 'polarAxis',
  62444. /**
  62445. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62446. */
  62447. axis: null,
  62448. /**
  62449. * @override
  62450. */
  62451. getCoordSysModel: function () {
  62452. return this.ecModel.queryComponents({
  62453. mainType: 'polar',
  62454. index: this.option.polarIndex,
  62455. id: this.option.polarId
  62456. })[0];
  62457. }
  62458. });
  62459. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  62460. var polarAxisDefaultExtendedOption = {
  62461. angle: {
  62462. // polarIndex: 0,
  62463. // polarId: '',
  62464. startAngle: 90,
  62465. clockwise: true,
  62466. splitNumber: 12,
  62467. axisLabel: {
  62468. rotate: false
  62469. }
  62470. },
  62471. radius: {
  62472. // polarIndex: 0,
  62473. // polarId: '',
  62474. splitNumber: 5
  62475. }
  62476. };
  62477. function getAxisType$3(axisDim, option) {
  62478. // Default axis with data is category axis
  62479. return option.type || (option.data ? 'category' : 'value');
  62480. }
  62481. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  62482. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  62483. /*
  62484. * Licensed to the Apache Software Foundation (ASF) under one
  62485. * or more contributor license agreements. See the NOTICE file
  62486. * distributed with this work for additional information
  62487. * regarding copyright ownership. The ASF licenses this file
  62488. * to you under the Apache License, Version 2.0 (the
  62489. * "License"); you may not use this file except in compliance
  62490. * with the License. You may obtain a copy of the License at
  62491. *
  62492. * http://www.apache.org/licenses/LICENSE-2.0
  62493. *
  62494. * Unless required by applicable law or agreed to in writing,
  62495. * software distributed under the License is distributed on an
  62496. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62497. * KIND, either express or implied. See the License for the
  62498. * specific language governing permissions and limitations
  62499. * under the License.
  62500. */
  62501. extendComponentModel({
  62502. type: 'polar',
  62503. dependencies: ['polarAxis', 'angleAxis'],
  62504. /**
  62505. * @type {module:echarts/coord/polar/Polar}
  62506. */
  62507. coordinateSystem: null,
  62508. /**
  62509. * @param {string} axisType
  62510. * @return {module:echarts/coord/polar/AxisModel}
  62511. */
  62512. findAxisModel: function (axisType) {
  62513. var foundAxisModel;
  62514. var ecModel = this.ecModel;
  62515. ecModel.eachComponent(axisType, function (axisModel) {
  62516. if (axisModel.getCoordSysModel() === this) {
  62517. foundAxisModel = axisModel;
  62518. }
  62519. }, this);
  62520. return foundAxisModel;
  62521. },
  62522. defaultOption: {
  62523. zlevel: 0,
  62524. z: 0,
  62525. center: ['50%', '50%'],
  62526. radius: '80%'
  62527. }
  62528. });
  62529. /*
  62530. * Licensed to the Apache Software Foundation (ASF) under one
  62531. * or more contributor license agreements. See the NOTICE file
  62532. * distributed with this work for additional information
  62533. * regarding copyright ownership. The ASF licenses this file
  62534. * to you under the Apache License, Version 2.0 (the
  62535. * "License"); you may not use this file except in compliance
  62536. * with the License. You may obtain a copy of the License at
  62537. *
  62538. * http://www.apache.org/licenses/LICENSE-2.0
  62539. *
  62540. * Unless required by applicable law or agreed to in writing,
  62541. * software distributed under the License is distributed on an
  62542. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62543. * KIND, either express or implied. See the License for the
  62544. * specific language governing permissions and limitations
  62545. * under the License.
  62546. */
  62547. // TODO Axis scale
  62548. /**
  62549. * Resize method bound to the polar
  62550. * @param {module:echarts/coord/polar/PolarModel} polarModel
  62551. * @param {module:echarts/ExtensionAPI} api
  62552. */
  62553. function resizePolar(polar, polarModel, api) {
  62554. var center = polarModel.get('center');
  62555. var width = api.getWidth();
  62556. var height = api.getHeight();
  62557. polar.cx = parsePercent$1(center[0], width);
  62558. polar.cy = parsePercent$1(center[1], height);
  62559. var radiusAxis = polar.getRadiusAxis();
  62560. var size = Math.min(width, height) / 2;
  62561. var radius = parsePercent$1(polarModel.get('radius'), size);
  62562. radiusAxis.inverse
  62563. ? radiusAxis.setExtent(radius, 0)
  62564. : radiusAxis.setExtent(0, radius);
  62565. }
  62566. /**
  62567. * Update polar
  62568. */
  62569. function updatePolarScale(ecModel, api) {
  62570. var polar = this;
  62571. var angleAxis = polar.getAngleAxis();
  62572. var radiusAxis = polar.getRadiusAxis();
  62573. // Reset scale
  62574. angleAxis.scale.setExtent(Infinity, -Infinity);
  62575. radiusAxis.scale.setExtent(Infinity, -Infinity);
  62576. ecModel.eachSeries(function (seriesModel) {
  62577. if (seriesModel.coordinateSystem === polar) {
  62578. var data = seriesModel.getData();
  62579. each$1(data.mapDimension('radius', true), function (dim) {
  62580. radiusAxis.scale.unionExtentFromData(
  62581. data, getStackedDimension(data, dim)
  62582. );
  62583. });
  62584. each$1(data.mapDimension('angle', true), function (dim) {
  62585. angleAxis.scale.unionExtentFromData(
  62586. data, getStackedDimension(data, dim)
  62587. );
  62588. });
  62589. }
  62590. });
  62591. niceScaleExtent(angleAxis.scale, angleAxis.model);
  62592. niceScaleExtent(radiusAxis.scale, radiusAxis.model);
  62593. // Fix extent of category angle axis
  62594. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  62595. var extent = angleAxis.getExtent();
  62596. var diff = 360 / angleAxis.scale.count();
  62597. angleAxis.inverse ? (extent[1] += diff) : (extent[1] -= diff);
  62598. angleAxis.setExtent(extent[0], extent[1]);
  62599. }
  62600. }
  62601. /**
  62602. * Set common axis properties
  62603. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  62604. * @param {module:echarts/coord/polar/AxisModel}
  62605. * @inner
  62606. */
  62607. function setAxis(axis, axisModel) {
  62608. axis.type = axisModel.get('type');
  62609. axis.scale = createScaleByModel(axisModel);
  62610. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  62611. axis.inverse = axisModel.get('inverse');
  62612. if (axisModel.mainType === 'angleAxis') {
  62613. axis.inverse ^= axisModel.get('clockwise');
  62614. var startAngle = axisModel.get('startAngle');
  62615. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  62616. }
  62617. // Inject axis instance
  62618. axisModel.axis = axis;
  62619. axis.model = axisModel;
  62620. }
  62621. var polarCreator = {
  62622. dimensions: Polar.prototype.dimensions,
  62623. create: function (ecModel, api) {
  62624. var polarList = [];
  62625. ecModel.eachComponent('polar', function (polarModel, idx) {
  62626. var polar = new Polar(idx);
  62627. // Inject resize and update method
  62628. polar.update = updatePolarScale;
  62629. var radiusAxis = polar.getRadiusAxis();
  62630. var angleAxis = polar.getAngleAxis();
  62631. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  62632. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  62633. setAxis(radiusAxis, radiusAxisModel);
  62634. setAxis(angleAxis, angleAxisModel);
  62635. resizePolar(polar, polarModel, api);
  62636. polarList.push(polar);
  62637. polarModel.coordinateSystem = polar;
  62638. polar.model = polarModel;
  62639. });
  62640. // Inject coordinateSystem to series
  62641. ecModel.eachSeries(function (seriesModel) {
  62642. if (seriesModel.get('coordinateSystem') === 'polar') {
  62643. var polarModel = ecModel.queryComponents({
  62644. mainType: 'polar',
  62645. index: seriesModel.get('polarIndex'),
  62646. id: seriesModel.get('polarId')
  62647. })[0];
  62648. if (__DEV__) {
  62649. if (!polarModel) {
  62650. throw new Error(
  62651. 'Polar "' + retrieve(
  62652. seriesModel.get('polarIndex'),
  62653. seriesModel.get('polarId'),
  62654. 0
  62655. ) + '" not found'
  62656. );
  62657. }
  62658. }
  62659. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  62660. }
  62661. });
  62662. return polarList;
  62663. }
  62664. };
  62665. CoordinateSystemManager.register('polar', polarCreator);
  62666. /*
  62667. * Licensed to the Apache Software Foundation (ASF) under one
  62668. * or more contributor license agreements. See the NOTICE file
  62669. * distributed with this work for additional information
  62670. * regarding copyright ownership. The ASF licenses this file
  62671. * to you under the Apache License, Version 2.0 (the
  62672. * "License"); you may not use this file except in compliance
  62673. * with the License. You may obtain a copy of the License at
  62674. *
  62675. * http://www.apache.org/licenses/LICENSE-2.0
  62676. *
  62677. * Unless required by applicable law or agreed to in writing,
  62678. * software distributed under the License is distributed on an
  62679. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62680. * KIND, either express or implied. See the License for the
  62681. * specific language governing permissions and limitations
  62682. * under the License.
  62683. */
  62684. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'splitLine', 'splitArea'];
  62685. function getAxisLineShape(polar, rExtent, angle) {
  62686. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  62687. var start = polar.coordToPoint([rExtent[0], angle]);
  62688. var end = polar.coordToPoint([rExtent[1], angle]);
  62689. return {
  62690. x1: start[0],
  62691. y1: start[1],
  62692. x2: end[0],
  62693. y2: end[1]
  62694. };
  62695. }
  62696. function getRadiusIdx(polar) {
  62697. var radiusAxis = polar.getRadiusAxis();
  62698. return radiusAxis.inverse ? 0 : 1;
  62699. }
  62700. // Remove the last tick which will overlap the first tick
  62701. function fixAngleOverlap(list) {
  62702. var firstItem = list[0];
  62703. var lastItem = list[list.length - 1];
  62704. if (firstItem
  62705. && lastItem
  62706. && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4
  62707. ) {
  62708. list.pop();
  62709. }
  62710. }
  62711. AxisView.extend({
  62712. type: 'angleAxis',
  62713. axisPointerClass: 'PolarAxisPointer',
  62714. render: function (angleAxisModel, ecModel) {
  62715. this.group.removeAll();
  62716. if (!angleAxisModel.get('show')) {
  62717. return;
  62718. }
  62719. var angleAxis = angleAxisModel.axis;
  62720. var polar = angleAxis.polar;
  62721. var radiusExtent = polar.getRadiusAxis().getExtent();
  62722. var ticksAngles = angleAxis.getTicksCoords();
  62723. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  62724. var labelItem = clone(labelItem);
  62725. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  62726. return labelItem;
  62727. });
  62728. fixAngleOverlap(labels);
  62729. fixAngleOverlap(ticksAngles);
  62730. each$1(elementList$1, function (name) {
  62731. if (angleAxisModel.get(name +'.show')
  62732. && (!angleAxis.scale.isBlank() || name === 'axisLine')
  62733. ) {
  62734. this['_' + name](angleAxisModel, polar, ticksAngles, radiusExtent, labels);
  62735. }
  62736. }, this);
  62737. },
  62738. /**
  62739. * @private
  62740. */
  62741. _axisLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62742. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle');
  62743. var circle = new Circle({
  62744. shape: {
  62745. cx: polar.cx,
  62746. cy: polar.cy,
  62747. r: radiusExtent[getRadiusIdx(polar)]
  62748. },
  62749. style: lineStyleModel.getLineStyle(),
  62750. z2: 1,
  62751. silent: true
  62752. });
  62753. circle.style.fill = null;
  62754. this.group.add(circle);
  62755. },
  62756. /**
  62757. * @private
  62758. */
  62759. _axisTick: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62760. var tickModel = angleAxisModel.getModel('axisTick');
  62761. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  62762. var radius = radiusExtent[getRadiusIdx(polar)];
  62763. var lines = map(ticksAngles, function (tickAngleItem) {
  62764. return new Line({
  62765. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  62766. });
  62767. });
  62768. this.group.add(mergePath(
  62769. lines, {
  62770. style: defaults(
  62771. tickModel.getModel('lineStyle').getLineStyle(),
  62772. {
  62773. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  62774. }
  62775. )
  62776. }
  62777. ));
  62778. },
  62779. /**
  62780. * @private
  62781. */
  62782. _axisLabel: function (angleAxisModel, polar, ticksAngles, radiusExtent, labels) {
  62783. var rawCategoryData = angleAxisModel.getCategories(true);
  62784. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  62785. var labelMargin = commonLabelModel.get('margin');
  62786. // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  62787. each$1(labels, function (labelItem, idx) {
  62788. var labelModel = commonLabelModel;
  62789. var tickValue = labelItem.tickValue;
  62790. var r = radiusExtent[getRadiusIdx(polar)];
  62791. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  62792. var cx = polar.cx;
  62793. var cy = polar.cy;
  62794. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3
  62795. ? 'center' : (p[0] > cx ? 'left' : 'right');
  62796. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3
  62797. ? 'middle' : (p[1] > cy ? 'top' : 'bottom');
  62798. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  62799. labelModel = new Model(rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel);
  62800. }
  62801. var textEl = new Text({silent: true});
  62802. this.group.add(textEl);
  62803. setTextStyle(textEl.style, labelModel, {
  62804. x: p[0],
  62805. y: p[1],
  62806. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  62807. text: labelItem.formattedLabel,
  62808. textAlign: labelTextAlign,
  62809. textVerticalAlign: labelTextVerticalAlign
  62810. });
  62811. }, this);
  62812. },
  62813. /**
  62814. * @private
  62815. */
  62816. _splitLine: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62817. var splitLineModel = angleAxisModel.getModel('splitLine');
  62818. var lineStyleModel = splitLineModel.getModel('lineStyle');
  62819. var lineColors = lineStyleModel.get('color');
  62820. var lineCount = 0;
  62821. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  62822. var splitLines = [];
  62823. for (var i = 0; i < ticksAngles.length; i++) {
  62824. var colorIndex = (lineCount++) % lineColors.length;
  62825. splitLines[colorIndex] = splitLines[colorIndex] || [];
  62826. splitLines[colorIndex].push(new Line({
  62827. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  62828. }));
  62829. }
  62830. // Simple optimization
  62831. // Batching the lines if color are the same
  62832. for (var i = 0; i < splitLines.length; i++) {
  62833. this.group.add(mergePath(splitLines[i], {
  62834. style: defaults({
  62835. stroke: lineColors[i % lineColors.length]
  62836. }, lineStyleModel.getLineStyle()),
  62837. silent: true,
  62838. z: angleAxisModel.get('z')
  62839. }));
  62840. }
  62841. },
  62842. /**
  62843. * @private
  62844. */
  62845. _splitArea: function (angleAxisModel, polar, ticksAngles, radiusExtent) {
  62846. if (!ticksAngles.length) {
  62847. return;
  62848. }
  62849. var splitAreaModel = angleAxisModel.getModel('splitArea');
  62850. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  62851. var areaColors = areaStyleModel.get('color');
  62852. var lineCount = 0;
  62853. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  62854. var splitAreas = [];
  62855. var RADIAN = Math.PI / 180;
  62856. var prevAngle = -ticksAngles[0].coord * RADIAN;
  62857. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  62858. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  62859. var clockwise = angleAxisModel.get('clockwise');
  62860. for (var i = 1; i < ticksAngles.length; i++) {
  62861. var colorIndex = (lineCount++) % areaColors.length;
  62862. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  62863. splitAreas[colorIndex].push(new Sector({
  62864. shape: {
  62865. cx: polar.cx,
  62866. cy: polar.cy,
  62867. r0: r0,
  62868. r: r1,
  62869. startAngle: prevAngle,
  62870. endAngle: -ticksAngles[i].coord * RADIAN,
  62871. clockwise: clockwise
  62872. },
  62873. silent: true
  62874. }));
  62875. prevAngle = -ticksAngles[i].coord * RADIAN;
  62876. }
  62877. // Simple optimization
  62878. // Batching the lines if color are the same
  62879. for (var i = 0; i < splitAreas.length; i++) {
  62880. this.group.add(mergePath(splitAreas[i], {
  62881. style: defaults({
  62882. fill: areaColors[i % areaColors.length]
  62883. }, areaStyleModel.getAreaStyle()),
  62884. silent: true
  62885. }));
  62886. }
  62887. }
  62888. });
  62889. /*
  62890. * Licensed to the Apache Software Foundation (ASF) under one
  62891. * or more contributor license agreements. See the NOTICE file
  62892. * distributed with this work for additional information
  62893. * regarding copyright ownership. The ASF licenses this file
  62894. * to you under the Apache License, Version 2.0 (the
  62895. * "License"); you may not use this file except in compliance
  62896. * with the License. You may obtain a copy of the License at
  62897. *
  62898. * http://www.apache.org/licenses/LICENSE-2.0
  62899. *
  62900. * Unless required by applicable law or agreed to in writing,
  62901. * software distributed under the License is distributed on an
  62902. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62903. * KIND, either express or implied. See the License for the
  62904. * specific language governing permissions and limitations
  62905. * under the License.
  62906. */
  62907. /*
  62908. * Licensed to the Apache Software Foundation (ASF) under one
  62909. * or more contributor license agreements. See the NOTICE file
  62910. * distributed with this work for additional information
  62911. * regarding copyright ownership. The ASF licenses this file
  62912. * to you under the Apache License, Version 2.0 (the
  62913. * "License"); you may not use this file except in compliance
  62914. * with the License. You may obtain a copy of the License at
  62915. *
  62916. * http://www.apache.org/licenses/LICENSE-2.0
  62917. *
  62918. * Unless required by applicable law or agreed to in writing,
  62919. * software distributed under the License is distributed on an
  62920. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62921. * KIND, either express or implied. See the License for the
  62922. * specific language governing permissions and limitations
  62923. * under the License.
  62924. */
  62925. var axisBuilderAttrs$3 = [
  62926. 'axisLine', 'axisTickLabel', 'axisName'
  62927. ];
  62928. var selfBuilderAttrs$1 = [
  62929. 'splitLine', 'splitArea'
  62930. ];
  62931. AxisView.extend({
  62932. type: 'radiusAxis',
  62933. axisPointerClass: 'PolarAxisPointer',
  62934. render: function (radiusAxisModel, ecModel) {
  62935. this.group.removeAll();
  62936. if (!radiusAxisModel.get('show')) {
  62937. return;
  62938. }
  62939. var radiusAxis = radiusAxisModel.axis;
  62940. var polar = radiusAxis.polar;
  62941. var angleAxis = polar.getAngleAxis();
  62942. var ticksCoords = radiusAxis.getTicksCoords();
  62943. var axisAngle = angleAxis.getExtent()[0];
  62944. var radiusExtent = radiusAxis.getExtent();
  62945. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  62946. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  62947. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  62948. this.group.add(axisBuilder.getGroup());
  62949. each$1(selfBuilderAttrs$1, function (name) {
  62950. if (radiusAxisModel.get(name +'.show') && !radiusAxis.scale.isBlank()) {
  62951. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords);
  62952. }
  62953. }, this);
  62954. },
  62955. /**
  62956. * @private
  62957. */
  62958. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  62959. var splitLineModel = radiusAxisModel.getModel('splitLine');
  62960. var lineStyleModel = splitLineModel.getModel('lineStyle');
  62961. var lineColors = lineStyleModel.get('color');
  62962. var lineCount = 0;
  62963. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  62964. var splitLines = [];
  62965. for (var i = 0; i < ticksCoords.length; i++) {
  62966. var colorIndex = (lineCount++) % lineColors.length;
  62967. splitLines[colorIndex] = splitLines[colorIndex] || [];
  62968. splitLines[colorIndex].push(new Circle({
  62969. shape: {
  62970. cx: polar.cx,
  62971. cy: polar.cy,
  62972. r: ticksCoords[i].coord
  62973. },
  62974. silent: true
  62975. }));
  62976. }
  62977. // Simple optimization
  62978. // Batching the lines if color are the same
  62979. for (var i = 0; i < splitLines.length; i++) {
  62980. this.group.add(mergePath(splitLines[i], {
  62981. style: defaults({
  62982. stroke: lineColors[i % lineColors.length],
  62983. fill: null
  62984. }, lineStyleModel.getLineStyle()),
  62985. silent: true
  62986. }));
  62987. }
  62988. },
  62989. /**
  62990. * @private
  62991. */
  62992. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  62993. if (!ticksCoords.length) {
  62994. return;
  62995. }
  62996. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  62997. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  62998. var areaColors = areaStyleModel.get('color');
  62999. var lineCount = 0;
  63000. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  63001. var splitAreas = [];
  63002. var prevRadius = ticksCoords[0].coord;
  63003. for (var i = 1; i < ticksCoords.length; i++) {
  63004. var colorIndex = (lineCount++) % areaColors.length;
  63005. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  63006. splitAreas[colorIndex].push(new Sector({
  63007. shape: {
  63008. cx: polar.cx,
  63009. cy: polar.cy,
  63010. r0: prevRadius,
  63011. r: ticksCoords[i].coord,
  63012. startAngle: 0,
  63013. endAngle: Math.PI * 2
  63014. },
  63015. silent: true
  63016. }));
  63017. prevRadius = ticksCoords[i].coord;
  63018. }
  63019. // Simple optimization
  63020. // Batching the lines if color are the same
  63021. for (var i = 0; i < splitAreas.length; i++) {
  63022. this.group.add(mergePath(splitAreas[i], {
  63023. style: defaults({
  63024. fill: areaColors[i % areaColors.length]
  63025. }, areaStyleModel.getAreaStyle()),
  63026. silent: true
  63027. }));
  63028. }
  63029. }
  63030. });
  63031. /**
  63032. * @inner
  63033. */
  63034. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  63035. return {
  63036. position: [polar.cx, polar.cy],
  63037. rotation: axisAngle / 180 * Math.PI,
  63038. labelDirection: -1,
  63039. tickDirection: -1,
  63040. nameDirection: 1,
  63041. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  63042. // Over splitLine and splitArea
  63043. z2: 1
  63044. };
  63045. }
  63046. /*
  63047. * Licensed to the Apache Software Foundation (ASF) under one
  63048. * or more contributor license agreements. See the NOTICE file
  63049. * distributed with this work for additional information
  63050. * regarding copyright ownership. The ASF licenses this file
  63051. * to you under the Apache License, Version 2.0 (the
  63052. * "License"); you may not use this file except in compliance
  63053. * with the License. You may obtain a copy of the License at
  63054. *
  63055. * http://www.apache.org/licenses/LICENSE-2.0
  63056. *
  63057. * Unless required by applicable law or agreed to in writing,
  63058. * software distributed under the License is distributed on an
  63059. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63060. * KIND, either express or implied. See the License for the
  63061. * specific language governing permissions and limitations
  63062. * under the License.
  63063. */
  63064. /*
  63065. * Licensed to the Apache Software Foundation (ASF) under one
  63066. * or more contributor license agreements. See the NOTICE file
  63067. * distributed with this work for additional information
  63068. * regarding copyright ownership. The ASF licenses this file
  63069. * to you under the Apache License, Version 2.0 (the
  63070. * "License"); you may not use this file except in compliance
  63071. * with the License. You may obtain a copy of the License at
  63072. *
  63073. * http://www.apache.org/licenses/LICENSE-2.0
  63074. *
  63075. * Unless required by applicable law or agreed to in writing,
  63076. * software distributed under the License is distributed on an
  63077. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63078. * KIND, either express or implied. See the License for the
  63079. * specific language governing permissions and limitations
  63080. * under the License.
  63081. */
  63082. var PolarAxisPointer = BaseAxisPointer.extend({
  63083. /**
  63084. * @override
  63085. */
  63086. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  63087. var axis = axisModel.axis;
  63088. if (axis.dim === 'angle') {
  63089. this.animationThreshold = Math.PI / 18;
  63090. }
  63091. var polar = axis.polar;
  63092. var otherAxis = polar.getOtherAxis(axis);
  63093. var otherExtent = otherAxis.getExtent();
  63094. var coordValue;
  63095. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  63096. var axisPointerType = axisPointerModel.get('type');
  63097. if (axisPointerType && axisPointerType !== 'none') {
  63098. var elStyle = buildElStyle(axisPointerModel);
  63099. var pointerOption = pointerShapeBuilder$2[axisPointerType](
  63100. axis, polar, coordValue, otherExtent, elStyle
  63101. );
  63102. pointerOption.style = elStyle;
  63103. elOption.graphicKey = pointerOption.type;
  63104. elOption.pointer = pointerOption;
  63105. }
  63106. var labelMargin = axisPointerModel.get('label.margin');
  63107. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  63108. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  63109. }
  63110. // Do not support handle, utill any user requires it.
  63111. });
  63112. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  63113. var axis = axisModel.axis;
  63114. var coord = axis.dataToCoord(value);
  63115. var axisAngle = polar.getAngleAxis().getExtent()[0];
  63116. axisAngle = axisAngle / 180 * Math.PI;
  63117. var radiusExtent = polar.getRadiusAxis().getExtent();
  63118. var position;
  63119. var align;
  63120. var verticalAlign;
  63121. if (axis.dim === 'radius') {
  63122. var transform = create$1();
  63123. rotate(transform, transform, axisAngle);
  63124. translate(transform, transform, [polar.cx, polar.cy]);
  63125. position = applyTransform$1([coord, -labelMargin], transform);
  63126. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  63127. var labelLayout = AxisBuilder.innerTextLayout(
  63128. axisAngle, labelRotation * Math.PI / 180, -1
  63129. );
  63130. align = labelLayout.textAlign;
  63131. verticalAlign = labelLayout.textVerticalAlign;
  63132. }
  63133. else { // angle axis
  63134. var r = radiusExtent[1];
  63135. position = polar.coordToPoint([r + labelMargin, coord]);
  63136. var cx = polar.cx;
  63137. var cy = polar.cy;
  63138. align = Math.abs(position[0] - cx) / r < 0.3
  63139. ? 'center' : (position[0] > cx ? 'left' : 'right');
  63140. verticalAlign = Math.abs(position[1] - cy) / r < 0.3
  63141. ? 'middle' : (position[1] > cy ? 'top' : 'bottom');
  63142. }
  63143. return {
  63144. position: position,
  63145. align: align,
  63146. verticalAlign: verticalAlign
  63147. };
  63148. }
  63149. var pointerShapeBuilder$2 = {
  63150. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  63151. return axis.dim === 'angle'
  63152. ? {
  63153. type: 'Line',
  63154. shape: makeLineShape(
  63155. polar.coordToPoint([otherExtent[0], coordValue]),
  63156. polar.coordToPoint([otherExtent[1], coordValue])
  63157. )
  63158. }
  63159. : {
  63160. type: 'Circle',
  63161. shape: {
  63162. cx: polar.cx,
  63163. cy: polar.cy,
  63164. r: coordValue
  63165. }
  63166. };
  63167. },
  63168. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  63169. var bandWidth = Math.max(1, axis.getBandWidth());
  63170. var radian = Math.PI / 180;
  63171. return axis.dim === 'angle'
  63172. ? {
  63173. type: 'Sector',
  63174. shape: makeSectorShape(
  63175. polar.cx, polar.cy,
  63176. otherExtent[0], otherExtent[1],
  63177. // In ECharts y is negative if angle is positive
  63178. (-coordValue - bandWidth / 2) * radian,
  63179. (-coordValue + bandWidth / 2) * radian
  63180. )
  63181. }
  63182. : {
  63183. type: 'Sector',
  63184. shape: makeSectorShape(
  63185. polar.cx, polar.cy,
  63186. coordValue - bandWidth / 2,
  63187. coordValue + bandWidth / 2,
  63188. 0, Math.PI * 2
  63189. )
  63190. };
  63191. }
  63192. };
  63193. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  63194. /*
  63195. * Licensed to the Apache Software Foundation (ASF) under one
  63196. * or more contributor license agreements. See the NOTICE file
  63197. * distributed with this work for additional information
  63198. * regarding copyright ownership. The ASF licenses this file
  63199. * to you under the Apache License, Version 2.0 (the
  63200. * "License"); you may not use this file except in compliance
  63201. * with the License. You may obtain a copy of the License at
  63202. *
  63203. * http://www.apache.org/licenses/LICENSE-2.0
  63204. *
  63205. * Unless required by applicable law or agreed to in writing,
  63206. * software distributed under the License is distributed on an
  63207. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63208. * KIND, either express or implied. See the License for the
  63209. * specific language governing permissions and limitations
  63210. * under the License.
  63211. */
  63212. // For reducing size of echarts.min, barLayoutPolar is required by polar.
  63213. registerLayout(curry(barLayoutPolar, 'bar'));
  63214. // Polar view
  63215. extendComponentView({
  63216. type: 'polar'
  63217. });
  63218. /*
  63219. * Licensed to the Apache Software Foundation (ASF) under one
  63220. * or more contributor license agreements. See the NOTICE file
  63221. * distributed with this work for additional information
  63222. * regarding copyright ownership. The ASF licenses this file
  63223. * to you under the Apache License, Version 2.0 (the
  63224. * "License"); you may not use this file except in compliance
  63225. * with the License. You may obtain a copy of the License at
  63226. *
  63227. * http://www.apache.org/licenses/LICENSE-2.0
  63228. *
  63229. * Unless required by applicable law or agreed to in writing,
  63230. * software distributed under the License is distributed on an
  63231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63232. * KIND, either express or implied. See the License for the
  63233. * specific language governing permissions and limitations
  63234. * under the License.
  63235. */
  63236. var GeoModel = ComponentModel.extend({
  63237. type: 'geo',
  63238. /**
  63239. * @type {module:echarts/coord/geo/Geo}
  63240. */
  63241. coordinateSystem: null,
  63242. layoutMode: 'box',
  63243. init: function (option) {
  63244. ComponentModel.prototype.init.apply(this, arguments);
  63245. // Default label emphasis `show`
  63246. defaultEmphasis(option, 'label', ['show']);
  63247. },
  63248. optionUpdated: function () {
  63249. var option = this.option;
  63250. var self = this;
  63251. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  63252. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  63253. if (regionOpt.name) {
  63254. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  63255. }
  63256. return optionModelMap;
  63257. }, createHashMap());
  63258. this.updateSelectedMap(option.regions);
  63259. },
  63260. defaultOption: {
  63261. zlevel: 0,
  63262. z: 0,
  63263. show: true,
  63264. left: 'center',
  63265. top: 'center',
  63266. // width:,
  63267. // height:,
  63268. // right
  63269. // bottom
  63270. // Aspect is width / height. Inited to be geoJson bbox aspect
  63271. // This parameter is used for scale this aspect
  63272. aspectScale: 0.75,
  63273. ///// Layout with center and size
  63274. // If you wan't to put map in a fixed size box with right aspect ratio
  63275. // This two properties may more conveninet
  63276. // layoutCenter: [50%, 50%]
  63277. // layoutSize: 100
  63278. silent: false,
  63279. // Map type
  63280. map: '',
  63281. // Define left-top, right-bottom coords to control view
  63282. // For example, [ [180, 90], [-180, -90] ]
  63283. boundingCoords: null,
  63284. // Default on center of map
  63285. center: null,
  63286. zoom: 1,
  63287. scaleLimit: null,
  63288. // selectedMode: false
  63289. label: {
  63290. show: false,
  63291. color: '#000'
  63292. },
  63293. itemStyle: {
  63294. // color: 各异,
  63295. borderWidth: 0.5,
  63296. borderColor: '#444',
  63297. color: '#eee'
  63298. },
  63299. emphasis: {
  63300. label: {
  63301. show: true,
  63302. color: 'rgb(100,0,0)'
  63303. },
  63304. itemStyle: {
  63305. color: 'rgba(255,215,0,0.8)'
  63306. }
  63307. },
  63308. regions: []
  63309. },
  63310. /**
  63311. * Get model of region
  63312. * @param {string} name
  63313. * @return {module:echarts/model/Model}
  63314. */
  63315. getRegionModel: function (name) {
  63316. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  63317. },
  63318. /**
  63319. * Format label
  63320. * @param {string} name Region name
  63321. * @param {string} [status='normal'] 'normal' or 'emphasis'
  63322. * @return {string}
  63323. */
  63324. getFormattedLabel: function (name, status) {
  63325. var regionModel = this.getRegionModel(name);
  63326. var formatter = regionModel.get('label.' + status + '.formatter');
  63327. var params = {
  63328. name: name
  63329. };
  63330. if (typeof formatter === 'function') {
  63331. params.status = status;
  63332. return formatter(params);
  63333. }
  63334. else if (typeof formatter === 'string') {
  63335. return formatter.replace('{a}', name != null ? name : '');
  63336. }
  63337. },
  63338. setZoom: function (zoom) {
  63339. this.option.zoom = zoom;
  63340. },
  63341. setCenter: function (center) {
  63342. this.option.center = center;
  63343. }
  63344. });
  63345. mixin(GeoModel, selectableMixin);
  63346. /*
  63347. * Licensed to the Apache Software Foundation (ASF) under one
  63348. * or more contributor license agreements. See the NOTICE file
  63349. * distributed with this work for additional information
  63350. * regarding copyright ownership. The ASF licenses this file
  63351. * to you under the Apache License, Version 2.0 (the
  63352. * "License"); you may not use this file except in compliance
  63353. * with the License. You may obtain a copy of the License at
  63354. *
  63355. * http://www.apache.org/licenses/LICENSE-2.0
  63356. *
  63357. * Unless required by applicable law or agreed to in writing,
  63358. * software distributed under the License is distributed on an
  63359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63360. * KIND, either express or implied. See the License for the
  63361. * specific language governing permissions and limitations
  63362. * under the License.
  63363. */
  63364. extendComponentView({
  63365. type: 'geo',
  63366. init: function (ecModel, api) {
  63367. var mapDraw = new MapDraw(api, true);
  63368. this._mapDraw = mapDraw;
  63369. this.group.add(mapDraw.group);
  63370. },
  63371. render: function (geoModel, ecModel, api, payload) {
  63372. // Not render if it is an toggleSelect action from self
  63373. if (payload && payload.type === 'geoToggleSelect'
  63374. && payload.from === this.uid
  63375. ) {
  63376. return;
  63377. }
  63378. var mapDraw = this._mapDraw;
  63379. if (geoModel.get('show')) {
  63380. mapDraw.draw(geoModel, ecModel, api, this, payload);
  63381. }
  63382. else {
  63383. this._mapDraw.group.removeAll();
  63384. }
  63385. this.group.silent = geoModel.get('silent');
  63386. },
  63387. dispose: function () {
  63388. this._mapDraw && this._mapDraw.remove();
  63389. }
  63390. });
  63391. /*
  63392. * Licensed to the Apache Software Foundation (ASF) under one
  63393. * or more contributor license agreements. See the NOTICE file
  63394. * distributed with this work for additional information
  63395. * regarding copyright ownership. The ASF licenses this file
  63396. * to you under the Apache License, Version 2.0 (the
  63397. * "License"); you may not use this file except in compliance
  63398. * with the License. You may obtain a copy of the License at
  63399. *
  63400. * http://www.apache.org/licenses/LICENSE-2.0
  63401. *
  63402. * Unless required by applicable law or agreed to in writing,
  63403. * software distributed under the License is distributed on an
  63404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63405. * KIND, either express or implied. See the License for the
  63406. * specific language governing permissions and limitations
  63407. * under the License.
  63408. */
  63409. function makeAction(method, actionInfo) {
  63410. actionInfo.update = 'updateView';
  63411. registerAction(actionInfo, function (payload, ecModel) {
  63412. var selected = {};
  63413. ecModel.eachComponent(
  63414. { mainType: 'geo', query: payload},
  63415. function (geoModel) {
  63416. geoModel[method](payload.name);
  63417. var geo = geoModel.coordinateSystem;
  63418. each$1(geo.regions, function (region) {
  63419. selected[region.name] = geoModel.isSelected(region.name) || false;
  63420. });
  63421. }
  63422. );
  63423. return {
  63424. selected: selected,
  63425. name: payload.name
  63426. };
  63427. });
  63428. }
  63429. makeAction('toggleSelected', {
  63430. type: 'geoToggleSelect',
  63431. event: 'geoselectchanged'
  63432. });
  63433. makeAction('select', {
  63434. type: 'geoSelect',
  63435. event: 'geoselected'
  63436. });
  63437. makeAction('unSelect', {
  63438. type: 'geoUnSelect',
  63439. event: 'geounselected'
  63440. });
  63441. /*
  63442. * Licensed to the Apache Software Foundation (ASF) under one
  63443. * or more contributor license agreements. See the NOTICE file
  63444. * distributed with this work for additional information
  63445. * regarding copyright ownership. The ASF licenses this file
  63446. * to you under the Apache License, Version 2.0 (the
  63447. * "License"); you may not use this file except in compliance
  63448. * with the License. You may obtain a copy of the License at
  63449. *
  63450. * http://www.apache.org/licenses/LICENSE-2.0
  63451. *
  63452. * Unless required by applicable law or agreed to in writing,
  63453. * software distributed under the License is distributed on an
  63454. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63455. * KIND, either express or implied. See the License for the
  63456. * specific language governing permissions and limitations
  63457. * under the License.
  63458. */
  63459. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  63460. var preprocessor$1 = function (option, isNew) {
  63461. var brushComponents = option && option.brush;
  63462. if (!isArray(brushComponents)) {
  63463. brushComponents = brushComponents ? [brushComponents] : [];
  63464. }
  63465. if (!brushComponents.length) {
  63466. return;
  63467. }
  63468. var brushComponentSpecifiedBtns = [];
  63469. each$1(brushComponents, function (brushOpt) {
  63470. var tbs = brushOpt.hasOwnProperty('toolbox')
  63471. ? brushOpt.toolbox : [];
  63472. if (tbs instanceof Array) {
  63473. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  63474. }
  63475. });
  63476. var toolbox = option && option.toolbox;
  63477. if (isArray(toolbox)) {
  63478. toolbox = toolbox[0];
  63479. }
  63480. if (!toolbox) {
  63481. toolbox = {feature: {}};
  63482. option.toolbox = [toolbox];
  63483. }
  63484. var toolboxFeature = (toolbox.feature || (toolbox.feature = {}));
  63485. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  63486. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  63487. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  63488. removeDuplicate(brushTypes);
  63489. if (isNew && !brushTypes.length) {
  63490. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  63491. }
  63492. };
  63493. function removeDuplicate(arr) {
  63494. var map$$1 = {};
  63495. each$1(arr, function (val) {
  63496. map$$1[val] = 1;
  63497. });
  63498. arr.length = 0;
  63499. each$1(map$$1, function (flag, val) {
  63500. arr.push(val);
  63501. });
  63502. }
  63503. /*
  63504. * Licensed to the Apache Software Foundation (ASF) under one
  63505. * or more contributor license agreements. See the NOTICE file
  63506. * distributed with this work for additional information
  63507. * regarding copyright ownership. The ASF licenses this file
  63508. * to you under the Apache License, Version 2.0 (the
  63509. * "License"); you may not use this file except in compliance
  63510. * with the License. You may obtain a copy of the License at
  63511. *
  63512. * http://www.apache.org/licenses/LICENSE-2.0
  63513. *
  63514. * Unless required by applicable law or agreed to in writing,
  63515. * software distributed under the License is distributed on an
  63516. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63517. * KIND, either express or implied. See the License for the
  63518. * specific language governing permissions and limitations
  63519. * under the License.
  63520. */
  63521. /**
  63522. * @file Visual solution, for consistent option specification.
  63523. */
  63524. var each$19 = each$1;
  63525. function hasKeys(obj) {
  63526. if (obj) {
  63527. for (var name in obj){
  63528. if (obj.hasOwnProperty(name)) {
  63529. return true;
  63530. }
  63531. }
  63532. }
  63533. }
  63534. /**
  63535. * @param {Object} option
  63536. * @param {Array.<string>} stateList
  63537. * @param {Function} [supplementVisualOption]
  63538. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  63539. */
  63540. function createVisualMappings(option, stateList, supplementVisualOption) {
  63541. var visualMappings = {};
  63542. each$19(stateList, function (state) {
  63543. var mappings = visualMappings[state] = createMappings();
  63544. each$19(option[state], function (visualData, visualType) {
  63545. if (!VisualMapping.isValidType(visualType)) {
  63546. return;
  63547. }
  63548. var mappingOption = {
  63549. type: visualType,
  63550. visual: visualData
  63551. };
  63552. supplementVisualOption && supplementVisualOption(mappingOption, state);
  63553. mappings[visualType] = new VisualMapping(mappingOption);
  63554. // Prepare a alpha for opacity, for some case that opacity
  63555. // is not supported, such as rendering using gradient color.
  63556. if (visualType === 'opacity') {
  63557. mappingOption = clone(mappingOption);
  63558. mappingOption.type = 'colorAlpha';
  63559. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  63560. }
  63561. });
  63562. });
  63563. return visualMappings;
  63564. function createMappings() {
  63565. var Creater = function () {};
  63566. // Make sure hidden fields will not be visited by
  63567. // object iteration (with hasOwnProperty checking).
  63568. Creater.prototype.__hidden = Creater.prototype;
  63569. var obj = new Creater();
  63570. return obj;
  63571. }
  63572. }
  63573. /**
  63574. * @param {Object} thisOption
  63575. * @param {Object} newOption
  63576. * @param {Array.<string>} keys
  63577. */
  63578. function replaceVisualOption(thisOption, newOption, keys) {
  63579. // Visual attributes merge is not supported, otherwise it
  63580. // brings overcomplicated merge logic. See #2853. So if
  63581. // newOption has anyone of these keys, all of these keys
  63582. // will be reset. Otherwise, all keys remain.
  63583. var has;
  63584. each$1(keys, function (key) {
  63585. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  63586. has = true;
  63587. }
  63588. });
  63589. has && each$1(keys, function (key) {
  63590. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  63591. thisOption[key] = clone(newOption[key]);
  63592. }
  63593. else {
  63594. delete thisOption[key];
  63595. }
  63596. });
  63597. }
  63598. /**
  63599. * @param {Array.<string>} stateList
  63600. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  63601. * @param {module:echarts/data/List} list
  63602. * @param {Function} getValueState param: valueOrIndex, return: state.
  63603. * @param {object} [scope] Scope for getValueState
  63604. * @param {string} [dimension] Concrete dimension, if used.
  63605. */
  63606. // ???! handle brush?
  63607. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  63608. var visualTypesMap = {};
  63609. each$1(stateList, function (state) {
  63610. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  63611. visualTypesMap[state] = visualTypes;
  63612. });
  63613. var dataIndex;
  63614. function getVisual(key) {
  63615. return data.getItemVisual(dataIndex, key);
  63616. }
  63617. function setVisual(key, value) {
  63618. data.setItemVisual(dataIndex, key, value);
  63619. }
  63620. if (dimension == null) {
  63621. data.each(eachItem);
  63622. }
  63623. else {
  63624. data.each([dimension], eachItem);
  63625. }
  63626. function eachItem(valueOrIndex, index) {
  63627. dataIndex = dimension == null ? valueOrIndex : index;
  63628. var rawDataItem = data.getRawDataItem(dataIndex);
  63629. // Consider performance
  63630. if (rawDataItem && rawDataItem.visualMap === false) {
  63631. return;
  63632. }
  63633. var valueState = getValueState.call(scope, valueOrIndex);
  63634. var mappings = visualMappings[valueState];
  63635. var visualTypes = visualTypesMap[valueState];
  63636. for (var i = 0, len = visualTypes.length; i < len; i++) {
  63637. var type = visualTypes[i];
  63638. mappings[type] && mappings[type].applyVisual(
  63639. valueOrIndex, getVisual, setVisual
  63640. );
  63641. }
  63642. }
  63643. }
  63644. /**
  63645. * @param {module:echarts/data/List} data
  63646. * @param {Array.<string>} stateList
  63647. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  63648. * @param {Function} getValueState param: valueOrIndex, return: state.
  63649. * @param {number} [dim] dimension or dimension index.
  63650. */
  63651. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  63652. var visualTypesMap = {};
  63653. each$1(stateList, function (state) {
  63654. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  63655. visualTypesMap[state] = visualTypes;
  63656. });
  63657. function progress(params, data) {
  63658. if (dim != null) {
  63659. dim = data.getDimension(dim);
  63660. }
  63661. function getVisual(key) {
  63662. return data.getItemVisual(dataIndex, key);
  63663. }
  63664. function setVisual(key, value) {
  63665. data.setItemVisual(dataIndex, key, value);
  63666. }
  63667. var dataIndex;
  63668. while ((dataIndex = params.next()) != null) {
  63669. var rawDataItem = data.getRawDataItem(dataIndex);
  63670. // Consider performance
  63671. if (rawDataItem && rawDataItem.visualMap === false) {
  63672. return;
  63673. }
  63674. var value = dim != null
  63675. ? data.get(dim, dataIndex, true)
  63676. : dataIndex;
  63677. var valueState = getValueState(value);
  63678. var mappings = visualMappings[valueState];
  63679. var visualTypes = visualTypesMap[valueState];
  63680. for (var i = 0, len = visualTypes.length; i < len; i++) {
  63681. var type = visualTypes[i];
  63682. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  63683. }
  63684. }
  63685. }
  63686. return {progress: progress};
  63687. }
  63688. /*
  63689. * Licensed to the Apache Software Foundation (ASF) under one
  63690. * or more contributor license agreements. See the NOTICE file
  63691. * distributed with this work for additional information
  63692. * regarding copyright ownership. The ASF licenses this file
  63693. * to you under the Apache License, Version 2.0 (the
  63694. * "License"); you may not use this file except in compliance
  63695. * with the License. You may obtain a copy of the License at
  63696. *
  63697. * http://www.apache.org/licenses/LICENSE-2.0
  63698. *
  63699. * Unless required by applicable law or agreed to in writing,
  63700. * software distributed under the License is distributed on an
  63701. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63702. * KIND, either express or implied. See the License for the
  63703. * specific language governing permissions and limitations
  63704. * under the License.
  63705. */
  63706. // Key of the first level is brushType: `line`, `rect`, `polygon`.
  63707. // Key of the second level is chart element type: `point`, `rect`.
  63708. // See moudule:echarts/component/helper/BrushController
  63709. // function param:
  63710. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  63711. // {Object} selectors {point: selector, rect: selector, ...}
  63712. // {Object} area {range: [[], [], ..], boudingRect}
  63713. // function return:
  63714. // {boolean} Whether in the given brush.
  63715. var selector = {
  63716. lineX: getLineSelectors(0),
  63717. lineY: getLineSelectors(1),
  63718. rect: {
  63719. point: function (itemLayout, selectors, area) {
  63720. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  63721. },
  63722. rect: function (itemLayout, selectors, area) {
  63723. return itemLayout && area.boundingRect.intersect(itemLayout);
  63724. }
  63725. },
  63726. polygon: {
  63727. point: function (itemLayout, selectors, area) {
  63728. return itemLayout
  63729. && area.boundingRect.contain(itemLayout[0], itemLayout[1])
  63730. && contain$1(area.range, itemLayout[0], itemLayout[1]);
  63731. },
  63732. rect: function (itemLayout, selectors, area) {
  63733. var points = area.range;
  63734. if (!itemLayout || points.length <= 1) {
  63735. return false;
  63736. }
  63737. var x = itemLayout.x;
  63738. var y = itemLayout.y;
  63739. var width = itemLayout.width;
  63740. var height = itemLayout.height;
  63741. var p = points[0];
  63742. if (contain$1(points, x, y)
  63743. || contain$1(points, x + width, y)
  63744. || contain$1(points, x, y + height)
  63745. || contain$1(points, x + width, y + height)
  63746. || BoundingRect.create(itemLayout).contain(p[0], p[1])
  63747. || lineIntersectPolygon(x, y, x + width, y, points)
  63748. || lineIntersectPolygon(x, y, x, y + height, points)
  63749. || lineIntersectPolygon(x + width, y, x + width, y + height, points)
  63750. || lineIntersectPolygon(x, y + height, x + width, y + height, points)
  63751. ) {
  63752. return true;
  63753. }
  63754. }
  63755. }
  63756. };
  63757. function getLineSelectors(xyIndex) {
  63758. var xy = ['x', 'y'];
  63759. var wh = ['width', 'height'];
  63760. return {
  63761. point: function (itemLayout, selectors, area) {
  63762. if (itemLayout) {
  63763. var range = area.range;
  63764. var p = itemLayout[xyIndex];
  63765. return inLineRange(p, range);
  63766. }
  63767. },
  63768. rect: function (itemLayout, selectors, area) {
  63769. if (itemLayout) {
  63770. var range = area.range;
  63771. var layoutRange = [
  63772. itemLayout[xy[xyIndex]],
  63773. itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]
  63774. ];
  63775. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  63776. return inLineRange(layoutRange[0], range)
  63777. || inLineRange(layoutRange[1], range)
  63778. || inLineRange(range[0], layoutRange)
  63779. || inLineRange(range[1], layoutRange);
  63780. }
  63781. }
  63782. };
  63783. }
  63784. function inLineRange(p, range) {
  63785. return range[0] <= p && p <= range[1];
  63786. }
  63787. function lineIntersectPolygon(lx, ly, l2x, l2y, points) {
  63788. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  63789. var p = points[i];
  63790. if (lineIntersect(lx, ly, l2x, l2y, p[0], p[1], p2[0], p2[1])) {
  63791. return true;
  63792. }
  63793. p2 = p;
  63794. }
  63795. }
  63796. // Code from <http://blog.csdn.net/rickliuxiao/article/details/6259322> with some fix.
  63797. // See <https://en.wikipedia.org/wiki/Line%E2%80%93line_intersection>
  63798. function lineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  63799. var delta = determinant(a2x - a1x, b1x - b2x, a2y - a1y, b1y - b2y);
  63800. if (nearZero(delta)) { // parallel
  63801. return false;
  63802. }
  63803. var namenda = determinant(b1x - a1x, b1x - b2x, b1y - a1y, b1y - b2y) / delta;
  63804. if (namenda < 0 || namenda > 1) {
  63805. return false;
  63806. }
  63807. var miu = determinant(a2x - a1x, b1x - a1x, a2y - a1y, b1y - a1y) / delta;
  63808. if (miu < 0 || miu > 1) {
  63809. return false;
  63810. }
  63811. return true;
  63812. }
  63813. function nearZero(val) {
  63814. return val <= (1e-6) && val >= -(1e-6);
  63815. }
  63816. function determinant(v1, v2, v3, v4) {
  63817. return v1 * v4 - v2 * v3;
  63818. }
  63819. /*
  63820. * Licensed to the Apache Software Foundation (ASF) under one
  63821. * or more contributor license agreements. See the NOTICE file
  63822. * distributed with this work for additional information
  63823. * regarding copyright ownership. The ASF licenses this file
  63824. * to you under the Apache License, Version 2.0 (the
  63825. * "License"); you may not use this file except in compliance
  63826. * with the License. You may obtain a copy of the License at
  63827. *
  63828. * http://www.apache.org/licenses/LICENSE-2.0
  63829. *
  63830. * Unless required by applicable law or agreed to in writing,
  63831. * software distributed under the License is distributed on an
  63832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63833. * KIND, either express or implied. See the License for the
  63834. * specific language governing permissions and limitations
  63835. * under the License.
  63836. */
  63837. var each$20 = each$1;
  63838. var indexOf$1 = indexOf;
  63839. var curry$5 = curry;
  63840. var COORD_CONVERTS = ['dataToPoint', 'pointToData'];
  63841. // FIXME
  63842. // how to genarialize to more coordinate systems.
  63843. var INCLUDE_FINDER_MAIN_TYPES = [
  63844. 'grid', 'xAxis', 'yAxis', 'geo', 'graph',
  63845. 'polar', 'radiusAxis', 'angleAxis', 'bmap'
  63846. ];
  63847. /**
  63848. * [option in constructor]:
  63849. * {
  63850. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  63851. * }
  63852. *
  63853. *
  63854. * [targetInfo]:
  63855. *
  63856. * There can be multiple axes in a single targetInfo. Consider the case
  63857. * of `grid` component, a targetInfo represents a grid which contains one or more
  63858. * cartesian and one or more axes. And consider the case of parallel system,
  63859. * which has multiple axes in a coordinate system.
  63860. * Can be {
  63861. * panelId: ...,
  63862. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  63863. * coordSyses: all cartesians.
  63864. * gridModel: <grid component>
  63865. * xAxes: correspond to coordSyses on index
  63866. * yAxes: correspond to coordSyses on index
  63867. * }
  63868. * or {
  63869. * panelId: ...,
  63870. * coordSys: <geo coord sys>
  63871. * coordSyses: [<geo coord sys>]
  63872. * geoModel: <geo component>
  63873. * }
  63874. *
  63875. *
  63876. * [panelOpt]:
  63877. *
  63878. * Make from targetInfo. Input to BrushController.
  63879. * {
  63880. * panelId: ...,
  63881. * rect: ...
  63882. * }
  63883. *
  63884. *
  63885. * [area]:
  63886. *
  63887. * Generated by BrushController or user input.
  63888. * {
  63889. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  63890. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  63891. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  63892. * range: pixel range.
  63893. * coordRange: representitive coord range (the first one of coordRanges).
  63894. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  63895. * }
  63896. */
  63897. /**
  63898. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  63899. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  63900. * @param {module:echarts/model/Global} ecModel
  63901. * @param {Object} [opt]
  63902. * @param {Array.<string>} [opt.include] include coordinate system types.
  63903. */
  63904. function BrushTargetManager(option, ecModel, opt) {
  63905. /**
  63906. * @private
  63907. * @type {Array.<Object>}
  63908. */
  63909. var targetInfoList = this._targetInfoList = [];
  63910. var info = {};
  63911. var foundCpts = parseFinder$1(ecModel, option);
  63912. each$20(targetInfoBuilders, function (builder, type) {
  63913. if (!opt || !opt.include || indexOf$1(opt.include, type) >= 0) {
  63914. builder(foundCpts, targetInfoList, info);
  63915. }
  63916. });
  63917. }
  63918. var proto$2 = BrushTargetManager.prototype;
  63919. proto$2.setOutputRanges = function (areas, ecModel) {
  63920. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  63921. (area.coordRanges || (area.coordRanges = [])).push(coordRange);
  63922. // area.coordRange is the first of area.coordRanges
  63923. if (!area.coordRange) {
  63924. area.coordRange = coordRange;
  63925. // In 'category' axis, coord to pixel is not reversible, so we can not
  63926. // rebuild range by coordRange accrately, which may bring trouble when
  63927. // brushing only one item. So we use __rangeOffset to rebuilding range
  63928. // by coordRange. And this it only used in brush component so it is no
  63929. // need to be adapted to coordRanges.
  63930. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  63931. area.__rangeOffset = {
  63932. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  63933. xyMinMax: result.xyMinMax
  63934. };
  63935. }
  63936. });
  63937. };
  63938. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  63939. each$20(areas, function (area) {
  63940. var targetInfo = this.findTargetInfo(area, ecModel);
  63941. if (targetInfo && targetInfo !== true) {
  63942. each$1(
  63943. targetInfo.coordSyses,
  63944. function (coordSys) {
  63945. var result = coordConvert[area.brushType](1, coordSys, area.range);
  63946. cb(area, result.values, coordSys, ecModel);
  63947. }
  63948. );
  63949. }
  63950. }, this);
  63951. };
  63952. proto$2.setInputRanges = function (areas, ecModel) {
  63953. each$20(areas, function (area) {
  63954. var targetInfo = this.findTargetInfo(area, ecModel);
  63955. if (__DEV__) {
  63956. assert$1(
  63957. !targetInfo || targetInfo === true || area.coordRange,
  63958. 'coordRange must be specified when coord index specified.'
  63959. );
  63960. assert$1(
  63961. !targetInfo || targetInfo !== true || area.range,
  63962. 'range must be specified in global brush.'
  63963. );
  63964. }
  63965. area.range = area.range || [];
  63966. // convert coordRange to global range and set panelId.
  63967. if (targetInfo && targetInfo !== true) {
  63968. area.panelId = targetInfo.panelId;
  63969. // (1) area.range shoule always be calculate from coordRange but does
  63970. // not keep its original value, for the sake of the dataZoom scenario,
  63971. // where area.coordRange remains unchanged but area.range may be changed.
  63972. // (2) Only support converting one coordRange to pixel range in brush
  63973. // component. So do not consider `coordRanges`.
  63974. // (3) About __rangeOffset, see comment above.
  63975. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  63976. var rangeOffset = area.__rangeOffset;
  63977. area.range = rangeOffset
  63978. ? diffProcessor[area.brushType](
  63979. result.values,
  63980. rangeOffset.offset,
  63981. getScales(result.xyMinMax, rangeOffset.xyMinMax)
  63982. )
  63983. : result.values;
  63984. }
  63985. }, this);
  63986. };
  63987. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  63988. return map(this._targetInfoList, function (targetInfo) {
  63989. var rect = targetInfo.getPanelRect();
  63990. return {
  63991. panelId: targetInfo.panelId,
  63992. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  63993. clipPath: makeRectPanelClipPath(rect),
  63994. isTargetByCursor: makeRectIsTargetByCursor(
  63995. rect, api, targetInfo.coordSysModel
  63996. ),
  63997. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  63998. };
  63999. });
  64000. };
  64001. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  64002. // Check whether area is bound in coord, and series do not belong to that coord.
  64003. // If do not do this check, some brush (like lineX) will controll all axes.
  64004. var targetInfo = this.findTargetInfo(area, ecModel);
  64005. return targetInfo === true || (
  64006. targetInfo && indexOf$1(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0
  64007. );
  64008. };
  64009. /**
  64010. * If return Object, a coord found.
  64011. * If reutrn true, global found.
  64012. * Otherwise nothing found.
  64013. *
  64014. * @param {Object} area
  64015. * @param {Array} targetInfoList
  64016. * @return {Object|boolean}
  64017. */
  64018. proto$2.findTargetInfo = function (area, ecModel) {
  64019. var targetInfoList = this._targetInfoList;
  64020. var foundCpts = parseFinder$1(ecModel, area);
  64021. for (var i = 0; i < targetInfoList.length; i++) {
  64022. var targetInfo = targetInfoList[i];
  64023. var areaPanelId = area.panelId;
  64024. if (areaPanelId) {
  64025. if (targetInfo.panelId === areaPanelId) {
  64026. return targetInfo;
  64027. }
  64028. }
  64029. else {
  64030. for (var i = 0; i < targetInfoMatchers.length; i++) {
  64031. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  64032. return targetInfo;
  64033. }
  64034. }
  64035. }
  64036. }
  64037. return true;
  64038. };
  64039. function formatMinMax(minMax) {
  64040. minMax[0] > minMax[1] && minMax.reverse();
  64041. return minMax;
  64042. }
  64043. function parseFinder$1(ecModel, option) {
  64044. return parseFinder(
  64045. ecModel, option, {includeMainTypes: INCLUDE_FINDER_MAIN_TYPES}
  64046. );
  64047. }
  64048. var targetInfoBuilders = {
  64049. grid: function (foundCpts, targetInfoList) {
  64050. var xAxisModels = foundCpts.xAxisModels;
  64051. var yAxisModels = foundCpts.yAxisModels;
  64052. var gridModels = foundCpts.gridModels;
  64053. // Remove duplicated.
  64054. var gridModelMap = createHashMap();
  64055. var xAxesHas = {};
  64056. var yAxesHas = {};
  64057. if (!xAxisModels && !yAxisModels && !gridModels) {
  64058. return;
  64059. }
  64060. each$20(xAxisModels, function (axisModel) {
  64061. var gridModel = axisModel.axis.grid.model;
  64062. gridModelMap.set(gridModel.id, gridModel);
  64063. xAxesHas[gridModel.id] = true;
  64064. });
  64065. each$20(yAxisModels, function (axisModel) {
  64066. var gridModel = axisModel.axis.grid.model;
  64067. gridModelMap.set(gridModel.id, gridModel);
  64068. yAxesHas[gridModel.id] = true;
  64069. });
  64070. each$20(gridModels, function (gridModel) {
  64071. gridModelMap.set(gridModel.id, gridModel);
  64072. xAxesHas[gridModel.id] = true;
  64073. yAxesHas[gridModel.id] = true;
  64074. });
  64075. gridModelMap.each(function (gridModel) {
  64076. var grid = gridModel.coordinateSystem;
  64077. var cartesians = [];
  64078. each$20(grid.getCartesians(), function (cartesian, index) {
  64079. if (indexOf$1(xAxisModels, cartesian.getAxis('x').model) >= 0
  64080. || indexOf$1(yAxisModels, cartesian.getAxis('y').model) >= 0
  64081. ) {
  64082. cartesians.push(cartesian);
  64083. }
  64084. });
  64085. targetInfoList.push({
  64086. panelId: 'grid--' + gridModel.id,
  64087. gridModel: gridModel,
  64088. coordSysModel: gridModel,
  64089. // Use the first one as the representitive coordSys.
  64090. coordSys: cartesians[0],
  64091. coordSyses: cartesians,
  64092. getPanelRect: panelRectBuilder.grid,
  64093. xAxisDeclared: xAxesHas[gridModel.id],
  64094. yAxisDeclared: yAxesHas[gridModel.id]
  64095. });
  64096. });
  64097. },
  64098. geo: function (foundCpts, targetInfoList) {
  64099. each$20(foundCpts.geoModels, function (geoModel) {
  64100. var coordSys = geoModel.coordinateSystem;
  64101. targetInfoList.push({
  64102. panelId: 'geo--' + geoModel.id,
  64103. geoModel: geoModel,
  64104. coordSysModel: geoModel,
  64105. coordSys: coordSys,
  64106. coordSyses: [coordSys],
  64107. getPanelRect: panelRectBuilder.geo
  64108. });
  64109. });
  64110. }
  64111. };
  64112. var targetInfoMatchers = [
  64113. // grid
  64114. function (foundCpts, targetInfo) {
  64115. var xAxisModel = foundCpts.xAxisModel;
  64116. var yAxisModel = foundCpts.yAxisModel;
  64117. var gridModel = foundCpts.gridModel;
  64118. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  64119. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  64120. return gridModel && gridModel === targetInfo.gridModel;
  64121. },
  64122. // geo
  64123. function (foundCpts, targetInfo) {
  64124. var geoModel = foundCpts.geoModel;
  64125. return geoModel && geoModel === targetInfo.geoModel;
  64126. }
  64127. ];
  64128. var panelRectBuilder = {
  64129. grid: function () {
  64130. // grid is not Transformable.
  64131. return this.coordSys.grid.getRect().clone();
  64132. },
  64133. geo: function () {
  64134. var coordSys = this.coordSys;
  64135. var rect = coordSys.getBoundingRect().clone();
  64136. // geo roam and zoom transform
  64137. rect.applyTransform(getTransform(coordSys));
  64138. return rect;
  64139. }
  64140. };
  64141. var coordConvert = {
  64142. lineX: curry$5(axisConvert, 0),
  64143. lineY: curry$5(axisConvert, 1),
  64144. rect: function (to, coordSys, rangeOrCoordRange) {
  64145. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  64146. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  64147. var values = [
  64148. formatMinMax([xminymin[0], xmaxymax[0]]),
  64149. formatMinMax([xminymin[1], xmaxymax[1]])
  64150. ];
  64151. return {values: values, xyMinMax: values};
  64152. },
  64153. polygon: function (to, coordSys, rangeOrCoordRange) {
  64154. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  64155. var values = map(rangeOrCoordRange, function (item) {
  64156. var p = coordSys[COORD_CONVERTS[to]](item);
  64157. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  64158. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  64159. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  64160. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  64161. return p;
  64162. });
  64163. return {values: values, xyMinMax: xyMinMax};
  64164. }
  64165. };
  64166. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  64167. if (__DEV__) {
  64168. assert$1(
  64169. coordSys.type === 'cartesian2d',
  64170. 'lineX/lineY brush is available only in cartesian2d.'
  64171. );
  64172. }
  64173. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  64174. var values = formatMinMax(map([0, 1], function (i) {
  64175. return to
  64176. ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i]))
  64177. : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  64178. }));
  64179. var xyMinMax = [];
  64180. xyMinMax[axisNameIndex] = values;
  64181. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  64182. return {values: values, xyMinMax: xyMinMax};
  64183. }
  64184. var diffProcessor = {
  64185. lineX: curry$5(axisDiffProcessor, 0),
  64186. lineY: curry$5(axisDiffProcessor, 1),
  64187. rect: function (values, refer, scales) {
  64188. return [
  64189. [values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]],
  64190. [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]
  64191. ];
  64192. },
  64193. polygon: function (values, refer, scales) {
  64194. return map(values, function (item, idx) {
  64195. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  64196. });
  64197. }
  64198. };
  64199. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  64200. return [
  64201. values[0] - scales[axisNameIndex] * refer[0],
  64202. values[1] - scales[axisNameIndex] * refer[1]
  64203. ];
  64204. }
  64205. // We have to process scale caused by dataZoom manually,
  64206. // although it might be not accurate.
  64207. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  64208. var sizeCurr = getSize(xyMinMaxCurr);
  64209. var sizeOrigin = getSize(xyMinMaxOrigin);
  64210. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  64211. isNaN(scales[0]) && (scales[0] = 1);
  64212. isNaN(scales[1]) && (scales[1] = 1);
  64213. return scales;
  64214. }
  64215. function getSize(xyMinMax) {
  64216. return xyMinMax
  64217. ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]]
  64218. : [NaN, NaN];
  64219. }
  64220. /*
  64221. * Licensed to the Apache Software Foundation (ASF) under one
  64222. * or more contributor license agreements. See the NOTICE file
  64223. * distributed with this work for additional information
  64224. * regarding copyright ownership. The ASF licenses this file
  64225. * to you under the Apache License, Version 2.0 (the
  64226. * "License"); you may not use this file except in compliance
  64227. * with the License. You may obtain a copy of the License at
  64228. *
  64229. * http://www.apache.org/licenses/LICENSE-2.0
  64230. *
  64231. * Unless required by applicable law or agreed to in writing,
  64232. * software distributed under the License is distributed on an
  64233. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64234. * KIND, either express or implied. See the License for the
  64235. * specific language governing permissions and limitations
  64236. * under the License.
  64237. */
  64238. var STATE_LIST = ['inBrush', 'outOfBrush'];
  64239. var DISPATCH_METHOD = '__ecBrushSelect';
  64240. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  64241. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  64242. /**
  64243. * Layout for visual, the priority higher than other layout, and before brush visual.
  64244. */
  64245. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  64246. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  64247. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(
  64248. payload.key === 'brush' ? payload.brushOption : {brushType: false}
  64249. );
  64250. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  64251. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  64252. });
  64253. });
  64254. /**
  64255. * Register the visual encoding if this modules required.
  64256. */
  64257. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  64258. var brushSelected = [];
  64259. var throttleType;
  64260. var throttleDelay;
  64261. ecModel.eachComponent({mainType: 'brush'}, function (brushModel, brushIndex) {
  64262. var thisBrushSelected = {
  64263. brushId: brushModel.id,
  64264. brushIndex: brushIndex,
  64265. brushName: brushModel.name,
  64266. areas: clone(brushModel.areas),
  64267. selected: []
  64268. };
  64269. // Every brush component exists in event params, convenient
  64270. // for user to find by index.
  64271. brushSelected.push(thisBrushSelected);
  64272. var brushOption = brushModel.option;
  64273. var brushLink = brushOption.brushLink;
  64274. var linkedSeriesMap = [];
  64275. var selectedDataIndexForLink = [];
  64276. var rangeInfoBySeries = [];
  64277. var hasBrushExists = 0;
  64278. if (!brushIndex) { // Only the first throttle setting works.
  64279. throttleType = brushOption.throttleType;
  64280. throttleDelay = brushOption.throttleDelay;
  64281. }
  64282. // Add boundingRect and selectors to range.
  64283. var areas = map(brushModel.areas, function (area) {
  64284. return bindSelector(
  64285. defaults(
  64286. {boundingRect: boundingRectBuilders[area.brushType](area)},
  64287. area
  64288. )
  64289. );
  64290. });
  64291. var visualMappings = createVisualMappings(
  64292. brushModel.option, STATE_LIST, function (mappingOption) {
  64293. mappingOption.mappingMethod = 'fixed';
  64294. }
  64295. );
  64296. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  64297. linkedSeriesMap[seriesIndex] = 1;
  64298. });
  64299. function linkOthers(seriesIndex) {
  64300. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  64301. }
  64302. // If no supported brush or no brush on the series,
  64303. // all visuals should be in original state.
  64304. function brushed(rangeInfoList) {
  64305. return !!rangeInfoList.length;
  64306. }
  64307. /**
  64308. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  64309. *
  64310. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  64311. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  64312. * └!hasBrushExist┘ └nothing.
  64313. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  64314. * └!hasBrushExist┘ └nothing.
  64315. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  64316. * !brushed┘ └nothing.
  64317. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  64318. */
  64319. // Step A
  64320. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  64321. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  64322. seriesModel.subType === 'parallel'
  64323. ? stepAParallel(seriesModel, seriesIndex, rangeInfoList)
  64324. : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  64325. });
  64326. function stepAParallel(seriesModel, seriesIndex) {
  64327. var coordSys = seriesModel.coordinateSystem;
  64328. hasBrushExists |= coordSys.hasAxisBrushed();
  64329. linkOthers(seriesIndex) && coordSys.eachActiveState(
  64330. seriesModel.getData(),
  64331. function (activeState, dataIndex) {
  64332. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  64333. }
  64334. );
  64335. }
  64336. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  64337. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  64338. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  64339. return;
  64340. }
  64341. each$1(areas, function (area) {
  64342. selectorsByBrushType[area.brushType]
  64343. && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel)
  64344. && rangeInfoList.push(area);
  64345. hasBrushExists |= brushed(rangeInfoList);
  64346. });
  64347. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  64348. var data = seriesModel.getData();
  64349. data.each(function (dataIndex) {
  64350. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  64351. selectedDataIndexForLink[dataIndex] = 1;
  64352. }
  64353. });
  64354. }
  64355. }
  64356. // Step B
  64357. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  64358. var seriesBrushSelected = {
  64359. seriesId: seriesModel.id,
  64360. seriesIndex: seriesIndex,
  64361. seriesName: seriesModel.name,
  64362. dataIndex: []
  64363. };
  64364. // Every series exists in event params, convenient
  64365. // for user to find series by seriesIndex.
  64366. thisBrushSelected.selected.push(seriesBrushSelected);
  64367. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  64368. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  64369. var data = seriesModel.getData();
  64370. var getValueState = linkOthers(seriesIndex)
  64371. ? function (dataIndex) {
  64372. return selectedDataIndexForLink[dataIndex]
  64373. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  64374. : 'outOfBrush';
  64375. }
  64376. : function (dataIndex) {
  64377. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)
  64378. ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush')
  64379. : 'outOfBrush';
  64380. };
  64381. // If no supported brush or no brush, all visuals are in original state.
  64382. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList))
  64383. && applyVisual(
  64384. STATE_LIST, visualMappings, data, getValueState
  64385. );
  64386. });
  64387. });
  64388. dispatchAction(api, throttleType, throttleDelay, brushSelected, payload);
  64389. });
  64390. function dispatchAction(api, throttleType, throttleDelay, brushSelected, payload) {
  64391. // This event will not be triggered when `setOpion`, otherwise dead lock may
  64392. // triggered when do `setOption` in event listener, which we do not find
  64393. // satisfactory way to solve yet. Some considered resolutions:
  64394. // (a) Diff with prevoius selected data ant only trigger event when changed.
  64395. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  64396. // also detect value changes in selected data) might bring complexity or fragility.
  64397. // (b) Use spectial param like `silent` to suppress event triggering.
  64398. // But such kind of volatile param may be weird in `setOption`.
  64399. if (!payload) {
  64400. return;
  64401. }
  64402. var zr = api.getZr();
  64403. if (zr[DISPATCH_FLAG]) {
  64404. return;
  64405. }
  64406. if (!zr[DISPATCH_METHOD]) {
  64407. zr[DISPATCH_METHOD] = doDispatch;
  64408. }
  64409. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  64410. fn(api, brushSelected);
  64411. }
  64412. function doDispatch(api, brushSelected) {
  64413. if (!api.isDisposed()) {
  64414. var zr = api.getZr();
  64415. zr[DISPATCH_FLAG] = true;
  64416. api.dispatchAction({
  64417. type: 'brushSelect',
  64418. batch: brushSelected
  64419. });
  64420. zr[DISPATCH_FLAG] = false;
  64421. }
  64422. }
  64423. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  64424. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  64425. var area = rangeInfoList[i];
  64426. if (selectorsByBrushType[area.brushType](
  64427. dataIndex, data, area.selectors, area
  64428. )) {
  64429. return true;
  64430. }
  64431. }
  64432. }
  64433. function getSelectorsByBrushType(seriesModel) {
  64434. var brushSelector = seriesModel.brushSelector;
  64435. if (isString(brushSelector)) {
  64436. var sels = [];
  64437. each$1(selector, function (selectorsByElementType, brushType) {
  64438. sels[brushType] = function (dataIndex, data, selectors, area) {
  64439. var itemLayout = data.getItemLayout(dataIndex);
  64440. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  64441. };
  64442. });
  64443. return sels;
  64444. }
  64445. else if (isFunction$1(brushSelector)) {
  64446. var bSelector = {};
  64447. each$1(selector, function (sel, brushType) {
  64448. bSelector[brushType] = brushSelector;
  64449. });
  64450. return bSelector;
  64451. }
  64452. return brushSelector;
  64453. }
  64454. function brushModelNotControll(brushModel, seriesIndex) {
  64455. var seriesIndices = brushModel.option.seriesIndex;
  64456. return seriesIndices != null
  64457. && seriesIndices !== 'all'
  64458. && (
  64459. isArray(seriesIndices)
  64460. ? indexOf(seriesIndices, seriesIndex) < 0
  64461. : seriesIndex !== seriesIndices
  64462. );
  64463. }
  64464. function bindSelector(area) {
  64465. var selectors = area.selectors = {};
  64466. each$1(selector[area.brushType], function (selFn, elType) {
  64467. // Do not use function binding or curry for performance.
  64468. selectors[elType] = function (itemLayout) {
  64469. return selFn(itemLayout, selectors, area);
  64470. };
  64471. });
  64472. return area;
  64473. }
  64474. var boundingRectBuilders = {
  64475. lineX: noop,
  64476. lineY: noop,
  64477. rect: function (area) {
  64478. return getBoundingRectFromMinMax(area.range);
  64479. },
  64480. polygon: function (area) {
  64481. var minMax;
  64482. var range = area.range;
  64483. for (var i = 0, len = range.length; i < len; i++) {
  64484. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  64485. var rg = range[i];
  64486. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  64487. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  64488. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  64489. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  64490. }
  64491. return minMax && getBoundingRectFromMinMax(minMax);
  64492. }
  64493. };
  64494. function getBoundingRectFromMinMax(minMax) {
  64495. return new BoundingRect(
  64496. minMax[0][0],
  64497. minMax[1][0],
  64498. minMax[0][1] - minMax[0][0],
  64499. minMax[1][1] - minMax[1][0]
  64500. );
  64501. }
  64502. /*
  64503. * Licensed to the Apache Software Foundation (ASF) under one
  64504. * or more contributor license agreements. See the NOTICE file
  64505. * distributed with this work for additional information
  64506. * regarding copyright ownership. The ASF licenses this file
  64507. * to you under the Apache License, Version 2.0 (the
  64508. * "License"); you may not use this file except in compliance
  64509. * with the License. You may obtain a copy of the License at
  64510. *
  64511. * http://www.apache.org/licenses/LICENSE-2.0
  64512. *
  64513. * Unless required by applicable law or agreed to in writing,
  64514. * software distributed under the License is distributed on an
  64515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64516. * KIND, either express or implied. See the License for the
  64517. * specific language governing permissions and limitations
  64518. * under the License.
  64519. */
  64520. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  64521. var BrushModel = extendComponentModel({
  64522. type: 'brush',
  64523. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  64524. /**
  64525. * @protected
  64526. */
  64527. defaultOption: {
  64528. // inBrush: null,
  64529. // outOfBrush: null,
  64530. toolbox: null, // Default value see preprocessor.
  64531. brushLink: null, // Series indices array, broadcast using dataIndex.
  64532. // or 'all', which means all series. 'none' or null means no series.
  64533. seriesIndex: 'all', // seriesIndex array, specify series controlled by this brush component.
  64534. geoIndex: null, //
  64535. xAxisIndex: null,
  64536. yAxisIndex: null,
  64537. brushType: 'rect', // Default brushType, see BrushController.
  64538. brushMode: 'single', // Default brushMode, 'single' or 'multiple'
  64539. transformable: true, // Default transformable.
  64540. brushStyle: { // Default brushStyle
  64541. borderWidth: 1,
  64542. color: 'rgba(120,140,180,0.3)',
  64543. borderColor: 'rgba(120,140,180,0.8)'
  64544. },
  64545. throttleType: 'fixRate',// Throttle in brushSelected event. 'fixRate' or 'debounce'.
  64546. // If null, no throttle. Valid only in the first brush component
  64547. throttleDelay: 0, // Unit: ms, 0 means every event will be triggered.
  64548. // FIXME
  64549. // 试验效果
  64550. removeOnClick: true,
  64551. z: 10000
  64552. },
  64553. /**
  64554. * @readOnly
  64555. * @type {Array.<Object>}
  64556. */
  64557. areas: [],
  64558. /**
  64559. * Current activated brush type.
  64560. * If null, brush is inactived.
  64561. * see module:echarts/component/helper/BrushController
  64562. * @readOnly
  64563. * @type {string}
  64564. */
  64565. brushType: null,
  64566. /**
  64567. * Current brush opt.
  64568. * see module:echarts/component/helper/BrushController
  64569. * @readOnly
  64570. * @type {Object}
  64571. */
  64572. brushOption: {},
  64573. /**
  64574. * @readOnly
  64575. * @type {Array.<Object>}
  64576. */
  64577. coordInfoList: [],
  64578. optionUpdated: function (newOption, isInit) {
  64579. var thisOption = this.option;
  64580. !isInit && replaceVisualOption(
  64581. thisOption, newOption, ['inBrush', 'outOfBrush']
  64582. );
  64583. var inBrush = thisOption.inBrush = thisOption.inBrush || {};
  64584. // Always give default visual, consider setOption at the second time.
  64585. thisOption.outOfBrush = thisOption.outOfBrush || {color: DEFAULT_OUT_OF_BRUSH_COLOR};
  64586. if (!inBrush.hasOwnProperty('liftZ')) {
  64587. // Bigger than the highlight z lift, otherwise it will
  64588. // be effected by the highlight z when brush.
  64589. inBrush.liftZ = 5;
  64590. }
  64591. },
  64592. /**
  64593. * If ranges is null/undefined, range state remain.
  64594. *
  64595. * @param {Array.<Object>} [ranges]
  64596. */
  64597. setAreas: function (areas) {
  64598. if (__DEV__) {
  64599. assert$1(isArray(areas));
  64600. each$1(areas, function (area) {
  64601. assert$1(area.brushType, 'Illegal areas');
  64602. });
  64603. }
  64604. // If ranges is null/undefined, range state remain.
  64605. // This helps user to dispatchAction({type: 'brush'}) with no areas
  64606. // set but just want to get the current brush select info from a `brush` event.
  64607. if (!areas) {
  64608. return;
  64609. }
  64610. this.areas = map(areas, function (area) {
  64611. return generateBrushOption(this.option, area);
  64612. }, this);
  64613. },
  64614. /**
  64615. * see module:echarts/component/helper/BrushController
  64616. * @param {Object} brushOption
  64617. */
  64618. setBrushOption: function (brushOption) {
  64619. this.brushOption = generateBrushOption(this.option, brushOption);
  64620. this.brushType = this.brushOption.brushType;
  64621. }
  64622. });
  64623. function generateBrushOption(option, brushOption) {
  64624. return merge(
  64625. {
  64626. brushType: option.brushType,
  64627. brushMode: option.brushMode,
  64628. transformable: option.transformable,
  64629. brushStyle: new Model(option.brushStyle).getItemStyle(),
  64630. removeOnClick: option.removeOnClick,
  64631. z: option.z
  64632. },
  64633. brushOption,
  64634. true
  64635. );
  64636. }
  64637. /*
  64638. * Licensed to the Apache Software Foundation (ASF) under one
  64639. * or more contributor license agreements. See the NOTICE file
  64640. * distributed with this work for additional information
  64641. * regarding copyright ownership. The ASF licenses this file
  64642. * to you under the Apache License, Version 2.0 (the
  64643. * "License"); you may not use this file except in compliance
  64644. * with the License. You may obtain a copy of the License at
  64645. *
  64646. * http://www.apache.org/licenses/LICENSE-2.0
  64647. *
  64648. * Unless required by applicable law or agreed to in writing,
  64649. * software distributed under the License is distributed on an
  64650. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64651. * KIND, either express or implied. See the License for the
  64652. * specific language governing permissions and limitations
  64653. * under the License.
  64654. */
  64655. extendComponentView({
  64656. type: 'brush',
  64657. init: function (ecModel, api) {
  64658. /**
  64659. * @readOnly
  64660. * @type {module:echarts/model/Global}
  64661. */
  64662. this.ecModel = ecModel;
  64663. /**
  64664. * @readOnly
  64665. * @type {module:echarts/ExtensionAPI}
  64666. */
  64667. this.api = api;
  64668. /**
  64669. * @readOnly
  64670. * @type {module:echarts/component/brush/BrushModel}
  64671. */
  64672. this.model;
  64673. /**
  64674. * @private
  64675. * @type {module:echarts/component/helper/BrushController}
  64676. */
  64677. (this._brushController = new BrushController(api.getZr()))
  64678. .on('brush', bind(this._onBrush, this))
  64679. .mount();
  64680. },
  64681. /**
  64682. * @override
  64683. */
  64684. render: function (brushModel) {
  64685. this.model = brushModel;
  64686. return updateController.apply(this, arguments);
  64687. },
  64688. /**
  64689. * @override
  64690. */
  64691. updateTransform: updateController,
  64692. /**
  64693. * @override
  64694. */
  64695. updateView: updateController,
  64696. // /**
  64697. // * @override
  64698. // */
  64699. // updateLayout: updateController,
  64700. // /**
  64701. // * @override
  64702. // */
  64703. // updateVisual: updateController,
  64704. /**
  64705. * @override
  64706. */
  64707. dispose: function () {
  64708. this._brushController.dispose();
  64709. },
  64710. /**
  64711. * @private
  64712. */
  64713. _onBrush: function (areas, opt) {
  64714. var modelId = this.model.id;
  64715. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel);
  64716. // Action is not dispatched on drag end, because the drag end
  64717. // emits the same params with the last drag move event, and
  64718. // may have some delay when using touch pad, which makes
  64719. // animation not smooth (when using debounce).
  64720. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  64721. type: 'brush',
  64722. brushId: modelId,
  64723. areas: clone(areas),
  64724. $from: modelId
  64725. });
  64726. }
  64727. });
  64728. function updateController(brushModel, ecModel, api, payload) {
  64729. // Do not update controller when drawing.
  64730. (!payload || payload.$from !== brushModel.id) && this._brushController
  64731. .setPanels(brushModel.brushTargetManager.makePanelOpts(api))
  64732. .enableBrush(brushModel.brushOption)
  64733. .updateCovers(brushModel.areas.slice());
  64734. }
  64735. /*
  64736. * Licensed to the Apache Software Foundation (ASF) under one
  64737. * or more contributor license agreements. See the NOTICE file
  64738. * distributed with this work for additional information
  64739. * regarding copyright ownership. The ASF licenses this file
  64740. * to you under the Apache License, Version 2.0 (the
  64741. * "License"); you may not use this file except in compliance
  64742. * with the License. You may obtain a copy of the License at
  64743. *
  64744. * http://www.apache.org/licenses/LICENSE-2.0
  64745. *
  64746. * Unless required by applicable law or agreed to in writing,
  64747. * software distributed under the License is distributed on an
  64748. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64749. * KIND, either express or implied. See the License for the
  64750. * specific language governing permissions and limitations
  64751. * under the License.
  64752. */
  64753. /**
  64754. * payload: {
  64755. * brushIndex: number, or,
  64756. * brushId: string, or,
  64757. * brushName: string,
  64758. * globalRanges: Array
  64759. * }
  64760. */
  64761. registerAction(
  64762. {type: 'brush', event: 'brush' /*, update: 'updateView' */},
  64763. function (payload, ecModel) {
  64764. ecModel.eachComponent({mainType: 'brush', query: payload}, function (brushModel) {
  64765. brushModel.setAreas(payload.areas);
  64766. });
  64767. }
  64768. );
  64769. /**
  64770. * payload: {
  64771. * brushComponents: [
  64772. * {
  64773. * brushId,
  64774. * brushIndex,
  64775. * brushName,
  64776. * series: [
  64777. * {
  64778. * seriesId,
  64779. * seriesIndex,
  64780. * seriesName,
  64781. * rawIndices: [21, 34, ...]
  64782. * },
  64783. * ...
  64784. * ]
  64785. * },
  64786. * ...
  64787. * ]
  64788. * }
  64789. */
  64790. registerAction(
  64791. {type: 'brushSelect', event: 'brushSelected', update: 'none'},
  64792. function () {}
  64793. );
  64794. /*
  64795. * Licensed to the Apache Software Foundation (ASF) under one
  64796. * or more contributor license agreements. See the NOTICE file
  64797. * distributed with this work for additional information
  64798. * regarding copyright ownership. The ASF licenses this file
  64799. * to you under the Apache License, Version 2.0 (the
  64800. * "License"); you may not use this file except in compliance
  64801. * with the License. You may obtain a copy of the License at
  64802. *
  64803. * http://www.apache.org/licenses/LICENSE-2.0
  64804. *
  64805. * Unless required by applicable law or agreed to in writing,
  64806. * software distributed under the License is distributed on an
  64807. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64808. * KIND, either express or implied. See the License for the
  64809. * specific language governing permissions and limitations
  64810. * under the License.
  64811. */
  64812. var features = {};
  64813. function register$1(name, ctor) {
  64814. features[name] = ctor;
  64815. }
  64816. function get$1(name) {
  64817. return features[name];
  64818. }
  64819. /*
  64820. * Licensed to the Apache Software Foundation (ASF) under one
  64821. * or more contributor license agreements. See the NOTICE file
  64822. * distributed with this work for additional information
  64823. * regarding copyright ownership. The ASF licenses this file
  64824. * to you under the Apache License, Version 2.0 (the
  64825. * "License"); you may not use this file except in compliance
  64826. * with the License. You may obtain a copy of the License at
  64827. *
  64828. * http://www.apache.org/licenses/LICENSE-2.0
  64829. *
  64830. * Unless required by applicable law or agreed to in writing,
  64831. * software distributed under the License is distributed on an
  64832. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64833. * KIND, either express or implied. See the License for the
  64834. * specific language governing permissions and limitations
  64835. * under the License.
  64836. */
  64837. var brushLang = lang.toolbox.brush;
  64838. function Brush(model, ecModel, api) {
  64839. this.model = model;
  64840. this.ecModel = ecModel;
  64841. this.api = api;
  64842. /**
  64843. * @private
  64844. * @type {string}
  64845. */
  64846. this._brushType;
  64847. /**
  64848. * @private
  64849. * @type {string}
  64850. */
  64851. this._brushMode;
  64852. }
  64853. Brush.defaultOption = {
  64854. show: true,
  64855. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  64856. icon: {
  64857. 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
  64858. 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
  64859. 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
  64860. 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
  64861. 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
  64862. 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
  64863. },
  64864. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  64865. title: clone(brushLang.title)
  64866. };
  64867. var proto$3 = Brush.prototype;
  64868. // proto.updateLayout = function (featureModel, ecModel, api) {
  64869. proto$3.render =
  64870. proto$3.updateView = function (featureModel, ecModel, api) {
  64871. var brushType;
  64872. var brushMode;
  64873. var isBrushed;
  64874. ecModel.eachComponent({mainType: 'brush'}, function (brushModel) {
  64875. brushType = brushModel.brushType;
  64876. brushMode = brushModel.brushOption.brushMode || 'single';
  64877. isBrushed |= brushModel.areas.length;
  64878. });
  64879. this._brushType = brushType;
  64880. this._brushMode = brushMode;
  64881. each$1(featureModel.get('type', true), function (type) {
  64882. featureModel.setIconStatus(
  64883. type,
  64884. (
  64885. type === 'keep'
  64886. ? brushMode === 'multiple'
  64887. : type === 'clear'
  64888. ? isBrushed
  64889. : type === brushType
  64890. ) ? 'emphasis' : 'normal'
  64891. );
  64892. });
  64893. };
  64894. proto$3.getIcons = function () {
  64895. var model = this.model;
  64896. var availableIcons = model.get('icon', true);
  64897. var icons = {};
  64898. each$1(model.get('type', true), function (type) {
  64899. if (availableIcons[type]) {
  64900. icons[type] = availableIcons[type];
  64901. }
  64902. });
  64903. return icons;
  64904. };
  64905. proto$3.onclick = function (ecModel, api, type) {
  64906. var brushType = this._brushType;
  64907. var brushMode = this._brushMode;
  64908. if (type === 'clear') {
  64909. // Trigger parallel action firstly
  64910. api.dispatchAction({
  64911. type: 'axisAreaSelect',
  64912. intervals: []
  64913. });
  64914. api.dispatchAction({
  64915. type: 'brush',
  64916. command: 'clear',
  64917. // Clear all areas of all brush components.
  64918. areas: []
  64919. });
  64920. }
  64921. else {
  64922. api.dispatchAction({
  64923. type: 'takeGlobalCursor',
  64924. key: 'brush',
  64925. brushOption: {
  64926. brushType: type === 'keep'
  64927. ? brushType
  64928. : (brushType === type ? false : type),
  64929. brushMode: type === 'keep'
  64930. ? (brushMode === 'multiple' ? 'single' : 'multiple')
  64931. : brushMode
  64932. }
  64933. });
  64934. }
  64935. };
  64936. register$1('brush', Brush);
  64937. /*
  64938. * Licensed to the Apache Software Foundation (ASF) under one
  64939. * or more contributor license agreements. See the NOTICE file
  64940. * distributed with this work for additional information
  64941. * regarding copyright ownership. The ASF licenses this file
  64942. * to you under the Apache License, Version 2.0 (the
  64943. * "License"); you may not use this file except in compliance
  64944. * with the License. You may obtain a copy of the License at
  64945. *
  64946. * http://www.apache.org/licenses/LICENSE-2.0
  64947. *
  64948. * Unless required by applicable law or agreed to in writing,
  64949. * software distributed under the License is distributed on an
  64950. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64951. * KIND, either express or implied. See the License for the
  64952. * specific language governing permissions and limitations
  64953. * under the License.
  64954. */
  64955. /**
  64956. * Brush component entry
  64957. */
  64958. registerPreprocessor(preprocessor$1);
  64959. /*
  64960. * Licensed to the Apache Software Foundation (ASF) under one
  64961. * or more contributor license agreements. See the NOTICE file
  64962. * distributed with this work for additional information
  64963. * regarding copyright ownership. The ASF licenses this file
  64964. * to you under the Apache License, Version 2.0 (the
  64965. * "License"); you may not use this file except in compliance
  64966. * with the License. You may obtain a copy of the License at
  64967. *
  64968. * http://www.apache.org/licenses/LICENSE-2.0
  64969. *
  64970. * Unless required by applicable law or agreed to in writing,
  64971. * software distributed under the License is distributed on an
  64972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64973. * KIND, either express or implied. See the License for the
  64974. * specific language governing permissions and limitations
  64975. * under the License.
  64976. */
  64977. // (24*60*60*1000)
  64978. var PROXIMATE_ONE_DAY = 86400000;
  64979. /**
  64980. * Calendar
  64981. *
  64982. * @constructor
  64983. *
  64984. * @param {Object} calendarModel calendarModel
  64985. * @param {Object} ecModel ecModel
  64986. * @param {Object} api api
  64987. */
  64988. function Calendar(calendarModel, ecModel, api) {
  64989. this._model = calendarModel;
  64990. }
  64991. Calendar.prototype = {
  64992. constructor: Calendar,
  64993. type: 'calendar',
  64994. dimensions: ['time', 'value'],
  64995. // Required in createListFromData
  64996. getDimensionsInfo: function () {
  64997. return [{name: 'time', type: 'time'}, 'value'];
  64998. },
  64999. getRangeInfo: function () {
  65000. return this._rangeInfo;
  65001. },
  65002. getModel: function () {
  65003. return this._model;
  65004. },
  65005. getRect: function () {
  65006. return this._rect;
  65007. },
  65008. getCellWidth: function () {
  65009. return this._sw;
  65010. },
  65011. getCellHeight: function () {
  65012. return this._sh;
  65013. },
  65014. getOrient: function () {
  65015. return this._orient;
  65016. },
  65017. /**
  65018. * getFirstDayOfWeek
  65019. *
  65020. * @example
  65021. * 0 : start at Sunday
  65022. * 1 : start at Monday
  65023. *
  65024. * @return {number}
  65025. */
  65026. getFirstDayOfWeek: function () {
  65027. return this._firstDayOfWeek;
  65028. },
  65029. /**
  65030. * get date info
  65031. *
  65032. * @param {string|number} date date
  65033. * @return {Object}
  65034. * {
  65035. * y: string, local full year, eg., '1940',
  65036. * m: string, local month, from '01' ot '12',
  65037. * d: string, local date, from '01' to '31' (if exists),
  65038. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  65039. * time: timestamp,
  65040. * formatedDate: string, yyyy-MM-dd,
  65041. * date: original date object.
  65042. * }
  65043. */
  65044. getDateInfo: function (date) {
  65045. date = parseDate(date);
  65046. var y = date.getFullYear();
  65047. var m = date.getMonth() + 1;
  65048. m = m < 10 ? '0' + m : m;
  65049. var d = date.getDate();
  65050. d = d < 10 ? '0' + d : d;
  65051. var day = date.getDay();
  65052. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  65053. return {
  65054. y: y,
  65055. m: m,
  65056. d: d,
  65057. day: day,
  65058. time: date.getTime(),
  65059. formatedDate: y + '-' + m + '-' + d,
  65060. date: date
  65061. };
  65062. },
  65063. getNextNDay: function (date, n) {
  65064. n = n || 0;
  65065. if (n === 0) {
  65066. return this.getDateInfo(date);
  65067. }
  65068. date = new Date(this.getDateInfo(date).time);
  65069. date.setDate(date.getDate() + n);
  65070. return this.getDateInfo(date);
  65071. },
  65072. update: function (ecModel, api) {
  65073. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  65074. this._orient = this._model.get('orient');
  65075. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  65076. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  65077. var weeks = this._rangeInfo.weeks || 1;
  65078. var whNames = ['width', 'height'];
  65079. var cellSize = this._model.get('cellSize').slice();
  65080. var layoutParams = this._model.getBoxLayoutParams();
  65081. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  65082. each$1([0, 1], function (idx) {
  65083. if (cellSizeSpecified(cellSize, idx)) {
  65084. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  65085. }
  65086. });
  65087. var whGlobal = {
  65088. width: api.getWidth(),
  65089. height: api.getHeight()
  65090. };
  65091. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  65092. each$1([0, 1], function (idx) {
  65093. if (!cellSizeSpecified(cellSize, idx)) {
  65094. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  65095. }
  65096. });
  65097. function cellSizeSpecified(cellSize, idx) {
  65098. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  65099. }
  65100. this._sw = cellSize[0];
  65101. this._sh = cellSize[1];
  65102. },
  65103. /**
  65104. * Convert a time data(time, value) item to (x, y) point.
  65105. *
  65106. * @override
  65107. * @param {Array|number} data data
  65108. * @param {boolean} [clamp=true] out of range
  65109. * @return {Array} point
  65110. */
  65111. dataToPoint: function (data, clamp) {
  65112. isArray(data) && (data = data[0]);
  65113. clamp == null && (clamp = true);
  65114. var dayInfo = this.getDateInfo(data);
  65115. var range = this._rangeInfo;
  65116. var date = dayInfo.formatedDate;
  65117. // if not in range return [NaN, NaN]
  65118. if (clamp && !(
  65119. dayInfo.time >= range.start.time
  65120. && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY
  65121. )) {
  65122. return [NaN, NaN];
  65123. }
  65124. var week = dayInfo.day;
  65125. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  65126. if (this._orient === 'vertical') {
  65127. return [
  65128. this._rect.x + week * this._sw + this._sw / 2,
  65129. this._rect.y + nthWeek * this._sh + this._sh / 2
  65130. ];
  65131. }
  65132. return [
  65133. this._rect.x + nthWeek * this._sw + this._sw / 2,
  65134. this._rect.y + week * this._sh + this._sh / 2
  65135. ];
  65136. },
  65137. /**
  65138. * Convert a (x, y) point to time data
  65139. *
  65140. * @override
  65141. * @param {string} point point
  65142. * @return {string} data
  65143. */
  65144. pointToData: function (point) {
  65145. var date = this.pointToDate(point);
  65146. return date && date.time;
  65147. },
  65148. /**
  65149. * Convert a time date item to (x, y) four point.
  65150. *
  65151. * @param {Array} data date[0] is date
  65152. * @param {boolean} [clamp=true] out of range
  65153. * @return {Object} point
  65154. */
  65155. dataToRect: function (data, clamp) {
  65156. var point = this.dataToPoint(data, clamp);
  65157. return {
  65158. contentShape: {
  65159. x: point[0] - (this._sw - this._lineWidth) / 2,
  65160. y: point[1] - (this._sh - this._lineWidth) / 2,
  65161. width: this._sw - this._lineWidth,
  65162. height: this._sh - this._lineWidth
  65163. },
  65164. center: point,
  65165. tl: [
  65166. point[0] - this._sw / 2,
  65167. point[1] - this._sh / 2
  65168. ],
  65169. tr: [
  65170. point[0] + this._sw / 2,
  65171. point[1] - this._sh / 2
  65172. ],
  65173. br: [
  65174. point[0] + this._sw / 2,
  65175. point[1] + this._sh / 2
  65176. ],
  65177. bl: [
  65178. point[0] - this._sw / 2,
  65179. point[1] + this._sh / 2
  65180. ]
  65181. };
  65182. },
  65183. /**
  65184. * Convert a (x, y) point to time date
  65185. *
  65186. * @param {Array} point point
  65187. * @return {Object} date
  65188. */
  65189. pointToDate: function (point) {
  65190. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  65191. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  65192. var range = this._rangeInfo.range;
  65193. if (this._orient === 'vertical') {
  65194. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  65195. }
  65196. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  65197. },
  65198. /**
  65199. * @inheritDoc
  65200. */
  65201. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  65202. /**
  65203. * @inheritDoc
  65204. */
  65205. convertFromPixel: curry(doConvert$2, 'pointToData'),
  65206. /**
  65207. * initRange
  65208. *
  65209. * @private
  65210. * @return {Array} [start, end]
  65211. */
  65212. _initRangeOption: function () {
  65213. var range = this._model.get('range');
  65214. var rg = range;
  65215. if (isArray(rg) && rg.length === 1) {
  65216. rg = rg[0];
  65217. }
  65218. if (/^\d{4}$/.test(rg)) {
  65219. range = [rg + '-01-01', rg + '-12-31'];
  65220. }
  65221. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  65222. var start = this.getDateInfo(rg);
  65223. var firstDay = start.date;
  65224. firstDay.setMonth(firstDay.getMonth() + 1);
  65225. var end = this.getNextNDay(firstDay, -1);
  65226. range = [start.formatedDate, end.formatedDate];
  65227. }
  65228. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  65229. range = [rg, rg];
  65230. }
  65231. var tmp = this._getRangeInfo(range);
  65232. if (tmp.start.time > tmp.end.time) {
  65233. range.reverse();
  65234. }
  65235. return range;
  65236. },
  65237. /**
  65238. * range info
  65239. *
  65240. * @private
  65241. * @param {Array} range range ['2017-01-01', '2017-07-08']
  65242. * If range[0] > range[1], they will not be reversed.
  65243. * @return {Object} obj
  65244. */
  65245. _getRangeInfo: function (range) {
  65246. range = [
  65247. this.getDateInfo(range[0]),
  65248. this.getDateInfo(range[1])
  65249. ];
  65250. var reversed;
  65251. if (range[0].time > range[1].time) {
  65252. reversed = true;
  65253. range.reverse();
  65254. }
  65255. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY)
  65256. - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1;
  65257. // Consider case:
  65258. // Firstly set system timezone as "Time Zone: America/Toronto",
  65259. // ```
  65260. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  65261. // var second = new Date(1478412000000);
  65262. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  65263. // ```
  65264. // will get wrong result because of DST. So we should fix it.
  65265. var date = new Date(range[0].time);
  65266. var startDateNum = date.getDate();
  65267. var endDateNum = range[1].date.getDate();
  65268. date.setDate(startDateNum + allDay - 1);
  65269. // The bias can not over a month, so just compare date.
  65270. if (date.getDate() !== endDateNum) {
  65271. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  65272. while (date.getDate() !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  65273. allDay -= sign;
  65274. date.setDate(startDateNum + allDay - 1);
  65275. }
  65276. }
  65277. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  65278. var nthWeek = reversed ? -weeks + 1: weeks - 1;
  65279. reversed && range.reverse();
  65280. return {
  65281. range: [range[0].formatedDate, range[1].formatedDate],
  65282. start: range[0],
  65283. end: range[1],
  65284. allDay: allDay,
  65285. weeks: weeks,
  65286. // From 0.
  65287. nthWeek: nthWeek,
  65288. fweek: range[0].day,
  65289. lweek: range[1].day
  65290. };
  65291. },
  65292. /**
  65293. * get date by nthWeeks and week day in range
  65294. *
  65295. * @private
  65296. * @param {number} nthWeek the week
  65297. * @param {number} day the week day
  65298. * @param {Array} range [d1, d2]
  65299. * @return {Object}
  65300. */
  65301. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  65302. var rangeInfo = this._getRangeInfo(range);
  65303. if (nthWeek > rangeInfo.weeks
  65304. || (nthWeek === 0 && day < rangeInfo.fweek)
  65305. || (nthWeek === rangeInfo.weeks && day > rangeInfo.lweek)
  65306. ) {
  65307. return false;
  65308. }
  65309. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  65310. var date = new Date(rangeInfo.start.time);
  65311. date.setDate(rangeInfo.start.d + nthDay);
  65312. return this.getDateInfo(date);
  65313. }
  65314. };
  65315. Calendar.dimensions = Calendar.prototype.dimensions;
  65316. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  65317. Calendar.create = function (ecModel, api) {
  65318. var calendarList = [];
  65319. ecModel.eachComponent('calendar', function (calendarModel) {
  65320. var calendar = new Calendar(calendarModel, ecModel, api);
  65321. calendarList.push(calendar);
  65322. calendarModel.coordinateSystem = calendar;
  65323. });
  65324. ecModel.eachSeries(function (calendarSeries) {
  65325. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  65326. // Inject coordinate system
  65327. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  65328. }
  65329. });
  65330. return calendarList;
  65331. };
  65332. function doConvert$2(methodName, ecModel, finder, value) {
  65333. var calendarModel = finder.calendarModel;
  65334. var seriesModel = finder.seriesModel;
  65335. var coordSys = calendarModel
  65336. ? calendarModel.coordinateSystem
  65337. : seriesModel
  65338. ? seriesModel.coordinateSystem
  65339. : null;
  65340. return coordSys === this ? coordSys[methodName](value) : null;
  65341. }
  65342. CoordinateSystemManager.register('calendar', Calendar);
  65343. /*
  65344. * Licensed to the Apache Software Foundation (ASF) under one
  65345. * or more contributor license agreements. See the NOTICE file
  65346. * distributed with this work for additional information
  65347. * regarding copyright ownership. The ASF licenses this file
  65348. * to you under the Apache License, Version 2.0 (the
  65349. * "License"); you may not use this file except in compliance
  65350. * with the License. You may obtain a copy of the License at
  65351. *
  65352. * http://www.apache.org/licenses/LICENSE-2.0
  65353. *
  65354. * Unless required by applicable law or agreed to in writing,
  65355. * software distributed under the License is distributed on an
  65356. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65357. * KIND, either express or implied. See the License for the
  65358. * specific language governing permissions and limitations
  65359. * under the License.
  65360. */
  65361. var CalendarModel = ComponentModel.extend({
  65362. type: 'calendar',
  65363. /**
  65364. * @type {module:echarts/coord/calendar/Calendar}
  65365. */
  65366. coordinateSystem: null,
  65367. defaultOption: {
  65368. zlevel: 0,
  65369. z: 2,
  65370. left: 80,
  65371. top: 60,
  65372. cellSize: 20,
  65373. // horizontal vertical
  65374. orient: 'horizontal',
  65375. // month separate line style
  65376. splitLine: {
  65377. show: true,
  65378. lineStyle: {
  65379. color: '#000',
  65380. width: 1,
  65381. type: 'solid'
  65382. }
  65383. },
  65384. // rect style temporarily unused emphasis
  65385. itemStyle: {
  65386. color: '#fff',
  65387. borderWidth: 1,
  65388. borderColor: '#ccc'
  65389. },
  65390. // week text style
  65391. dayLabel: {
  65392. show: true,
  65393. // a week first day
  65394. firstDay: 0,
  65395. // start end
  65396. position: 'start',
  65397. margin: '50%', // 50% of cellSize
  65398. nameMap: 'en',
  65399. color: '#000'
  65400. },
  65401. // month text style
  65402. monthLabel: {
  65403. show: true,
  65404. // start end
  65405. position: 'start',
  65406. margin: 5,
  65407. // center or left
  65408. align: 'center',
  65409. // cn en []
  65410. nameMap: 'en',
  65411. formatter: null,
  65412. color: '#000'
  65413. },
  65414. // year text style
  65415. yearLabel: {
  65416. show: true,
  65417. // top bottom left right
  65418. position: null,
  65419. margin: 30,
  65420. formatter: null,
  65421. color: '#ccc',
  65422. fontFamily: 'sans-serif',
  65423. fontWeight: 'bolder',
  65424. fontSize: 20
  65425. }
  65426. },
  65427. /**
  65428. * @override
  65429. */
  65430. init: function (option, parentModel, ecModel, extraOpt) {
  65431. var inputPositionParams = getLayoutParams(option);
  65432. CalendarModel.superApply(this, 'init', arguments);
  65433. mergeAndNormalizeLayoutParams$1(option, inputPositionParams);
  65434. },
  65435. /**
  65436. * @override
  65437. */
  65438. mergeOption: function (option, extraOpt) {
  65439. CalendarModel.superApply(this, 'mergeOption', arguments);
  65440. mergeAndNormalizeLayoutParams$1(this.option, option);
  65441. }
  65442. });
  65443. function mergeAndNormalizeLayoutParams$1(target, raw) {
  65444. // Normalize cellSize
  65445. var cellSize = target.cellSize;
  65446. if (!isArray(cellSize)) {
  65447. cellSize = target.cellSize = [cellSize, cellSize];
  65448. }
  65449. else if (cellSize.length === 1) {
  65450. cellSize[1] = cellSize[0];
  65451. }
  65452. var ignoreSize = map([0, 1], function (hvIdx) {
  65453. // If user have set `width` or both `left` and `right`, cellSize
  65454. // will be automatically set to 'auto', otherwise the default
  65455. // setting of cellSize will make `width` setting not work.
  65456. if (sizeCalculable(raw, hvIdx)) {
  65457. cellSize[hvIdx] = 'auto';
  65458. }
  65459. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  65460. });
  65461. mergeLayoutParam(target, raw, {
  65462. type: 'box', ignoreSize: ignoreSize
  65463. });
  65464. }
  65465. /*
  65466. * Licensed to the Apache Software Foundation (ASF) under one
  65467. * or more contributor license agreements. See the NOTICE file
  65468. * distributed with this work for additional information
  65469. * regarding copyright ownership. The ASF licenses this file
  65470. * to you under the Apache License, Version 2.0 (the
  65471. * "License"); you may not use this file except in compliance
  65472. * with the License. You may obtain a copy of the License at
  65473. *
  65474. * http://www.apache.org/licenses/LICENSE-2.0
  65475. *
  65476. * Unless required by applicable law or agreed to in writing,
  65477. * software distributed under the License is distributed on an
  65478. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65479. * KIND, either express or implied. See the License for the
  65480. * specific language governing permissions and limitations
  65481. * under the License.
  65482. */
  65483. var MONTH_TEXT = {
  65484. EN: [
  65485. 'Jan', 'Feb', 'Mar',
  65486. 'Apr', 'May', 'Jun',
  65487. 'Jul', 'Aug', 'Sep',
  65488. 'Oct', 'Nov', 'Dec'
  65489. ],
  65490. CN: [
  65491. '一月', '二月', '三月',
  65492. '四月', '五月', '六月',
  65493. '七月', '八月', '九月',
  65494. '十月', '十一月', '十二月'
  65495. ]
  65496. };
  65497. var WEEK_TEXT = {
  65498. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  65499. CN: ['日', '一', '二', '三', '四', '五', '六']
  65500. };
  65501. extendComponentView({
  65502. type: 'calendar',
  65503. /**
  65504. * top/left line points
  65505. * @private
  65506. */
  65507. _tlpoints: null,
  65508. /**
  65509. * bottom/right line points
  65510. * @private
  65511. */
  65512. _blpoints: null,
  65513. /**
  65514. * first day of month
  65515. * @private
  65516. */
  65517. _firstDayOfMonth: null,
  65518. /**
  65519. * first day point of month
  65520. * @private
  65521. */
  65522. _firstDayPoints: null,
  65523. render: function (calendarModel, ecModel, api) {
  65524. var group = this.group;
  65525. group.removeAll();
  65526. var coordSys = calendarModel.coordinateSystem;
  65527. // range info
  65528. var rangeData = coordSys.getRangeInfo();
  65529. var orient = coordSys.getOrient();
  65530. this._renderDayRect(calendarModel, rangeData, group);
  65531. // _renderLines must be called prior to following function
  65532. this._renderLines(calendarModel, rangeData, orient, group);
  65533. this._renderYearText(calendarModel, rangeData, orient, group);
  65534. this._renderMonthText(calendarModel, orient, group);
  65535. this._renderWeekText(calendarModel, rangeData, orient, group);
  65536. },
  65537. // render day rect
  65538. _renderDayRect: function (calendarModel, rangeData, group) {
  65539. var coordSys = calendarModel.coordinateSystem;
  65540. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  65541. var sw = coordSys.getCellWidth();
  65542. var sh = coordSys.getCellHeight();
  65543. for (var i = rangeData.start.time;
  65544. i <= rangeData.end.time;
  65545. i = coordSys.getNextNDay(i, 1).time
  65546. ) {
  65547. var point = coordSys.dataToRect([i], false).tl;
  65548. // every rect
  65549. var rect = new Rect({
  65550. shape: {
  65551. x: point[0],
  65552. y: point[1],
  65553. width: sw,
  65554. height: sh
  65555. },
  65556. cursor: 'default',
  65557. style: itemRectStyleModel
  65558. });
  65559. group.add(rect);
  65560. }
  65561. },
  65562. // render separate line
  65563. _renderLines: function (calendarModel, rangeData, orient, group) {
  65564. var self = this;
  65565. var coordSys = calendarModel.coordinateSystem;
  65566. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  65567. var show = calendarModel.get('splitLine.show');
  65568. var lineWidth = lineStyleModel.lineWidth;
  65569. this._tlpoints = [];
  65570. this._blpoints = [];
  65571. this._firstDayOfMonth = [];
  65572. this._firstDayPoints = [];
  65573. var firstDay = rangeData.start;
  65574. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  65575. addPoints(firstDay.formatedDate);
  65576. if (i === 0) {
  65577. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  65578. }
  65579. var date = firstDay.date;
  65580. date.setMonth(date.getMonth() + 1);
  65581. firstDay = coordSys.getDateInfo(date);
  65582. }
  65583. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  65584. function addPoints(date) {
  65585. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  65586. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  65587. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  65588. self._tlpoints.push(points[0]);
  65589. self._blpoints.push(points[points.length - 1]);
  65590. show && self._drawSplitline(points, lineStyleModel, group);
  65591. }
  65592. // render top/left line
  65593. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group);
  65594. // render bottom/right line
  65595. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  65596. },
  65597. // get points at both ends
  65598. _getEdgesPoints: function (points, lineWidth, orient) {
  65599. var rs = [points[0].slice(), points[points.length - 1].slice()];
  65600. var idx = orient === 'horizontal' ? 0 : 1;
  65601. // both ends of the line are extend half lineWidth
  65602. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  65603. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  65604. return rs;
  65605. },
  65606. // render split line
  65607. _drawSplitline: function (points, lineStyleModel, group) {
  65608. var poyline = new Polyline({
  65609. z2: 20,
  65610. shape: {
  65611. points: points
  65612. },
  65613. style: lineStyleModel
  65614. });
  65615. group.add(poyline);
  65616. },
  65617. // render month line of one week points
  65618. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  65619. var coordSys = calendarModel.coordinateSystem;
  65620. date = coordSys.getDateInfo(date);
  65621. var points = [];
  65622. for (var i = 0; i < 7; i++) {
  65623. var tmpD = coordSys.getNextNDay(date.time, i);
  65624. var point = coordSys.dataToRect([tmpD.time], false);
  65625. points[2 * tmpD.day] = point.tl;
  65626. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  65627. }
  65628. return points;
  65629. },
  65630. _formatterLabel: function (formatter, params) {
  65631. if (typeof formatter === 'string' && formatter) {
  65632. return formatTplSimple(formatter, params);
  65633. }
  65634. if (typeof formatter === 'function') {
  65635. return formatter(params);
  65636. }
  65637. return params.nameMap;
  65638. },
  65639. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  65640. point = point.slice();
  65641. var aligns = ['center', 'bottom'];
  65642. if (position === 'bottom') {
  65643. point[1] += margin;
  65644. aligns = ['center', 'top'];
  65645. }
  65646. else if (position === 'left') {
  65647. point[0] -= margin;
  65648. }
  65649. else if (position === 'right') {
  65650. point[0] += margin;
  65651. aligns = ['center', 'top'];
  65652. }
  65653. else { // top
  65654. point[1] -= margin;
  65655. }
  65656. var rotate = 0;
  65657. if (position === 'left' || position === 'right') {
  65658. rotate = Math.PI / 2;
  65659. }
  65660. return {
  65661. rotation: rotate,
  65662. position: point,
  65663. style: {
  65664. textAlign: aligns[0],
  65665. textVerticalAlign: aligns[1]
  65666. }
  65667. };
  65668. },
  65669. // render year
  65670. _renderYearText: function (calendarModel, rangeData, orient, group) {
  65671. var yearLabel = calendarModel.getModel('yearLabel');
  65672. if (!yearLabel.get('show')) {
  65673. return;
  65674. }
  65675. var margin = yearLabel.get('margin');
  65676. var pos = yearLabel.get('position');
  65677. if (!pos) {
  65678. pos = orient !== 'horizontal' ? 'top' : 'left';
  65679. }
  65680. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  65681. var xc = (points[0][0] + points[1][0]) / 2;
  65682. var yc = (points[0][1] + points[1][1]) / 2;
  65683. var idx = orient === 'horizontal' ? 0 : 1;
  65684. var posPoints = {
  65685. top: [xc, points[idx][1]],
  65686. bottom: [xc, points[1 - idx][1]],
  65687. left: [points[1 - idx][0], yc],
  65688. right: [points[idx][0], yc]
  65689. };
  65690. var name = rangeData.start.y;
  65691. if (+rangeData.end.y > +rangeData.start.y) {
  65692. name = name + '-' + rangeData.end.y;
  65693. }
  65694. var formatter = yearLabel.get('formatter');
  65695. var params = {
  65696. start: rangeData.start.y,
  65697. end: rangeData.end.y,
  65698. nameMap: name
  65699. };
  65700. var content = this._formatterLabel(formatter, params);
  65701. var yearText = new Text({z2: 30});
  65702. setTextStyle(yearText.style, yearLabel, {text: content}),
  65703. yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  65704. group.add(yearText);
  65705. },
  65706. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  65707. var align = 'left';
  65708. var vAlign = 'top';
  65709. var x = point[0];
  65710. var y = point[1];
  65711. if (orient === 'horizontal') {
  65712. y = y + margin;
  65713. if (isCenter) {
  65714. align = 'center';
  65715. }
  65716. if (position === 'start') {
  65717. vAlign = 'bottom';
  65718. }
  65719. }
  65720. else {
  65721. x = x + margin;
  65722. if (isCenter) {
  65723. vAlign = 'middle';
  65724. }
  65725. if (position === 'start') {
  65726. align = 'right';
  65727. }
  65728. }
  65729. return {
  65730. x: x,
  65731. y: y,
  65732. textAlign: align,
  65733. textVerticalAlign: vAlign
  65734. };
  65735. },
  65736. // render month and year text
  65737. _renderMonthText: function (calendarModel, orient, group) {
  65738. var monthLabel = calendarModel.getModel('monthLabel');
  65739. if (!monthLabel.get('show')) {
  65740. return;
  65741. }
  65742. var nameMap = monthLabel.get('nameMap');
  65743. var margin = monthLabel.get('margin');
  65744. var pos = monthLabel.get('position');
  65745. var align = monthLabel.get('align');
  65746. var termPoints = [this._tlpoints, this._blpoints];
  65747. if (isString(nameMap)) {
  65748. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  65749. }
  65750. var idx = pos === 'start' ? 0 : 1;
  65751. var axis = orient === 'horizontal' ? 0 : 1;
  65752. margin = pos === 'start' ? -margin : margin;
  65753. var isCenter = (align === 'center');
  65754. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  65755. var tmp = termPoints[idx][i].slice();
  65756. var firstDay = this._firstDayOfMonth[i];
  65757. if (isCenter) {
  65758. var firstDayPoints = this._firstDayPoints[i];
  65759. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  65760. }
  65761. var formatter = monthLabel.get('formatter');
  65762. var name = nameMap[+firstDay.m - 1];
  65763. var params = {
  65764. yyyy: firstDay.y,
  65765. yy: (firstDay.y + '').slice(2),
  65766. MM: firstDay.m,
  65767. M: +firstDay.m,
  65768. nameMap: name
  65769. };
  65770. var content = this._formatterLabel(formatter, params);
  65771. var monthText = new Text({z2: 30});
  65772. extend(
  65773. setTextStyle(monthText.style, monthLabel, {text: content}),
  65774. this._monthTextPositionControl(tmp, isCenter, orient, pos, margin)
  65775. );
  65776. group.add(monthText);
  65777. }
  65778. },
  65779. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  65780. var align = 'center';
  65781. var vAlign = 'middle';
  65782. var x = point[0];
  65783. var y = point[1];
  65784. var isStart = position === 'start';
  65785. if (orient === 'horizontal') {
  65786. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  65787. align = isStart ? 'right' : 'left';
  65788. }
  65789. else {
  65790. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  65791. vAlign = isStart ? 'bottom' : 'top';
  65792. }
  65793. return {
  65794. x: x,
  65795. y: y,
  65796. textAlign: align,
  65797. textVerticalAlign: vAlign
  65798. };
  65799. },
  65800. // render weeks
  65801. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  65802. var dayLabel = calendarModel.getModel('dayLabel');
  65803. if (!dayLabel.get('show')) {
  65804. return;
  65805. }
  65806. var coordSys = calendarModel.coordinateSystem;
  65807. var pos = dayLabel.get('position');
  65808. var nameMap = dayLabel.get('nameMap');
  65809. var margin = dayLabel.get('margin');
  65810. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  65811. if (isString(nameMap)) {
  65812. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  65813. }
  65814. var start = coordSys.getNextNDay(
  65815. rangeData.end.time, (7 - rangeData.lweek)
  65816. ).time;
  65817. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  65818. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  65819. if (pos === 'start') {
  65820. start = coordSys.getNextNDay(
  65821. rangeData.start.time, -(7 + rangeData.fweek)
  65822. ).time;
  65823. margin = -margin;
  65824. }
  65825. for (var i = 0; i < 7; i++) {
  65826. var tmpD = coordSys.getNextNDay(start, i);
  65827. var point = coordSys.dataToRect([tmpD.time], false).center;
  65828. var day = i;
  65829. day = Math.abs((i + firstDayOfWeek) % 7);
  65830. var weekText = new Text({z2: 30});
  65831. extend(
  65832. setTextStyle(weekText.style, dayLabel, {text: nameMap[day]}),
  65833. this._weekTextPositionControl(point, orient, pos, margin, cellSize)
  65834. );
  65835. group.add(weekText);
  65836. }
  65837. }
  65838. });
  65839. /*
  65840. * Licensed to the Apache Software Foundation (ASF) under one
  65841. * or more contributor license agreements. See the NOTICE file
  65842. * distributed with this work for additional information
  65843. * regarding copyright ownership. The ASF licenses this file
  65844. * to you under the Apache License, Version 2.0 (the
  65845. * "License"); you may not use this file except in compliance
  65846. * with the License. You may obtain a copy of the License at
  65847. *
  65848. * http://www.apache.org/licenses/LICENSE-2.0
  65849. *
  65850. * Unless required by applicable law or agreed to in writing,
  65851. * software distributed under the License is distributed on an
  65852. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65853. * KIND, either express or implied. See the License for the
  65854. * specific language governing permissions and limitations
  65855. * under the License.
  65856. */
  65857. /**
  65858. * @file calendar.js
  65859. * @author dxh
  65860. */
  65861. /*
  65862. * Licensed to the Apache Software Foundation (ASF) under one
  65863. * or more contributor license agreements. See the NOTICE file
  65864. * distributed with this work for additional information
  65865. * regarding copyright ownership. The ASF licenses this file
  65866. * to you under the Apache License, Version 2.0 (the
  65867. * "License"); you may not use this file except in compliance
  65868. * with the License. You may obtain a copy of the License at
  65869. *
  65870. * http://www.apache.org/licenses/LICENSE-2.0
  65871. *
  65872. * Unless required by applicable law or agreed to in writing,
  65873. * software distributed under the License is distributed on an
  65874. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65875. * KIND, either express or implied. See the License for the
  65876. * specific language governing permissions and limitations
  65877. * under the License.
  65878. */
  65879. // Model
  65880. extendComponentModel({
  65881. type: 'title',
  65882. layoutMode: {type: 'box', ignoreSize: true},
  65883. defaultOption: {
  65884. // 一级层叠
  65885. zlevel: 0,
  65886. // 二级层叠
  65887. z: 6,
  65888. show: true,
  65889. text: '',
  65890. // 超链接跳转
  65891. // link: null,
  65892. // 仅支持self | blank
  65893. target: 'blank',
  65894. subtext: '',
  65895. // 超链接跳转
  65896. // sublink: null,
  65897. // 仅支持self | blank
  65898. subtarget: 'blank',
  65899. // 'center' ¦ 'left' ¦ 'right'
  65900. // ¦ {number}(x坐标,单位px)
  65901. left: 0,
  65902. // 'top' ¦ 'bottom' ¦ 'center'
  65903. // ¦ {number}(y坐标,单位px)
  65904. top: 0,
  65905. // 水平对齐
  65906. // 'auto' | 'left' | 'right' | 'center'
  65907. // 默认根据 left 的位置判断是左对齐还是右对齐
  65908. // textAlign: null
  65909. //
  65910. // 垂直对齐
  65911. // 'auto' | 'top' | 'bottom' | 'middle'
  65912. // 默认根据 top 位置判断是上对齐还是下对齐
  65913. // textBaseline: null
  65914. backgroundColor: 'rgba(0,0,0,0)',
  65915. // 标题边框颜色
  65916. borderColor: '#ccc',
  65917. // 标题边框线宽,单位px,默认为0(无边框)
  65918. borderWidth: 0,
  65919. // 标题内边距,单位px,默认各方向内边距为5,
  65920. // 接受数组分别设定上右下左边距,同css
  65921. padding: [13,5,5,16],
  65922. // 主副标题纵向间隔,单位px,默认为10,
  65923. itemGap: 10,
  65924. textStyle: {
  65925. fontSize: 18,
  65926. fontWeight: 'bolder',
  65927. color: '#333'
  65928. },
  65929. subtextStyle: {
  65930. color: '#aaa'
  65931. }
  65932. }
  65933. });
  65934. // View
  65935. extendComponentView({
  65936. type: 'title',
  65937. render: function (titleModel, ecModel, api) {
  65938. this.group.removeAll();
  65939. if (!titleModel.get('show')) {
  65940. return;
  65941. }
  65942. var group = this.group;
  65943. var textStyleModel = titleModel.getModel('textStyle');
  65944. var subtextStyleModel = titleModel.getModel('subtextStyle');
  65945. var textAlign = titleModel.get('textAlign');
  65946. var textBaseline = titleModel.get('textBaseline');
  65947. var textEl = new Text({
  65948. style: setTextStyle({}, textStyleModel, {
  65949. text: titleModel.get('text'),
  65950. textFill: textStyleModel.getTextColor()
  65951. }, {disableBox: true}),
  65952. z2: 10
  65953. });
  65954. var textRect = textEl.getBoundingRect();
  65955. var subText = titleModel.get('subtext');
  65956. var subTextEl = new Text({
  65957. style: setTextStyle({}, subtextStyleModel, {
  65958. text: subText,
  65959. textFill: subtextStyleModel.getTextColor(),
  65960. y: textRect.height + titleModel.get('itemGap'),
  65961. textVerticalAlign: 'top'
  65962. }, {disableBox: true}),
  65963. z2: 10
  65964. });
  65965. var link = titleModel.get('link');
  65966. var sublink = titleModel.get('sublink');
  65967. textEl.silent = !link;
  65968. subTextEl.silent = !sublink;
  65969. if (link) {
  65970. textEl.on('click', function () {
  65971. window.open(link, '_' + titleModel.get('target'));
  65972. });
  65973. }
  65974. if (sublink) {
  65975. subTextEl.on('click', function () {
  65976. window.open(sublink, '_' + titleModel.get('subtarget'));
  65977. });
  65978. }
  65979. group.add(textEl);
  65980. subText && group.add(subTextEl);
  65981. // If no subText, but add subTextEl, there will be an empty line.
  65982. var groupRect = group.getBoundingRect();
  65983. var layoutOption = titleModel.getBoxLayoutParams();
  65984. layoutOption.width = groupRect.width;
  65985. layoutOption.height = groupRect.height;
  65986. var layoutRect = getLayoutRect(
  65987. layoutOption, {
  65988. width: api.getWidth(),
  65989. height: api.getHeight()
  65990. }, titleModel.get('padding')
  65991. );
  65992. // Adjust text align based on position
  65993. if (!textAlign) {
  65994. // Align left if title is on the left. center and right is same
  65995. textAlign = titleModel.get('left') || titleModel.get('right');
  65996. if (textAlign === 'middle') {
  65997. textAlign = 'center';
  65998. }
  65999. // Adjust layout by text align
  66000. if (textAlign === 'right') {
  66001. layoutRect.x += layoutRect.width;
  66002. }
  66003. else if (textAlign === 'center') {
  66004. layoutRect.x += layoutRect.width / 2;
  66005. }
  66006. }
  66007. if (!textBaseline) {
  66008. textBaseline = titleModel.get('top') || titleModel.get('bottom');
  66009. if (textBaseline === 'center') {
  66010. textBaseline = 'middle';
  66011. }
  66012. if (textBaseline === 'bottom') {
  66013. layoutRect.y += layoutRect.height;
  66014. }
  66015. else if (textBaseline === 'middle') {
  66016. layoutRect.y += layoutRect.height / 2;
  66017. }
  66018. textBaseline = textBaseline || 'top';
  66019. }
  66020. group.attr('position', [layoutRect.x, layoutRect.y]);
  66021. var alignStyle = {
  66022. textAlign: textAlign,
  66023. textVerticalAlign: textBaseline
  66024. };
  66025. textEl.setStyle(alignStyle);
  66026. subTextEl.setStyle(alignStyle);
  66027. // Render background
  66028. // Get groupRect again because textAlign has been changed
  66029. groupRect = group.getBoundingRect();
  66030. var padding = layoutRect.margin;
  66031. var style = titleModel.getItemStyle(['color', 'opacity']);
  66032. style.fill = titleModel.get('backgroundColor');
  66033. var rect = new Rect({
  66034. shape: {
  66035. x: groupRect.x - padding[3],
  66036. y: groupRect.y - padding[0],
  66037. width: groupRect.width + padding[1] + padding[3],
  66038. height: groupRect.height + padding[0] + padding[2],
  66039. r: titleModel.get('borderRadius')
  66040. },
  66041. style: style,
  66042. silent: true
  66043. });
  66044. subPixelOptimizeRect(rect);
  66045. group.add(rect);
  66046. }
  66047. });
  66048. /*
  66049. * Licensed to the Apache Software Foundation (ASF) under one
  66050. * or more contributor license agreements. See the NOTICE file
  66051. * distributed with this work for additional information
  66052. * regarding copyright ownership. The ASF licenses this file
  66053. * to you under the Apache License, Version 2.0 (the
  66054. * "License"); you may not use this file except in compliance
  66055. * with the License. You may obtain a copy of the License at
  66056. *
  66057. * http://www.apache.org/licenses/LICENSE-2.0
  66058. *
  66059. * Unless required by applicable law or agreed to in writing,
  66060. * software distributed under the License is distributed on an
  66061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66062. * KIND, either express or implied. See the License for the
  66063. * specific language governing permissions and limitations
  66064. * under the License.
  66065. */
  66066. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  66067. // Default 'slider' when no type specified.
  66068. return 'slider';
  66069. });
  66070. /*
  66071. * Licensed to the Apache Software Foundation (ASF) under one
  66072. * or more contributor license agreements. See the NOTICE file
  66073. * distributed with this work for additional information
  66074. * regarding copyright ownership. The ASF licenses this file
  66075. * to you under the Apache License, Version 2.0 (the
  66076. * "License"); you may not use this file except in compliance
  66077. * with the License. You may obtain a copy of the License at
  66078. *
  66079. * http://www.apache.org/licenses/LICENSE-2.0
  66080. *
  66081. * Unless required by applicable law or agreed to in writing,
  66082. * software distributed under the License is distributed on an
  66083. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66084. * KIND, either express or implied. See the License for the
  66085. * specific language governing permissions and limitations
  66086. * under the License.
  66087. */
  66088. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single'];
  66089. // Supported coords.
  66090. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  66091. /**
  66092. * @param {string} coordType
  66093. * @return {boolean}
  66094. */
  66095. function isCoordSupported(coordType) {
  66096. return indexOf(COORDS, coordType) >= 0;
  66097. }
  66098. /**
  66099. * Create "each" method to iterate names.
  66100. *
  66101. * @pubilc
  66102. * @param {Array.<string>} names
  66103. * @param {Array.<string>=} attrs
  66104. * @return {Function}
  66105. */
  66106. function createNameEach(names, attrs) {
  66107. names = names.slice();
  66108. var capitalNames = map(names, capitalFirst);
  66109. attrs = (attrs || []).slice();
  66110. var capitalAttrs = map(attrs, capitalFirst);
  66111. return function (callback, context) {
  66112. each$1(names, function (name, index) {
  66113. var nameObj = {name: name, capital: capitalNames[index]};
  66114. for (var j = 0; j < attrs.length; j++) {
  66115. nameObj[attrs[j]] = name + capitalAttrs[j];
  66116. }
  66117. callback.call(context, nameObj);
  66118. });
  66119. };
  66120. }
  66121. /**
  66122. * Iterate each dimension name.
  66123. *
  66124. * @public
  66125. * @param {Function} callback The parameter is like:
  66126. * {
  66127. * name: 'angle',
  66128. * capital: 'Angle',
  66129. * axis: 'angleAxis',
  66130. * axisIndex: 'angleAixs',
  66131. * index: 'angleIndex'
  66132. * }
  66133. * @param {Object} context
  66134. */
  66135. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  66136. /**
  66137. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  66138. * dataZoomModels and 'links' make up one or more graphics.
  66139. * This function finds the graphic where the source dataZoomModel is in.
  66140. *
  66141. * @public
  66142. * @param {Function} forEachNode Node iterator.
  66143. * @param {Function} forEachEdgeType edgeType iterator
  66144. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  66145. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  66146. */
  66147. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  66148. return function (sourceNode) {
  66149. var result = {
  66150. nodes: [],
  66151. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  66152. };
  66153. forEachEdgeType(function (edgeType) {
  66154. result.records[edgeType.name] = {};
  66155. });
  66156. if (!sourceNode) {
  66157. return result;
  66158. }
  66159. absorb(sourceNode, result);
  66160. var existsLink;
  66161. do {
  66162. existsLink = false;
  66163. forEachNode(processSingleNode);
  66164. }
  66165. while (existsLink);
  66166. function processSingleNode(node) {
  66167. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  66168. absorb(node, result);
  66169. existsLink = true;
  66170. }
  66171. }
  66172. return result;
  66173. };
  66174. function isNodeAbsorded(node, result) {
  66175. return indexOf(result.nodes, node) >= 0;
  66176. }
  66177. function isLinked(node, result) {
  66178. var hasLink = false;
  66179. forEachEdgeType(function (edgeType) {
  66180. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  66181. result.records[edgeType.name][edgeId] && (hasLink = true);
  66182. });
  66183. });
  66184. return hasLink;
  66185. }
  66186. function absorb(node, result) {
  66187. result.nodes.push(node);
  66188. forEachEdgeType(function (edgeType) {
  66189. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  66190. result.records[edgeType.name][edgeId] = true;
  66191. });
  66192. });
  66193. }
  66194. }
  66195. /*
  66196. * Licensed to the Apache Software Foundation (ASF) under one
  66197. * or more contributor license agreements. See the NOTICE file
  66198. * distributed with this work for additional information
  66199. * regarding copyright ownership. The ASF licenses this file
  66200. * to you under the Apache License, Version 2.0 (the
  66201. * "License"); you may not use this file except in compliance
  66202. * with the License. You may obtain a copy of the License at
  66203. *
  66204. * http://www.apache.org/licenses/LICENSE-2.0
  66205. *
  66206. * Unless required by applicable law or agreed to in writing,
  66207. * software distributed under the License is distributed on an
  66208. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66209. * KIND, either express or implied. See the License for the
  66210. * specific language governing permissions and limitations
  66211. * under the License.
  66212. */
  66213. var each$22 = each$1;
  66214. var asc$1 = asc;
  66215. /**
  66216. * Operate single axis.
  66217. * One axis can only operated by one axis operator.
  66218. * Different dataZoomModels may be defined to operate the same axis.
  66219. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  66220. * So dataZoomModels share one axisProxy in that case.
  66221. *
  66222. * @class
  66223. */
  66224. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  66225. /**
  66226. * @private
  66227. * @type {string}
  66228. */
  66229. this._dimName = dimName;
  66230. /**
  66231. * @private
  66232. */
  66233. this._axisIndex = axisIndex;
  66234. /**
  66235. * @private
  66236. * @type {Array.<number>}
  66237. */
  66238. this._valueWindow;
  66239. /**
  66240. * @private
  66241. * @type {Array.<number>}
  66242. */
  66243. this._percentWindow;
  66244. /**
  66245. * @private
  66246. * @type {Array.<number>}
  66247. */
  66248. this._dataExtent;
  66249. /**
  66250. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  66251. * @private
  66252. * @type {Object}
  66253. */
  66254. this._minMaxSpan;
  66255. /**
  66256. * @readOnly
  66257. * @type {module: echarts/model/Global}
  66258. */
  66259. this.ecModel = ecModel;
  66260. /**
  66261. * @private
  66262. * @type {module: echarts/component/dataZoom/DataZoomModel}
  66263. */
  66264. this._dataZoomModel = dataZoomModel;
  66265. // /**
  66266. // * @readOnly
  66267. // * @private
  66268. // */
  66269. // this.hasSeriesStacked;
  66270. };
  66271. AxisProxy.prototype = {
  66272. constructor: AxisProxy,
  66273. /**
  66274. * Whether the axisProxy is hosted by dataZoomModel.
  66275. *
  66276. * @public
  66277. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66278. * @return {boolean}
  66279. */
  66280. hostedBy: function (dataZoomModel) {
  66281. return this._dataZoomModel === dataZoomModel;
  66282. },
  66283. /**
  66284. * @return {Array.<number>} Value can only be NaN or finite value.
  66285. */
  66286. getDataValueWindow: function () {
  66287. return this._valueWindow.slice();
  66288. },
  66289. /**
  66290. * @return {Array.<number>}
  66291. */
  66292. getDataPercentWindow: function () {
  66293. return this._percentWindow.slice();
  66294. },
  66295. /**
  66296. * @public
  66297. * @param {number} axisIndex
  66298. * @return {Array} seriesModels
  66299. */
  66300. getTargetSeriesModels: function () {
  66301. var seriesModels = [];
  66302. var ecModel = this.ecModel;
  66303. ecModel.eachSeries(function (seriesModel) {
  66304. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  66305. var dimName = this._dimName;
  66306. var axisModel = ecModel.queryComponents({
  66307. mainType: dimName + 'Axis',
  66308. index: seriesModel.get(dimName + 'AxisIndex'),
  66309. id: seriesModel.get(dimName + 'AxisId')
  66310. })[0];
  66311. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  66312. seriesModels.push(seriesModel);
  66313. }
  66314. }
  66315. }, this);
  66316. return seriesModels;
  66317. },
  66318. getAxisModel: function () {
  66319. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  66320. },
  66321. getOtherAxisModel: function () {
  66322. var axisDim = this._dimName;
  66323. var ecModel = this.ecModel;
  66324. var axisModel = this.getAxisModel();
  66325. var isCartesian = axisDim === 'x' || axisDim === 'y';
  66326. var otherAxisDim;
  66327. var coordSysIndexName;
  66328. if (isCartesian) {
  66329. coordSysIndexName = 'gridIndex';
  66330. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  66331. }
  66332. else {
  66333. coordSysIndexName = 'polarIndex';
  66334. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  66335. }
  66336. var foundOtherAxisModel;
  66337. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  66338. if ((otherAxisModel.get(coordSysIndexName) || 0)
  66339. === (axisModel.get(coordSysIndexName) || 0)
  66340. ) {
  66341. foundOtherAxisModel = otherAxisModel;
  66342. }
  66343. });
  66344. return foundOtherAxisModel;
  66345. },
  66346. getMinMaxSpan: function () {
  66347. return clone(this._minMaxSpan);
  66348. },
  66349. /**
  66350. * Only calculate by given range and this._dataExtent, do not change anything.
  66351. *
  66352. * @param {Object} opt
  66353. * @param {number} [opt.start]
  66354. * @param {number} [opt.end]
  66355. * @param {number} [opt.startValue]
  66356. * @param {number} [opt.endValue]
  66357. */
  66358. calculateDataWindow: function (opt) {
  66359. var dataExtent = this._dataExtent;
  66360. var axisModel = this.getAxisModel();
  66361. var scale = axisModel.axis.scale;
  66362. var rangePropMode = this._dataZoomModel.getRangePropMode();
  66363. var percentExtent = [0, 100];
  66364. var percentWindow = [
  66365. opt.start,
  66366. opt.end
  66367. ];
  66368. var valueWindow = [];
  66369. each$22(['startValue', 'endValue'], function (prop) {
  66370. valueWindow.push(opt[prop] != null ? scale.parse(opt[prop]) : null);
  66371. });
  66372. // Normalize bound.
  66373. each$22([0, 1], function (idx) {
  66374. var boundValue = valueWindow[idx];
  66375. var boundPercent = percentWindow[idx];
  66376. // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  66377. // on `valueProp` ('startValue', 'endValue'). The former one is suitable
  66378. // for cases that a dataZoom component controls multiple axes with different
  66379. // unit or extent, and the latter one is suitable for accurate zoom by pixel
  66380. // (e.g., in dataZoomSelect). `valueProp` can be calculated from `percentProp`,
  66381. // but it is awkward that `percentProp` can not be obtained from `valueProp`
  66382. // accurately (because all of values that are overflow the `dataExtent` will
  66383. // be calculated to percent '100%'). So we have to use
  66384. // `dataZoom.getRangePropMode()` to mark which prop is used.
  66385. // `rangePropMode` is updated only when setOption or dispatchAction, otherwise
  66386. // it remains its original value.
  66387. if (rangePropMode[idx] === 'percent') {
  66388. if (boundPercent == null) {
  66389. boundPercent = percentExtent[idx];
  66390. }
  66391. // Use scale.parse to math round for category or time axis.
  66392. boundValue = scale.parse(linearMap(
  66393. boundPercent, percentExtent, dataExtent, true
  66394. ));
  66395. }
  66396. else {
  66397. // Calculating `percent` from `value` may be not accurate, because
  66398. // This calculation can not be inversed, because all of values that
  66399. // are overflow the `dataExtent` will be calculated to percent '100%'
  66400. boundPercent = linearMap(
  66401. boundValue, dataExtent, percentExtent, true
  66402. );
  66403. }
  66404. // valueWindow[idx] = round(boundValue);
  66405. // percentWindow[idx] = round(boundPercent);
  66406. valueWindow[idx] = boundValue;
  66407. percentWindow[idx] = boundPercent;
  66408. });
  66409. return {
  66410. valueWindow: asc$1(valueWindow),
  66411. percentWindow: asc$1(percentWindow)
  66412. };
  66413. },
  66414. /**
  66415. * Notice: reset should not be called before series.restoreData() called,
  66416. * so it is recommanded to be called in "process stage" but not "model init
  66417. * stage".
  66418. *
  66419. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66420. */
  66421. reset: function (dataZoomModel) {
  66422. if (dataZoomModel !== this._dataZoomModel) {
  66423. return;
  66424. }
  66425. var targetSeries = this.getTargetSeriesModels();
  66426. // Culculate data window and data extent, and record them.
  66427. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries);
  66428. // this.hasSeriesStacked = false;
  66429. // each(targetSeries, function (series) {
  66430. // var data = series.getData();
  66431. // var dataDim = data.mapDimension(this._dimName);
  66432. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  66433. // if (stackedDimension && stackedDimension === dataDim) {
  66434. // this.hasSeriesStacked = true;
  66435. // }
  66436. // }, this);
  66437. var dataWindow = this.calculateDataWindow(dataZoomModel.option);
  66438. this._valueWindow = dataWindow.valueWindow;
  66439. this._percentWindow = dataWindow.percentWindow;
  66440. setMinMaxSpan(this);
  66441. // Update axis setting then.
  66442. setAxisModel(this);
  66443. },
  66444. /**
  66445. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66446. */
  66447. restore: function (dataZoomModel) {
  66448. if (dataZoomModel !== this._dataZoomModel) {
  66449. return;
  66450. }
  66451. this._valueWindow = this._percentWindow = null;
  66452. setAxisModel(this, true);
  66453. },
  66454. /**
  66455. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  66456. */
  66457. filterData: function (dataZoomModel, api) {
  66458. if (dataZoomModel !== this._dataZoomModel) {
  66459. return;
  66460. }
  66461. var axisDim = this._dimName;
  66462. var seriesModels = this.getTargetSeriesModels();
  66463. var filterMode = dataZoomModel.get('filterMode');
  66464. var valueWindow = this._valueWindow;
  66465. if (filterMode === 'none') {
  66466. return;
  66467. }
  66468. // FIXME
  66469. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  66470. // with NaN data, NaN will be filtered and stack will be wrong.
  66471. // So we need to force the mode to be set empty.
  66472. // In fect, it is not a big deal that do not support filterMode-'filter'
  66473. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  66474. // selection" some day, which might need "adapt to data extent on the
  66475. // otherAxis", which is disabled by filterMode-'empty'.
  66476. // But currently, stack has been fixed to based on value but not index,
  66477. // so this is not an issue any more.
  66478. // var otherAxisModel = this.getOtherAxisModel();
  66479. // if (dataZoomModel.get('$fromToolbox')
  66480. // && otherAxisModel
  66481. // && otherAxisModel.hasSeriesStacked
  66482. // ) {
  66483. // filterMode = 'empty';
  66484. // }
  66485. // TODO
  66486. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  66487. // Process series data
  66488. each$22(seriesModels, function (seriesModel) {
  66489. var seriesData = seriesModel.getData();
  66490. var dataDims = seriesData.mapDimension(axisDim, true);
  66491. if (filterMode === 'weakFilter') {
  66492. seriesData.filterSelf(function (dataIndex) {
  66493. var leftOut;
  66494. var rightOut;
  66495. var hasValue;
  66496. for (var i = 0; i < dataDims.length; i++) {
  66497. var value = seriesData.get(dataDims[i], dataIndex);
  66498. var thisHasValue = !isNaN(value);
  66499. var thisLeftOut = value < valueWindow[0];
  66500. var thisRightOut = value > valueWindow[1];
  66501. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  66502. return true;
  66503. }
  66504. thisHasValue && (hasValue = true);
  66505. thisLeftOut && (leftOut = true);
  66506. thisRightOut && (rightOut = true);
  66507. }
  66508. // If both left out and right out, do not filter.
  66509. return hasValue && leftOut && rightOut;
  66510. });
  66511. }
  66512. else {
  66513. each$22(dataDims, function (dim) {
  66514. if (filterMode === 'empty') {
  66515. seriesModel.setData(
  66516. seriesData.map(dim, function (value) {
  66517. return !isInWindow(value) ? NaN : value;
  66518. })
  66519. );
  66520. }
  66521. else {
  66522. var range = {};
  66523. range[dim] = valueWindow;
  66524. // console.time('select');
  66525. seriesData.selectRange(range);
  66526. // console.timeEnd('select');
  66527. }
  66528. });
  66529. }
  66530. each$22(dataDims, function (dim) {
  66531. seriesData.setApproximateExtent(valueWindow, dim);
  66532. });
  66533. });
  66534. function isInWindow(value) {
  66535. return value >= valueWindow[0] && value <= valueWindow[1];
  66536. }
  66537. }
  66538. };
  66539. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  66540. var dataExtent = [Infinity, -Infinity];
  66541. each$22(seriesModels, function (seriesModel) {
  66542. var seriesData = seriesModel.getData();
  66543. if (seriesData) {
  66544. each$22(seriesData.mapDimension(axisDim, true), function (dim) {
  66545. var seriesExtent = seriesData.getApproximateExtent(dim);
  66546. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  66547. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  66548. });
  66549. }
  66550. });
  66551. if (dataExtent[1] < dataExtent[0]) {
  66552. dataExtent = [NaN, NaN];
  66553. }
  66554. // It is important to get "consistent" extent when more then one axes is
  66555. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  66556. // when zooming. But it is difficult to know what is "consistent", considering
  66557. // axes have different type or even different meanings (For example, two
  66558. // time axes are used to compare data of the same date in different years).
  66559. // So basically dataZoom just obtains extent by series.data (in category axis
  66560. // extent can be obtained from axis.data).
  66561. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  66562. // consistent.
  66563. fixExtentByAxis(axisProxy, dataExtent);
  66564. return dataExtent;
  66565. }
  66566. function fixExtentByAxis(axisProxy, dataExtent) {
  66567. var axisModel = axisProxy.getAxisModel();
  66568. var min = axisModel.getMin(true);
  66569. // For category axis, if min/max/scale are not set, extent is determined
  66570. // by axis.data by default.
  66571. var isCategoryAxis = axisModel.get('type') === 'category';
  66572. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  66573. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  66574. dataExtent[0] = min;
  66575. }
  66576. else if (isCategoryAxis) {
  66577. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  66578. }
  66579. var max = axisModel.getMax(true);
  66580. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  66581. dataExtent[1] = max;
  66582. }
  66583. else if (isCategoryAxis) {
  66584. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  66585. }
  66586. if (!axisModel.get('scale', true)) {
  66587. dataExtent[0] > 0 && (dataExtent[0] = 0);
  66588. dataExtent[1] < 0 && (dataExtent[1] = 0);
  66589. }
  66590. // For value axis, if min/max/scale are not set, we just use the extent obtained
  66591. // by series data, which may be a little different from the extent calculated by
  66592. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  66593. // little when zooming. So it will not be fixed until some users require it strongly.
  66594. return dataExtent;
  66595. }
  66596. function setAxisModel(axisProxy, isRestore) {
  66597. var axisModel = axisProxy.getAxisModel();
  66598. var percentWindow = axisProxy._percentWindow;
  66599. var valueWindow = axisProxy._valueWindow;
  66600. if (!percentWindow) {
  66601. return;
  66602. }
  66603. // [0, 500]: arbitrary value, guess axis extent.
  66604. var precision = getPixelPrecision(valueWindow, [0, 500]);
  66605. precision = Math.min(precision, 20);
  66606. // isRestore or isFull
  66607. var useOrigin = isRestore || (percentWindow[0] === 0 && percentWindow[1] === 100);
  66608. axisModel.setRange(
  66609. useOrigin ? null : +valueWindow[0].toFixed(precision),
  66610. useOrigin ? null : +valueWindow[1].toFixed(precision)
  66611. );
  66612. }
  66613. function setMinMaxSpan(axisProxy) {
  66614. var minMaxSpan = axisProxy._minMaxSpan = {};
  66615. var dataZoomModel = axisProxy._dataZoomModel;
  66616. each$22(['min', 'max'], function (minMax) {
  66617. minMaxSpan[minMax + 'Span'] = dataZoomModel.get(minMax + 'Span');
  66618. // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  66619. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  66620. if (valueSpan != null) {
  66621. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  66622. valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan);
  66623. if (valueSpan != null) {
  66624. var dataExtent = axisProxy._dataExtent;
  66625. minMaxSpan[minMax + 'Span'] = linearMap(
  66626. dataExtent[0] + valueSpan, dataExtent, [0, 100], true
  66627. );
  66628. }
  66629. }
  66630. });
  66631. }
  66632. /*
  66633. * Licensed to the Apache Software Foundation (ASF) under one
  66634. * or more contributor license agreements. See the NOTICE file
  66635. * distributed with this work for additional information
  66636. * regarding copyright ownership. The ASF licenses this file
  66637. * to you under the Apache License, Version 2.0 (the
  66638. * "License"); you may not use this file except in compliance
  66639. * with the License. You may obtain a copy of the License at
  66640. *
  66641. * http://www.apache.org/licenses/LICENSE-2.0
  66642. *
  66643. * Unless required by applicable law or agreed to in writing,
  66644. * software distributed under the License is distributed on an
  66645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66646. * KIND, either express or implied. See the License for the
  66647. * specific language governing permissions and limitations
  66648. * under the License.
  66649. */
  66650. var each$21 = each$1;
  66651. var eachAxisDim = eachAxisDim$1;
  66652. var DataZoomModel = extendComponentModel({
  66653. type: 'dataZoom',
  66654. dependencies: [
  66655. 'xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'
  66656. ],
  66657. /**
  66658. * @protected
  66659. */
  66660. defaultOption: {
  66661. zlevel: 0,
  66662. z: 4, // Higher than normal component (z: 2).
  66663. orient: null, // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  66664. xAxisIndex: null, // Default the first horizontal category axis.
  66665. yAxisIndex: null, // Default the first vertical category axis.
  66666. filterMode: 'filter', // Possible values: 'filter' or 'empty' or 'weakFilter'.
  66667. // 'filter': data items which are out of window will be removed. This option is
  66668. // applicable when filtering outliers. For each data item, it will be
  66669. // filtered if one of the relevant dimensions is out of the window.
  66670. // 'weakFilter': data items which are out of window will be removed. This option
  66671. // is applicable when filtering outliers. For each data item, it will be
  66672. // filtered only if all of the relevant dimensions are out of the same
  66673. // side of the window.
  66674. // 'empty': data items which are out of window will be set to empty.
  66675. // This option is applicable when user should not neglect
  66676. // that there are some data items out of window.
  66677. // 'none': Do not filter.
  66678. // Taking line chart as an example, line will be broken in
  66679. // the filtered points when filterModel is set to 'empty', but
  66680. // be connected when set to 'filter'.
  66681. throttle: null, // Dispatch action by the fixed rate, avoid frequency.
  66682. // default 100. Do not throttle when use null/undefined.
  66683. // If animation === true and animationDurationUpdate > 0,
  66684. // default value is 100, otherwise 20.
  66685. start: 0, // Start percent. 0 ~ 100
  66686. end: 100, // End percent. 0 ~ 100
  66687. startValue: null, // Start value. If startValue specified, start is ignored.
  66688. endValue: null, // End value. If endValue specified, end is ignored.
  66689. minSpan: null, // 0 ~ 100
  66690. maxSpan: null, // 0 ~ 100
  66691. minValueSpan: null, // The range of dataZoom can not be smaller than that.
  66692. maxValueSpan: null, // The range of dataZoom can not be larger than that.
  66693. rangeMode: null // Array, can be 'value' or 'percent'.
  66694. },
  66695. /**
  66696. * @override
  66697. */
  66698. init: function (option, parentModel, ecModel) {
  66699. /**
  66700. * key like x_0, y_1
  66701. * @private
  66702. * @type {Object}
  66703. */
  66704. this._dataIntervalByAxis = {};
  66705. /**
  66706. * @private
  66707. */
  66708. this._dataInfo = {};
  66709. /**
  66710. * key like x_0, y_1
  66711. * @private
  66712. */
  66713. this._axisProxies = {};
  66714. /**
  66715. * @readOnly
  66716. */
  66717. this.textStyleModel;
  66718. /**
  66719. * @private
  66720. */
  66721. this._autoThrottle = true;
  66722. /**
  66723. * 'percent' or 'value'
  66724. * @private
  66725. */
  66726. this._rangePropMode = ['percent', 'percent'];
  66727. var rawOption = retrieveRaw(option);
  66728. this.mergeDefaultAndTheme(option, ecModel);
  66729. this.doInit(rawOption);
  66730. },
  66731. /**
  66732. * @override
  66733. */
  66734. mergeOption: function (newOption) {
  66735. var rawOption = retrieveRaw(newOption);
  66736. //FIX #2591
  66737. merge(this.option, newOption, true);
  66738. this.doInit(rawOption);
  66739. },
  66740. /**
  66741. * @protected
  66742. */
  66743. doInit: function (rawOption) {
  66744. var thisOption = this.option;
  66745. // Disable realtime view update if canvas is not supported.
  66746. if (!env$1.canvasSupported) {
  66747. thisOption.realtime = false;
  66748. }
  66749. this._setDefaultThrottle(rawOption);
  66750. updateRangeUse(this, rawOption);
  66751. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  66752. // start/end has higher priority over startValue/endValue if they
  66753. // both set, but we should make chart.setOption({endValue: 1000})
  66754. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  66755. if (this._rangePropMode[index] === 'value') {
  66756. thisOption[names[0]] = null;
  66757. }
  66758. // Otherwise do nothing and use the merge result.
  66759. }, this);
  66760. this.textStyleModel = this.getModel('textStyle');
  66761. this._resetTarget();
  66762. this._giveAxisProxies();
  66763. },
  66764. /**
  66765. * @private
  66766. */
  66767. _giveAxisProxies: function () {
  66768. var axisProxies = this._axisProxies;
  66769. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  66770. var axisModel = this.dependentModels[dimNames.axis][axisIndex];
  66771. // If exists, share axisProxy with other dataZoomModels.
  66772. var axisProxy = axisModel.__dzAxisProxy || (
  66773. // Use the first dataZoomModel as the main model of axisProxy.
  66774. axisModel.__dzAxisProxy = new AxisProxy(
  66775. dimNames.name, axisIndex, this, ecModel
  66776. )
  66777. );
  66778. // FIXME
  66779. // dispose __dzAxisProxy
  66780. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  66781. }, this);
  66782. },
  66783. /**
  66784. * @private
  66785. */
  66786. _resetTarget: function () {
  66787. var thisOption = this.option;
  66788. var autoMode = this._judgeAutoMode();
  66789. eachAxisDim(function (dimNames) {
  66790. var axisIndexName = dimNames.axisIndex;
  66791. thisOption[axisIndexName] = normalizeToArray(
  66792. thisOption[axisIndexName]
  66793. );
  66794. }, this);
  66795. if (autoMode === 'axisIndex') {
  66796. this._autoSetAxisIndex();
  66797. }
  66798. else if (autoMode === 'orient') {
  66799. this._autoSetOrient();
  66800. }
  66801. },
  66802. /**
  66803. * @private
  66804. */
  66805. _judgeAutoMode: function () {
  66806. // Auto set only works for setOption at the first time.
  66807. // The following is user's reponsibility. So using merged
  66808. // option is OK.
  66809. var thisOption = this.option;
  66810. var hasIndexSpecified = false;
  66811. eachAxisDim(function (dimNames) {
  66812. // When user set axisIndex as a empty array, we think that user specify axisIndex
  66813. // but do not want use auto mode. Because empty array may be encountered when
  66814. // some error occured.
  66815. if (thisOption[dimNames.axisIndex] != null) {
  66816. hasIndexSpecified = true;
  66817. }
  66818. }, this);
  66819. var orient = thisOption.orient;
  66820. if (orient == null && hasIndexSpecified) {
  66821. return 'orient';
  66822. }
  66823. else if (!hasIndexSpecified) {
  66824. if (orient == null) {
  66825. thisOption.orient = 'horizontal';
  66826. }
  66827. return 'axisIndex';
  66828. }
  66829. },
  66830. /**
  66831. * @private
  66832. */
  66833. _autoSetAxisIndex: function () {
  66834. var autoAxisIndex = true;
  66835. var orient = this.get('orient', true);
  66836. var thisOption = this.option;
  66837. var dependentModels = this.dependentModels;
  66838. if (autoAxisIndex) {
  66839. // Find axis that parallel to dataZoom as default.
  66840. var dimName = orient === 'vertical' ? 'y' : 'x';
  66841. if (dependentModels[dimName + 'Axis'].length) {
  66842. thisOption[dimName + 'AxisIndex'] = [0];
  66843. autoAxisIndex = false;
  66844. }
  66845. else {
  66846. each$21(dependentModels.singleAxis, function (singleAxisModel) {
  66847. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  66848. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  66849. autoAxisIndex = false;
  66850. }
  66851. });
  66852. }
  66853. }
  66854. if (autoAxisIndex) {
  66855. // Find the first category axis as default. (consider polar)
  66856. eachAxisDim(function (dimNames) {
  66857. if (!autoAxisIndex) {
  66858. return;
  66859. }
  66860. var axisIndices = [];
  66861. var axisModels = this.dependentModels[dimNames.axis];
  66862. if (axisModels.length && !axisIndices.length) {
  66863. for (var i = 0, len = axisModels.length; i < len; i++) {
  66864. if (axisModels[i].get('type') === 'category') {
  66865. axisIndices.push(i);
  66866. }
  66867. }
  66868. }
  66869. thisOption[dimNames.axisIndex] = axisIndices;
  66870. if (axisIndices.length) {
  66871. autoAxisIndex = false;
  66872. }
  66873. }, this);
  66874. }
  66875. if (autoAxisIndex) {
  66876. // FIXME
  66877. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  66878. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  66879. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  66880. // dataZoom component auto adopts series that reference to
  66881. // both xAxis and yAxis which type is 'value'.
  66882. this.ecModel.eachSeries(function (seriesModel) {
  66883. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  66884. eachAxisDim(function (dimNames) {
  66885. var axisIndices = thisOption[dimNames.axisIndex];
  66886. var axisIndex = seriesModel.get(dimNames.axisIndex);
  66887. var axisId = seriesModel.get(dimNames.axisId);
  66888. var axisModel = seriesModel.ecModel.queryComponents({
  66889. mainType: dimNames.axis,
  66890. index: axisIndex,
  66891. id: axisId
  66892. })[0];
  66893. if (__DEV__) {
  66894. if (!axisModel) {
  66895. throw new Error(
  66896. dimNames.axis + ' "' + retrieve(
  66897. axisIndex,
  66898. axisId,
  66899. 0
  66900. ) + '" not found'
  66901. );
  66902. }
  66903. }
  66904. axisIndex = axisModel.componentIndex;
  66905. if (indexOf(axisIndices, axisIndex) < 0) {
  66906. axisIndices.push(axisIndex);
  66907. }
  66908. });
  66909. }
  66910. }, this);
  66911. }
  66912. },
  66913. /**
  66914. * @private
  66915. */
  66916. _autoSetOrient: function () {
  66917. var dim;
  66918. // Find the first axis
  66919. this.eachTargetAxis(function (dimNames) {
  66920. !dim && (dim = dimNames.name);
  66921. }, this);
  66922. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  66923. },
  66924. /**
  66925. * @private
  66926. */
  66927. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  66928. // FIXME
  66929. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  66930. // 例如series.type === scatter时。
  66931. var is = true;
  66932. eachAxisDim(function (dimNames) {
  66933. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  66934. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  66935. if (!axisModel || axisModel.get('type') !== axisType) {
  66936. is = false;
  66937. }
  66938. }, this);
  66939. return is;
  66940. },
  66941. /**
  66942. * @private
  66943. */
  66944. _setDefaultThrottle: function (rawOption) {
  66945. // When first time user set throttle, auto throttle ends.
  66946. if (rawOption.hasOwnProperty('throttle')) {
  66947. this._autoThrottle = false;
  66948. }
  66949. if (this._autoThrottle) {
  66950. var globalOption = this.ecModel.option;
  66951. this.option.throttle =
  66952. (globalOption.animation && globalOption.animationDurationUpdate > 0)
  66953. ? 100 : 20;
  66954. }
  66955. },
  66956. /**
  66957. * @public
  66958. */
  66959. getFirstTargetAxisModel: function () {
  66960. var firstAxisModel;
  66961. eachAxisDim(function (dimNames) {
  66962. if (firstAxisModel == null) {
  66963. var indices = this.get(dimNames.axisIndex);
  66964. if (indices.length) {
  66965. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  66966. }
  66967. }
  66968. }, this);
  66969. return firstAxisModel;
  66970. },
  66971. /**
  66972. * @public
  66973. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  66974. */
  66975. eachTargetAxis: function (callback, context) {
  66976. var ecModel = this.ecModel;
  66977. eachAxisDim(function (dimNames) {
  66978. each$21(
  66979. this.get(dimNames.axisIndex),
  66980. function (axisIndex) {
  66981. callback.call(context, dimNames, axisIndex, this, ecModel);
  66982. },
  66983. this
  66984. );
  66985. }, this);
  66986. },
  66987. /**
  66988. * @param {string} dimName
  66989. * @param {number} axisIndex
  66990. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  66991. */
  66992. getAxisProxy: function (dimName, axisIndex) {
  66993. return this._axisProxies[dimName + '_' + axisIndex];
  66994. },
  66995. /**
  66996. * @param {string} dimName
  66997. * @param {number} axisIndex
  66998. * @return {module:echarts/model/Model} If not found, return null/undefined.
  66999. */
  67000. getAxisModel: function (dimName, axisIndex) {
  67001. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  67002. return axisProxy && axisProxy.getAxisModel();
  67003. },
  67004. /**
  67005. * If not specified, set to undefined.
  67006. *
  67007. * @public
  67008. * @param {Object} opt
  67009. * @param {number} [opt.start]
  67010. * @param {number} [opt.end]
  67011. * @param {number} [opt.startValue]
  67012. * @param {number} [opt.endValue]
  67013. * @param {boolean} [ignoreUpdateRangeUsg=false]
  67014. */
  67015. setRawRange: function (opt, ignoreUpdateRangeUsg) {
  67016. var option = this.option;
  67017. each$21([['start', 'startValue'], ['end', 'endValue']], function (names) {
  67018. // If only one of 'start' and 'startValue' is not null/undefined, the other
  67019. // should be cleared, which enable clear the option.
  67020. // If both of them are not set, keep option with the original value, which
  67021. // enable use only set start but not set end when calling `dispatchAction`.
  67022. // The same as 'end' and 'endValue'.
  67023. if (opt[names[0]] != null || opt[names[1]] != null) {
  67024. option[names[0]] = opt[names[0]];
  67025. option[names[1]] = opt[names[1]];
  67026. }
  67027. }, this);
  67028. !ignoreUpdateRangeUsg && updateRangeUse(this, opt);
  67029. },
  67030. /**
  67031. * @public
  67032. * @return {Array.<number>} [startPercent, endPercent]
  67033. */
  67034. getPercentRange: function () {
  67035. var axisProxy = this.findRepresentativeAxisProxy();
  67036. if (axisProxy) {
  67037. return axisProxy.getDataPercentWindow();
  67038. }
  67039. },
  67040. /**
  67041. * @public
  67042. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  67043. *
  67044. * @param {string} [axisDimName]
  67045. * @param {number} [axisIndex]
  67046. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  67047. */
  67048. getValueRange: function (axisDimName, axisIndex) {
  67049. if (axisDimName == null && axisIndex == null) {
  67050. var axisProxy = this.findRepresentativeAxisProxy();
  67051. if (axisProxy) {
  67052. return axisProxy.getDataValueWindow();
  67053. }
  67054. }
  67055. else {
  67056. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  67057. }
  67058. },
  67059. /**
  67060. * @public
  67061. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  67062. * corresponding to the axisModel
  67063. * @return {module:echarts/component/dataZoom/AxisProxy}
  67064. */
  67065. findRepresentativeAxisProxy: function (axisModel) {
  67066. if (axisModel) {
  67067. return axisModel.__dzAxisProxy;
  67068. }
  67069. // Find the first hosted axisProxy
  67070. var axisProxies = this._axisProxies;
  67071. for (var key in axisProxies) {
  67072. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  67073. return axisProxies[key];
  67074. }
  67075. }
  67076. // If no hosted axis find not hosted axisProxy.
  67077. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  67078. // and the option.start or option.end settings are different. The percentRange
  67079. // should follow axisProxy.
  67080. // (We encounter this problem in toolbox data zoom.)
  67081. for (var key in axisProxies) {
  67082. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  67083. return axisProxies[key];
  67084. }
  67085. }
  67086. },
  67087. /**
  67088. * @return {Array.<string>}
  67089. */
  67090. getRangePropMode: function () {
  67091. return this._rangePropMode.slice();
  67092. }
  67093. });
  67094. function retrieveRaw(option) {
  67095. var ret = {};
  67096. each$21(
  67097. ['start', 'end', 'startValue', 'endValue', 'throttle'],
  67098. function (name) {
  67099. option.hasOwnProperty(name) && (ret[name] = option[name]);
  67100. }
  67101. );
  67102. return ret;
  67103. }
  67104. function updateRangeUse(dataZoomModel, rawOption) {
  67105. var rangePropMode = dataZoomModel._rangePropMode;
  67106. var rangeModeInOption = dataZoomModel.get('rangeMode');
  67107. each$21([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  67108. var percentSpecified = rawOption[names[0]] != null;
  67109. var valueSpecified = rawOption[names[1]] != null;
  67110. if (percentSpecified && !valueSpecified) {
  67111. rangePropMode[index] = 'percent';
  67112. }
  67113. else if (!percentSpecified && valueSpecified) {
  67114. rangePropMode[index] = 'value';
  67115. }
  67116. else if (rangeModeInOption) {
  67117. rangePropMode[index] = rangeModeInOption[index];
  67118. }
  67119. else if (percentSpecified) { // percentSpecified && valueSpecified
  67120. rangePropMode[index] = 'percent';
  67121. }
  67122. // else remain its original setting.
  67123. });
  67124. }
  67125. /*
  67126. * Licensed to the Apache Software Foundation (ASF) under one
  67127. * or more contributor license agreements. See the NOTICE file
  67128. * distributed with this work for additional information
  67129. * regarding copyright ownership. The ASF licenses this file
  67130. * to you under the Apache License, Version 2.0 (the
  67131. * "License"); you may not use this file except in compliance
  67132. * with the License. You may obtain a copy of the License at
  67133. *
  67134. * http://www.apache.org/licenses/LICENSE-2.0
  67135. *
  67136. * Unless required by applicable law or agreed to in writing,
  67137. * software distributed under the License is distributed on an
  67138. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67139. * KIND, either express or implied. See the License for the
  67140. * specific language governing permissions and limitations
  67141. * under the License.
  67142. */
  67143. var DataZoomView = Component.extend({
  67144. type: 'dataZoom',
  67145. render: function (dataZoomModel, ecModel, api, payload) {
  67146. this.dataZoomModel = dataZoomModel;
  67147. this.ecModel = ecModel;
  67148. this.api = api;
  67149. },
  67150. /**
  67151. * Find the first target coordinate system.
  67152. *
  67153. * @protected
  67154. * @return {Object} {
  67155. * grid: [
  67156. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  67157. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  67158. * ...
  67159. * ], // cartesians must not be null/undefined.
  67160. * polar: [
  67161. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  67162. * ...
  67163. * ], // polars must not be null/undefined.
  67164. * singleAxis: [
  67165. * {model: coord0, axisModels: [], coordIndex: 0}
  67166. * ]
  67167. */
  67168. getTargetCoordInfo: function () {
  67169. var dataZoomModel = this.dataZoomModel;
  67170. var ecModel = this.ecModel;
  67171. var coordSysLists = {};
  67172. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  67173. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  67174. if (axisModel) {
  67175. var coordModel = axisModel.getCoordSysModel();
  67176. coordModel && save(
  67177. coordModel,
  67178. axisModel,
  67179. coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []),
  67180. coordModel.componentIndex
  67181. );
  67182. }
  67183. }, this);
  67184. function save(coordModel, axisModel, store, coordIndex) {
  67185. var item;
  67186. for (var i = 0; i < store.length; i++) {
  67187. if (store[i].model === coordModel) {
  67188. item = store[i];
  67189. break;
  67190. }
  67191. }
  67192. if (!item) {
  67193. store.push(item = {
  67194. model: coordModel, axisModels: [], coordIndex: coordIndex
  67195. });
  67196. }
  67197. item.axisModels.push(axisModel);
  67198. }
  67199. return coordSysLists;
  67200. }
  67201. });
  67202. /*
  67203. * Licensed to the Apache Software Foundation (ASF) under one
  67204. * or more contributor license agreements. See the NOTICE file
  67205. * distributed with this work for additional information
  67206. * regarding copyright ownership. The ASF licenses this file
  67207. * to you under the Apache License, Version 2.0 (the
  67208. * "License"); you may not use this file except in compliance
  67209. * with the License. You may obtain a copy of the License at
  67210. *
  67211. * http://www.apache.org/licenses/LICENSE-2.0
  67212. *
  67213. * Unless required by applicable law or agreed to in writing,
  67214. * software distributed under the License is distributed on an
  67215. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67216. * KIND, either express or implied. See the License for the
  67217. * specific language governing permissions and limitations
  67218. * under the License.
  67219. */
  67220. var SliderZoomModel = DataZoomModel.extend({
  67221. type: 'dataZoom.slider',
  67222. layoutMode: 'box',
  67223. /**
  67224. * @protected
  67225. */
  67226. defaultOption: {
  67227. show: true,
  67228. // ph => placeholder. Using placehoder here because
  67229. // deault value can only be drived in view stage.
  67230. right: 'ph', // Default align to grid rect.
  67231. top: 'ph', // Default align to grid rect.
  67232. width: 'ph', // Default align to grid rect.
  67233. height: 'ph', // Default align to grid rect.
  67234. left: null, // Default align to grid rect.
  67235. bottom: null, // Default align to grid rect.
  67236. backgroundColor: 'rgba(47,69,84,0)', // Background of slider zoom component.
  67237. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  67238. // highest priority, remain for compatibility of
  67239. // previous version, but not recommended any more.
  67240. dataBackground: {
  67241. lineStyle: {
  67242. color: '#2f4554',
  67243. width: 0.5,
  67244. opacity: 0.3
  67245. },
  67246. areaStyle: {
  67247. color: 'rgba(47,69,84,0.3)',
  67248. opacity: 0.3
  67249. }
  67250. },
  67251. borderColor: '#ddd', // border color of the box. For compatibility,
  67252. // if dataBackgroundColor is set, borderColor
  67253. // is ignored.
  67254. fillerColor: 'rgba(167,183,204,0.4)', // Color of selected area.
  67255. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  67256. // 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',
  67257. 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',
  67258. // Percent of the slider height
  67259. handleSize: '100%',
  67260. handleStyle: {
  67261. color: '#a7b7cc'
  67262. },
  67263. labelPrecision: null,
  67264. labelFormatter: null,
  67265. showDetail: true,
  67266. showDataShadow: 'auto', // Default auto decision.
  67267. realtime: true,
  67268. zoomLock: false, // Whether disable zoom.
  67269. textStyle: {
  67270. color: '#333'
  67271. }
  67272. }
  67273. });
  67274. /*
  67275. * Licensed to the Apache Software Foundation (ASF) under one
  67276. * or more contributor license agreements. See the NOTICE file
  67277. * distributed with this work for additional information
  67278. * regarding copyright ownership. The ASF licenses this file
  67279. * to you under the Apache License, Version 2.0 (the
  67280. * "License"); you may not use this file except in compliance
  67281. * with the License. You may obtain a copy of the License at
  67282. *
  67283. * http://www.apache.org/licenses/LICENSE-2.0
  67284. *
  67285. * Unless required by applicable law or agreed to in writing,
  67286. * software distributed under the License is distributed on an
  67287. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67288. * KIND, either express or implied. See the License for the
  67289. * specific language governing permissions and limitations
  67290. * under the License.
  67291. */
  67292. var Rect$2 = Rect;
  67293. var linearMap$1 = linearMap;
  67294. var asc$2 = asc;
  67295. var bind$4 = bind;
  67296. var each$23 = each$1;
  67297. // Constants
  67298. var DEFAULT_LOCATION_EDGE_GAP = 7;
  67299. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  67300. var DEFAULT_FILLER_SIZE = 30;
  67301. var HORIZONTAL = 'horizontal';
  67302. var VERTICAL = 'vertical';
  67303. var LABEL_GAP = 5;
  67304. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  67305. var SliderZoomView = DataZoomView.extend({
  67306. type: 'dataZoom.slider',
  67307. init: function (ecModel, api) {
  67308. /**
  67309. * @private
  67310. * @type {Object}
  67311. */
  67312. this._displayables = {};
  67313. /**
  67314. * @private
  67315. * @type {string}
  67316. */
  67317. this._orient;
  67318. /**
  67319. * [0, 100]
  67320. * @private
  67321. */
  67322. this._range;
  67323. /**
  67324. * [coord of the first handle, coord of the second handle]
  67325. * @private
  67326. */
  67327. this._handleEnds;
  67328. /**
  67329. * [length, thick]
  67330. * @private
  67331. * @type {Array.<number>}
  67332. */
  67333. this._size;
  67334. /**
  67335. * @private
  67336. * @type {number}
  67337. */
  67338. this._handleWidth;
  67339. /**
  67340. * @private
  67341. * @type {number}
  67342. */
  67343. this._handleHeight;
  67344. /**
  67345. * @private
  67346. */
  67347. this._location;
  67348. /**
  67349. * @private
  67350. */
  67351. this._dragging;
  67352. /**
  67353. * @private
  67354. */
  67355. this._dataShadowInfo;
  67356. this.api = api;
  67357. },
  67358. /**
  67359. * @override
  67360. */
  67361. render: function (dataZoomModel, ecModel, api, payload) {
  67362. SliderZoomView.superApply(this, 'render', arguments);
  67363. createOrUpdate(
  67364. this,
  67365. '_dispatchZoomAction',
  67366. this.dataZoomModel.get('throttle'),
  67367. 'fixRate'
  67368. );
  67369. this._orient = dataZoomModel.get('orient');
  67370. if (this.dataZoomModel.get('show') === false) {
  67371. this.group.removeAll();
  67372. return;
  67373. }
  67374. // Notice: this._resetInterval() should not be executed when payload.type
  67375. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  67376. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  67377. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  67378. this._buildView();
  67379. }
  67380. this._updateView();
  67381. },
  67382. /**
  67383. * @override
  67384. */
  67385. remove: function () {
  67386. SliderZoomView.superApply(this, 'remove', arguments);
  67387. clear(this, '_dispatchZoomAction');
  67388. },
  67389. /**
  67390. * @override
  67391. */
  67392. dispose: function () {
  67393. SliderZoomView.superApply(this, 'dispose', arguments);
  67394. clear(this, '_dispatchZoomAction');
  67395. },
  67396. _buildView: function () {
  67397. var thisGroup = this.group;
  67398. thisGroup.removeAll();
  67399. this._resetLocation();
  67400. this._resetInterval();
  67401. var barGroup = this._displayables.barGroup = new Group();
  67402. this._renderBackground();
  67403. this._renderHandle();
  67404. this._renderDataShadow();
  67405. thisGroup.add(barGroup);
  67406. this._positionGroup();
  67407. },
  67408. /**
  67409. * @private
  67410. */
  67411. _resetLocation: function () {
  67412. var dataZoomModel = this.dataZoomModel;
  67413. var api = this.api;
  67414. // If some of x/y/width/height are not specified,
  67415. // auto-adapt according to target grid.
  67416. var coordRect = this._findCoordRect();
  67417. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  67418. // Default align by coordinate system rect.
  67419. var positionInfo = this._orient === HORIZONTAL
  67420. ? {
  67421. // Why using 'right', because right should be used in vertical,
  67422. // and it is better to be consistent for dealing with position param merge.
  67423. right: ecSize.width - coordRect.x - coordRect.width,
  67424. top: (ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP),
  67425. width: coordRect.width,
  67426. height: DEFAULT_FILLER_SIZE
  67427. }
  67428. : { // vertical
  67429. right: DEFAULT_LOCATION_EDGE_GAP,
  67430. top: coordRect.y,
  67431. width: DEFAULT_FILLER_SIZE,
  67432. height: coordRect.height
  67433. };
  67434. // Do not write back to option and replace value 'ph', because
  67435. // the 'ph' value should be recalculated when resize.
  67436. var layoutParams = getLayoutParams(dataZoomModel.option);
  67437. // Replace the placeholder value.
  67438. each$1(['right', 'top', 'width', 'height'], function (name) {
  67439. if (layoutParams[name] === 'ph') {
  67440. layoutParams[name] = positionInfo[name];
  67441. }
  67442. });
  67443. var layoutRect = getLayoutRect(
  67444. layoutParams,
  67445. ecSize,
  67446. dataZoomModel.padding
  67447. );
  67448. this._location = {x: layoutRect.x, y: layoutRect.y};
  67449. this._size = [layoutRect.width, layoutRect.height];
  67450. this._orient === VERTICAL && this._size.reverse();
  67451. },
  67452. /**
  67453. * @private
  67454. */
  67455. _positionGroup: function () {
  67456. var thisGroup = this.group;
  67457. var location = this._location;
  67458. var orient = this._orient;
  67459. // Just use the first axis to determine mapping.
  67460. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  67461. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  67462. var barGroup = this._displayables.barGroup;
  67463. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse;
  67464. // Transform barGroup.
  67465. barGroup.attr(
  67466. (orient === HORIZONTAL && !inverse)
  67467. ? {scale: otherAxisInverse ? [1, 1] : [1, -1]}
  67468. : (orient === HORIZONTAL && inverse)
  67469. ? {scale: otherAxisInverse ? [-1, 1] : [-1, -1]}
  67470. : (orient === VERTICAL && !inverse)
  67471. ? {scale: otherAxisInverse ? [1, -1] : [1, 1], rotation: Math.PI / 2}
  67472. // Dont use Math.PI, considering shadow direction.
  67473. : {scale: otherAxisInverse ? [-1, -1] : [-1, 1], rotation: Math.PI / 2}
  67474. );
  67475. // Position barGroup
  67476. var rect = thisGroup.getBoundingRect([barGroup]);
  67477. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  67478. },
  67479. /**
  67480. * @private
  67481. */
  67482. _getViewExtent: function () {
  67483. return [0, this._size[0]];
  67484. },
  67485. _renderBackground: function () {
  67486. var dataZoomModel = this.dataZoomModel;
  67487. var size = this._size;
  67488. var barGroup = this._displayables.barGroup;
  67489. barGroup.add(new Rect$2({
  67490. silent: true,
  67491. shape: {
  67492. x: 0, y: 0, width: size[0], height: size[1]
  67493. },
  67494. style: {
  67495. fill: dataZoomModel.get('backgroundColor')
  67496. },
  67497. z2: -40
  67498. }));
  67499. // Click panel, over shadow, below handles.
  67500. barGroup.add(new Rect$2({
  67501. shape: {
  67502. x: 0, y: 0, width: size[0], height: size[1]
  67503. },
  67504. style: {
  67505. fill: 'transparent'
  67506. },
  67507. z2: 0,
  67508. onclick: bind(this._onClickPanelClick, this)
  67509. }));
  67510. },
  67511. _renderDataShadow: function () {
  67512. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  67513. if (!info) {
  67514. return;
  67515. }
  67516. var size = this._size;
  67517. var seriesModel = info.series;
  67518. var data = seriesModel.getRawData();
  67519. var otherDim = seriesModel.getShadowDim
  67520. ? seriesModel.getShadowDim() // @see candlestick
  67521. : info.otherDim;
  67522. if (otherDim == null) {
  67523. return;
  67524. }
  67525. var otherDataExtent = data.getDataExtent(otherDim);
  67526. // Nice extent.
  67527. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  67528. otherDataExtent = [
  67529. otherDataExtent[0] - otherOffset,
  67530. otherDataExtent[1] + otherOffset
  67531. ];
  67532. var otherShadowExtent = [0, size[1]];
  67533. var thisShadowExtent = [0, size[0]];
  67534. var areaPoints = [[size[0], 0], [0, 0]];
  67535. var linePoints = [];
  67536. var step = thisShadowExtent[1] / (data.count() - 1);
  67537. var thisCoord = 0;
  67538. // Optimize for large data shadow
  67539. var stride = Math.round(data.count() / size[0]);
  67540. var lastIsEmpty;
  67541. data.each([otherDim], function (value, index) {
  67542. if (stride > 0 && (index % stride)) {
  67543. thisCoord += step;
  67544. return;
  67545. }
  67546. // FIXME
  67547. // Should consider axis.min/axis.max when drawing dataShadow.
  67548. // FIXME
  67549. // 应该使用统一的空判断?还是在list里进行空判断?
  67550. var isEmpty = value == null || isNaN(value) || value === '';
  67551. // See #4235.
  67552. var otherCoord = isEmpty
  67553. ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true);
  67554. // Attempt to draw data shadow precisely when there are empty value.
  67555. if (isEmpty && !lastIsEmpty && index) {
  67556. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  67557. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  67558. }
  67559. else if (!isEmpty && lastIsEmpty) {
  67560. areaPoints.push([thisCoord, 0]);
  67561. linePoints.push([thisCoord, 0]);
  67562. }
  67563. areaPoints.push([thisCoord, otherCoord]);
  67564. linePoints.push([thisCoord, otherCoord]);
  67565. thisCoord += step;
  67566. lastIsEmpty = isEmpty;
  67567. });
  67568. var dataZoomModel = this.dataZoomModel;
  67569. // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  67570. this._displayables.barGroup.add(new Polygon({
  67571. shape: {points: areaPoints},
  67572. style: defaults(
  67573. {fill: dataZoomModel.get('dataBackgroundColor')},
  67574. dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()
  67575. ),
  67576. silent: true,
  67577. z2: -20
  67578. }));
  67579. this._displayables.barGroup.add(new Polyline({
  67580. shape: {points: linePoints},
  67581. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  67582. silent: true,
  67583. z2: -19
  67584. }));
  67585. },
  67586. _prepareDataShadowInfo: function () {
  67587. var dataZoomModel = this.dataZoomModel;
  67588. var showDataShadow = dataZoomModel.get('showDataShadow');
  67589. if (showDataShadow === false) {
  67590. return;
  67591. }
  67592. // Find a representative series.
  67593. var result;
  67594. var ecModel = this.ecModel;
  67595. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  67596. var seriesModels = dataZoomModel
  67597. .getAxisProxy(dimNames.name, axisIndex)
  67598. .getTargetSeriesModels();
  67599. each$1(seriesModels, function (seriesModel) {
  67600. if (result) {
  67601. return;
  67602. }
  67603. if (showDataShadow !== true && indexOf(
  67604. SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')
  67605. ) < 0
  67606. ) {
  67607. return;
  67608. }
  67609. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  67610. var otherDim = getOtherDim(dimNames.name);
  67611. var otherAxisInverse;
  67612. var coordSys = seriesModel.coordinateSystem;
  67613. if (otherDim != null && coordSys.getOtherAxis) {
  67614. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  67615. }
  67616. otherDim = seriesModel.getData().mapDimension(otherDim);
  67617. result = {
  67618. thisAxis: thisAxis,
  67619. series: seriesModel,
  67620. thisDim: dimNames.name,
  67621. otherDim: otherDim,
  67622. otherAxisInverse: otherAxisInverse
  67623. };
  67624. }, this);
  67625. }, this);
  67626. return result;
  67627. },
  67628. _renderHandle: function () {
  67629. var displaybles = this._displayables;
  67630. var handles = displaybles.handles = [];
  67631. var handleLabels = displaybles.handleLabels = [];
  67632. var barGroup = this._displayables.barGroup;
  67633. var size = this._size;
  67634. var dataZoomModel = this.dataZoomModel;
  67635. barGroup.add(displaybles.filler = new Rect$2({
  67636. draggable: true,
  67637. cursor: getCursor(this._orient),
  67638. drift: bind$4(this._onDragMove, this, 'all'),
  67639. onmousemove: function (e) {
  67640. // Fot mobile devicem, prevent screen slider on the button.
  67641. stop(e.event);
  67642. },
  67643. ondragstart: bind$4(this._showDataInfo, this, true),
  67644. ondragend: bind$4(this._onDragEnd, this),
  67645. onmouseover: bind$4(this._showDataInfo, this, true),
  67646. onmouseout: bind$4(this._showDataInfo, this, false),
  67647. style: {
  67648. fill: dataZoomModel.get('fillerColor'),
  67649. textPosition : 'inside'
  67650. }
  67651. }));
  67652. // Frame border.
  67653. barGroup.add(new Rect$2(subPixelOptimizeRect({
  67654. silent: true,
  67655. shape: {
  67656. x: 0,
  67657. y: 0,
  67658. width: size[0],
  67659. height: size[1]
  67660. },
  67661. style: {
  67662. stroke: dataZoomModel.get('dataBackgroundColor')
  67663. || dataZoomModel.get('borderColor'),
  67664. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  67665. fill: 'rgba(0,0,0,0)'
  67666. }
  67667. })));
  67668. each$23([0, 1], function (handleIndex) {
  67669. var path = createIcon(
  67670. dataZoomModel.get('handleIcon'),
  67671. {
  67672. cursor: getCursor(this._orient),
  67673. draggable: true,
  67674. drift: bind$4(this._onDragMove, this, handleIndex),
  67675. onmousemove: function (e) {
  67676. // Fot mobile devicem, prevent screen slider on the button.
  67677. stop(e.event);
  67678. },
  67679. ondragend: bind$4(this._onDragEnd, this),
  67680. onmouseover: bind$4(this._showDataInfo, this, true),
  67681. onmouseout: bind$4(this._showDataInfo, this, false)
  67682. },
  67683. {x: -1, y: 0, width: 2, height: 2}
  67684. );
  67685. var bRect = path.getBoundingRect();
  67686. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  67687. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  67688. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  67689. var handleColor = dataZoomModel.get('handleColor');
  67690. // Compatitable with previous version
  67691. if (handleColor != null) {
  67692. path.style.fill = handleColor;
  67693. }
  67694. barGroup.add(handles[handleIndex] = path);
  67695. var textStyleModel = dataZoomModel.textStyleModel;
  67696. this.group.add(
  67697. handleLabels[handleIndex] = new Text({
  67698. silent: true,
  67699. invisible: true,
  67700. style: {
  67701. x: 0, y: 0, text: '',
  67702. textVerticalAlign: 'middle',
  67703. textAlign: 'center',
  67704. textFill: textStyleModel.getTextColor(),
  67705. textFont: textStyleModel.getFont()
  67706. },
  67707. z2: 10
  67708. }));
  67709. }, this);
  67710. },
  67711. /**
  67712. * @private
  67713. */
  67714. _resetInterval: function () {
  67715. var range = this._range = this.dataZoomModel.getPercentRange();
  67716. var viewExtent = this._getViewExtent();
  67717. this._handleEnds = [
  67718. linearMap$1(range[0], [0, 100], viewExtent, true),
  67719. linearMap$1(range[1], [0, 100], viewExtent, true)
  67720. ];
  67721. },
  67722. /**
  67723. * @private
  67724. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  67725. * @param {number} delta
  67726. * @return {boolean} changed
  67727. */
  67728. _updateInterval: function (handleIndex, delta) {
  67729. var dataZoomModel = this.dataZoomModel;
  67730. var handleEnds = this._handleEnds;
  67731. var viewExtend = this._getViewExtent();
  67732. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  67733. var percentExtent = [0, 100];
  67734. sliderMove(
  67735. delta,
  67736. handleEnds,
  67737. viewExtend,
  67738. dataZoomModel.get('zoomLock') ? 'all' : handleIndex,
  67739. minMaxSpan.minSpan != null
  67740. ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null,
  67741. minMaxSpan.maxSpan != null
  67742. ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null
  67743. );
  67744. var lastRange = this._range;
  67745. var range = this._range = asc$2([
  67746. linearMap$1(handleEnds[0], viewExtend, percentExtent, true),
  67747. linearMap$1(handleEnds[1], viewExtend, percentExtent, true)
  67748. ]);
  67749. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  67750. },
  67751. /**
  67752. * @private
  67753. */
  67754. _updateView: function (nonRealtime) {
  67755. var displaybles = this._displayables;
  67756. var handleEnds = this._handleEnds;
  67757. var handleInterval = asc$2(handleEnds.slice());
  67758. var size = this._size;
  67759. each$23([0, 1], function (handleIndex) {
  67760. // Handles
  67761. var handle = displaybles.handles[handleIndex];
  67762. var handleHeight = this._handleHeight;
  67763. handle.attr({
  67764. scale: [handleHeight / 2, handleHeight / 2],
  67765. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  67766. });
  67767. }, this);
  67768. // Filler
  67769. displaybles.filler.setShape({
  67770. x: handleInterval[0],
  67771. y: 0,
  67772. width: handleInterval[1] - handleInterval[0],
  67773. height: size[1]
  67774. });
  67775. this._updateDataInfo(nonRealtime);
  67776. },
  67777. /**
  67778. * @private
  67779. */
  67780. _updateDataInfo: function (nonRealtime) {
  67781. var dataZoomModel = this.dataZoomModel;
  67782. var displaybles = this._displayables;
  67783. var handleLabels = displaybles.handleLabels;
  67784. var orient = this._orient;
  67785. var labelTexts = ['', ''];
  67786. // FIXME
  67787. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  67788. if (dataZoomModel.get('showDetail')) {
  67789. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  67790. if (axisProxy) {
  67791. var axis = axisProxy.getAxisModel().axis;
  67792. var range = this._range;
  67793. var dataInterval = nonRealtime
  67794. // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  67795. ? axisProxy.calculateDataWindow({
  67796. start: range[0], end: range[1]
  67797. }).valueWindow
  67798. : axisProxy.getDataValueWindow();
  67799. labelTexts = [
  67800. this._formatLabel(dataInterval[0], axis),
  67801. this._formatLabel(dataInterval[1], axis)
  67802. ];
  67803. }
  67804. }
  67805. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  67806. setLabel.call(this, 0);
  67807. setLabel.call(this, 1);
  67808. function setLabel(handleIndex) {
  67809. // Label
  67810. // Text should not transform by barGroup.
  67811. // Ignore handlers transform
  67812. var barTransform = getTransform(
  67813. displaybles.handles[handleIndex].parent, this.group
  67814. );
  67815. var direction = transformDirection(
  67816. handleIndex === 0 ? 'right' : 'left', barTransform
  67817. );
  67818. var offset = this._handleWidth / 2 + LABEL_GAP;
  67819. var textPoint = applyTransform$1(
  67820. [
  67821. orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset),
  67822. this._size[1] / 2
  67823. ],
  67824. barTransform
  67825. );
  67826. handleLabels[handleIndex].setStyle({
  67827. x: textPoint[0],
  67828. y: textPoint[1],
  67829. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  67830. textAlign: orient === HORIZONTAL ? direction : 'center',
  67831. text: labelTexts[handleIndex]
  67832. });
  67833. }
  67834. },
  67835. /**
  67836. * @private
  67837. */
  67838. _formatLabel: function (value, axis) {
  67839. var dataZoomModel = this.dataZoomModel;
  67840. var labelFormatter = dataZoomModel.get('labelFormatter');
  67841. var labelPrecision = dataZoomModel.get('labelPrecision');
  67842. if (labelPrecision == null || labelPrecision === 'auto') {
  67843. labelPrecision = axis.getPixelPrecision();
  67844. }
  67845. var valueStr = (value == null || isNaN(value))
  67846. ? ''
  67847. // FIXME Glue code
  67848. : (axis.type === 'category' || axis.type === 'time')
  67849. ? axis.scale.getLabel(Math.round(value))
  67850. // param of toFixed should less then 20.
  67851. : value.toFixed(Math.min(labelPrecision, 20));
  67852. return isFunction$1(labelFormatter)
  67853. ? labelFormatter(value, valueStr)
  67854. : isString(labelFormatter)
  67855. ? labelFormatter.replace('{value}', valueStr)
  67856. : valueStr;
  67857. },
  67858. /**
  67859. * @private
  67860. * @param {boolean} showOrHide true: show, false: hide
  67861. */
  67862. _showDataInfo: function (showOrHide) {
  67863. // Always show when drgging.
  67864. showOrHide = this._dragging || showOrHide;
  67865. var handleLabels = this._displayables.handleLabels;
  67866. handleLabels[0].attr('invisible', !showOrHide);
  67867. handleLabels[1].attr('invisible', !showOrHide);
  67868. },
  67869. _onDragMove: function (handleIndex, dx, dy) {
  67870. this._dragging = true;
  67871. // Transform dx, dy to bar coordination.
  67872. var barTransform = this._displayables.barGroup.getLocalTransform();
  67873. var vertex = applyTransform$1([dx, dy], barTransform, true);
  67874. var changed = this._updateInterval(handleIndex, vertex[0]);
  67875. var realtime = this.dataZoomModel.get('realtime');
  67876. this._updateView(!realtime);
  67877. // Avoid dispatch dataZoom repeatly but range not changed,
  67878. // which cause bad visual effect when progressive enabled.
  67879. changed && realtime && this._dispatchZoomAction();
  67880. },
  67881. _onDragEnd: function () {
  67882. this._dragging = false;
  67883. this._showDataInfo(false);
  67884. // While in realtime mode and stream mode, dispatch action when
  67885. // drag end will cause the whole view rerender, which is unnecessary.
  67886. var realtime = this.dataZoomModel.get('realtime');
  67887. !realtime && this._dispatchZoomAction();
  67888. },
  67889. _onClickPanelClick: function (e) {
  67890. var size = this._size;
  67891. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  67892. if (localPoint[0] < 0 || localPoint[0] > size[0]
  67893. || localPoint[1] < 0 || localPoint[1] > size[1]
  67894. ) {
  67895. return;
  67896. }
  67897. var handleEnds = this._handleEnds;
  67898. var center = (handleEnds[0] + handleEnds[1]) / 2;
  67899. var changed = this._updateInterval('all', localPoint[0] - center);
  67900. this._updateView();
  67901. changed && this._dispatchZoomAction();
  67902. },
  67903. /**
  67904. * This action will be throttled.
  67905. * @private
  67906. */
  67907. _dispatchZoomAction: function () {
  67908. var range = this._range;
  67909. this.api.dispatchAction({
  67910. type: 'dataZoom',
  67911. from: this.uid,
  67912. dataZoomId: this.dataZoomModel.id,
  67913. start: range[0],
  67914. end: range[1]
  67915. });
  67916. },
  67917. /**
  67918. * @private
  67919. */
  67920. _findCoordRect: function () {
  67921. // Find the grid coresponding to the first axis referred by dataZoom.
  67922. var rect;
  67923. each$23(this.getTargetCoordInfo(), function (coordInfoList) {
  67924. if (!rect && coordInfoList.length) {
  67925. var coordSys = coordInfoList[0].model.coordinateSystem;
  67926. rect = coordSys.getRect && coordSys.getRect();
  67927. }
  67928. });
  67929. if (!rect) {
  67930. var width = this.api.getWidth();
  67931. var height = this.api.getHeight();
  67932. rect = {
  67933. x: width * 0.2,
  67934. y: height * 0.2,
  67935. width: width * 0.6,
  67936. height: height * 0.6
  67937. };
  67938. }
  67939. return rect;
  67940. }
  67941. });
  67942. function getOtherDim(thisDim) {
  67943. // FIXME
  67944. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  67945. var map$$1 = {x: 'y', y: 'x', radius: 'angle', angle: 'radius'};
  67946. return map$$1[thisDim];
  67947. }
  67948. function getCursor(orient) {
  67949. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  67950. }
  67951. /*
  67952. * Licensed to the Apache Software Foundation (ASF) under one
  67953. * or more contributor license agreements. See the NOTICE file
  67954. * distributed with this work for additional information
  67955. * regarding copyright ownership. The ASF licenses this file
  67956. * to you under the Apache License, Version 2.0 (the
  67957. * "License"); you may not use this file except in compliance
  67958. * with the License. You may obtain a copy of the License at
  67959. *
  67960. * http://www.apache.org/licenses/LICENSE-2.0
  67961. *
  67962. * Unless required by applicable law or agreed to in writing,
  67963. * software distributed under the License is distributed on an
  67964. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67965. * KIND, either express or implied. See the License for the
  67966. * specific language governing permissions and limitations
  67967. * under the License.
  67968. */
  67969. DataZoomModel.extend({
  67970. type: 'dataZoom.inside',
  67971. /**
  67972. * @protected
  67973. */
  67974. defaultOption: {
  67975. disabled: false, // Whether disable this inside zoom.
  67976. zoomLock: false, // Whether disable zoom but only pan.
  67977. zoomOnMouseWheel: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  67978. moveOnMouseMove: true, // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  67979. preventDefaultMouseMove: true
  67980. }
  67981. });
  67982. /*
  67983. * Licensed to the Apache Software Foundation (ASF) under one
  67984. * or more contributor license agreements. See the NOTICE file
  67985. * distributed with this work for additional information
  67986. * regarding copyright ownership. The ASF licenses this file
  67987. * to you under the Apache License, Version 2.0 (the
  67988. * "License"); you may not use this file except in compliance
  67989. * with the License. You may obtain a copy of the License at
  67990. *
  67991. * http://www.apache.org/licenses/LICENSE-2.0
  67992. *
  67993. * Unless required by applicable law or agreed to in writing,
  67994. * software distributed under the License is distributed on an
  67995. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67996. * KIND, either express or implied. See the License for the
  67997. * specific language governing permissions and limitations
  67998. * under the License.
  67999. */
  68000. // Only create one roam controller for each coordinate system.
  68001. // one roam controller might be refered by two inside data zoom
  68002. // components (for example, one for x and one for y). When user
  68003. // pan or zoom, only dispatch one action for those data zoom
  68004. // components.
  68005. var curry$6 = curry;
  68006. var ATTR$1 = '\0_ec_dataZoom_roams';
  68007. /**
  68008. * @public
  68009. * @param {module:echarts/ExtensionAPI} api
  68010. * @param {Object} dataZoomInfo
  68011. * @param {string} dataZoomInfo.coordId
  68012. * @param {Function} dataZoomInfo.containsPoint
  68013. * @param {Array.<string>} dataZoomInfo.allCoordIds
  68014. * @param {string} dataZoomInfo.dataZoomId
  68015. * @param {number} dataZoomInfo.throttleRate
  68016. * @param {Function} dataZoomInfo.panGetRange
  68017. * @param {Function} dataZoomInfo.zoomGetRange
  68018. * @param {boolean} [dataZoomInfo.zoomLock]
  68019. * @param {boolean} [dataZoomInfo.disabled]
  68020. */
  68021. function register$2(api, dataZoomInfo) {
  68022. var store = giveStore(api);
  68023. var theDataZoomId = dataZoomInfo.dataZoomId;
  68024. var theCoordId = dataZoomInfo.coordId;
  68025. // Do clean when a dataZoom changes its target coordnate system.
  68026. // Avoid memory leak, dispose all not-used-registered.
  68027. each$1(store, function (record, coordId) {
  68028. var dataZoomInfos = record.dataZoomInfos;
  68029. if (dataZoomInfos[theDataZoomId]
  68030. && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0
  68031. ) {
  68032. delete dataZoomInfos[theDataZoomId];
  68033. record.count--;
  68034. }
  68035. });
  68036. cleanStore(store);
  68037. var record = store[theCoordId];
  68038. // Create if needed.
  68039. if (!record) {
  68040. record = store[theCoordId] = {
  68041. coordId: theCoordId,
  68042. dataZoomInfos: {},
  68043. count: 0
  68044. };
  68045. record.controller = createController(api, record);
  68046. record.dispatchAction = curry(dispatchAction$1, api);
  68047. }
  68048. // Update reference of dataZoom.
  68049. !(record.dataZoomInfos[theDataZoomId]) && record.count++;
  68050. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  68051. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  68052. record.controller.enable(controllerParams.controlType, controllerParams.opt);
  68053. // Consider resize, area should be always updated.
  68054. record.controller.setPointerChecker(dataZoomInfo.containsPoint);
  68055. // Update throttle.
  68056. createOrUpdate(
  68057. record,
  68058. 'dispatchAction',
  68059. dataZoomInfo.throttleRate,
  68060. 'fixRate'
  68061. );
  68062. }
  68063. /**
  68064. * @public
  68065. * @param {module:echarts/ExtensionAPI} api
  68066. * @param {string} dataZoomId
  68067. */
  68068. function unregister$1(api, dataZoomId) {
  68069. var store = giveStore(api);
  68070. each$1(store, function (record) {
  68071. record.controller.dispose();
  68072. var dataZoomInfos = record.dataZoomInfos;
  68073. if (dataZoomInfos[dataZoomId]) {
  68074. delete dataZoomInfos[dataZoomId];
  68075. record.count--;
  68076. }
  68077. });
  68078. cleanStore(store);
  68079. }
  68080. /**
  68081. * @public
  68082. */
  68083. function generateCoordId(coordModel) {
  68084. return coordModel.type + '\0_' + coordModel.id;
  68085. }
  68086. /**
  68087. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  68088. * @type {Array.<Object>}
  68089. */
  68090. function giveStore(api) {
  68091. // Mount store on zrender instance, so that we do not
  68092. // need to worry about dispose.
  68093. var zr = api.getZr();
  68094. return zr[ATTR$1] || (zr[ATTR$1] = {});
  68095. }
  68096. function createController(api, newRecord) {
  68097. var controller = new RoamController(api.getZr());
  68098. controller.on('pan', curry$6(onPan, newRecord));
  68099. controller.on('zoom', curry$6(onZoom, newRecord));
  68100. return controller;
  68101. }
  68102. function cleanStore(store) {
  68103. each$1(store, function (record, coordId) {
  68104. if (!record.count) {
  68105. record.controller.dispose();
  68106. delete store[coordId];
  68107. }
  68108. });
  68109. }
  68110. function onPan(record, dx, dy, oldX, oldY, newX, newY) {
  68111. wrapAndDispatch(record, function (info) {
  68112. return info.panGetRange(record.controller, dx, dy, oldX, oldY, newX, newY);
  68113. });
  68114. }
  68115. function onZoom(record, scale, mouseX, mouseY) {
  68116. wrapAndDispatch(record, function (info) {
  68117. return info.zoomGetRange(record.controller, scale, mouseX, mouseY);
  68118. });
  68119. }
  68120. function wrapAndDispatch(record, getRange) {
  68121. var batch = [];
  68122. each$1(record.dataZoomInfos, function (info) {
  68123. var range = getRange(info);
  68124. !info.disabled && range && batch.push({
  68125. dataZoomId: info.dataZoomId,
  68126. start: range[0],
  68127. end: range[1]
  68128. });
  68129. });
  68130. batch.length && record.dispatchAction(batch);
  68131. }
  68132. /**
  68133. * This action will be throttled.
  68134. */
  68135. function dispatchAction$1(api, batch) {
  68136. api.dispatchAction({
  68137. type: 'dataZoom',
  68138. batch: batch
  68139. });
  68140. }
  68141. /**
  68142. * Merge roamController settings when multiple dataZooms share one roamController.
  68143. */
  68144. function mergeControllerParams(dataZoomInfos) {
  68145. var controlType;
  68146. var opt = {};
  68147. // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  68148. // as string, it is probably revert to reserved word by compress tool. See #7411.
  68149. var prefix = 'type_';
  68150. var typePriority = {
  68151. 'type_true': 2,
  68152. 'type_move': 1,
  68153. 'type_false': 0,
  68154. 'type_undefined': -1
  68155. };
  68156. each$1(dataZoomInfos, function (dataZoomInfo) {
  68157. var oneType = dataZoomInfo.disabled ? false : dataZoomInfo.zoomLock ? 'move' : true;
  68158. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  68159. controlType = oneType;
  68160. }
  68161. // Do not support that different 'shift'/'ctrl'/'alt' setting used in one coord sys.
  68162. extend(opt, dataZoomInfo.roamControllerOpt);
  68163. });
  68164. return {
  68165. controlType: controlType,
  68166. opt: opt
  68167. };
  68168. }
  68169. /*
  68170. * Licensed to the Apache Software Foundation (ASF) under one
  68171. * or more contributor license agreements. See the NOTICE file
  68172. * distributed with this work for additional information
  68173. * regarding copyright ownership. The ASF licenses this file
  68174. * to you under the Apache License, Version 2.0 (the
  68175. * "License"); you may not use this file except in compliance
  68176. * with the License. You may obtain a copy of the License at
  68177. *
  68178. * http://www.apache.org/licenses/LICENSE-2.0
  68179. *
  68180. * Unless required by applicable law or agreed to in writing,
  68181. * software distributed under the License is distributed on an
  68182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68183. * KIND, either express or implied. See the License for the
  68184. * specific language governing permissions and limitations
  68185. * under the License.
  68186. */
  68187. var bind$5 = bind;
  68188. var InsideZoomView = DataZoomView.extend({
  68189. type: 'dataZoom.inside',
  68190. /**
  68191. * @override
  68192. */
  68193. init: function (ecModel, api) {
  68194. /**
  68195. * 'throttle' is used in this.dispatchAction, so we save range
  68196. * to avoid missing some 'pan' info.
  68197. * @private
  68198. * @type {Array.<number>}
  68199. */
  68200. this._range;
  68201. },
  68202. /**
  68203. * @override
  68204. */
  68205. render: function (dataZoomModel, ecModel, api, payload) {
  68206. InsideZoomView.superApply(this, 'render', arguments);
  68207. // Hance the `throttle` util ensures to preserve command order,
  68208. // here simply updating range all the time will not cause missing
  68209. // any of the the roam change.
  68210. this._range = dataZoomModel.getPercentRange();
  68211. // Reset controllers.
  68212. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  68213. var allCoordIds = map(coordInfoList, function (coordInfo) {
  68214. return generateCoordId(coordInfo.model);
  68215. });
  68216. each$1(coordInfoList, function (coordInfo) {
  68217. var coordModel = coordInfo.model;
  68218. var dataZoomOption = dataZoomModel.option;
  68219. register$2(
  68220. api,
  68221. {
  68222. coordId: generateCoordId(coordModel),
  68223. allCoordIds: allCoordIds,
  68224. containsPoint: function (e, x, y) {
  68225. return coordModel.coordinateSystem.containPoint([x, y]);
  68226. },
  68227. dataZoomId: dataZoomModel.id,
  68228. throttleRate: dataZoomModel.get('throttle', true),
  68229. panGetRange: bind$5(this._onPan, this, coordInfo, coordSysName),
  68230. zoomGetRange: bind$5(this._onZoom, this, coordInfo, coordSysName),
  68231. zoomLock: dataZoomOption.zoomLock,
  68232. disabled: dataZoomOption.disabled,
  68233. roamControllerOpt: {
  68234. zoomOnMouseWheel: dataZoomOption.zoomOnMouseWheel,
  68235. moveOnMouseMove: dataZoomOption.moveOnMouseMove,
  68236. preventDefaultMouseMove: dataZoomOption.preventDefaultMouseMove
  68237. }
  68238. }
  68239. );
  68240. }, this);
  68241. }, this);
  68242. },
  68243. /**
  68244. * @override
  68245. */
  68246. dispose: function () {
  68247. unregister$1(this.api, this.dataZoomModel.id);
  68248. InsideZoomView.superApply(this, 'dispose', arguments);
  68249. this._range = null;
  68250. },
  68251. /**
  68252. * @private
  68253. */
  68254. _onPan: function (coordInfo, coordSysName, controller, dx, dy, oldX, oldY, newX, newY) {
  68255. var lastRange = this._range;
  68256. var range = lastRange.slice();
  68257. // Calculate transform by the first axis.
  68258. var axisModel = coordInfo.axisModels[0];
  68259. if (!axisModel) {
  68260. return;
  68261. }
  68262. var directionInfo = getDirectionInfo[coordSysName](
  68263. [oldX, oldY], [newX, newY], axisModel, controller, coordInfo
  68264. );
  68265. var percentDelta = directionInfo.signal
  68266. * (range[1] - range[0])
  68267. * directionInfo.pixel / directionInfo.pixelLength;
  68268. sliderMove(percentDelta, range, [0, 100], 'all');
  68269. this._range = range;
  68270. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  68271. return range;
  68272. }
  68273. },
  68274. /**
  68275. * @private
  68276. */
  68277. _onZoom: function (coordInfo, coordSysName, controller, scale, mouseX, mouseY) {
  68278. var lastRange = this._range;
  68279. var range = lastRange.slice();
  68280. // Calculate transform by the first axis.
  68281. var axisModel = coordInfo.axisModels[0];
  68282. if (!axisModel) {
  68283. return;
  68284. }
  68285. var directionInfo = getDirectionInfo[coordSysName](
  68286. null, [mouseX, mouseY], axisModel, controller, coordInfo
  68287. );
  68288. var percentPoint = (
  68289. directionInfo.signal > 0
  68290. ? (directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel)
  68291. : (directionInfo.pixel - directionInfo.pixelStart)
  68292. ) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  68293. scale = Math.max(1 / scale, 0);
  68294. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  68295. range[1] = (range[1] - percentPoint) * scale + percentPoint;
  68296. // Restrict range.
  68297. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  68298. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  68299. this._range = range;
  68300. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  68301. return range;
  68302. }
  68303. }
  68304. });
  68305. var getDirectionInfo = {
  68306. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68307. var axis = axisModel.axis;
  68308. var ret = {};
  68309. var rect = coordInfo.model.coordinateSystem.getRect();
  68310. oldPoint = oldPoint || [0, 0];
  68311. if (axis.dim === 'x') {
  68312. ret.pixel = newPoint[0] - oldPoint[0];
  68313. ret.pixelLength = rect.width;
  68314. ret.pixelStart = rect.x;
  68315. ret.signal = axis.inverse ? 1 : -1;
  68316. }
  68317. else { // axis.dim === 'y'
  68318. ret.pixel = newPoint[1] - oldPoint[1];
  68319. ret.pixelLength = rect.height;
  68320. ret.pixelStart = rect.y;
  68321. ret.signal = axis.inverse ? -1 : 1;
  68322. }
  68323. return ret;
  68324. },
  68325. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68326. var axis = axisModel.axis;
  68327. var ret = {};
  68328. var polar = coordInfo.model.coordinateSystem;
  68329. var radiusExtent = polar.getRadiusAxis().getExtent();
  68330. var angleExtent = polar.getAngleAxis().getExtent();
  68331. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  68332. newPoint = polar.pointToCoord(newPoint);
  68333. if (axisModel.mainType === 'radiusAxis') {
  68334. ret.pixel = newPoint[0] - oldPoint[0];
  68335. // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  68336. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  68337. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  68338. ret.pixelStart = radiusExtent[0];
  68339. ret.signal = axis.inverse ? 1 : -1;
  68340. }
  68341. else { // 'angleAxis'
  68342. ret.pixel = newPoint[1] - oldPoint[1];
  68343. // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  68344. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  68345. ret.pixelLength = angleExtent[1] - angleExtent[0];
  68346. ret.pixelStart = angleExtent[0];
  68347. ret.signal = axis.inverse ? -1 : 1;
  68348. }
  68349. return ret;
  68350. },
  68351. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  68352. var axis = axisModel.axis;
  68353. var rect = coordInfo.model.coordinateSystem.getRect();
  68354. var ret = {};
  68355. oldPoint = oldPoint || [0, 0];
  68356. if (axis.orient === 'horizontal') {
  68357. ret.pixel = newPoint[0] - oldPoint[0];
  68358. ret.pixelLength = rect.width;
  68359. ret.pixelStart = rect.x;
  68360. ret.signal = axis.inverse ? 1 : -1;
  68361. }
  68362. else { // 'vertical'
  68363. ret.pixel = newPoint[1] - oldPoint[1];
  68364. ret.pixelLength = rect.height;
  68365. ret.pixelStart = rect.y;
  68366. ret.signal = axis.inverse ? -1 : 1;
  68367. }
  68368. return ret;
  68369. }
  68370. };
  68371. /*
  68372. * Licensed to the Apache Software Foundation (ASF) under one
  68373. * or more contributor license agreements. See the NOTICE file
  68374. * distributed with this work for additional information
  68375. * regarding copyright ownership. The ASF licenses this file
  68376. * to you under the Apache License, Version 2.0 (the
  68377. * "License"); you may not use this file except in compliance
  68378. * with the License. You may obtain a copy of the License at
  68379. *
  68380. * http://www.apache.org/licenses/LICENSE-2.0
  68381. *
  68382. * Unless required by applicable law or agreed to in writing,
  68383. * software distributed under the License is distributed on an
  68384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68385. * KIND, either express or implied. See the License for the
  68386. * specific language governing permissions and limitations
  68387. * under the License.
  68388. */
  68389. registerProcessor({
  68390. // `dataZoomProcessor` will only be performed in needed series. Consider if
  68391. // there is a line series and a pie series, it is better not to update the
  68392. // line series if only pie series is needed to be updated.
  68393. getTargetSeries: function (ecModel) {
  68394. var seriesModelMap = createHashMap();
  68395. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68396. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68397. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  68398. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  68399. seriesModelMap.set(seriesModel.uid, seriesModel);
  68400. });
  68401. });
  68402. });
  68403. return seriesModelMap;
  68404. },
  68405. modifyOutputEnd: true,
  68406. // Consider appendData, where filter should be performed. Because data process is
  68407. // in block mode currently, it is not need to worry about that the overallProgress
  68408. // execute every frame.
  68409. overallReset: function (ecModel, api) {
  68410. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68411. // We calculate window and reset axis here but not in model
  68412. // init stage and not after action dispatch handler, because
  68413. // reset should be called after seriesData.restoreData.
  68414. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68415. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  68416. });
  68417. // Caution: data zoom filtering is order sensitive when using
  68418. // percent range and no min/max/scale set on axis.
  68419. // For example, we have dataZoom definition:
  68420. // [
  68421. // {xAxisIndex: 0, start: 30, end: 70},
  68422. // {yAxisIndex: 0, start: 20, end: 80}
  68423. // ]
  68424. // In this case, [20, 80] of y-dataZoom should be based on data
  68425. // that have filtered by x-dataZoom using range of [30, 70],
  68426. // but should not be based on full raw data. Thus sliding
  68427. // x-dataZoom will change both ranges of xAxis and yAxis,
  68428. // while sliding y-dataZoom will only change the range of yAxis.
  68429. // So we should filter x-axis after reset x-axis immediately,
  68430. // and then reset y-axis and filter y-axis.
  68431. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  68432. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  68433. });
  68434. });
  68435. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  68436. // Fullfill all of the range props so that user
  68437. // is able to get them from chart.getOption().
  68438. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  68439. var percentRange = axisProxy.getDataPercentWindow();
  68440. var valueRange = axisProxy.getDataValueWindow();
  68441. dataZoomModel.setRawRange({
  68442. start: percentRange[0],
  68443. end: percentRange[1],
  68444. startValue: valueRange[0],
  68445. endValue: valueRange[1]
  68446. }, true);
  68447. });
  68448. }
  68449. });
  68450. /*
  68451. * Licensed to the Apache Software Foundation (ASF) under one
  68452. * or more contributor license agreements. See the NOTICE file
  68453. * distributed with this work for additional information
  68454. * regarding copyright ownership. The ASF licenses this file
  68455. * to you under the Apache License, Version 2.0 (the
  68456. * "License"); you may not use this file except in compliance
  68457. * with the License. You may obtain a copy of the License at
  68458. *
  68459. * http://www.apache.org/licenses/LICENSE-2.0
  68460. *
  68461. * Unless required by applicable law or agreed to in writing,
  68462. * software distributed under the License is distributed on an
  68463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68464. * KIND, either express or implied. See the License for the
  68465. * specific language governing permissions and limitations
  68466. * under the License.
  68467. */
  68468. registerAction('dataZoom', function (payload, ecModel) {
  68469. var linkedNodesFinder = createLinkedNodesFinder(
  68470. bind(ecModel.eachComponent, ecModel, 'dataZoom'),
  68471. eachAxisDim$1,
  68472. function (model, dimNames) {
  68473. return model.get(dimNames.axisIndex);
  68474. }
  68475. );
  68476. var effectedModels = [];
  68477. ecModel.eachComponent(
  68478. {mainType: 'dataZoom', query: payload},
  68479. function (model, index) {
  68480. effectedModels.push.apply(
  68481. effectedModels, linkedNodesFinder(model).nodes
  68482. );
  68483. }
  68484. );
  68485. each$1(effectedModels, function (dataZoomModel, index) {
  68486. dataZoomModel.setRawRange({
  68487. start: payload.start,
  68488. end: payload.end,
  68489. startValue: payload.startValue,
  68490. endValue: payload.endValue
  68491. });
  68492. });
  68493. });
  68494. /*
  68495. * Licensed to the Apache Software Foundation (ASF) under one
  68496. * or more contributor license agreements. See the NOTICE file
  68497. * distributed with this work for additional information
  68498. * regarding copyright ownership. The ASF licenses this file
  68499. * to you under the Apache License, Version 2.0 (the
  68500. * "License"); you may not use this file except in compliance
  68501. * with the License. You may obtain a copy of the License at
  68502. *
  68503. * http://www.apache.org/licenses/LICENSE-2.0
  68504. *
  68505. * Unless required by applicable law or agreed to in writing,
  68506. * software distributed under the License is distributed on an
  68507. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68508. * KIND, either express or implied. See the License for the
  68509. * specific language governing permissions and limitations
  68510. * under the License.
  68511. */
  68512. /**
  68513. * DataZoom component entry
  68514. */
  68515. /*
  68516. * Licensed to the Apache Software Foundation (ASF) under one
  68517. * or more contributor license agreements. See the NOTICE file
  68518. * distributed with this work for additional information
  68519. * regarding copyright ownership. The ASF licenses this file
  68520. * to you under the Apache License, Version 2.0 (the
  68521. * "License"); you may not use this file except in compliance
  68522. * with the License. You may obtain a copy of the License at
  68523. *
  68524. * http://www.apache.org/licenses/LICENSE-2.0
  68525. *
  68526. * Unless required by applicable law or agreed to in writing,
  68527. * software distributed under the License is distributed on an
  68528. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68529. * KIND, either express or implied. See the License for the
  68530. * specific language governing permissions and limitations
  68531. * under the License.
  68532. */
  68533. var each$24 = each$1;
  68534. var preprocessor$2 = function (option) {
  68535. var visualMap = option && option.visualMap;
  68536. if (!isArray(visualMap)) {
  68537. visualMap = visualMap ? [visualMap] : [];
  68538. }
  68539. each$24(visualMap, function (opt) {
  68540. if (!opt) {
  68541. return;
  68542. }
  68543. // rename splitList to pieces
  68544. if (has$1(opt, 'splitList') && !has$1(opt, 'pieces')) {
  68545. opt.pieces = opt.splitList;
  68546. delete opt.splitList;
  68547. }
  68548. var pieces = opt.pieces;
  68549. if (pieces && isArray(pieces)) {
  68550. each$24(pieces, function (piece) {
  68551. if (isObject$1(piece)) {
  68552. if (has$1(piece, 'start') && !has$1(piece, 'min')) {
  68553. piece.min = piece.start;
  68554. }
  68555. if (has$1(piece, 'end') && !has$1(piece, 'max')) {
  68556. piece.max = piece.end;
  68557. }
  68558. }
  68559. });
  68560. }
  68561. });
  68562. };
  68563. function has$1(obj, name) {
  68564. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  68565. }
  68566. /*
  68567. * Licensed to the Apache Software Foundation (ASF) under one
  68568. * or more contributor license agreements. See the NOTICE file
  68569. * distributed with this work for additional information
  68570. * regarding copyright ownership. The ASF licenses this file
  68571. * to you under the Apache License, Version 2.0 (the
  68572. * "License"); you may not use this file except in compliance
  68573. * with the License. You may obtain a copy of the License at
  68574. *
  68575. * http://www.apache.org/licenses/LICENSE-2.0
  68576. *
  68577. * Unless required by applicable law or agreed to in writing,
  68578. * software distributed under the License is distributed on an
  68579. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68580. * KIND, either express or implied. See the License for the
  68581. * specific language governing permissions and limitations
  68582. * under the License.
  68583. */
  68584. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  68585. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  68586. return (
  68587. !option.categories
  68588. && (
  68589. !(
  68590. option.pieces
  68591. ? option.pieces.length > 0
  68592. : option.splitNumber > 0
  68593. )
  68594. || option.calculable
  68595. )
  68596. )
  68597. ? 'continuous' : 'piecewise';
  68598. });
  68599. /*
  68600. * Licensed to the Apache Software Foundation (ASF) under one
  68601. * or more contributor license agreements. See the NOTICE file
  68602. * distributed with this work for additional information
  68603. * regarding copyright ownership. The ASF licenses this file
  68604. * to you under the Apache License, Version 2.0 (the
  68605. * "License"); you may not use this file except in compliance
  68606. * with the License. You may obtain a copy of the License at
  68607. *
  68608. * http://www.apache.org/licenses/LICENSE-2.0
  68609. *
  68610. * Unless required by applicable law or agreed to in writing,
  68611. * software distributed under the License is distributed on an
  68612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68613. * KIND, either express or implied. See the License for the
  68614. * specific language governing permissions and limitations
  68615. * under the License.
  68616. */
  68617. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  68618. registerVisual(VISUAL_PRIORITY, {
  68619. createOnAllSeries: true,
  68620. reset: function (seriesModel, ecModel) {
  68621. var resetDefines = [];
  68622. ecModel.eachComponent('visualMap', function (visualMapModel) {
  68623. var pipelineContext = seriesModel.pipelineContext;
  68624. if (!visualMapModel.isTargetSeries(seriesModel)
  68625. || (pipelineContext && pipelineContext.large)
  68626. ) {
  68627. return;
  68628. }
  68629. resetDefines.push(incrementalApplyVisual(
  68630. visualMapModel.stateList,
  68631. visualMapModel.targetVisuals,
  68632. bind(visualMapModel.getValueState, visualMapModel),
  68633. visualMapModel.getDataDimension(seriesModel.getData())
  68634. ));
  68635. });
  68636. return resetDefines;
  68637. }
  68638. });
  68639. // Only support color.
  68640. registerVisual(VISUAL_PRIORITY, {
  68641. createOnAllSeries: true,
  68642. reset: function (seriesModel, ecModel) {
  68643. var data = seriesModel.getData();
  68644. var visualMetaList = [];
  68645. ecModel.eachComponent('visualMap', function (visualMapModel) {
  68646. if (visualMapModel.isTargetSeries(seriesModel)) {
  68647. var visualMeta = visualMapModel.getVisualMeta(
  68648. bind(getColorVisual, null, seriesModel, visualMapModel)
  68649. ) || {stops: [], outerColors: []};
  68650. var concreteDim = visualMapModel.getDataDimension(data);
  68651. var dimInfo = data.getDimensionInfo(concreteDim);
  68652. if (dimInfo != null) {
  68653. // visualMeta.dimension should be dimension index, but not concrete dimension.
  68654. visualMeta.dimension = dimInfo.index;
  68655. visualMetaList.push(visualMeta);
  68656. }
  68657. }
  68658. });
  68659. // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  68660. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  68661. }
  68662. });
  68663. // FIXME
  68664. // performance and export for heatmap?
  68665. // value can be Infinity or -Infinity
  68666. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  68667. var mappings = visualMapModel.targetVisuals[valueState];
  68668. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  68669. var resultVisual = {
  68670. color: seriesModel.getData().getVisual('color') // default color.
  68671. };
  68672. for (var i = 0, len = visualTypes.length; i < len; i++) {
  68673. var type = visualTypes[i];
  68674. var mapping = mappings[
  68675. type === 'opacity' ? '__alphaForOpacity' : type
  68676. ];
  68677. mapping && mapping.applyVisual(value, getVisual, setVisual);
  68678. }
  68679. return resultVisual.color;
  68680. function getVisual(key) {
  68681. return resultVisual[key];
  68682. }
  68683. function setVisual(key, value) {
  68684. resultVisual[key] = value;
  68685. }
  68686. }
  68687. /*
  68688. * Licensed to the Apache Software Foundation (ASF) under one
  68689. * or more contributor license agreements. See the NOTICE file
  68690. * distributed with this work for additional information
  68691. * regarding copyright ownership. The ASF licenses this file
  68692. * to you under the Apache License, Version 2.0 (the
  68693. * "License"); you may not use this file except in compliance
  68694. * with the License. You may obtain a copy of the License at
  68695. *
  68696. * http://www.apache.org/licenses/LICENSE-2.0
  68697. *
  68698. * Unless required by applicable law or agreed to in writing,
  68699. * software distributed under the License is distributed on an
  68700. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68701. * KIND, either express or implied. See the License for the
  68702. * specific language governing permissions and limitations
  68703. * under the License.
  68704. */
  68705. /**
  68706. * @file Visual mapping.
  68707. */
  68708. var visualDefault = {
  68709. /**
  68710. * @public
  68711. */
  68712. get: function (visualType, key, isCategory) {
  68713. var value = clone(
  68714. (defaultOption$3[visualType] || {})[key]
  68715. );
  68716. return isCategory
  68717. ? (isArray(value) ? value[value.length - 1] : value)
  68718. : value;
  68719. }
  68720. };
  68721. var defaultOption$3 = {
  68722. color: {
  68723. active: ['#006edd', '#e0ffff'],
  68724. inactive: ['rgba(0,0,0,0)']
  68725. },
  68726. colorHue: {
  68727. active: [0, 360],
  68728. inactive: [0, 0]
  68729. },
  68730. colorSaturation: {
  68731. active: [0.3, 1],
  68732. inactive: [0, 0]
  68733. },
  68734. colorLightness: {
  68735. active: [0.9, 0.5],
  68736. inactive: [0, 0]
  68737. },
  68738. colorAlpha: {
  68739. active: [0.3, 1],
  68740. inactive: [0, 0]
  68741. },
  68742. opacity: {
  68743. active: [0.3, 1],
  68744. inactive: [0, 0]
  68745. },
  68746. symbol: {
  68747. active: ['circle', 'roundRect', 'diamond'],
  68748. inactive: ['none']
  68749. },
  68750. symbolSize: {
  68751. active: [10, 50],
  68752. inactive: [0, 0]
  68753. }
  68754. };
  68755. /*
  68756. * Licensed to the Apache Software Foundation (ASF) under one
  68757. * or more contributor license agreements. See the NOTICE file
  68758. * distributed with this work for additional information
  68759. * regarding copyright ownership. The ASF licenses this file
  68760. * to you under the Apache License, Version 2.0 (the
  68761. * "License"); you may not use this file except in compliance
  68762. * with the License. You may obtain a copy of the License at
  68763. *
  68764. * http://www.apache.org/licenses/LICENSE-2.0
  68765. *
  68766. * Unless required by applicable law or agreed to in writing,
  68767. * software distributed under the License is distributed on an
  68768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68769. * KIND, either express or implied. See the License for the
  68770. * specific language governing permissions and limitations
  68771. * under the License.
  68772. */
  68773. var mapVisual$2 = VisualMapping.mapVisual;
  68774. var eachVisual = VisualMapping.eachVisual;
  68775. var isArray$3 = isArray;
  68776. var each$25 = each$1;
  68777. var asc$3 = asc;
  68778. var linearMap$2 = linearMap;
  68779. var noop$2 = noop;
  68780. var VisualMapModel = extendComponentModel({
  68781. type: 'visualMap',
  68782. dependencies: ['series'],
  68783. /**
  68784. * @readOnly
  68785. * @type {Array.<string>}
  68786. */
  68787. stateList: ['inRange', 'outOfRange'],
  68788. /**
  68789. * @readOnly
  68790. * @type {Array.<string>}
  68791. */
  68792. replacableOptionKeys: [
  68793. 'inRange', 'outOfRange', 'target', 'controller', 'color'
  68794. ],
  68795. /**
  68796. * [lowerBound, upperBound]
  68797. *
  68798. * @readOnly
  68799. * @type {Array.<number>}
  68800. */
  68801. dataBound: [-Infinity, Infinity],
  68802. /**
  68803. * @readOnly
  68804. * @type {string|Object}
  68805. */
  68806. layoutMode: {type: 'box', ignoreSize: true},
  68807. /**
  68808. * @protected
  68809. */
  68810. defaultOption: {
  68811. show: true,
  68812. zlevel: 0,
  68813. z: 4,
  68814. seriesIndex: 'all', // 'all' or null/undefined: all series.
  68815. // A number or an array of number: the specified series.
  68816. // set min: 0, max: 200, only for campatible with ec2.
  68817. // In fact min max should not have default value.
  68818. min: 0, // min value, must specified if pieces is not specified.
  68819. max: 200, // max value, must specified if pieces is not specified.
  68820. dimension: null,
  68821. inRange: null, // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  68822. // 'symbol', 'symbolSize'
  68823. outOfRange: null, // 'color', 'colorHue', 'colorSaturation',
  68824. // 'colorLightness', 'colorAlpha',
  68825. // 'symbol', 'symbolSize'
  68826. left: 0, // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  68827. right: null, // The same as left.
  68828. top: null, // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  68829. bottom: 0, // The same as top.
  68830. itemWidth: null,
  68831. itemHeight: null,
  68832. inverse: false,
  68833. orient: 'vertical', // 'horizontal' ¦ 'vertical'
  68834. backgroundColor: 'rgba(0,0,0,0)',
  68835. borderColor: '#ccc', // 值域边框颜色
  68836. contentColor: '#5793f3',
  68837. inactiveColor: '#aaa',
  68838. borderWidth: 0, // 值域边框线宽,单位px,默认为0(无边框)
  68839. padding: 5, // 值域内边距,单位px,默认各方向内边距为5,
  68840. // 接受数组分别设定上右下左边距,同css
  68841. textGap: 10, //
  68842. precision: 0, // 小数精度,默认为0,无小数点
  68843. color: null, //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  68844. formatter: null,
  68845. text: null, // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  68846. textStyle: {
  68847. color: '#333' // 值域文字颜色
  68848. }
  68849. },
  68850. /**
  68851. * @protected
  68852. */
  68853. init: function (option, parentModel, ecModel) {
  68854. /**
  68855. * @private
  68856. * @type {Array.<number>}
  68857. */
  68858. this._dataExtent;
  68859. /**
  68860. * @readOnly
  68861. */
  68862. this.targetVisuals = {};
  68863. /**
  68864. * @readOnly
  68865. */
  68866. this.controllerVisuals = {};
  68867. /**
  68868. * @readOnly
  68869. */
  68870. this.textStyleModel;
  68871. /**
  68872. * [width, height]
  68873. * @readOnly
  68874. * @type {Array.<number>}
  68875. */
  68876. this.itemSize;
  68877. this.mergeDefaultAndTheme(option, ecModel);
  68878. },
  68879. /**
  68880. * @protected
  68881. */
  68882. optionUpdated: function (newOption, isInit) {
  68883. var thisOption = this.option;
  68884. // FIXME
  68885. // necessary?
  68886. // Disable realtime view update if canvas is not supported.
  68887. if (!env$1.canvasSupported) {
  68888. thisOption.realtime = false;
  68889. }
  68890. !isInit && replaceVisualOption(
  68891. thisOption, newOption, this.replacableOptionKeys
  68892. );
  68893. this.textStyleModel = this.getModel('textStyle');
  68894. this.resetItemSize();
  68895. this.completeVisualOption();
  68896. },
  68897. /**
  68898. * @protected
  68899. */
  68900. resetVisual: function (supplementVisualOption) {
  68901. var stateList = this.stateList;
  68902. supplementVisualOption = bind(supplementVisualOption, this);
  68903. this.controllerVisuals = createVisualMappings(
  68904. this.option.controller, stateList, supplementVisualOption
  68905. );
  68906. this.targetVisuals = createVisualMappings(
  68907. this.option.target, stateList, supplementVisualOption
  68908. );
  68909. },
  68910. /**
  68911. * @protected
  68912. * @return {Array.<number>} An array of series indices.
  68913. */
  68914. getTargetSeriesIndices: function () {
  68915. var optionSeriesIndex = this.option.seriesIndex;
  68916. var seriesIndices = [];
  68917. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  68918. this.ecModel.eachSeries(function (seriesModel, index) {
  68919. seriesIndices.push(index);
  68920. });
  68921. }
  68922. else {
  68923. seriesIndices = normalizeToArray(optionSeriesIndex);
  68924. }
  68925. return seriesIndices;
  68926. },
  68927. /**
  68928. * @public
  68929. */
  68930. eachTargetSeries: function (callback, context) {
  68931. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  68932. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  68933. }, this);
  68934. },
  68935. /**
  68936. * @pubilc
  68937. */
  68938. isTargetSeries: function (seriesModel) {
  68939. var is = false;
  68940. this.eachTargetSeries(function (model) {
  68941. model === seriesModel && (is = true);
  68942. });
  68943. return is;
  68944. },
  68945. /**
  68946. * @example
  68947. * this.formatValueText(someVal); // format single numeric value to text.
  68948. * this.formatValueText(someVal, true); // format single category value to text.
  68949. * this.formatValueText([min, max]); // format numeric min-max to text.
  68950. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  68951. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  68952. *
  68953. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  68954. * @param {boolean} [isCategory=false] Only available when value is number.
  68955. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  68956. * @return {string}
  68957. * @protected
  68958. */
  68959. formatValueText: function(value, isCategory, edgeSymbols) {
  68960. var option = this.option;
  68961. var precision = option.precision;
  68962. var dataBound = this.dataBound;
  68963. var formatter = option.formatter;
  68964. var isMinMax;
  68965. var textValue;
  68966. edgeSymbols = edgeSymbols || ['<', '>'];
  68967. if (isArray(value)) {
  68968. value = value.slice();
  68969. isMinMax = true;
  68970. }
  68971. textValue = isCategory
  68972. ? value
  68973. : (isMinMax
  68974. ? [toFixed(value[0]), toFixed(value[1])]
  68975. : toFixed(value)
  68976. );
  68977. if (isString(formatter)) {
  68978. return formatter
  68979. .replace('{value}', isMinMax ? textValue[0] : textValue)
  68980. .replace('{value2}', isMinMax ? textValue[1] : textValue);
  68981. }
  68982. else if (isFunction$1(formatter)) {
  68983. return isMinMax
  68984. ? formatter(value[0], value[1])
  68985. : formatter(value);
  68986. }
  68987. if (isMinMax) {
  68988. if (value[0] === dataBound[0]) {
  68989. return edgeSymbols[0] + ' ' + textValue[1];
  68990. }
  68991. else if (value[1] === dataBound[1]) {
  68992. return edgeSymbols[1] + ' ' + textValue[0];
  68993. }
  68994. else {
  68995. return textValue[0] + ' - ' + textValue[1];
  68996. }
  68997. }
  68998. else { // Format single value (includes category case).
  68999. return textValue;
  69000. }
  69001. function toFixed(val) {
  69002. return val === dataBound[0]
  69003. ? 'min'
  69004. : val === dataBound[1]
  69005. ? 'max'
  69006. : (+val).toFixed(Math.min(precision, 20));
  69007. }
  69008. },
  69009. /**
  69010. * @protected
  69011. */
  69012. resetExtent: function () {
  69013. var thisOption = this.option;
  69014. // Can not calculate data extent by data here.
  69015. // Because series and data may be modified in processing stage.
  69016. // So we do not support the feature "auto min/max".
  69017. var extent = asc$3([thisOption.min, thisOption.max]);
  69018. this._dataExtent = extent;
  69019. },
  69020. /**
  69021. * @public
  69022. * @param {module:echarts/data/List} list
  69023. * @return {string} Concrete dimention. If return null/undefined,
  69024. * no dimension used.
  69025. */
  69026. getDataDimension: function (list) {
  69027. var optDim = this.option.dimension;
  69028. var listDimensions = list.dimensions;
  69029. if (optDim == null && !listDimensions.length) {
  69030. return;
  69031. }
  69032. if (optDim != null) {
  69033. return list.getDimension(optDim);
  69034. }
  69035. var dimNames = list.dimensions;
  69036. for (var i = dimNames.length - 1; i >= 0; i--) {
  69037. var dimName = dimNames[i];
  69038. var dimInfo = list.getDimensionInfo(dimName);
  69039. if (!dimInfo.isCalculationCoord) {
  69040. return dimName;
  69041. }
  69042. }
  69043. },
  69044. /**
  69045. * @public
  69046. * @override
  69047. */
  69048. getExtent: function () {
  69049. return this._dataExtent.slice();
  69050. },
  69051. /**
  69052. * @protected
  69053. */
  69054. completeVisualOption: function () {
  69055. var ecModel = this.ecModel;
  69056. var thisOption = this.option;
  69057. var base = {inRange: thisOption.inRange, outOfRange: thisOption.outOfRange};
  69058. var target = thisOption.target || (thisOption.target = {});
  69059. var controller = thisOption.controller || (thisOption.controller = {});
  69060. merge(target, base); // Do not override
  69061. merge(controller, base); // Do not override
  69062. var isCategory = this.isCategory();
  69063. completeSingle.call(this, target);
  69064. completeSingle.call(this, controller);
  69065. completeInactive.call(this, target, 'inRange', 'outOfRange');
  69066. // completeInactive.call(this, target, 'outOfRange', 'inRange');
  69067. completeController.call(this, controller);
  69068. function completeSingle(base) {
  69069. // Compatible with ec2 dataRange.color.
  69070. // The mapping order of dataRange.color is: [high value, ..., low value]
  69071. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  69072. // Notice: ec2 has no inverse.
  69073. if (isArray$3(thisOption.color)
  69074. // If there has been inRange: {symbol: ...}, adding color is a mistake.
  69075. // So adding color only when no inRange defined.
  69076. && !base.inRange
  69077. ) {
  69078. base.inRange = {color: thisOption.color.slice().reverse()};
  69079. }
  69080. // Compatible with previous logic, always give a defautl color, otherwise
  69081. // simple config with no inRange and outOfRange will not work.
  69082. // Originally we use visualMap.color as the default color, but setOption at
  69083. // the second time the default color will be erased. So we change to use
  69084. // constant DEFAULT_COLOR.
  69085. // If user do not want the defualt color, set inRange: {color: null}.
  69086. base.inRange = base.inRange || {color: ecModel.get('gradientColor')};
  69087. // If using shortcut like: {inRange: 'symbol'}, complete default value.
  69088. each$25(this.stateList, function (state) {
  69089. var visualType = base[state];
  69090. if (isString(visualType)) {
  69091. var defa = visualDefault.get(visualType, 'active', isCategory);
  69092. if (defa) {
  69093. base[state] = {};
  69094. base[state][visualType] = defa;
  69095. }
  69096. else {
  69097. // Mark as not specified.
  69098. delete base[state];
  69099. }
  69100. }
  69101. }, this);
  69102. }
  69103. function completeInactive(base, stateExist, stateAbsent) {
  69104. var optExist = base[stateExist];
  69105. var optAbsent = base[stateAbsent];
  69106. if (optExist && !optAbsent) {
  69107. optAbsent = base[stateAbsent] = {};
  69108. each$25(optExist, function (visualData, visualType) {
  69109. if (!VisualMapping.isValidType(visualType)) {
  69110. return;
  69111. }
  69112. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  69113. if (defa != null) {
  69114. optAbsent[visualType] = defa;
  69115. // Compatibable with ec2:
  69116. // Only inactive color to rgba(0,0,0,0) can not
  69117. // make label transparent, so use opacity also.
  69118. if (visualType === 'color'
  69119. && !optAbsent.hasOwnProperty('opacity')
  69120. && !optAbsent.hasOwnProperty('colorAlpha')
  69121. ) {
  69122. optAbsent.opacity = [0, 0];
  69123. }
  69124. }
  69125. });
  69126. }
  69127. }
  69128. function completeController(controller) {
  69129. var symbolExists = (controller.inRange || {}).symbol
  69130. || (controller.outOfRange || {}).symbol;
  69131. var symbolSizeExists = (controller.inRange || {}).symbolSize
  69132. || (controller.outOfRange || {}).symbolSize;
  69133. var inactiveColor = this.get('inactiveColor');
  69134. each$25(this.stateList, function (state) {
  69135. var itemSize = this.itemSize;
  69136. var visuals = controller[state];
  69137. // Set inactive color for controller if no other color
  69138. // attr (like colorAlpha) specified.
  69139. if (!visuals) {
  69140. visuals = controller[state] = {
  69141. color: isCategory ? inactiveColor : [inactiveColor]
  69142. };
  69143. }
  69144. // Consistent symbol and symbolSize if not specified.
  69145. if (visuals.symbol == null) {
  69146. visuals.symbol = symbolExists
  69147. && clone(symbolExists)
  69148. || (isCategory ? 'roundRect' : ['roundRect']);
  69149. }
  69150. if (visuals.symbolSize == null) {
  69151. visuals.symbolSize = symbolSizeExists
  69152. && clone(symbolSizeExists)
  69153. || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  69154. }
  69155. // Filter square and none.
  69156. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  69157. return (symbol === 'none' || symbol === 'square') ? 'roundRect' : symbol;
  69158. });
  69159. // Normalize symbolSize
  69160. var symbolSize = visuals.symbolSize;
  69161. if (symbolSize != null) {
  69162. var max = -Infinity;
  69163. // symbolSize can be object when categories defined.
  69164. eachVisual(symbolSize, function (value) {
  69165. value > max && (max = value);
  69166. });
  69167. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  69168. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  69169. });
  69170. }
  69171. }, this);
  69172. }
  69173. },
  69174. /**
  69175. * @protected
  69176. */
  69177. resetItemSize: function () {
  69178. this.itemSize = [
  69179. parseFloat(this.get('itemWidth')),
  69180. parseFloat(this.get('itemHeight'))
  69181. ];
  69182. },
  69183. /**
  69184. * @public
  69185. */
  69186. isCategory: function () {
  69187. return !!this.option.categories;
  69188. },
  69189. /**
  69190. * @public
  69191. * @abstract
  69192. */
  69193. setSelected: noop$2,
  69194. /**
  69195. * @public
  69196. * @abstract
  69197. * @param {*|module:echarts/data/List} valueOrData
  69198. * @param {number} dataIndex
  69199. * @return {string} state See this.stateList
  69200. */
  69201. getValueState: noop$2,
  69202. /**
  69203. * FIXME
  69204. * Do not publish to thirt-part-dev temporarily
  69205. * util the interface is stable. (Should it return
  69206. * a function but not visual meta?)
  69207. *
  69208. * @pubilc
  69209. * @abstract
  69210. * @param {Function} getColorVisual
  69211. * params: value, valueState
  69212. * return: color
  69213. * @return {Object} visualMeta
  69214. * should includes {stops, outerColors}
  69215. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  69216. */
  69217. getVisualMeta: noop$2
  69218. });
  69219. /*
  69220. * Licensed to the Apache Software Foundation (ASF) under one
  69221. * or more contributor license agreements. See the NOTICE file
  69222. * distributed with this work for additional information
  69223. * regarding copyright ownership. The ASF licenses this file
  69224. * to you under the Apache License, Version 2.0 (the
  69225. * "License"); you may not use this file except in compliance
  69226. * with the License. You may obtain a copy of the License at
  69227. *
  69228. * http://www.apache.org/licenses/LICENSE-2.0
  69229. *
  69230. * Unless required by applicable law or agreed to in writing,
  69231. * software distributed under the License is distributed on an
  69232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69233. * KIND, either express or implied. See the License for the
  69234. * specific language governing permissions and limitations
  69235. * under the License.
  69236. */
  69237. // Constant
  69238. var DEFAULT_BAR_BOUND = [20, 140];
  69239. var ContinuousModel = VisualMapModel.extend({
  69240. type: 'visualMap.continuous',
  69241. /**
  69242. * @protected
  69243. */
  69244. defaultOption: {
  69245. align: 'auto', // 'auto', 'left', 'right', 'top', 'bottom'
  69246. calculable: false, // This prop effect default component type determine,
  69247. // See echarts/component/visualMap/typeDefaulter.
  69248. range: null, // selected range. In default case `range` is [min, max]
  69249. // and can auto change along with modification of min max,
  69250. // util use specifid a range.
  69251. realtime: true, // Whether realtime update.
  69252. itemHeight: null, // The length of the range control edge.
  69253. itemWidth: null, // The length of the other side.
  69254. hoverLink: true, // Enable hover highlight.
  69255. hoverLinkDataSize: null,// The size of hovered data.
  69256. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  69257. // If not specified, follow the value of `realtime`.
  69258. },
  69259. /**
  69260. * @override
  69261. */
  69262. optionUpdated: function (newOption, isInit) {
  69263. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  69264. this.resetExtent();
  69265. this.resetVisual(function (mappingOption) {
  69266. mappingOption.mappingMethod = 'linear';
  69267. mappingOption.dataExtent = this.getExtent();
  69268. });
  69269. this._resetRange();
  69270. },
  69271. /**
  69272. * @protected
  69273. * @override
  69274. */
  69275. resetItemSize: function () {
  69276. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  69277. var itemSize = this.itemSize;
  69278. this._orient === 'horizontal' && itemSize.reverse();
  69279. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  69280. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  69281. },
  69282. /**
  69283. * @private
  69284. */
  69285. _resetRange: function () {
  69286. var dataExtent = this.getExtent();
  69287. var range = this.option.range;
  69288. if (!range || range.auto) {
  69289. // `range` should always be array (so we dont use other
  69290. // value like 'auto') for user-friend. (consider getOption).
  69291. dataExtent.auto = 1;
  69292. this.option.range = dataExtent;
  69293. }
  69294. else if (isArray(range)) {
  69295. if (range[0] > range[1]) {
  69296. range.reverse();
  69297. }
  69298. range[0] = Math.max(range[0], dataExtent[0]);
  69299. range[1] = Math.min(range[1], dataExtent[1]);
  69300. }
  69301. },
  69302. /**
  69303. * @protected
  69304. * @override
  69305. */
  69306. completeVisualOption: function () {
  69307. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  69308. each$1(this.stateList, function (state) {
  69309. var symbolSize = this.option.controller[state].symbolSize;
  69310. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  69311. symbolSize[0] = 0; // For good looking.
  69312. }
  69313. }, this);
  69314. },
  69315. /**
  69316. * @override
  69317. */
  69318. setSelected: function (selected) {
  69319. this.option.range = selected.slice();
  69320. this._resetRange();
  69321. },
  69322. /**
  69323. * @public
  69324. */
  69325. getSelected: function () {
  69326. var dataExtent = this.getExtent();
  69327. var dataInterval = asc(
  69328. (this.get('range') || []).slice()
  69329. );
  69330. // Clamp
  69331. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  69332. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  69333. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  69334. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  69335. return dataInterval;
  69336. },
  69337. /**
  69338. * @override
  69339. */
  69340. getValueState: function (value) {
  69341. var range = this.option.range;
  69342. var dataExtent = this.getExtent();
  69343. // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  69344. // range[1] is processed likewise.
  69345. return (
  69346. (range[0] <= dataExtent[0] || range[0] <= value)
  69347. && (range[1] >= dataExtent[1] || value <= range[1])
  69348. ) ? 'inRange' : 'outOfRange';
  69349. },
  69350. /**
  69351. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  69352. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  69353. */
  69354. findTargetDataIndices: function (range) {
  69355. var result = [];
  69356. this.eachTargetSeries(function (seriesModel) {
  69357. var dataIndices = [];
  69358. var data = seriesModel.getData();
  69359. data.each(this.getDataDimension(data), function (value, dataIndex) {
  69360. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  69361. }, this);
  69362. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  69363. }, this);
  69364. return result;
  69365. },
  69366. /**
  69367. * @implement
  69368. */
  69369. getVisualMeta: function (getColorVisual) {
  69370. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  69371. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  69372. var stops = [];
  69373. function setStop(value, valueState) {
  69374. stops.push({
  69375. value: value,
  69376. color: getColorVisual(value, valueState)
  69377. });
  69378. }
  69379. // Format to: outOfRange -- inRange -- outOfRange.
  69380. var iIdx = 0;
  69381. var oIdx = 0;
  69382. var iLen = iVals.length;
  69383. var oLen = oVals.length;
  69384. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  69385. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  69386. if (oVals[oIdx] < iVals[iIdx]) {
  69387. setStop(oVals[oIdx], 'outOfRange');
  69388. }
  69389. }
  69390. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  69391. // If range is full, value beyond min, max will be clamped.
  69392. // make a singularity
  69393. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  69394. setStop(iVals[iIdx], 'inRange');
  69395. }
  69396. for (var first = 1; oIdx < oLen; oIdx++) {
  69397. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  69398. // make a singularity
  69399. if (first) {
  69400. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  69401. first = 0;
  69402. }
  69403. setStop(oVals[oIdx], 'outOfRange');
  69404. }
  69405. }
  69406. var stopsLen = stops.length;
  69407. return {
  69408. stops: stops,
  69409. outerColors: [
  69410. stopsLen ? stops[0].color : 'transparent',
  69411. stopsLen ? stops[stopsLen - 1].color : 'transparent'
  69412. ]
  69413. };
  69414. }
  69415. });
  69416. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  69417. if (dataExtent[0] === dataExtent[1]) {
  69418. return dataExtent.slice();
  69419. }
  69420. // When using colorHue mapping, it is not linear color any more.
  69421. // Moreover, canvas gradient seems not to be accurate linear.
  69422. // FIXME
  69423. // Should be arbitrary value 100? or based on pixel size?
  69424. var count = 200;
  69425. var step = (dataExtent[1] - dataExtent[0]) / count;
  69426. var value = dataExtent[0];
  69427. var stopValues = [];
  69428. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  69429. stopValues.push(value);
  69430. value += step;
  69431. }
  69432. stopValues.push(dataExtent[1]);
  69433. return stopValues;
  69434. }
  69435. /*
  69436. * Licensed to the Apache Software Foundation (ASF) under one
  69437. * or more contributor license agreements. See the NOTICE file
  69438. * distributed with this work for additional information
  69439. * regarding copyright ownership. The ASF licenses this file
  69440. * to you under the Apache License, Version 2.0 (the
  69441. * "License"); you may not use this file except in compliance
  69442. * with the License. You may obtain a copy of the License at
  69443. *
  69444. * http://www.apache.org/licenses/LICENSE-2.0
  69445. *
  69446. * Unless required by applicable law or agreed to in writing,
  69447. * software distributed under the License is distributed on an
  69448. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69449. * KIND, either express or implied. See the License for the
  69450. * specific language governing permissions and limitations
  69451. * under the License.
  69452. */
  69453. var VisualMapView = extendComponentView({
  69454. type: 'visualMap',
  69455. /**
  69456. * @readOnly
  69457. * @type {Object}
  69458. */
  69459. autoPositionValues: {left: 1, right: 1, top: 1, bottom: 1},
  69460. init: function (ecModel, api) {
  69461. /**
  69462. * @readOnly
  69463. * @type {module:echarts/model/Global}
  69464. */
  69465. this.ecModel = ecModel;
  69466. /**
  69467. * @readOnly
  69468. * @type {module:echarts/ExtensionAPI}
  69469. */
  69470. this.api = api;
  69471. /**
  69472. * @readOnly
  69473. * @type {module:echarts/component/visualMap/visualMapModel}
  69474. */
  69475. this.visualMapModel;
  69476. },
  69477. /**
  69478. * @protected
  69479. */
  69480. render: function (visualMapModel, ecModel, api, payload) {
  69481. this.visualMapModel = visualMapModel;
  69482. if (visualMapModel.get('show') === false) {
  69483. this.group.removeAll();
  69484. return;
  69485. }
  69486. this.doRender.apply(this, arguments);
  69487. },
  69488. /**
  69489. * @protected
  69490. */
  69491. renderBackground: function (group) {
  69492. var visualMapModel = this.visualMapModel;
  69493. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  69494. var rect = group.getBoundingRect();
  69495. group.add(new Rect({
  69496. z2: -1, // Lay background rect on the lowest layer.
  69497. silent: true,
  69498. shape: {
  69499. x: rect.x - padding[3],
  69500. y: rect.y - padding[0],
  69501. width: rect.width + padding[3] + padding[1],
  69502. height: rect.height + padding[0] + padding[2]
  69503. },
  69504. style: {
  69505. fill: visualMapModel.get('backgroundColor'),
  69506. stroke: visualMapModel.get('borderColor'),
  69507. lineWidth: visualMapModel.get('borderWidth')
  69508. }
  69509. }));
  69510. },
  69511. /**
  69512. * @protected
  69513. * @param {number} targetValue can be Infinity or -Infinity
  69514. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  69515. * @param {Object} [opts]
  69516. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  69517. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  69518. * @return {*} Visual value.
  69519. */
  69520. getControllerVisual: function (targetValue, visualCluster, opts) {
  69521. opts = opts || {};
  69522. var forceState = opts.forceState;
  69523. var visualMapModel = this.visualMapModel;
  69524. var visualObj = {};
  69525. // Default values.
  69526. if (visualCluster === 'symbol') {
  69527. visualObj.symbol = visualMapModel.get('itemSymbol');
  69528. }
  69529. if (visualCluster === 'color') {
  69530. var defaultColor = visualMapModel.get('contentColor');
  69531. visualObj.color = defaultColor;
  69532. }
  69533. function getter(key) {
  69534. return visualObj[key];
  69535. }
  69536. function setter(key, value) {
  69537. visualObj[key] = value;
  69538. }
  69539. var mappings = visualMapModel.controllerVisuals[
  69540. forceState || visualMapModel.getValueState(targetValue)
  69541. ];
  69542. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  69543. each$1(visualTypes, function (type) {
  69544. var visualMapping = mappings[type];
  69545. if (opts.convertOpacityToAlpha && type === 'opacity') {
  69546. type = 'colorAlpha';
  69547. visualMapping = mappings.__alphaForOpacity;
  69548. }
  69549. if (VisualMapping.dependsOn(type, visualCluster)) {
  69550. visualMapping && visualMapping.applyVisual(
  69551. targetValue, getter, setter
  69552. );
  69553. }
  69554. });
  69555. return visualObj[visualCluster];
  69556. },
  69557. /**
  69558. * @protected
  69559. */
  69560. positionGroup: function (group) {
  69561. var model = this.visualMapModel;
  69562. var api = this.api;
  69563. positionElement(
  69564. group,
  69565. model.getBoxLayoutParams(),
  69566. {width: api.getWidth(), height: api.getHeight()}
  69567. );
  69568. },
  69569. /**
  69570. * @protected
  69571. * @abstract
  69572. */
  69573. doRender: noop
  69574. });
  69575. /*
  69576. * Licensed to the Apache Software Foundation (ASF) under one
  69577. * or more contributor license agreements. See the NOTICE file
  69578. * distributed with this work for additional information
  69579. * regarding copyright ownership. The ASF licenses this file
  69580. * to you under the Apache License, Version 2.0 (the
  69581. * "License"); you may not use this file except in compliance
  69582. * with the License. You may obtain a copy of the License at
  69583. *
  69584. * http://www.apache.org/licenses/LICENSE-2.0
  69585. *
  69586. * Unless required by applicable law or agreed to in writing,
  69587. * software distributed under the License is distributed on an
  69588. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69589. * KIND, either express or implied. See the License for the
  69590. * specific language governing permissions and limitations
  69591. * under the License.
  69592. */
  69593. /**
  69594. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  69595. * @param {module:echarts/ExtensionAPI} api
  69596. * @param {Array.<number>} itemSize always [short, long]
  69597. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  69598. */
  69599. function getItemAlign(visualMapModel, api, itemSize) {
  69600. var modelOption = visualMapModel.option;
  69601. var itemAlign = modelOption.align;
  69602. if (itemAlign != null && itemAlign !== 'auto') {
  69603. return itemAlign;
  69604. }
  69605. // Auto decision align.
  69606. var ecSize = {width: api.getWidth(), height: api.getHeight()};
  69607. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  69608. var paramsSet = [
  69609. ['left', 'right', 'width'],
  69610. ['top', 'bottom', 'height']
  69611. ];
  69612. var reals = paramsSet[realIndex];
  69613. var fakeValue = [0, null, 10];
  69614. var layoutInput = {};
  69615. for (var i = 0; i < 3; i++) {
  69616. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  69617. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  69618. }
  69619. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  69620. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  69621. return reals[
  69622. (rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5
  69623. < ecSize[rParam[1]] * 0.5 ? 0 : 1
  69624. ];
  69625. }
  69626. /**
  69627. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  69628. * dataIndexInside means filtered index.
  69629. */
  69630. function convertDataIndex(batch) {
  69631. each$1(batch || [], function (batchItem) {
  69632. if (batch.dataIndex != null) {
  69633. batch.dataIndexInside = batch.dataIndex;
  69634. batch.dataIndex = null;
  69635. }
  69636. });
  69637. return batch;
  69638. }
  69639. /*
  69640. * Licensed to the Apache Software Foundation (ASF) under one
  69641. * or more contributor license agreements. See the NOTICE file
  69642. * distributed with this work for additional information
  69643. * regarding copyright ownership. The ASF licenses this file
  69644. * to you under the Apache License, Version 2.0 (the
  69645. * "License"); you may not use this file except in compliance
  69646. * with the License. You may obtain a copy of the License at
  69647. *
  69648. * http://www.apache.org/licenses/LICENSE-2.0
  69649. *
  69650. * Unless required by applicable law or agreed to in writing,
  69651. * software distributed under the License is distributed on an
  69652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69653. * KIND, either express or implied. See the License for the
  69654. * specific language governing permissions and limitations
  69655. * under the License.
  69656. */
  69657. var linearMap$3 = linearMap;
  69658. var each$26 = each$1;
  69659. var mathMin$7 = Math.min;
  69660. var mathMax$7 = Math.max;
  69661. // Arbitrary value
  69662. var HOVER_LINK_SIZE = 12;
  69663. var HOVER_LINK_OUT = 6;
  69664. // Notice:
  69665. // Any "interval" should be by the order of [low, high].
  69666. // "handle0" (handleIndex === 0) maps to
  69667. // low data value: this._dataInterval[0] and has low coord.
  69668. // "handle1" (handleIndex === 1) maps to
  69669. // high data value: this._dataInterval[1] and has high coord.
  69670. // The logic of transform is implemented in this._createBarGroup.
  69671. var ContinuousView = VisualMapView.extend({
  69672. type: 'visualMap.continuous',
  69673. /**
  69674. * @override
  69675. */
  69676. init: function () {
  69677. ContinuousView.superApply(this, 'init', arguments);
  69678. /**
  69679. * @private
  69680. */
  69681. this._shapes = {};
  69682. /**
  69683. * @private
  69684. */
  69685. this._dataInterval = [];
  69686. /**
  69687. * @private
  69688. */
  69689. this._handleEnds = [];
  69690. /**
  69691. * @private
  69692. */
  69693. this._orient;
  69694. /**
  69695. * @private
  69696. */
  69697. this._useHandle;
  69698. /**
  69699. * @private
  69700. */
  69701. this._hoverLinkDataIndices = [];
  69702. /**
  69703. * @private
  69704. */
  69705. this._dragging;
  69706. /**
  69707. * @private
  69708. */
  69709. this._hovering;
  69710. },
  69711. /**
  69712. * @protected
  69713. * @override
  69714. */
  69715. doRender: function (visualMapModel, ecModel, api, payload) {
  69716. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  69717. this._buildView();
  69718. }
  69719. },
  69720. /**
  69721. * @private
  69722. */
  69723. _buildView: function () {
  69724. this.group.removeAll();
  69725. var visualMapModel = this.visualMapModel;
  69726. var thisGroup = this.group;
  69727. this._orient = visualMapModel.get('orient');
  69728. this._useHandle = visualMapModel.get('calculable');
  69729. this._resetInterval();
  69730. this._renderBar(thisGroup);
  69731. var dataRangeText = visualMapModel.get('text');
  69732. this._renderEndsText(thisGroup, dataRangeText, 0);
  69733. this._renderEndsText(thisGroup, dataRangeText, 1);
  69734. // Do this for background size calculation.
  69735. this._updateView(true);
  69736. // After updating view, inner shapes is built completely,
  69737. // and then background can be rendered.
  69738. this.renderBackground(thisGroup);
  69739. // Real update view
  69740. this._updateView();
  69741. this._enableHoverLinkToSeries();
  69742. this._enableHoverLinkFromSeries();
  69743. this.positionGroup(thisGroup);
  69744. },
  69745. /**
  69746. * @private
  69747. */
  69748. _renderEndsText: function (group, dataRangeText, endsIndex) {
  69749. if (!dataRangeText) {
  69750. return;
  69751. }
  69752. // Compatible with ec2, text[0] map to high value, text[1] map low value.
  69753. var text = dataRangeText[1 - endsIndex];
  69754. text = text != null ? text + '' : '';
  69755. var visualMapModel = this.visualMapModel;
  69756. var textGap = visualMapModel.get('textGap');
  69757. var itemSize = visualMapModel.itemSize;
  69758. var barGroup = this._shapes.barGroup;
  69759. var position = this._applyTransform(
  69760. [
  69761. itemSize[0] / 2,
  69762. endsIndex === 0 ? -textGap : itemSize[1] + textGap
  69763. ],
  69764. barGroup
  69765. );
  69766. var align = this._applyTransform(
  69767. endsIndex === 0 ? 'bottom' : 'top',
  69768. barGroup
  69769. );
  69770. var orient = this._orient;
  69771. var textStyleModel = this.visualMapModel.textStyleModel;
  69772. this.group.add(new Text({
  69773. style: {
  69774. x: position[0],
  69775. y: position[1],
  69776. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  69777. textAlign: orient === 'horizontal' ? align : 'center',
  69778. text: text,
  69779. textFont: textStyleModel.getFont(),
  69780. textFill: textStyleModel.getTextColor()
  69781. }
  69782. }));
  69783. },
  69784. /**
  69785. * @private
  69786. */
  69787. _renderBar: function (targetGroup) {
  69788. var visualMapModel = this.visualMapModel;
  69789. var shapes = this._shapes;
  69790. var itemSize = visualMapModel.itemSize;
  69791. var orient = this._orient;
  69792. var useHandle = this._useHandle;
  69793. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  69794. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign);
  69795. // Bar
  69796. barGroup.add(shapes.outOfRange = createPolygon());
  69797. barGroup.add(shapes.inRange = createPolygon(
  69798. null,
  69799. useHandle ? getCursor$1(this._orient) : null,
  69800. bind(this._dragHandle, this, 'all', false),
  69801. bind(this._dragHandle, this, 'all', true)
  69802. ));
  69803. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  69804. var textSize = mathMax$7(textRect.width, textRect.height);
  69805. // Handle
  69806. if (useHandle) {
  69807. shapes.handleThumbs = [];
  69808. shapes.handleLabels = [];
  69809. shapes.handleLabelPoints = [];
  69810. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  69811. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  69812. }
  69813. this._createIndicator(barGroup, itemSize, textSize, orient);
  69814. targetGroup.add(barGroup);
  69815. },
  69816. /**
  69817. * @private
  69818. */
  69819. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  69820. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  69821. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  69822. var handleThumb = createPolygon(
  69823. createHandlePoints(handleIndex, textSize),
  69824. getCursor$1(this._orient),
  69825. onDrift,
  69826. onDragEnd
  69827. );
  69828. handleThumb.position[0] = itemSize[0];
  69829. barGroup.add(handleThumb);
  69830. // Text is always horizontal layout but should not be effected by
  69831. // transform (orient/inverse). So label is built separately but not
  69832. // use zrender/graphic/helper/RectText, and is located based on view
  69833. // group (according to handleLabelPoint) but not barGroup.
  69834. var textStyleModel = this.visualMapModel.textStyleModel;
  69835. var handleLabel = new Text({
  69836. draggable: true,
  69837. drift: onDrift,
  69838. onmousemove: function (e) {
  69839. // Fot mobile devicem, prevent screen slider on the button.
  69840. stop(e.event);
  69841. },
  69842. ondragend: onDragEnd,
  69843. style: {
  69844. x: 0, y: 0, text: '',
  69845. textFont: textStyleModel.getFont(),
  69846. textFill: textStyleModel.getTextColor()
  69847. }
  69848. });
  69849. this.group.add(handleLabel);
  69850. var handleLabelPoint = [
  69851. orient === 'horizontal'
  69852. ? textSize / 2
  69853. : textSize * 1.5,
  69854. orient === 'horizontal'
  69855. ? (handleIndex === 0 ? -(textSize * 1.5) : (textSize * 1.5))
  69856. : (handleIndex === 0 ? -textSize / 2 : textSize / 2)
  69857. ];
  69858. var shapes = this._shapes;
  69859. shapes.handleThumbs[handleIndex] = handleThumb;
  69860. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  69861. shapes.handleLabels[handleIndex] = handleLabel;
  69862. },
  69863. /**
  69864. * @private
  69865. */
  69866. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  69867. var indicator = createPolygon([[0, 0]], 'move');
  69868. indicator.position[0] = itemSize[0];
  69869. indicator.attr({invisible: true, silent: true});
  69870. barGroup.add(indicator);
  69871. var textStyleModel = this.visualMapModel.textStyleModel;
  69872. var indicatorLabel = new Text({
  69873. silent: true,
  69874. invisible: true,
  69875. style: {
  69876. x: 0, y: 0, text: '',
  69877. textFont: textStyleModel.getFont(),
  69878. textFill: textStyleModel.getTextColor()
  69879. }
  69880. });
  69881. this.group.add(indicatorLabel);
  69882. var indicatorLabelPoint = [
  69883. orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3,
  69884. 0
  69885. ];
  69886. var shapes = this._shapes;
  69887. shapes.indicator = indicator;
  69888. shapes.indicatorLabel = indicatorLabel;
  69889. shapes.indicatorLabelPoint = indicatorLabelPoint;
  69890. },
  69891. /**
  69892. * @private
  69893. */
  69894. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  69895. if (!this._useHandle) {
  69896. return;
  69897. }
  69898. this._dragging = !isEnd;
  69899. if (!isEnd) {
  69900. // Transform dx, dy to bar coordination.
  69901. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  69902. this._updateInterval(handleIndex, vertex[1]);
  69903. // Considering realtime, update view should be executed
  69904. // before dispatch action.
  69905. this._updateView();
  69906. }
  69907. // dragEnd do not dispatch action when realtime.
  69908. if (isEnd === !this.visualMapModel.get('realtime')) { // jshint ignore:line
  69909. this.api.dispatchAction({
  69910. type: 'selectDataRange',
  69911. from: this.uid,
  69912. visualMapId: this.visualMapModel.id,
  69913. selected: this._dataInterval.slice()
  69914. });
  69915. }
  69916. if (isEnd) {
  69917. !this._hovering && this._clearHoverLinkToSeries();
  69918. }
  69919. else if (useHoverLinkOnHandle(this.visualMapModel)) {
  69920. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  69921. }
  69922. },
  69923. /**
  69924. * @private
  69925. */
  69926. _resetInterval: function () {
  69927. var visualMapModel = this.visualMapModel;
  69928. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  69929. var dataExtent = visualMapModel.getExtent();
  69930. var sizeExtent = [0, visualMapModel.itemSize[1]];
  69931. this._handleEnds = [
  69932. linearMap$3(dataInterval[0], dataExtent, sizeExtent, true),
  69933. linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)
  69934. ];
  69935. },
  69936. /**
  69937. * @private
  69938. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  69939. * @param {number} dx
  69940. * @param {number} dy
  69941. */
  69942. _updateInterval: function (handleIndex, delta) {
  69943. delta = delta || 0;
  69944. var visualMapModel = this.visualMapModel;
  69945. var handleEnds = this._handleEnds;
  69946. var sizeExtent = [0, visualMapModel.itemSize[1]];
  69947. sliderMove(
  69948. delta,
  69949. handleEnds,
  69950. sizeExtent,
  69951. handleIndex,
  69952. // cross is forbiden
  69953. 0
  69954. );
  69955. var dataExtent = visualMapModel.getExtent();
  69956. // Update data interval.
  69957. this._dataInterval = [
  69958. linearMap$3(handleEnds[0], sizeExtent, dataExtent, true),
  69959. linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)
  69960. ];
  69961. },
  69962. /**
  69963. * @private
  69964. */
  69965. _updateView: function (forSketch) {
  69966. var visualMapModel = this.visualMapModel;
  69967. var dataExtent = visualMapModel.getExtent();
  69968. var shapes = this._shapes;
  69969. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  69970. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  69971. var visualInRange = this._createBarVisual(
  69972. this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange'
  69973. );
  69974. var visualOutOfRange = this._createBarVisual(
  69975. dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange'
  69976. );
  69977. shapes.inRange
  69978. .setStyle({
  69979. fill: visualInRange.barColor,
  69980. opacity: visualInRange.opacity
  69981. })
  69982. .setShape('points', visualInRange.barPoints);
  69983. shapes.outOfRange
  69984. .setStyle({
  69985. fill: visualOutOfRange.barColor,
  69986. opacity: visualOutOfRange.opacity
  69987. })
  69988. .setShape('points', visualOutOfRange.barPoints);
  69989. this._updateHandle(inRangeHandleEnds, visualInRange);
  69990. },
  69991. /**
  69992. * @private
  69993. */
  69994. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  69995. var opts = {
  69996. forceState: forceState,
  69997. convertOpacityToAlpha: true
  69998. };
  69999. var colorStops = this._makeColorGradient(dataInterval, opts);
  70000. var symbolSizes = [
  70001. this.getControllerVisual(dataInterval[0], 'symbolSize', opts),
  70002. this.getControllerVisual(dataInterval[1], 'symbolSize', opts)
  70003. ];
  70004. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  70005. return {
  70006. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  70007. barPoints: barPoints,
  70008. handlesColor: [
  70009. colorStops[0].color,
  70010. colorStops[colorStops.length - 1].color
  70011. ]
  70012. };
  70013. },
  70014. /**
  70015. * @private
  70016. */
  70017. _makeColorGradient: function (dataInterval, opts) {
  70018. // Considering colorHue, which is not linear, so we have to sample
  70019. // to calculate gradient color stops, but not only caculate head
  70020. // and tail.
  70021. var sampleNumber = 100; // Arbitrary value.
  70022. var colorStops = [];
  70023. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  70024. colorStops.push({
  70025. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  70026. offset: 0
  70027. });
  70028. for (var i = 1; i < sampleNumber; i++) {
  70029. var currValue = dataInterval[0] + step * i;
  70030. if (currValue > dataInterval[1]) {
  70031. break;
  70032. }
  70033. colorStops.push({
  70034. color: this.getControllerVisual(currValue, 'color', opts),
  70035. offset: i / sampleNumber
  70036. });
  70037. }
  70038. colorStops.push({
  70039. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  70040. offset: 1
  70041. });
  70042. return colorStops;
  70043. },
  70044. /**
  70045. * @private
  70046. */
  70047. _createBarPoints: function (handleEnds, symbolSizes) {
  70048. var itemSize = this.visualMapModel.itemSize;
  70049. return [
  70050. [itemSize[0] - symbolSizes[0], handleEnds[0]],
  70051. [itemSize[0], handleEnds[0]],
  70052. [itemSize[0], handleEnds[1]],
  70053. [itemSize[0] - symbolSizes[1], handleEnds[1]]
  70054. ];
  70055. },
  70056. /**
  70057. * @private
  70058. */
  70059. _createBarGroup: function (itemAlign) {
  70060. var orient = this._orient;
  70061. var inverse = this.visualMapModel.get('inverse');
  70062. return new Group(
  70063. (orient === 'horizontal' && !inverse)
  70064. ? {scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1], rotation: Math.PI / 2}
  70065. : (orient === 'horizontal' && inverse)
  70066. ? {scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1], rotation: -Math.PI / 2}
  70067. : (orient === 'vertical' && !inverse)
  70068. ? {scale: itemAlign === 'left' ? [1, -1] : [-1, -1]}
  70069. : {scale: itemAlign === 'left' ? [1, 1] : [-1, 1]}
  70070. );
  70071. },
  70072. /**
  70073. * @private
  70074. */
  70075. _updateHandle: function (handleEnds, visualInRange) {
  70076. if (!this._useHandle) {
  70077. return;
  70078. }
  70079. var shapes = this._shapes;
  70080. var visualMapModel = this.visualMapModel;
  70081. var handleThumbs = shapes.handleThumbs;
  70082. var handleLabels = shapes.handleLabels;
  70083. each$26([0, 1], function (handleIndex) {
  70084. var handleThumb = handleThumbs[handleIndex];
  70085. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  70086. handleThumb.position[1] = handleEnds[handleIndex];
  70087. // Update handle label position.
  70088. var textPoint = applyTransform$1(
  70089. shapes.handleLabelPoints[handleIndex],
  70090. getTransform(handleThumb, this.group)
  70091. );
  70092. handleLabels[handleIndex].setStyle({
  70093. x: textPoint[0],
  70094. y: textPoint[1],
  70095. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  70096. textVerticalAlign: 'middle',
  70097. textAlign: this._applyTransform(
  70098. this._orient === 'horizontal'
  70099. ? (handleIndex === 0 ? 'bottom' : 'top')
  70100. : 'left',
  70101. shapes.barGroup
  70102. )
  70103. });
  70104. }, this);
  70105. },
  70106. /**
  70107. * @private
  70108. * @param {number} cursorValue
  70109. * @param {number} textValue
  70110. * @param {string} [rangeSymbol]
  70111. * @param {number} [halfHoverLinkSize]
  70112. */
  70113. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  70114. var visualMapModel = this.visualMapModel;
  70115. var dataExtent = visualMapModel.getExtent();
  70116. var itemSize = visualMapModel.itemSize;
  70117. var sizeExtent = [0, itemSize[1]];
  70118. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  70119. var shapes = this._shapes;
  70120. var indicator = shapes.indicator;
  70121. if (!indicator) {
  70122. return;
  70123. }
  70124. indicator.position[1] = pos;
  70125. indicator.attr('invisible', false);
  70126. indicator.setShape('points', createIndicatorPoints(
  70127. !!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]
  70128. ));
  70129. var opts = {convertOpacityToAlpha: true};
  70130. var color = this.getControllerVisual(cursorValue, 'color', opts);
  70131. indicator.setStyle('fill', color);
  70132. // Update handle label position.
  70133. var textPoint = applyTransform$1(
  70134. shapes.indicatorLabelPoint,
  70135. getTransform(indicator, this.group)
  70136. );
  70137. var indicatorLabel = shapes.indicatorLabel;
  70138. indicatorLabel.attr('invisible', false);
  70139. var align = this._applyTransform('left', shapes.barGroup);
  70140. var orient = this._orient;
  70141. indicatorLabel.setStyle({
  70142. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  70143. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  70144. textAlign: orient === 'horizontal' ? 'center' : align,
  70145. x: textPoint[0],
  70146. y: textPoint[1]
  70147. });
  70148. },
  70149. /**
  70150. * @private
  70151. */
  70152. _enableHoverLinkToSeries: function () {
  70153. var self = this;
  70154. this._shapes.barGroup
  70155. .on('mousemove', function (e) {
  70156. self._hovering = true;
  70157. if (!self._dragging) {
  70158. var itemSize = self.visualMapModel.itemSize;
  70159. var pos = self._applyTransform(
  70160. [e.offsetX, e.offsetY], self._shapes.barGroup, true, true
  70161. );
  70162. // For hover link show when hover handle, which might be
  70163. // below or upper than sizeExtent.
  70164. pos[1] = mathMin$7(mathMax$7(0, pos[1]), itemSize[1]);
  70165. self._doHoverLinkToSeries(
  70166. pos[1],
  70167. 0 <= pos[0] && pos[0] <= itemSize[0]
  70168. );
  70169. }
  70170. })
  70171. .on('mouseout', function () {
  70172. // When mouse is out of handle, hoverLink still need
  70173. // to be displayed when realtime is set as false.
  70174. self._hovering = false;
  70175. !self._dragging && self._clearHoverLinkToSeries();
  70176. });
  70177. },
  70178. /**
  70179. * @private
  70180. */
  70181. _enableHoverLinkFromSeries: function () {
  70182. var zr = this.api.getZr();
  70183. if (this.visualMapModel.option.hoverLink) {
  70184. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  70185. zr.on('mouseout', this._hideIndicator, this);
  70186. }
  70187. else {
  70188. this._clearHoverLinkFromSeries();
  70189. }
  70190. },
  70191. /**
  70192. * @private
  70193. */
  70194. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  70195. var visualMapModel = this.visualMapModel;
  70196. var itemSize = visualMapModel.itemSize;
  70197. if (!visualMapModel.option.hoverLink) {
  70198. return;
  70199. }
  70200. var sizeExtent = [0, itemSize[1]];
  70201. var dataExtent = visualMapModel.getExtent();
  70202. // For hover link show when hover handle, which might be below or upper than sizeExtent.
  70203. cursorPos = mathMin$7(mathMax$7(sizeExtent[0], cursorPos), sizeExtent[1]);
  70204. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  70205. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  70206. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  70207. var valueRange = [
  70208. linearMap$3(hoverRange[0], sizeExtent, dataExtent, true),
  70209. linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)
  70210. ];
  70211. // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  70212. // where china and india has very large population.
  70213. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  70214. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity);
  70215. // Do not show indicator when mouse is over handle,
  70216. // otherwise labels overlap, especially when dragging.
  70217. if (hoverOnBar) {
  70218. if (valueRange[0] === -Infinity) {
  70219. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  70220. }
  70221. else if (valueRange[1] === Infinity) {
  70222. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  70223. }
  70224. else {
  70225. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  70226. }
  70227. }
  70228. // When realtime is set as false, handles, which are in barGroup,
  70229. // also trigger hoverLink, which help user to realize where they
  70230. // focus on when dragging. (see test/heatmap-large.html)
  70231. // When realtime is set as true, highlight will not show when hover
  70232. // handle, because the label on handle, which displays a exact value
  70233. // but not range, might mislead users.
  70234. var oldBatch = this._hoverLinkDataIndices;
  70235. var newBatch = [];
  70236. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  70237. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  70238. }
  70239. var resultBatches = compressBatches(oldBatch, newBatch);
  70240. this._dispatchHighDown('downplay', convertDataIndex(resultBatches[0]));
  70241. this._dispatchHighDown('highlight', convertDataIndex(resultBatches[1]));
  70242. },
  70243. /**
  70244. * @private
  70245. */
  70246. _hoverLinkFromSeriesMouseOver: function (e) {
  70247. var el = e.target;
  70248. var visualMapModel = this.visualMapModel;
  70249. if (!el || el.dataIndex == null) {
  70250. return;
  70251. }
  70252. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  70253. if (!visualMapModel.isTargetSeries(dataModel)) {
  70254. return;
  70255. }
  70256. var data = dataModel.getData(el.dataType);
  70257. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  70258. if (!isNaN(value)) {
  70259. this._showIndicator(value, value);
  70260. }
  70261. },
  70262. /**
  70263. * @private
  70264. */
  70265. _hideIndicator: function () {
  70266. var shapes = this._shapes;
  70267. shapes.indicator && shapes.indicator.attr('invisible', true);
  70268. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  70269. },
  70270. /**
  70271. * @private
  70272. */
  70273. _clearHoverLinkToSeries: function () {
  70274. this._hideIndicator();
  70275. var indices = this._hoverLinkDataIndices;
  70276. this._dispatchHighDown('downplay', convertDataIndex(indices));
  70277. indices.length = 0;
  70278. },
  70279. /**
  70280. * @private
  70281. */
  70282. _clearHoverLinkFromSeries: function () {
  70283. this._hideIndicator();
  70284. var zr = this.api.getZr();
  70285. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  70286. zr.off('mouseout', this._hideIndicator);
  70287. },
  70288. /**
  70289. * @private
  70290. */
  70291. _applyTransform: function (vertex, element, inverse, global) {
  70292. var transform = getTransform(element, global ? null : this.group);
  70293. return graphic[
  70294. isArray(vertex) ? 'applyTransform' : 'transformDirection'
  70295. ](vertex, transform, inverse);
  70296. },
  70297. /**
  70298. * @private
  70299. */
  70300. _dispatchHighDown: function (type, batch) {
  70301. batch && batch.length && this.api.dispatchAction({
  70302. type: type,
  70303. batch: batch
  70304. });
  70305. },
  70306. /**
  70307. * @override
  70308. */
  70309. dispose: function () {
  70310. this._clearHoverLinkFromSeries();
  70311. this._clearHoverLinkToSeries();
  70312. },
  70313. /**
  70314. * @override
  70315. */
  70316. remove: function () {
  70317. this._clearHoverLinkFromSeries();
  70318. this._clearHoverLinkToSeries();
  70319. }
  70320. });
  70321. function createPolygon(points, cursor, onDrift, onDragEnd) {
  70322. return new Polygon({
  70323. shape: {points: points},
  70324. draggable: !!onDrift,
  70325. cursor: cursor,
  70326. drift: onDrift,
  70327. onmousemove: function (e) {
  70328. // Fot mobile devicem, prevent screen slider on the button.
  70329. stop(e.event);
  70330. },
  70331. ondragend: onDragEnd
  70332. });
  70333. }
  70334. function createHandlePoints(handleIndex, textSize) {
  70335. return handleIndex === 0
  70336. ? [[0, 0], [textSize, 0], [textSize, -textSize]]
  70337. : [[0, 0], [textSize, 0], [textSize, textSize]];
  70338. }
  70339. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  70340. return isRange
  70341. ? [ // indicate range
  70342. [0, -mathMin$7(halfHoverLinkSize, mathMax$7(pos, 0))],
  70343. [HOVER_LINK_OUT, 0],
  70344. [0, mathMin$7(halfHoverLinkSize, mathMax$7(extentMax - pos, 0))]
  70345. ]
  70346. : [ // indicate single value
  70347. [0, 0], [5, -5], [5, 5]
  70348. ];
  70349. }
  70350. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  70351. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  70352. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  70353. if (hoverLinkDataSize) {
  70354. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  70355. }
  70356. return halfHoverLinkSize;
  70357. }
  70358. function useHoverLinkOnHandle(visualMapModel) {
  70359. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  70360. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  70361. }
  70362. function getCursor$1(orient) {
  70363. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  70364. }
  70365. /*
  70366. * Licensed to the Apache Software Foundation (ASF) under one
  70367. * or more contributor license agreements. See the NOTICE file
  70368. * distributed with this work for additional information
  70369. * regarding copyright ownership. The ASF licenses this file
  70370. * to you under the Apache License, Version 2.0 (the
  70371. * "License"); you may not use this file except in compliance
  70372. * with the License. You may obtain a copy of the License at
  70373. *
  70374. * http://www.apache.org/licenses/LICENSE-2.0
  70375. *
  70376. * Unless required by applicable law or agreed to in writing,
  70377. * software distributed under the License is distributed on an
  70378. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70379. * KIND, either express or implied. See the License for the
  70380. * specific language governing permissions and limitations
  70381. * under the License.
  70382. */
  70383. var actionInfo$2 = {
  70384. type: 'selectDataRange',
  70385. event: 'dataRangeSelected',
  70386. // FIXME use updateView appears wrong
  70387. update: 'update'
  70388. };
  70389. registerAction(actionInfo$2, function (payload, ecModel) {
  70390. ecModel.eachComponent({mainType: 'visualMap', query: payload}, function (model) {
  70391. model.setSelected(payload.selected);
  70392. });
  70393. });
  70394. /*
  70395. * Licensed to the Apache Software Foundation (ASF) under one
  70396. * or more contributor license agreements. See the NOTICE file
  70397. * distributed with this work for additional information
  70398. * regarding copyright ownership. The ASF licenses this file
  70399. * to you under the Apache License, Version 2.0 (the
  70400. * "License"); you may not use this file except in compliance
  70401. * with the License. You may obtain a copy of the License at
  70402. *
  70403. * http://www.apache.org/licenses/LICENSE-2.0
  70404. *
  70405. * Unless required by applicable law or agreed to in writing,
  70406. * software distributed under the License is distributed on an
  70407. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70408. * KIND, either express or implied. See the License for the
  70409. * specific language governing permissions and limitations
  70410. * under the License.
  70411. */
  70412. /**
  70413. * DataZoom component entry
  70414. */
  70415. registerPreprocessor(preprocessor$2);
  70416. /*
  70417. * Licensed to the Apache Software Foundation (ASF) under one
  70418. * or more contributor license agreements. See the NOTICE file
  70419. * distributed with this work for additional information
  70420. * regarding copyright ownership. The ASF licenses this file
  70421. * to you under the Apache License, Version 2.0 (the
  70422. * "License"); you may not use this file except in compliance
  70423. * with the License. You may obtain a copy of the License at
  70424. *
  70425. * http://www.apache.org/licenses/LICENSE-2.0
  70426. *
  70427. * Unless required by applicable law or agreed to in writing,
  70428. * software distributed under the License is distributed on an
  70429. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70430. * KIND, either express or implied. See the License for the
  70431. * specific language governing permissions and limitations
  70432. * under the License.
  70433. */
  70434. var PiecewiseModel = VisualMapModel.extend({
  70435. type: 'visualMap.piecewise',
  70436. /**
  70437. * Order Rule:
  70438. *
  70439. * option.categories / option.pieces / option.text / option.selected:
  70440. * If !option.inverse,
  70441. * Order when vertical: ['top', ..., 'bottom'].
  70442. * Order when horizontal: ['left', ..., 'right'].
  70443. * If option.inverse, the meaning of
  70444. * the order should be reversed.
  70445. *
  70446. * this._pieceList:
  70447. * The order is always [low, ..., high].
  70448. *
  70449. * Mapping from location to low-high:
  70450. * If !option.inverse
  70451. * When vertical, top is high.
  70452. * When horizontal, right is high.
  70453. * If option.inverse, reverse.
  70454. */
  70455. /**
  70456. * @protected
  70457. */
  70458. defaultOption: {
  70459. selected: null, // Object. If not specified, means selected.
  70460. // When pieces and splitNumber: {'0': true, '5': true}
  70461. // When categories: {'cate1': false, 'cate3': true}
  70462. // When selected === false, means all unselected.
  70463. minOpen: false, // Whether include values that smaller than `min`.
  70464. maxOpen: false, // Whether include values that bigger than `max`.
  70465. align: 'auto', // 'auto', 'left', 'right'
  70466. itemWidth: 20, // When put the controller vertically, it is the length of
  70467. // horizontal side of each item. Otherwise, vertical side.
  70468. itemHeight: 14, // When put the controller vertically, it is the length of
  70469. // vertical side of each item. Otherwise, horizontal side.
  70470. itemSymbol: 'roundRect',
  70471. pieceList: null, // Each item is Object, with some of those attrs:
  70472. // {min, max, lt, gt, lte, gte, value,
  70473. // color, colorSaturation, colorAlpha, opacity,
  70474. // symbol, symbolSize}, which customize the range or visual
  70475. // coding of the certain piece. Besides, see "Order Rule".
  70476. categories: null, // category names, like: ['some1', 'some2', 'some3'].
  70477. // Attr min/max are ignored when categories set. See "Order Rule"
  70478. splitNumber: 5, // If set to 5, auto split five pieces equally.
  70479. // If set to 0 and component type not set, component type will be
  70480. // determined as "continuous". (It is less reasonable but for ec2
  70481. // compatibility, see echarts/component/visualMap/typeDefaulter)
  70482. selectedMode: 'multiple', // Can be 'multiple' or 'single'.
  70483. itemGap: 10, // The gap between two items, in px.
  70484. hoverLink: true, // Enable hover highlight.
  70485. showLabel: null // By default, when text is used, label will hide (the logic
  70486. // is remained for compatibility reason)
  70487. },
  70488. /**
  70489. * @override
  70490. */
  70491. optionUpdated: function (newOption, isInit) {
  70492. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  70493. /**
  70494. * The order is always [low, ..., high].
  70495. * [{text: string, interval: Array.<number>}, ...]
  70496. * @private
  70497. * @type {Array.<Object>}
  70498. */
  70499. this._pieceList = [];
  70500. this.resetExtent();
  70501. /**
  70502. * 'pieces', 'categories', 'splitNumber'
  70503. * @type {string}
  70504. */
  70505. var mode = this._mode = this._determineMode();
  70506. resetMethods[this._mode].call(this);
  70507. this._resetSelected(newOption, isInit);
  70508. var categories = this.option.categories;
  70509. this.resetVisual(function (mappingOption, state) {
  70510. if (mode === 'categories') {
  70511. mappingOption.mappingMethod = 'category';
  70512. mappingOption.categories = clone(categories);
  70513. }
  70514. else {
  70515. mappingOption.dataExtent = this.getExtent();
  70516. mappingOption.mappingMethod = 'piecewise';
  70517. mappingOption.pieceList = map(this._pieceList, function (piece) {
  70518. var piece = clone(piece);
  70519. if (state !== 'inRange') {
  70520. // FIXME
  70521. // outOfRange do not support special visual in pieces.
  70522. piece.visual = null;
  70523. }
  70524. return piece;
  70525. });
  70526. }
  70527. });
  70528. },
  70529. /**
  70530. * @protected
  70531. * @override
  70532. */
  70533. completeVisualOption: function () {
  70534. // Consider this case:
  70535. // visualMap: {
  70536. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  70537. // }
  70538. // where no inRange/outOfRange set but only pieces. So we should make
  70539. // default inRange/outOfRange for this case, otherwise visuals that only
  70540. // appear in `pieces` will not be taken into account in visual encoding.
  70541. var option = this.option;
  70542. var visualTypesInPieces = {};
  70543. var visualTypes = VisualMapping.listVisualTypes();
  70544. var isCategory = this.isCategory();
  70545. each$1(option.pieces, function (piece) {
  70546. each$1(visualTypes, function (visualType) {
  70547. if (piece.hasOwnProperty(visualType)) {
  70548. visualTypesInPieces[visualType] = 1;
  70549. }
  70550. });
  70551. });
  70552. each$1(visualTypesInPieces, function (v, visualType) {
  70553. var exists = 0;
  70554. each$1(this.stateList, function (state) {
  70555. exists |= has(option, state, visualType)
  70556. || has(option.target, state, visualType);
  70557. }, this);
  70558. !exists && each$1(this.stateList, function (state) {
  70559. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(
  70560. visualType, state === 'inRange' ? 'active' : 'inactive', isCategory
  70561. );
  70562. });
  70563. }, this);
  70564. function has(obj, state, visualType) {
  70565. return obj && obj[state] && (
  70566. isObject$1(obj[state])
  70567. ? obj[state].hasOwnProperty(visualType)
  70568. : obj[state] === visualType // e.g., inRange: 'symbol'
  70569. );
  70570. }
  70571. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  70572. },
  70573. _resetSelected: function (newOption, isInit) {
  70574. var thisOption = this.option;
  70575. var pieceList = this._pieceList;
  70576. // Selected do not merge but all override.
  70577. var selected = (isInit ? thisOption : newOption).selected || {};
  70578. thisOption.selected = selected;
  70579. // Consider 'not specified' means true.
  70580. each$1(pieceList, function (piece, index) {
  70581. var key = this.getSelectedMapKey(piece);
  70582. if (!selected.hasOwnProperty(key)) {
  70583. selected[key] = true;
  70584. }
  70585. }, this);
  70586. if (thisOption.selectedMode === 'single') {
  70587. // Ensure there is only one selected.
  70588. var hasSel = false;
  70589. each$1(pieceList, function (piece, index) {
  70590. var key = this.getSelectedMapKey(piece);
  70591. if (selected[key]) {
  70592. hasSel
  70593. ? (selected[key] = false)
  70594. : (hasSel = true);
  70595. }
  70596. }, this);
  70597. }
  70598. // thisOption.selectedMode === 'multiple', default: all selected.
  70599. },
  70600. /**
  70601. * @public
  70602. */
  70603. getSelectedMapKey: function (piece) {
  70604. return this._mode === 'categories'
  70605. ? piece.value + '' : piece.index + '';
  70606. },
  70607. /**
  70608. * @public
  70609. */
  70610. getPieceList: function () {
  70611. return this._pieceList;
  70612. },
  70613. /**
  70614. * @private
  70615. * @return {string}
  70616. */
  70617. _determineMode: function () {
  70618. var option = this.option;
  70619. return option.pieces && option.pieces.length > 0
  70620. ? 'pieces'
  70621. : this.option.categories
  70622. ? 'categories'
  70623. : 'splitNumber';
  70624. },
  70625. /**
  70626. * @public
  70627. * @override
  70628. */
  70629. setSelected: function (selected) {
  70630. this.option.selected = clone(selected);
  70631. },
  70632. /**
  70633. * @public
  70634. * @override
  70635. */
  70636. getValueState: function (value) {
  70637. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  70638. return index != null
  70639. ? (this.option.selected[this.getSelectedMapKey(this._pieceList[index])]
  70640. ? 'inRange' : 'outOfRange'
  70641. )
  70642. : 'outOfRange';
  70643. },
  70644. /**
  70645. * @public
  70646. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  70647. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  70648. */
  70649. findTargetDataIndices: function (pieceIndex) {
  70650. var result = [];
  70651. this.eachTargetSeries(function (seriesModel) {
  70652. var dataIndices = [];
  70653. var data = seriesModel.getData();
  70654. data.each(this.getDataDimension(data), function (value, dataIndex) {
  70655. // Should always base on model pieceList, because it is order sensitive.
  70656. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  70657. pIdx === pieceIndex && dataIndices.push(dataIndex);
  70658. }, this);
  70659. result.push({seriesId: seriesModel.id, dataIndex: dataIndices});
  70660. }, this);
  70661. return result;
  70662. },
  70663. /**
  70664. * @private
  70665. * @param {Object} piece piece.value or piece.interval is required.
  70666. * @return {number} Can be Infinity or -Infinity
  70667. */
  70668. getRepresentValue: function (piece) {
  70669. var representValue;
  70670. if (this.isCategory()) {
  70671. representValue = piece.value;
  70672. }
  70673. else {
  70674. if (piece.value != null) {
  70675. representValue = piece.value;
  70676. }
  70677. else {
  70678. var pieceInterval = piece.interval || [];
  70679. representValue = (pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity)
  70680. ? 0
  70681. : (pieceInterval[0] + pieceInterval[1]) / 2;
  70682. }
  70683. }
  70684. return representValue;
  70685. },
  70686. getVisualMeta: function (getColorVisual) {
  70687. // Do not support category. (category axis is ordinal, numerical)
  70688. if (this.isCategory()) {
  70689. return;
  70690. }
  70691. var stops = [];
  70692. var outerColors = [];
  70693. var visualMapModel = this;
  70694. function setStop(interval, valueState) {
  70695. var representValue = visualMapModel.getRepresentValue({interval: interval});
  70696. if (!valueState) {
  70697. valueState = visualMapModel.getValueState(representValue);
  70698. }
  70699. var color = getColorVisual(representValue, valueState);
  70700. if (interval[0] === -Infinity) {
  70701. outerColors[0] = color;
  70702. }
  70703. else if (interval[1] === Infinity) {
  70704. outerColors[1] = color;
  70705. }
  70706. else {
  70707. stops.push(
  70708. {value: interval[0], color: color},
  70709. {value: interval[1], color: color}
  70710. );
  70711. }
  70712. }
  70713. // Suplement
  70714. var pieceList = this._pieceList.slice();
  70715. if (!pieceList.length) {
  70716. pieceList.push({interval: [-Infinity, Infinity]});
  70717. }
  70718. else {
  70719. var edge = pieceList[0].interval[0];
  70720. edge !== -Infinity && pieceList.unshift({interval: [-Infinity, edge]});
  70721. edge = pieceList[pieceList.length - 1].interval[1];
  70722. edge !== Infinity && pieceList.push({interval: [edge, Infinity]});
  70723. }
  70724. var curr = -Infinity;
  70725. each$1(pieceList, function (piece) {
  70726. var interval = piece.interval;
  70727. if (interval) {
  70728. // Fulfill gap.
  70729. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  70730. setStop(interval.slice());
  70731. curr = interval[1];
  70732. }
  70733. }, this);
  70734. return {stops: stops, outerColors: outerColors};
  70735. }
  70736. });
  70737. /**
  70738. * Key is this._mode
  70739. * @type {Object}
  70740. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  70741. */
  70742. var resetMethods = {
  70743. splitNumber: function () {
  70744. var thisOption = this.option;
  70745. var pieceList = this._pieceList;
  70746. var precision = Math.min(thisOption.precision, 20);
  70747. var dataExtent = this.getExtent();
  70748. var splitNumber = thisOption.splitNumber;
  70749. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  70750. thisOption.splitNumber = splitNumber;
  70751. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber;
  70752. // Precision auto-adaption
  70753. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  70754. precision++;
  70755. }
  70756. thisOption.precision = precision;
  70757. splitStep = +splitStep.toFixed(precision);
  70758. var index = 0;
  70759. if (thisOption.minOpen) {
  70760. pieceList.push({
  70761. index: index++,
  70762. interval: [-Infinity, dataExtent[0]],
  70763. close: [0, 0]
  70764. });
  70765. }
  70766. for (
  70767. var curr = dataExtent[0], len = index + splitNumber;
  70768. index < len;
  70769. curr += splitStep
  70770. ) {
  70771. var max = index === splitNumber - 1 ? dataExtent[1] : (curr + splitStep);
  70772. pieceList.push({
  70773. index: index++,
  70774. interval: [curr, max],
  70775. close: [1, 1]
  70776. });
  70777. }
  70778. if (thisOption.maxOpen) {
  70779. pieceList.push({
  70780. index: index++,
  70781. interval: [dataExtent[1], Infinity],
  70782. close: [0, 0]
  70783. });
  70784. }
  70785. reformIntervals(pieceList);
  70786. each$1(pieceList, function (piece) {
  70787. piece.text = this.formatValueText(piece.interval);
  70788. }, this);
  70789. },
  70790. categories: function () {
  70791. var thisOption = this.option;
  70792. each$1(thisOption.categories, function (cate) {
  70793. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  70794. // 是否改一致。
  70795. this._pieceList.push({
  70796. text: this.formatValueText(cate, true),
  70797. value: cate
  70798. });
  70799. }, this);
  70800. // See "Order Rule".
  70801. normalizeReverse(thisOption, this._pieceList);
  70802. },
  70803. pieces: function () {
  70804. var thisOption = this.option;
  70805. var pieceList = this._pieceList;
  70806. each$1(thisOption.pieces, function (pieceListItem, index) {
  70807. if (!isObject$1(pieceListItem)) {
  70808. pieceListItem = {value: pieceListItem};
  70809. }
  70810. var item = {text: '', index: index};
  70811. if (pieceListItem.label != null) {
  70812. item.text = pieceListItem.label;
  70813. }
  70814. if (pieceListItem.hasOwnProperty('value')) {
  70815. var value = item.value = pieceListItem.value;
  70816. item.interval = [value, value];
  70817. item.close = [1, 1];
  70818. }
  70819. else {
  70820. // `min` `max` is legacy option.
  70821. // `lt` `gt` `lte` `gte` is recommanded.
  70822. var interval = item.interval = [];
  70823. var close = item.close = [0, 0];
  70824. var closeList = [1, 0, 1];
  70825. var infinityList = [-Infinity, Infinity];
  70826. var useMinMax = [];
  70827. for (var lg = 0; lg < 2; lg++) {
  70828. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  70829. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  70830. interval[lg] = pieceListItem[names[i]];
  70831. close[lg] = closeList[i];
  70832. useMinMax[lg] = i === 2;
  70833. }
  70834. interval[lg] == null && (interval[lg] = infinityList[lg]);
  70835. }
  70836. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  70837. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  70838. if (__DEV__) {
  70839. if (interval[0] > interval[1]) {
  70840. console.warn(
  70841. 'Piece ' + index + 'is illegal: ' + interval
  70842. + ' lower bound should not greater then uppper bound.'
  70843. );
  70844. }
  70845. }
  70846. if (interval[0] === interval[1] && close[0] && close[1]) {
  70847. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  70848. // we use value to lift the priority when min === max
  70849. item.value = interval[0];
  70850. }
  70851. }
  70852. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  70853. pieceList.push(item);
  70854. }, this);
  70855. // See "Order Rule".
  70856. normalizeReverse(thisOption, pieceList);
  70857. // Only pieces
  70858. reformIntervals(pieceList);
  70859. each$1(pieceList, function (piece) {
  70860. var close = piece.close;
  70861. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  70862. piece.text = piece.text || this.formatValueText(
  70863. piece.value != null ? piece.value : piece.interval,
  70864. false,
  70865. edgeSymbols
  70866. );
  70867. }, this);
  70868. }
  70869. };
  70870. function normalizeReverse(thisOption, pieceList) {
  70871. var inverse = thisOption.inverse;
  70872. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  70873. pieceList.reverse();
  70874. }
  70875. }
  70876. /*
  70877. * Licensed to the Apache Software Foundation (ASF) under one
  70878. * or more contributor license agreements. See the NOTICE file
  70879. * distributed with this work for additional information
  70880. * regarding copyright ownership. The ASF licenses this file
  70881. * to you under the Apache License, Version 2.0 (the
  70882. * "License"); you may not use this file except in compliance
  70883. * with the License. You may obtain a copy of the License at
  70884. *
  70885. * http://www.apache.org/licenses/LICENSE-2.0
  70886. *
  70887. * Unless required by applicable law or agreed to in writing,
  70888. * software distributed under the License is distributed on an
  70889. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70890. * KIND, either express or implied. See the License for the
  70891. * specific language governing permissions and limitations
  70892. * under the License.
  70893. */
  70894. var PiecewiseVisualMapView = VisualMapView.extend({
  70895. type: 'visualMap.piecewise',
  70896. /**
  70897. * @protected
  70898. * @override
  70899. */
  70900. doRender: function () {
  70901. var thisGroup = this.group;
  70902. thisGroup.removeAll();
  70903. var visualMapModel = this.visualMapModel;
  70904. var textGap = visualMapModel.get('textGap');
  70905. var textStyleModel = visualMapModel.textStyleModel;
  70906. var textFont = textStyleModel.getFont();
  70907. var textFill = textStyleModel.getTextColor();
  70908. var itemAlign = this._getItemAlign();
  70909. var itemSize = visualMapModel.itemSize;
  70910. var viewData = this._getViewData();
  70911. var endsText = viewData.endsText;
  70912. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  70913. endsText && this._renderEndsText(
  70914. thisGroup, endsText[0], itemSize, showLabel, itemAlign
  70915. );
  70916. each$1(viewData.viewPieceList, renderItem, this);
  70917. endsText && this._renderEndsText(
  70918. thisGroup, endsText[1], itemSize, showLabel, itemAlign
  70919. );
  70920. box(
  70921. visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap')
  70922. );
  70923. this.renderBackground(thisGroup);
  70924. this.positionGroup(thisGroup);
  70925. function renderItem(item) {
  70926. var piece = item.piece;
  70927. var itemGroup = new Group();
  70928. itemGroup.onclick = bind(this._onItemClick, this, piece);
  70929. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  70930. var representValue = visualMapModel.getRepresentValue(piece);
  70931. this._createItemSymbol(
  70932. itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]
  70933. );
  70934. if (showLabel) {
  70935. var visualState = this.visualMapModel.getValueState(representValue);
  70936. itemGroup.add(new Text({
  70937. style: {
  70938. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  70939. y: itemSize[1] / 2,
  70940. text: piece.text,
  70941. textVerticalAlign: 'middle',
  70942. textAlign: itemAlign,
  70943. textFont: textFont,
  70944. textFill: textFill,
  70945. opacity: visualState === 'outOfRange' ? 0.5 : 1
  70946. }
  70947. }));
  70948. }
  70949. thisGroup.add(itemGroup);
  70950. }
  70951. },
  70952. /**
  70953. * @private
  70954. */
  70955. _enableHoverLink: function (itemGroup, pieceIndex) {
  70956. itemGroup
  70957. .on('mouseover', bind(onHoverLink, this, 'highlight'))
  70958. .on('mouseout', bind(onHoverLink, this, 'downplay'));
  70959. function onHoverLink(method) {
  70960. var visualMapModel = this.visualMapModel;
  70961. visualMapModel.option.hoverLink && this.api.dispatchAction({
  70962. type: method,
  70963. batch: convertDataIndex(
  70964. visualMapModel.findTargetDataIndices(pieceIndex)
  70965. )
  70966. });
  70967. }
  70968. },
  70969. /**
  70970. * @private
  70971. */
  70972. _getItemAlign: function () {
  70973. var visualMapModel = this.visualMapModel;
  70974. var modelOption = visualMapModel.option;
  70975. if (modelOption.orient === 'vertical') {
  70976. return getItemAlign(
  70977. visualMapModel, this.api, visualMapModel.itemSize
  70978. );
  70979. }
  70980. else { // horizontal, most case left unless specifying right.
  70981. var align = modelOption.align;
  70982. if (!align || align === 'auto') {
  70983. align = 'left';
  70984. }
  70985. return align;
  70986. }
  70987. },
  70988. /**
  70989. * @private
  70990. */
  70991. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  70992. if (!text) {
  70993. return;
  70994. }
  70995. var itemGroup = new Group();
  70996. var textStyleModel = this.visualMapModel.textStyleModel;
  70997. itemGroup.add(new Text({
  70998. style: {
  70999. x: showLabel ? (itemAlign === 'right' ? itemSize[0] : 0) : itemSize[0] / 2,
  71000. y: itemSize[1] / 2,
  71001. textVerticalAlign: 'middle',
  71002. textAlign: showLabel ? itemAlign : 'center',
  71003. text: text,
  71004. textFont: textStyleModel.getFont(),
  71005. textFill: textStyleModel.getTextColor()
  71006. }
  71007. }));
  71008. group.add(itemGroup);
  71009. },
  71010. /**
  71011. * @private
  71012. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  71013. */
  71014. _getViewData: function () {
  71015. var visualMapModel = this.visualMapModel;
  71016. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  71017. return {piece: piece, indexInModelPieceList: index};
  71018. });
  71019. var endsText = visualMapModel.get('text');
  71020. // Consider orient and inverse.
  71021. var orient = visualMapModel.get('orient');
  71022. var inverse = visualMapModel.get('inverse');
  71023. // Order of model pieceList is always [low, ..., high]
  71024. if (orient === 'horizontal' ? inverse : !inverse) {
  71025. viewPieceList.reverse();
  71026. }
  71027. // Origin order of endsText is [high, low]
  71028. else if (endsText) {
  71029. endsText = endsText.slice().reverse();
  71030. }
  71031. return {viewPieceList: viewPieceList, endsText: endsText};
  71032. },
  71033. /**
  71034. * @private
  71035. */
  71036. _createItemSymbol: function (group, representValue, shapeParam) {
  71037. group.add(createSymbol(
  71038. this.getControllerVisual(representValue, 'symbol'),
  71039. shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3],
  71040. this.getControllerVisual(representValue, 'color')
  71041. ));
  71042. },
  71043. /**
  71044. * @private
  71045. */
  71046. _onItemClick: function (piece) {
  71047. var visualMapModel = this.visualMapModel;
  71048. var option = visualMapModel.option;
  71049. var selected = clone(option.selected);
  71050. var newKey = visualMapModel.getSelectedMapKey(piece);
  71051. if (option.selectedMode === 'single') {
  71052. selected[newKey] = true;
  71053. each$1(selected, function (o, key) {
  71054. selected[key] = key === newKey;
  71055. });
  71056. }
  71057. else {
  71058. selected[newKey] = !selected[newKey];
  71059. }
  71060. this.api.dispatchAction({
  71061. type: 'selectDataRange',
  71062. from: this.uid,
  71063. visualMapId: this.visualMapModel.id,
  71064. selected: selected
  71065. });
  71066. }
  71067. });
  71068. /*
  71069. * Licensed to the Apache Software Foundation (ASF) under one
  71070. * or more contributor license agreements. See the NOTICE file
  71071. * distributed with this work for additional information
  71072. * regarding copyright ownership. The ASF licenses this file
  71073. * to you under the Apache License, Version 2.0 (the
  71074. * "License"); you may not use this file except in compliance
  71075. * with the License. You may obtain a copy of the License at
  71076. *
  71077. * http://www.apache.org/licenses/LICENSE-2.0
  71078. *
  71079. * Unless required by applicable law or agreed to in writing,
  71080. * software distributed under the License is distributed on an
  71081. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71082. * KIND, either express or implied. See the License for the
  71083. * specific language governing permissions and limitations
  71084. * under the License.
  71085. */
  71086. /**
  71087. * DataZoom component entry
  71088. */
  71089. registerPreprocessor(preprocessor$2);
  71090. /*
  71091. * Licensed to the Apache Software Foundation (ASF) under one
  71092. * or more contributor license agreements. See the NOTICE file
  71093. * distributed with this work for additional information
  71094. * regarding copyright ownership. The ASF licenses this file
  71095. * to you under the Apache License, Version 2.0 (the
  71096. * "License"); you may not use this file except in compliance
  71097. * with the License. You may obtain a copy of the License at
  71098. *
  71099. * http://www.apache.org/licenses/LICENSE-2.0
  71100. *
  71101. * Unless required by applicable law or agreed to in writing,
  71102. * software distributed under the License is distributed on an
  71103. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71104. * KIND, either express or implied. See the License for the
  71105. * specific language governing permissions and limitations
  71106. * under the License.
  71107. */
  71108. /**
  71109. * visualMap component entry
  71110. */
  71111. /*
  71112. * Licensed to the Apache Software Foundation (ASF) under one
  71113. * or more contributor license agreements. See the NOTICE file
  71114. * distributed with this work for additional information
  71115. * regarding copyright ownership. The ASF licenses this file
  71116. * to you under the Apache License, Version 2.0 (the
  71117. * "License"); you may not use this file except in compliance
  71118. * with the License. You may obtain a copy of the License at
  71119. *
  71120. * http://www.apache.org/licenses/LICENSE-2.0
  71121. *
  71122. * Unless required by applicable law or agreed to in writing,
  71123. * software distributed under the License is distributed on an
  71124. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71125. * KIND, either express or implied. See the License for the
  71126. * specific language governing permissions and limitations
  71127. * under the License.
  71128. */
  71129. var addCommas$1 = addCommas;
  71130. var encodeHTML$1 = encodeHTML;
  71131. function fillLabel(opt) {
  71132. defaultEmphasis(opt, 'label', ['show']);
  71133. }
  71134. var MarkerModel = extendComponentModel({
  71135. type: 'marker',
  71136. dependencies: ['series', 'grid', 'polar', 'geo'],
  71137. /**
  71138. * @overrite
  71139. */
  71140. init: function (option, parentModel, ecModel, extraOpt) {
  71141. if (__DEV__) {
  71142. if (this.type === 'marker') {
  71143. throw new Error('Marker component is abstract component. Use markLine, markPoint, markArea instead.');
  71144. }
  71145. }
  71146. this.mergeDefaultAndTheme(option, ecModel);
  71147. this.mergeOption(option, ecModel, extraOpt.createdBySelf, true);
  71148. },
  71149. /**
  71150. * @return {boolean}
  71151. */
  71152. isAnimationEnabled: function () {
  71153. if (env$1.node) {
  71154. return false;
  71155. }
  71156. var hostSeries = this.__hostSeries;
  71157. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  71158. },
  71159. mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  71160. var MarkerModel = this.constructor;
  71161. var modelPropName = this.mainType + 'Model';
  71162. if (!createdBySelf) {
  71163. ecModel.eachSeries(function (seriesModel) {
  71164. var markerOpt = seriesModel.get(this.mainType, true);
  71165. var markerModel = seriesModel[modelPropName];
  71166. if (!markerOpt || !markerOpt.data) {
  71167. seriesModel[modelPropName] = null;
  71168. return;
  71169. }
  71170. if (!markerModel) {
  71171. if (isInit) {
  71172. // Default label emphasis `position` and `show`
  71173. fillLabel(markerOpt);
  71174. }
  71175. each$1(markerOpt.data, function (item) {
  71176. // FIXME Overwrite fillLabel method ?
  71177. if (item instanceof Array) {
  71178. fillLabel(item[0]);
  71179. fillLabel(item[1]);
  71180. }
  71181. else {
  71182. fillLabel(item);
  71183. }
  71184. });
  71185. markerModel = new MarkerModel(
  71186. markerOpt, this, ecModel
  71187. );
  71188. extend(markerModel, {
  71189. mainType: this.mainType,
  71190. // Use the same series index and name
  71191. seriesIndex: seriesModel.seriesIndex,
  71192. name: seriesModel.name,
  71193. createdBySelf: true
  71194. });
  71195. markerModel.__hostSeries = seriesModel;
  71196. }
  71197. else {
  71198. markerModel.mergeOption(markerOpt, ecModel, true);
  71199. }
  71200. seriesModel[modelPropName] = markerModel;
  71201. }, this);
  71202. }
  71203. },
  71204. formatTooltip: function (dataIndex) {
  71205. var data = this.getData();
  71206. var value = this.getRawValue(dataIndex);
  71207. var formattedValue = isArray(value)
  71208. ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  71209. var name = data.getName(dataIndex);
  71210. var html = encodeHTML$1(this.name);
  71211. if (value != null || name) {
  71212. html += '<br />';
  71213. }
  71214. if (name) {
  71215. html += encodeHTML$1(name);
  71216. if (value != null) {
  71217. html += ' : ';
  71218. }
  71219. }
  71220. if (value != null) {
  71221. html += encodeHTML$1(formattedValue);
  71222. }
  71223. return html;
  71224. },
  71225. getData: function () {
  71226. return this._data;
  71227. },
  71228. setData: function (data) {
  71229. this._data = data;
  71230. }
  71231. });
  71232. mixin(MarkerModel, dataFormatMixin);
  71233. /*
  71234. * Licensed to the Apache Software Foundation (ASF) under one
  71235. * or more contributor license agreements. See the NOTICE file
  71236. * distributed with this work for additional information
  71237. * regarding copyright ownership. The ASF licenses this file
  71238. * to you under the Apache License, Version 2.0 (the
  71239. * "License"); you may not use this file except in compliance
  71240. * with the License. You may obtain a copy of the License at
  71241. *
  71242. * http://www.apache.org/licenses/LICENSE-2.0
  71243. *
  71244. * Unless required by applicable law or agreed to in writing,
  71245. * software distributed under the License is distributed on an
  71246. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71247. * KIND, either express or implied. See the License for the
  71248. * specific language governing permissions and limitations
  71249. * under the License.
  71250. */
  71251. MarkerModel.extend({
  71252. type: 'markPoint',
  71253. defaultOption: {
  71254. zlevel: 0,
  71255. z: 5,
  71256. symbol: 'pin',
  71257. symbolSize: 50,
  71258. //symbolRotate: 0,
  71259. //symbolOffset: [0, 0]
  71260. tooltip: {
  71261. trigger: 'item'
  71262. },
  71263. label: {
  71264. show: true,
  71265. position: 'inside'
  71266. },
  71267. itemStyle: {
  71268. borderWidth: 2
  71269. },
  71270. emphasis: {
  71271. label: {
  71272. show: true
  71273. }
  71274. }
  71275. }
  71276. });
  71277. /*
  71278. * Licensed to the Apache Software Foundation (ASF) under one
  71279. * or more contributor license agreements. See the NOTICE file
  71280. * distributed with this work for additional information
  71281. * regarding copyright ownership. The ASF licenses this file
  71282. * to you under the Apache License, Version 2.0 (the
  71283. * "License"); you may not use this file except in compliance
  71284. * with the License. You may obtain a copy of the License at
  71285. *
  71286. * http://www.apache.org/licenses/LICENSE-2.0
  71287. *
  71288. * Unless required by applicable law or agreed to in writing,
  71289. * software distributed under the License is distributed on an
  71290. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71291. * KIND, either express or implied. See the License for the
  71292. * specific language governing permissions and limitations
  71293. * under the License.
  71294. */
  71295. var indexOf$2 = indexOf;
  71296. function hasXOrY(item) {
  71297. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  71298. }
  71299. function hasXAndY(item) {
  71300. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  71301. }
  71302. // Make it simple, do not visit all stacked value to count precision.
  71303. // function getPrecision(data, valueAxisDim, dataIndex) {
  71304. // var precision = -1;
  71305. // var stackedDim = data.mapDimension(valueAxisDim);
  71306. // do {
  71307. // precision = Math.max(
  71308. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  71309. // precision
  71310. // );
  71311. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  71312. // if (stackedOnSeries) {
  71313. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  71314. // data = stackedOnSeries.getData();
  71315. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  71316. // stackedDim = data.getCalculationInfo('stackedDimension');
  71317. // }
  71318. // else {
  71319. // data = null;
  71320. // }
  71321. // } while (data);
  71322. // return precision;
  71323. // }
  71324. function markerTypeCalculatorWithExtent(
  71325. mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex
  71326. ) {
  71327. var coordArr = [];
  71328. var stacked = isDimensionStacked(data, targetDataDim /*, otherDataDim*/);
  71329. var calcDataDim = stacked
  71330. ? data.getCalculationInfo('stackResultDimension')
  71331. : targetDataDim;
  71332. var value = numCalculate(data, calcDataDim, mlType);
  71333. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  71334. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  71335. coordArr[targetCoordIndex] = data.get(targetDataDim, dataIndex);
  71336. // Make it simple, do not visit all stacked value to count precision.
  71337. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  71338. precision = Math.min(precision, 20);
  71339. if (precision >= 0) {
  71340. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  71341. }
  71342. return coordArr;
  71343. }
  71344. var curry$7 = curry;
  71345. // TODO Specified percent
  71346. var markerTypeCalculator = {
  71347. /**
  71348. * @method
  71349. * @param {module:echarts/data/List} data
  71350. * @param {string} baseAxisDim
  71351. * @param {string} valueAxisDim
  71352. */
  71353. min: curry$7(markerTypeCalculatorWithExtent, 'min'),
  71354. /**
  71355. * @method
  71356. * @param {module:echarts/data/List} data
  71357. * @param {string} baseAxisDim
  71358. * @param {string} valueAxisDim
  71359. */
  71360. max: curry$7(markerTypeCalculatorWithExtent, 'max'),
  71361. /**
  71362. * @method
  71363. * @param {module:echarts/data/List} data
  71364. * @param {string} baseAxisDim
  71365. * @param {string} valueAxisDim
  71366. */
  71367. average: curry$7(markerTypeCalculatorWithExtent, 'average')
  71368. };
  71369. /**
  71370. * Transform markPoint data item to format used in List by do the following
  71371. * 1. Calculate statistic like `max`, `min`, `average`
  71372. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  71373. * @param {module:echarts/model/Series} seriesModel
  71374. * @param {module:echarts/coord/*} [coordSys]
  71375. * @param {Object} item
  71376. * @return {Object}
  71377. */
  71378. function dataTransform(seriesModel, item) {
  71379. var data = seriesModel.getData();
  71380. var coordSys = seriesModel.coordinateSystem;
  71381. // 1. If not specify the position with pixel directly
  71382. // 2. If `coord` is not a data array. Which uses `xAxis`,
  71383. // `yAxis` to specify the coord on each dimension
  71384. // parseFloat first because item.x and item.y can be percent string like '20%'
  71385. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  71386. var dims = coordSys.dimensions;
  71387. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  71388. // Clone the option
  71389. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  71390. item = clone(item);
  71391. if (item.type
  71392. && markerTypeCalculator[item.type]
  71393. && axisInfo.baseAxis && axisInfo.valueAxis
  71394. ) {
  71395. var otherCoordIndex = indexOf$2(dims, axisInfo.baseAxis.dim);
  71396. var targetCoordIndex = indexOf$2(dims, axisInfo.valueAxis.dim);
  71397. item.coord = markerTypeCalculator[item.type](
  71398. data, axisInfo.baseDataDim, axisInfo.valueDataDim,
  71399. otherCoordIndex, targetCoordIndex
  71400. );
  71401. // Force to use the value of calculated value.
  71402. item.value = item.coord[targetCoordIndex];
  71403. }
  71404. else {
  71405. // FIXME Only has one of xAxis and yAxis.
  71406. var coord = [
  71407. item.xAxis != null ? item.xAxis : item.radiusAxis,
  71408. item.yAxis != null ? item.yAxis : item.angleAxis
  71409. ];
  71410. // Each coord support max, min, average
  71411. for (var i = 0; i < 2; i++) {
  71412. if (markerTypeCalculator[coord[i]]) {
  71413. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  71414. }
  71415. }
  71416. item.coord = coord;
  71417. }
  71418. }
  71419. return item;
  71420. }
  71421. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  71422. var ret = {};
  71423. if (item.valueIndex != null || item.valueDim != null) {
  71424. ret.valueDataDim = item.valueIndex != null
  71425. ? data.getDimension(item.valueIndex) : item.valueDim;
  71426. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  71427. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  71428. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  71429. }
  71430. else {
  71431. ret.baseAxis = seriesModel.getBaseAxis();
  71432. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  71433. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  71434. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  71435. }
  71436. return ret;
  71437. }
  71438. function dataDimToCoordDim(seriesModel, dataDim) {
  71439. var data = seriesModel.getData();
  71440. var dimensions = data.dimensions;
  71441. dataDim = data.getDimension(dataDim);
  71442. for (var i = 0; i < dimensions.length; i++) {
  71443. var dimItem = data.getDimensionInfo(dimensions[i]);
  71444. if (dimItem.name === dataDim) {
  71445. return dimItem.coordDim;
  71446. }
  71447. }
  71448. }
  71449. /**
  71450. * Filter data which is out of coordinateSystem range
  71451. * [dataFilter description]
  71452. * @param {module:echarts/coord/*} [coordSys]
  71453. * @param {Object} item
  71454. * @return {boolean}
  71455. */
  71456. function dataFilter$1(coordSys, item) {
  71457. // Alwalys return true if there is no coordSys
  71458. return (coordSys && coordSys.containData && item.coord && !hasXOrY(item))
  71459. ? coordSys.containData(item.coord) : true;
  71460. }
  71461. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  71462. // x, y, radius, angle
  71463. if (dimIndex < 2) {
  71464. return item.coord && item.coord[dimIndex];
  71465. }
  71466. return item.value;
  71467. }
  71468. function numCalculate(data, valueDataDim, type) {
  71469. if (type === 'average') {
  71470. var sum = 0;
  71471. var count = 0;
  71472. data.each(valueDataDim, function (val, idx) {
  71473. if (!isNaN(val)) {
  71474. sum += val;
  71475. count++;
  71476. }
  71477. });
  71478. return sum / count;
  71479. }
  71480. else if (type === 'median') {
  71481. return data.getMedian(valueDataDim);
  71482. }
  71483. else {
  71484. // max & min
  71485. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  71486. }
  71487. }
  71488. /*
  71489. * Licensed to the Apache Software Foundation (ASF) under one
  71490. * or more contributor license agreements. See the NOTICE file
  71491. * distributed with this work for additional information
  71492. * regarding copyright ownership. The ASF licenses this file
  71493. * to you under the Apache License, Version 2.0 (the
  71494. * "License"); you may not use this file except in compliance
  71495. * with the License. You may obtain a copy of the License at
  71496. *
  71497. * http://www.apache.org/licenses/LICENSE-2.0
  71498. *
  71499. * Unless required by applicable law or agreed to in writing,
  71500. * software distributed under the License is distributed on an
  71501. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71502. * KIND, either express or implied. See the License for the
  71503. * specific language governing permissions and limitations
  71504. * under the License.
  71505. */
  71506. var MarkerView = extendComponentView({
  71507. type: 'marker',
  71508. init: function () {
  71509. /**
  71510. * Markline grouped by series
  71511. * @private
  71512. * @type {module:zrender/core/util.HashMap}
  71513. */
  71514. this.markerGroupMap = createHashMap();
  71515. },
  71516. render: function (markerModel, ecModel, api) {
  71517. var markerGroupMap = this.markerGroupMap;
  71518. markerGroupMap.each(function (item) {
  71519. item.__keep = false;
  71520. });
  71521. var markerModelKey = this.type + 'Model';
  71522. ecModel.eachSeries(function (seriesModel) {
  71523. var markerModel = seriesModel[markerModelKey];
  71524. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  71525. }, this);
  71526. markerGroupMap.each(function (item) {
  71527. !item.__keep && this.group.remove(item.group);
  71528. }, this);
  71529. },
  71530. renderSeries: function () {}
  71531. });
  71532. /*
  71533. * Licensed to the Apache Software Foundation (ASF) under one
  71534. * or more contributor license agreements. See the NOTICE file
  71535. * distributed with this work for additional information
  71536. * regarding copyright ownership. The ASF licenses this file
  71537. * to you under the Apache License, Version 2.0 (the
  71538. * "License"); you may not use this file except in compliance
  71539. * with the License. You may obtain a copy of the License at
  71540. *
  71541. * http://www.apache.org/licenses/LICENSE-2.0
  71542. *
  71543. * Unless required by applicable law or agreed to in writing,
  71544. * software distributed under the License is distributed on an
  71545. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71546. * KIND, either express or implied. See the License for the
  71547. * specific language governing permissions and limitations
  71548. * under the License.
  71549. */
  71550. function updateMarkerLayout(mpData, seriesModel, api) {
  71551. var coordSys = seriesModel.coordinateSystem;
  71552. mpData.each(function (idx) {
  71553. var itemModel = mpData.getItemModel(idx);
  71554. var point;
  71555. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  71556. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  71557. if (!isNaN(xPx) && !isNaN(yPx)) {
  71558. point = [xPx, yPx];
  71559. }
  71560. // Chart like bar may have there own marker positioning logic
  71561. else if (seriesModel.getMarkerPosition) {
  71562. // Use the getMarkerPoisition
  71563. point = seriesModel.getMarkerPosition(
  71564. mpData.getValues(mpData.dimensions, idx)
  71565. );
  71566. }
  71567. else if (coordSys) {
  71568. var x = mpData.get(coordSys.dimensions[0], idx);
  71569. var y = mpData.get(coordSys.dimensions[1], idx);
  71570. point = coordSys.dataToPoint([x, y]);
  71571. }
  71572. // Use x, y if has any
  71573. if (!isNaN(xPx)) {
  71574. point[0] = xPx;
  71575. }
  71576. if (!isNaN(yPx)) {
  71577. point[1] = yPx;
  71578. }
  71579. mpData.setItemLayout(idx, point);
  71580. });
  71581. }
  71582. MarkerView.extend({
  71583. type: 'markPoint',
  71584. // updateLayout: function (markPointModel, ecModel, api) {
  71585. // ecModel.eachSeries(function (seriesModel) {
  71586. // var mpModel = seriesModel.markPointModel;
  71587. // if (mpModel) {
  71588. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71589. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  71590. // }
  71591. // }, this);
  71592. // },
  71593. updateTransform: function (markPointModel, ecModel, api) {
  71594. ecModel.eachSeries(function (seriesModel) {
  71595. var mpModel = seriesModel.markPointModel;
  71596. if (mpModel) {
  71597. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71598. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  71599. }
  71600. }, this);
  71601. },
  71602. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  71603. var coordSys = seriesModel.coordinateSystem;
  71604. var seriesId = seriesModel.id;
  71605. var seriesData = seriesModel.getData();
  71606. var symbolDrawMap = this.markerGroupMap;
  71607. var symbolDraw = symbolDrawMap.get(seriesId)
  71608. || symbolDrawMap.set(seriesId, new SymbolDraw());
  71609. var mpData = createList$1(coordSys, seriesModel, mpModel);
  71610. // FIXME
  71611. mpModel.setData(mpData);
  71612. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  71613. mpData.each(function (idx) {
  71614. var itemModel = mpData.getItemModel(idx);
  71615. var symbolSize = itemModel.getShallow('symbolSize');
  71616. if (typeof symbolSize === 'function') {
  71617. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  71618. symbolSize = symbolSize(
  71619. mpModel.getRawValue(idx), mpModel.getDataParams(idx)
  71620. );
  71621. }
  71622. mpData.setItemVisual(idx, {
  71623. symbolSize: symbolSize,
  71624. color: itemModel.get('itemStyle.color')
  71625. || seriesData.getVisual('color'),
  71626. symbol: itemModel.getShallow('symbol')
  71627. });
  71628. });
  71629. // TODO Text are wrong
  71630. symbolDraw.updateData(mpData);
  71631. this.group.add(symbolDraw.group);
  71632. // Set host model for tooltip
  71633. // FIXME
  71634. mpData.eachItemGraphicEl(function (el) {
  71635. el.traverse(function (child) {
  71636. child.dataModel = mpModel;
  71637. });
  71638. });
  71639. symbolDraw.__keep = true;
  71640. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  71641. }
  71642. });
  71643. /**
  71644. * @inner
  71645. * @param {module:echarts/coord/*} [coordSys]
  71646. * @param {module:echarts/model/Series} seriesModel
  71647. * @param {module:echarts/model/Model} mpModel
  71648. */
  71649. function createList$1(coordSys, seriesModel, mpModel) {
  71650. var coordDimsInfos;
  71651. if (coordSys) {
  71652. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  71653. var info = seriesModel.getData().getDimensionInfo(
  71654. seriesModel.getData().mapDimension(coordDim)
  71655. ) || {};
  71656. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  71657. return defaults({name: coordDim}, info);
  71658. });
  71659. }
  71660. else {
  71661. coordDimsInfos =[{
  71662. name: 'value',
  71663. type: 'float'
  71664. }];
  71665. }
  71666. var mpData = new List(coordDimsInfos, mpModel);
  71667. var dataOpt = map(mpModel.get('data'), curry(
  71668. dataTransform, seriesModel
  71669. ));
  71670. if (coordSys) {
  71671. dataOpt = filter(
  71672. dataOpt, curry(dataFilter$1, coordSys)
  71673. );
  71674. }
  71675. mpData.initData(dataOpt, null,
  71676. coordSys ? dimValueGetter : function (item) {
  71677. return item.value;
  71678. }
  71679. );
  71680. return mpData;
  71681. }
  71682. /*
  71683. * Licensed to the Apache Software Foundation (ASF) under one
  71684. * or more contributor license agreements. See the NOTICE file
  71685. * distributed with this work for additional information
  71686. * regarding copyright ownership. The ASF licenses this file
  71687. * to you under the Apache License, Version 2.0 (the
  71688. * "License"); you may not use this file except in compliance
  71689. * with the License. You may obtain a copy of the License at
  71690. *
  71691. * http://www.apache.org/licenses/LICENSE-2.0
  71692. *
  71693. * Unless required by applicable law or agreed to in writing,
  71694. * software distributed under the License is distributed on an
  71695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71696. * KIND, either express or implied. See the License for the
  71697. * specific language governing permissions and limitations
  71698. * under the License.
  71699. */
  71700. // HINT Markpoint can't be used too much
  71701. registerPreprocessor(function (opt) {
  71702. // Make sure markPoint component is enabled
  71703. opt.markPoint = opt.markPoint || {};
  71704. });
  71705. /*
  71706. * Licensed to the Apache Software Foundation (ASF) under one
  71707. * or more contributor license agreements. See the NOTICE file
  71708. * distributed with this work for additional information
  71709. * regarding copyright ownership. The ASF licenses this file
  71710. * to you under the Apache License, Version 2.0 (the
  71711. * "License"); you may not use this file except in compliance
  71712. * with the License. You may obtain a copy of the License at
  71713. *
  71714. * http://www.apache.org/licenses/LICENSE-2.0
  71715. *
  71716. * Unless required by applicable law or agreed to in writing,
  71717. * software distributed under the License is distributed on an
  71718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71719. * KIND, either express or implied. See the License for the
  71720. * specific language governing permissions and limitations
  71721. * under the License.
  71722. */
  71723. MarkerModel.extend({
  71724. type: 'markLine',
  71725. defaultOption: {
  71726. zlevel: 0,
  71727. z: 5,
  71728. symbol: ['circle', 'arrow'],
  71729. symbolSize: [8, 16],
  71730. //symbolRotate: 0,
  71731. precision: 2,
  71732. tooltip: {
  71733. trigger: 'item'
  71734. },
  71735. label: {
  71736. show: true,
  71737. position: 'end'
  71738. },
  71739. lineStyle: {
  71740. type: 'dashed'
  71741. },
  71742. emphasis: {
  71743. label: {
  71744. show: true
  71745. },
  71746. lineStyle: {
  71747. width: 3
  71748. }
  71749. },
  71750. animationEasing: 'linear'
  71751. }
  71752. });
  71753. /*
  71754. * Licensed to the Apache Software Foundation (ASF) under one
  71755. * or more contributor license agreements. See the NOTICE file
  71756. * distributed with this work for additional information
  71757. * regarding copyright ownership. The ASF licenses this file
  71758. * to you under the Apache License, Version 2.0 (the
  71759. * "License"); you may not use this file except in compliance
  71760. * with the License. You may obtain a copy of the License at
  71761. *
  71762. * http://www.apache.org/licenses/LICENSE-2.0
  71763. *
  71764. * Unless required by applicable law or agreed to in writing,
  71765. * software distributed under the License is distributed on an
  71766. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71767. * KIND, either express or implied. See the License for the
  71768. * specific language governing permissions and limitations
  71769. * under the License.
  71770. */
  71771. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  71772. var data = seriesModel.getData();
  71773. // Special type markLine like 'min', 'max', 'average', 'median'
  71774. var mlType = item.type;
  71775. if (!isArray(item)
  71776. && (
  71777. mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median'
  71778. // In case
  71779. // data: [{
  71780. // yAxis: 10
  71781. // }]
  71782. || (item.xAxis != null || item.yAxis != null)
  71783. )
  71784. ) {
  71785. var valueAxis;
  71786. var valueDataDim;
  71787. var value;
  71788. if (item.yAxis != null || item.xAxis != null) {
  71789. valueDataDim = item.yAxis != null ? 'y' : 'x';
  71790. valueAxis = coordSys.getAxis(valueDataDim);
  71791. value = retrieve(item.yAxis, item.xAxis);
  71792. }
  71793. else {
  71794. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  71795. valueDataDim = axisInfo.valueDataDim;
  71796. valueAxis = axisInfo.valueAxis;
  71797. value = numCalculate(data, valueDataDim, mlType);
  71798. }
  71799. var valueIndex = valueDataDim === 'x' ? 0 : 1;
  71800. var baseIndex = 1 - valueIndex;
  71801. var mlFrom = clone(item);
  71802. var mlTo = {};
  71803. mlFrom.type = null;
  71804. mlFrom.coord = [];
  71805. mlTo.coord = [];
  71806. mlFrom.coord[baseIndex] = -Infinity;
  71807. mlTo.coord[baseIndex] = Infinity;
  71808. var precision = mlModel.get('precision');
  71809. if (precision >= 0 && typeof value === 'number') {
  71810. value = +value.toFixed(Math.min(precision, 20));
  71811. }
  71812. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  71813. item = [mlFrom, mlTo, { // Extra option for tooltip and label
  71814. type: mlType,
  71815. valueIndex: item.valueIndex,
  71816. // Force to use the value of calculated value.
  71817. value: value
  71818. }];
  71819. }
  71820. item = [
  71821. dataTransform(seriesModel, item[0]),
  71822. dataTransform(seriesModel, item[1]),
  71823. extend({}, item[2])
  71824. ];
  71825. // Avoid line data type is extended by from(to) data type
  71826. item[2].type = item[2].type || '';
  71827. // Merge from option and to option into line option
  71828. merge(item[2], item[0]);
  71829. merge(item[2], item[1]);
  71830. return item;
  71831. };
  71832. function isInifinity(val) {
  71833. return !isNaN(val) && !isFinite(val);
  71834. }
  71835. // If a markLine has one dim
  71836. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  71837. var otherDimIndex = 1 - dimIndex;
  71838. var dimName = coordSys.dimensions[dimIndex];
  71839. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex])
  71840. && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  71841. }
  71842. function markLineFilter(coordSys, item) {
  71843. if (coordSys.type === 'cartesian2d') {
  71844. var fromCoord = item[0].coord;
  71845. var toCoord = item[1].coord;
  71846. // In case
  71847. // {
  71848. // markLine: {
  71849. // data: [{ yAxis: 2 }]
  71850. // }
  71851. // }
  71852. if (
  71853. fromCoord && toCoord &&
  71854. (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys)
  71855. || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))
  71856. ) {
  71857. return true;
  71858. }
  71859. }
  71860. return dataFilter$1(coordSys, item[0])
  71861. && dataFilter$1(coordSys, item[1]);
  71862. }
  71863. function updateSingleMarkerEndLayout(
  71864. data, idx, isFrom, seriesModel, api
  71865. ) {
  71866. var coordSys = seriesModel.coordinateSystem;
  71867. var itemModel = data.getItemModel(idx);
  71868. var point;
  71869. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  71870. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  71871. if (!isNaN(xPx) && !isNaN(yPx)) {
  71872. point = [xPx, yPx];
  71873. }
  71874. else {
  71875. // Chart like bar may have there own marker positioning logic
  71876. if (seriesModel.getMarkerPosition) {
  71877. // Use the getMarkerPoisition
  71878. point = seriesModel.getMarkerPosition(
  71879. data.getValues(data.dimensions, idx)
  71880. );
  71881. }
  71882. else {
  71883. var dims = coordSys.dimensions;
  71884. var x = data.get(dims[0], idx);
  71885. var y = data.get(dims[1], idx);
  71886. point = coordSys.dataToPoint([x, y]);
  71887. }
  71888. // Expand line to the edge of grid if value on one axis is Inifnity
  71889. // In case
  71890. // markLine: {
  71891. // data: [{
  71892. // yAxis: 2
  71893. // // or
  71894. // type: 'average'
  71895. // }]
  71896. // }
  71897. if (coordSys.type === 'cartesian2d') {
  71898. var xAxis = coordSys.getAxis('x');
  71899. var yAxis = coordSys.getAxis('y');
  71900. var dims = coordSys.dimensions;
  71901. if (isInifinity(data.get(dims[0], idx))) {
  71902. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  71903. }
  71904. else if (isInifinity(data.get(dims[1], idx))) {
  71905. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  71906. }
  71907. }
  71908. // Use x, y if has any
  71909. if (!isNaN(xPx)) {
  71910. point[0] = xPx;
  71911. }
  71912. if (!isNaN(yPx)) {
  71913. point[1] = yPx;
  71914. }
  71915. }
  71916. data.setItemLayout(idx, point);
  71917. }
  71918. MarkerView.extend({
  71919. type: 'markLine',
  71920. // updateLayout: function (markLineModel, ecModel, api) {
  71921. // ecModel.eachSeries(function (seriesModel) {
  71922. // var mlModel = seriesModel.markLineModel;
  71923. // if (mlModel) {
  71924. // var mlData = mlModel.getData();
  71925. // var fromData = mlModel.__from;
  71926. // var toData = mlModel.__to;
  71927. // // Update visual and layout of from symbol and to symbol
  71928. // fromData.each(function (idx) {
  71929. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  71930. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  71931. // });
  71932. // // Update layout of line
  71933. // mlData.each(function (idx) {
  71934. // mlData.setItemLayout(idx, [
  71935. // fromData.getItemLayout(idx),
  71936. // toData.getItemLayout(idx)
  71937. // ]);
  71938. // });
  71939. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  71940. // }
  71941. // }, this);
  71942. // },
  71943. updateTransform: function (markLineModel, ecModel, api) {
  71944. ecModel.eachSeries(function (seriesModel) {
  71945. var mlModel = seriesModel.markLineModel;
  71946. if (mlModel) {
  71947. var mlData = mlModel.getData();
  71948. var fromData = mlModel.__from;
  71949. var toData = mlModel.__to;
  71950. // Update visual and layout of from symbol and to symbol
  71951. fromData.each(function (idx) {
  71952. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  71953. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  71954. });
  71955. // Update layout of line
  71956. mlData.each(function (idx) {
  71957. mlData.setItemLayout(idx, [
  71958. fromData.getItemLayout(idx),
  71959. toData.getItemLayout(idx)
  71960. ]);
  71961. });
  71962. this.markerGroupMap.get(seriesModel.id).updateLayout();
  71963. }
  71964. }, this);
  71965. },
  71966. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  71967. var coordSys = seriesModel.coordinateSystem;
  71968. var seriesId = seriesModel.id;
  71969. var seriesData = seriesModel.getData();
  71970. var lineDrawMap = this.markerGroupMap;
  71971. var lineDraw = lineDrawMap.get(seriesId)
  71972. || lineDrawMap.set(seriesId, new LineDraw());
  71973. this.group.add(lineDraw.group);
  71974. var mlData = createList$2(coordSys, seriesModel, mlModel);
  71975. var fromData = mlData.from;
  71976. var toData = mlData.to;
  71977. var lineData = mlData.line;
  71978. mlModel.__from = fromData;
  71979. mlModel.__to = toData;
  71980. // Line data for tooltip and formatter
  71981. mlModel.setData(lineData);
  71982. var symbolType = mlModel.get('symbol');
  71983. var symbolSize = mlModel.get('symbolSize');
  71984. if (!isArray(symbolType)) {
  71985. symbolType = [symbolType, symbolType];
  71986. }
  71987. if (typeof symbolSize === 'number') {
  71988. symbolSize = [symbolSize, symbolSize];
  71989. }
  71990. // Update visual and layout of from symbol and to symbol
  71991. mlData.from.each(function (idx) {
  71992. updateDataVisualAndLayout(fromData, idx, true);
  71993. updateDataVisualAndLayout(toData, idx, false);
  71994. });
  71995. // Update visual and layout of line
  71996. lineData.each(function (idx) {
  71997. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  71998. lineData.setItemVisual(idx, {
  71999. color: lineColor || fromData.getItemVisual(idx, 'color')
  72000. });
  72001. lineData.setItemLayout(idx, [
  72002. fromData.getItemLayout(idx),
  72003. toData.getItemLayout(idx)
  72004. ]);
  72005. lineData.setItemVisual(idx, {
  72006. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  72007. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  72008. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  72009. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  72010. });
  72011. });
  72012. lineDraw.updateData(lineData);
  72013. // Set host model for tooltip
  72014. // FIXME
  72015. mlData.line.eachItemGraphicEl(function (el, idx) {
  72016. el.traverse(function (child) {
  72017. child.dataModel = mlModel;
  72018. });
  72019. });
  72020. function updateDataVisualAndLayout(data, idx, isFrom) {
  72021. var itemModel = data.getItemModel(idx);
  72022. updateSingleMarkerEndLayout(
  72023. data, idx, isFrom, seriesModel, api
  72024. );
  72025. data.setItemVisual(idx, {
  72026. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  72027. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  72028. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  72029. });
  72030. }
  72031. lineDraw.__keep = true;
  72032. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  72033. }
  72034. });
  72035. /**
  72036. * @inner
  72037. * @param {module:echarts/coord/*} coordSys
  72038. * @param {module:echarts/model/Series} seriesModel
  72039. * @param {module:echarts/model/Model} mpModel
  72040. */
  72041. function createList$2(coordSys, seriesModel, mlModel) {
  72042. var coordDimsInfos;
  72043. if (coordSys) {
  72044. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72045. var info = seriesModel.getData().getDimensionInfo(
  72046. seriesModel.getData().mapDimension(coordDim)
  72047. ) || {};
  72048. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  72049. return defaults({name: coordDim}, info);
  72050. });
  72051. }
  72052. else {
  72053. coordDimsInfos =[{
  72054. name: 'value',
  72055. type: 'float'
  72056. }];
  72057. }
  72058. var fromData = new List(coordDimsInfos, mlModel);
  72059. var toData = new List(coordDimsInfos, mlModel);
  72060. // No dimensions
  72061. var lineData = new List([], mlModel);
  72062. var optData = map(mlModel.get('data'), curry(
  72063. markLineTransform, seriesModel, coordSys, mlModel
  72064. ));
  72065. if (coordSys) {
  72066. optData = filter(
  72067. optData, curry(markLineFilter, coordSys)
  72068. );
  72069. }
  72070. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  72071. return item.value;
  72072. };
  72073. fromData.initData(
  72074. map(optData, function (item) { return item[0]; }),
  72075. null, dimValueGetter$$1
  72076. );
  72077. toData.initData(
  72078. map(optData, function (item) { return item[1]; }),
  72079. null, dimValueGetter$$1
  72080. );
  72081. lineData.initData(
  72082. map(optData, function (item) { return item[2]; })
  72083. );
  72084. lineData.hasItemOption = true;
  72085. return {
  72086. from: fromData,
  72087. to: toData,
  72088. line: lineData
  72089. };
  72090. }
  72091. /*
  72092. * Licensed to the Apache Software Foundation (ASF) under one
  72093. * or more contributor license agreements. See the NOTICE file
  72094. * distributed with this work for additional information
  72095. * regarding copyright ownership. The ASF licenses this file
  72096. * to you under the Apache License, Version 2.0 (the
  72097. * "License"); you may not use this file except in compliance
  72098. * with the License. You may obtain a copy of the License at
  72099. *
  72100. * http://www.apache.org/licenses/LICENSE-2.0
  72101. *
  72102. * Unless required by applicable law or agreed to in writing,
  72103. * software distributed under the License is distributed on an
  72104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72105. * KIND, either express or implied. See the License for the
  72106. * specific language governing permissions and limitations
  72107. * under the License.
  72108. */
  72109. registerPreprocessor(function (opt) {
  72110. // Make sure markLine component is enabled
  72111. opt.markLine = opt.markLine || {};
  72112. });
  72113. /*
  72114. * Licensed to the Apache Software Foundation (ASF) under one
  72115. * or more contributor license agreements. See the NOTICE file
  72116. * distributed with this work for additional information
  72117. * regarding copyright ownership. The ASF licenses this file
  72118. * to you under the Apache License, Version 2.0 (the
  72119. * "License"); you may not use this file except in compliance
  72120. * with the License. You may obtain a copy of the License at
  72121. *
  72122. * http://www.apache.org/licenses/LICENSE-2.0
  72123. *
  72124. * Unless required by applicable law or agreed to in writing,
  72125. * software distributed under the License is distributed on an
  72126. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72127. * KIND, either express or implied. See the License for the
  72128. * specific language governing permissions and limitations
  72129. * under the License.
  72130. */
  72131. MarkerModel.extend({
  72132. type: 'markArea',
  72133. defaultOption: {
  72134. zlevel: 0,
  72135. // PENDING
  72136. z: 1,
  72137. tooltip: {
  72138. trigger: 'item'
  72139. },
  72140. // markArea should fixed on the coordinate system
  72141. animation: false,
  72142. label: {
  72143. show: true,
  72144. position: 'top'
  72145. },
  72146. itemStyle: {
  72147. // color and borderColor default to use color from series
  72148. // color: 'auto'
  72149. // borderColor: 'auto'
  72150. borderWidth: 0
  72151. },
  72152. emphasis: {
  72153. label: {
  72154. show: true,
  72155. position: 'top'
  72156. }
  72157. }
  72158. }
  72159. });
  72160. /*
  72161. * Licensed to the Apache Software Foundation (ASF) under one
  72162. * or more contributor license agreements. See the NOTICE file
  72163. * distributed with this work for additional information
  72164. * regarding copyright ownership. The ASF licenses this file
  72165. * to you under the Apache License, Version 2.0 (the
  72166. * "License"); you may not use this file except in compliance
  72167. * with the License. You may obtain a copy of the License at
  72168. *
  72169. * http://www.apache.org/licenses/LICENSE-2.0
  72170. *
  72171. * Unless required by applicable law or agreed to in writing,
  72172. * software distributed under the License is distributed on an
  72173. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72174. * KIND, either express or implied. See the License for the
  72175. * specific language governing permissions and limitations
  72176. * under the License.
  72177. */
  72178. // TODO Better on polar
  72179. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  72180. var lt = dataTransform(seriesModel, item[0]);
  72181. var rb = dataTransform(seriesModel, item[1]);
  72182. var retrieve$$1 = retrieve;
  72183. // FIXME make sure lt is less than rb
  72184. var ltCoord = lt.coord;
  72185. var rbCoord = rb.coord;
  72186. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  72187. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  72188. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  72189. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity);
  72190. // Merge option into one
  72191. var result = mergeAll([{}, lt, rb]);
  72192. result.coord = [
  72193. lt.coord, rb.coord
  72194. ];
  72195. result.x0 = lt.x;
  72196. result.y0 = lt.y;
  72197. result.x1 = rb.x;
  72198. result.y1 = rb.y;
  72199. return result;
  72200. };
  72201. function isInifinity$1(val) {
  72202. return !isNaN(val) && !isFinite(val);
  72203. }
  72204. // If a markArea has one dim
  72205. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  72206. var otherDimIndex = 1 - dimIndex;
  72207. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  72208. }
  72209. function markAreaFilter(coordSys, item) {
  72210. var fromCoord = item.coord[0];
  72211. var toCoord = item.coord[1];
  72212. if (coordSys.type === 'cartesian2d') {
  72213. // In case
  72214. // {
  72215. // markArea: {
  72216. // data: [{ yAxis: 2 }]
  72217. // }
  72218. // }
  72219. if (
  72220. fromCoord && toCoord &&
  72221. (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys)
  72222. || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))
  72223. ) {
  72224. return true;
  72225. }
  72226. }
  72227. return dataFilter$1(coordSys, {
  72228. coord: fromCoord,
  72229. x: item.x0,
  72230. y: item.y0
  72231. })
  72232. || dataFilter$1(coordSys, {
  72233. coord: toCoord,
  72234. x: item.x1,
  72235. y: item.y1
  72236. });
  72237. }
  72238. // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  72239. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  72240. var coordSys = seriesModel.coordinateSystem;
  72241. var itemModel = data.getItemModel(idx);
  72242. var point;
  72243. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  72244. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  72245. if (!isNaN(xPx) && !isNaN(yPx)) {
  72246. point = [xPx, yPx];
  72247. }
  72248. else {
  72249. // Chart like bar may have there own marker positioning logic
  72250. if (seriesModel.getMarkerPosition) {
  72251. // Use the getMarkerPoisition
  72252. point = seriesModel.getMarkerPosition(
  72253. data.getValues(dims, idx)
  72254. );
  72255. }
  72256. else {
  72257. var x = data.get(dims[0], idx);
  72258. var y = data.get(dims[1], idx);
  72259. var pt = [x, y];
  72260. coordSys.clampData && coordSys.clampData(pt, pt);
  72261. point = coordSys.dataToPoint(pt, true);
  72262. }
  72263. if (coordSys.type === 'cartesian2d') {
  72264. var xAxis = coordSys.getAxis('x');
  72265. var yAxis = coordSys.getAxis('y');
  72266. var x = data.get(dims[0], idx);
  72267. var y = data.get(dims[1], idx);
  72268. if (isInifinity$1(x)) {
  72269. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  72270. }
  72271. else if (isInifinity$1(y)) {
  72272. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  72273. }
  72274. }
  72275. // Use x, y if has any
  72276. if (!isNaN(xPx)) {
  72277. point[0] = xPx;
  72278. }
  72279. if (!isNaN(yPx)) {
  72280. point[1] = yPx;
  72281. }
  72282. }
  72283. return point;
  72284. }
  72285. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  72286. MarkerView.extend({
  72287. type: 'markArea',
  72288. // updateLayout: function (markAreaModel, ecModel, api) {
  72289. // ecModel.eachSeries(function (seriesModel) {
  72290. // var maModel = seriesModel.markAreaModel;
  72291. // if (maModel) {
  72292. // var areaData = maModel.getData();
  72293. // areaData.each(function (idx) {
  72294. // var points = zrUtil.map(dimPermutations, function (dim) {
  72295. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72296. // });
  72297. // // Layout
  72298. // areaData.setItemLayout(idx, points);
  72299. // var el = areaData.getItemGraphicEl(idx);
  72300. // el.setShape('points', points);
  72301. // });
  72302. // }
  72303. // }, this);
  72304. // },
  72305. updateTransform: function (markAreaModel, ecModel, api) {
  72306. ecModel.eachSeries(function (seriesModel) {
  72307. var maModel = seriesModel.markAreaModel;
  72308. if (maModel) {
  72309. var areaData = maModel.getData();
  72310. areaData.each(function (idx) {
  72311. var points = map(dimPermutations, function (dim) {
  72312. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72313. });
  72314. // Layout
  72315. areaData.setItemLayout(idx, points);
  72316. var el = areaData.getItemGraphicEl(idx);
  72317. el.setShape('points', points);
  72318. });
  72319. }
  72320. }, this);
  72321. },
  72322. renderSeries: function (seriesModel, maModel, ecModel, api) {
  72323. var coordSys = seriesModel.coordinateSystem;
  72324. var seriesId = seriesModel.id;
  72325. var seriesData = seriesModel.getData();
  72326. var areaGroupMap = this.markerGroupMap;
  72327. var polygonGroup = areaGroupMap.get(seriesId)
  72328. || areaGroupMap.set(seriesId, {group: new Group()});
  72329. this.group.add(polygonGroup.group);
  72330. polygonGroup.__keep = true;
  72331. var areaData = createList$3(coordSys, seriesModel, maModel);
  72332. // Line data for tooltip and formatter
  72333. maModel.setData(areaData);
  72334. // Update visual and layout of line
  72335. areaData.each(function (idx) {
  72336. // Layout
  72337. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  72338. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  72339. }));
  72340. // Visual
  72341. areaData.setItemVisual(idx, {
  72342. color: seriesData.getVisual('color')
  72343. });
  72344. });
  72345. areaData.diff(polygonGroup.__data)
  72346. .add(function (idx) {
  72347. var polygon = new Polygon({
  72348. shape: {
  72349. points: areaData.getItemLayout(idx)
  72350. }
  72351. });
  72352. areaData.setItemGraphicEl(idx, polygon);
  72353. polygonGroup.group.add(polygon);
  72354. })
  72355. .update(function (newIdx, oldIdx) {
  72356. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  72357. updateProps(polygon, {
  72358. shape: {
  72359. points: areaData.getItemLayout(newIdx)
  72360. }
  72361. }, maModel, newIdx);
  72362. polygonGroup.group.add(polygon);
  72363. areaData.setItemGraphicEl(newIdx, polygon);
  72364. })
  72365. .remove(function (idx) {
  72366. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  72367. polygonGroup.group.remove(polygon);
  72368. })
  72369. .execute();
  72370. areaData.eachItemGraphicEl(function (polygon, idx) {
  72371. var itemModel = areaData.getItemModel(idx);
  72372. var labelModel = itemModel.getModel('label');
  72373. var labelHoverModel = itemModel.getModel('emphasis.label');
  72374. var color = areaData.getItemVisual(idx, 'color');
  72375. polygon.useStyle(
  72376. defaults(
  72377. itemModel.getModel('itemStyle').getItemStyle(),
  72378. {
  72379. fill: modifyAlpha(color, 0.4),
  72380. stroke: color
  72381. }
  72382. )
  72383. );
  72384. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  72385. setLabelStyle(
  72386. polygon.style, polygon.hoverStyle, labelModel, labelHoverModel,
  72387. {
  72388. labelFetcher: maModel,
  72389. labelDataIndex: idx,
  72390. defaultText: areaData.getName(idx) || '',
  72391. isRectText: true,
  72392. autoColor: color
  72393. }
  72394. );
  72395. setHoverStyle(polygon, {});
  72396. polygon.dataModel = maModel;
  72397. });
  72398. polygonGroup.__data = areaData;
  72399. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  72400. }
  72401. });
  72402. /**
  72403. * @inner
  72404. * @param {module:echarts/coord/*} coordSys
  72405. * @param {module:echarts/model/Series} seriesModel
  72406. * @param {module:echarts/model/Model} mpModel
  72407. */
  72408. function createList$3(coordSys, seriesModel, maModel) {
  72409. var coordDimsInfos;
  72410. var areaData;
  72411. var dims = ['x0', 'y0', 'x1', 'y1'];
  72412. if (coordSys) {
  72413. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  72414. var data = seriesModel.getData();
  72415. var info = data.getDimensionInfo(
  72416. data.mapDimension(coordDim)
  72417. ) || {};
  72418. // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  72419. return defaults({name: coordDim}, info);
  72420. });
  72421. areaData = new List(map(dims, function (dim, idx) {
  72422. return {
  72423. name: dim,
  72424. type: coordDimsInfos[idx % 2].type
  72425. };
  72426. }), maModel);
  72427. }
  72428. else {
  72429. coordDimsInfos =[{
  72430. name: 'value',
  72431. type: 'float'
  72432. }];
  72433. areaData = new List(coordDimsInfos, maModel);
  72434. }
  72435. var optData = map(maModel.get('data'), curry(
  72436. markAreaTransform, seriesModel, coordSys, maModel
  72437. ));
  72438. if (coordSys) {
  72439. optData = filter(
  72440. optData, curry(markAreaFilter, coordSys)
  72441. );
  72442. }
  72443. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  72444. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  72445. } : function (item) {
  72446. return item.value;
  72447. };
  72448. areaData.initData(optData, null, dimValueGetter$$1);
  72449. areaData.hasItemOption = true;
  72450. return areaData;
  72451. }
  72452. /*
  72453. * Licensed to the Apache Software Foundation (ASF) under one
  72454. * or more contributor license agreements. See the NOTICE file
  72455. * distributed with this work for additional information
  72456. * regarding copyright ownership. The ASF licenses this file
  72457. * to you under the Apache License, Version 2.0 (the
  72458. * "License"); you may not use this file except in compliance
  72459. * with the License. You may obtain a copy of the License at
  72460. *
  72461. * http://www.apache.org/licenses/LICENSE-2.0
  72462. *
  72463. * Unless required by applicable law or agreed to in writing,
  72464. * software distributed under the License is distributed on an
  72465. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72466. * KIND, either express or implied. See the License for the
  72467. * specific language governing permissions and limitations
  72468. * under the License.
  72469. */
  72470. registerPreprocessor(function (opt) {
  72471. // Make sure markArea component is enabled
  72472. opt.markArea = opt.markArea || {};
  72473. });
  72474. /*
  72475. * Licensed to the Apache Software Foundation (ASF) under one
  72476. * or more contributor license agreements. See the NOTICE file
  72477. * distributed with this work for additional information
  72478. * regarding copyright ownership. The ASF licenses this file
  72479. * to you under the Apache License, Version 2.0 (the
  72480. * "License"); you may not use this file except in compliance
  72481. * with the License. You may obtain a copy of the License at
  72482. *
  72483. * http://www.apache.org/licenses/LICENSE-2.0
  72484. *
  72485. * Unless required by applicable law or agreed to in writing,
  72486. * software distributed under the License is distributed on an
  72487. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72488. * KIND, either express or implied. See the License for the
  72489. * specific language governing permissions and limitations
  72490. * under the License.
  72491. */
  72492. var preprocessor$3 = function (option) {
  72493. var timelineOpt = option && option.timeline;
  72494. if (!isArray(timelineOpt)) {
  72495. timelineOpt = timelineOpt ? [timelineOpt] : [];
  72496. }
  72497. each$1(timelineOpt, function (opt) {
  72498. if (!opt) {
  72499. return;
  72500. }
  72501. compatibleEC2(opt);
  72502. });
  72503. };
  72504. function compatibleEC2(opt) {
  72505. var type = opt.type;
  72506. var ec2Types = {'number': 'value', 'time': 'time'};
  72507. // Compatible with ec2
  72508. if (ec2Types[type]) {
  72509. opt.axisType = ec2Types[type];
  72510. delete opt.type;
  72511. }
  72512. transferItem(opt);
  72513. if (has$2(opt, 'controlPosition')) {
  72514. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  72515. if (!has$2(controlStyle, 'position')) {
  72516. controlStyle.position = opt.controlPosition;
  72517. }
  72518. if (controlStyle.position === 'none' && !has$2(controlStyle, 'show')) {
  72519. controlStyle.show = false;
  72520. delete controlStyle.position;
  72521. }
  72522. delete opt.controlPosition;
  72523. }
  72524. each$1(opt.data || [], function (dataItem) {
  72525. if (isObject$1(dataItem) && !isArray(dataItem)) {
  72526. if (!has$2(dataItem, 'value') && has$2(dataItem, 'name')) {
  72527. // In ec2, using name as value.
  72528. dataItem.value = dataItem.name;
  72529. }
  72530. transferItem(dataItem);
  72531. }
  72532. });
  72533. }
  72534. function transferItem(opt) {
  72535. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  72536. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {});
  72537. // Transfer label out
  72538. var label = opt.label || (opt.label || {});
  72539. var labelNormal = label.normal || (label.normal = {});
  72540. var excludeLabelAttr = {normal: 1, emphasis: 1};
  72541. each$1(label, function (value, name) {
  72542. if (!excludeLabelAttr[name] && !has$2(labelNormal, name)) {
  72543. labelNormal[name] = value;
  72544. }
  72545. });
  72546. if (itemStyleEmphasis.label && !has$2(label, 'emphasis')) {
  72547. label.emphasis = itemStyleEmphasis.label;
  72548. delete itemStyleEmphasis.label;
  72549. }
  72550. }
  72551. function has$2(obj, attr) {
  72552. return obj.hasOwnProperty(attr);
  72553. }
  72554. /*
  72555. * Licensed to the Apache Software Foundation (ASF) under one
  72556. * or more contributor license agreements. See the NOTICE file
  72557. * distributed with this work for additional information
  72558. * regarding copyright ownership. The ASF licenses this file
  72559. * to you under the Apache License, Version 2.0 (the
  72560. * "License"); you may not use this file except in compliance
  72561. * with the License. You may obtain a copy of the License at
  72562. *
  72563. * http://www.apache.org/licenses/LICENSE-2.0
  72564. *
  72565. * Unless required by applicable law or agreed to in writing,
  72566. * software distributed under the License is distributed on an
  72567. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72568. * KIND, either express or implied. See the License for the
  72569. * specific language governing permissions and limitations
  72570. * under the License.
  72571. */
  72572. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  72573. // Only slider now.
  72574. return 'slider';
  72575. });
  72576. /*
  72577. * Licensed to the Apache Software Foundation (ASF) under one
  72578. * or more contributor license agreements. See the NOTICE file
  72579. * distributed with this work for additional information
  72580. * regarding copyright ownership. The ASF licenses this file
  72581. * to you under the Apache License, Version 2.0 (the
  72582. * "License"); you may not use this file except in compliance
  72583. * with the License. You may obtain a copy of the License at
  72584. *
  72585. * http://www.apache.org/licenses/LICENSE-2.0
  72586. *
  72587. * Unless required by applicable law or agreed to in writing,
  72588. * software distributed under the License is distributed on an
  72589. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72590. * KIND, either express or implied. See the License for the
  72591. * specific language governing permissions and limitations
  72592. * under the License.
  72593. */
  72594. registerAction(
  72595. {type: 'timelineChange', event: 'timelineChanged', update: 'prepareAndUpdate'},
  72596. function (payload, ecModel) {
  72597. var timelineModel = ecModel.getComponent('timeline');
  72598. if (timelineModel && payload.currentIndex != null) {
  72599. timelineModel.setCurrentIndex(payload.currentIndex);
  72600. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  72601. timelineModel.setPlayState(false);
  72602. }
  72603. }
  72604. // Set normalized currentIndex to payload.
  72605. ecModel.resetOption('timeline');
  72606. return defaults({
  72607. currentIndex: timelineModel.option.currentIndex
  72608. }, payload);
  72609. }
  72610. );
  72611. registerAction(
  72612. {type: 'timelinePlayChange', event: 'timelinePlayChanged', update: 'update'},
  72613. function (payload, ecModel) {
  72614. var timelineModel = ecModel.getComponent('timeline');
  72615. if (timelineModel && payload.playState != null) {
  72616. timelineModel.setPlayState(payload.playState);
  72617. }
  72618. }
  72619. );
  72620. /*
  72621. * Licensed to the Apache Software Foundation (ASF) under one
  72622. * or more contributor license agreements. See the NOTICE file
  72623. * distributed with this work for additional information
  72624. * regarding copyright ownership. The ASF licenses this file
  72625. * to you under the Apache License, Version 2.0 (the
  72626. * "License"); you may not use this file except in compliance
  72627. * with the License. You may obtain a copy of the License at
  72628. *
  72629. * http://www.apache.org/licenses/LICENSE-2.0
  72630. *
  72631. * Unless required by applicable law or agreed to in writing,
  72632. * software distributed under the License is distributed on an
  72633. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72634. * KIND, either express or implied. See the License for the
  72635. * specific language governing permissions and limitations
  72636. * under the License.
  72637. */
  72638. var TimelineModel = ComponentModel.extend({
  72639. type: 'timeline',
  72640. layoutMode: 'box',
  72641. /**
  72642. * @protected
  72643. */
  72644. defaultOption: {
  72645. zlevel: 0, // 一级层叠
  72646. z: 4, // 二级层叠
  72647. show: true,
  72648. axisType: 'time', // 模式是时间类型,支持 value, category
  72649. realtime: true,
  72650. left: '20%',
  72651. top: null,
  72652. right: '20%',
  72653. bottom: 0,
  72654. width: null,
  72655. height: 40,
  72656. padding: 5,
  72657. controlPosition: 'left', // 'left' 'right' 'top' 'bottom' 'none'
  72658. autoPlay: false,
  72659. rewind: false, // 反向播放
  72660. loop: true,
  72661. playInterval: 2000, // 播放时间间隔,单位ms
  72662. currentIndex: 0,
  72663. itemStyle: {},
  72664. label: {
  72665. color: '#000'
  72666. },
  72667. data: []
  72668. },
  72669. /**
  72670. * @override
  72671. */
  72672. init: function (option, parentModel, ecModel) {
  72673. /**
  72674. * @private
  72675. * @type {module:echarts/data/List}
  72676. */
  72677. this._data;
  72678. /**
  72679. * @private
  72680. * @type {Array.<string>}
  72681. */
  72682. this._names;
  72683. this.mergeDefaultAndTheme(option, ecModel);
  72684. this._initData();
  72685. },
  72686. /**
  72687. * @override
  72688. */
  72689. mergeOption: function (option) {
  72690. TimelineModel.superApply(this, 'mergeOption', arguments);
  72691. this._initData();
  72692. },
  72693. /**
  72694. * @param {number} [currentIndex]
  72695. */
  72696. setCurrentIndex: function (currentIndex) {
  72697. if (currentIndex == null) {
  72698. currentIndex = this.option.currentIndex;
  72699. }
  72700. var count = this._data.count();
  72701. if (this.option.loop) {
  72702. currentIndex = (currentIndex % count + count) % count;
  72703. }
  72704. else {
  72705. currentIndex >= count && (currentIndex = count - 1);
  72706. currentIndex < 0 && (currentIndex = 0);
  72707. }
  72708. this.option.currentIndex = currentIndex;
  72709. },
  72710. /**
  72711. * @return {number} currentIndex
  72712. */
  72713. getCurrentIndex: function () {
  72714. return this.option.currentIndex;
  72715. },
  72716. /**
  72717. * @return {boolean}
  72718. */
  72719. isIndexMax: function () {
  72720. return this.getCurrentIndex() >= this._data.count() - 1;
  72721. },
  72722. /**
  72723. * @param {boolean} state true: play, false: stop
  72724. */
  72725. setPlayState: function (state) {
  72726. this.option.autoPlay = !!state;
  72727. },
  72728. /**
  72729. * @return {boolean} true: play, false: stop
  72730. */
  72731. getPlayState: function () {
  72732. return !!this.option.autoPlay;
  72733. },
  72734. /**
  72735. * @private
  72736. */
  72737. _initData: function () {
  72738. var thisOption = this.option;
  72739. var dataArr = thisOption.data || [];
  72740. var axisType = thisOption.axisType;
  72741. var names = this._names = [];
  72742. if (axisType === 'category') {
  72743. var idxArr = [];
  72744. each$1(dataArr, function (item, index) {
  72745. var value = getDataItemValue(item);
  72746. var newItem;
  72747. if (isObject$1(item)) {
  72748. newItem = clone(item);
  72749. newItem.value = index;
  72750. }
  72751. else {
  72752. newItem = index;
  72753. }
  72754. idxArr.push(newItem);
  72755. if (!isString(value) && (value == null || isNaN(value))) {
  72756. value = '';
  72757. }
  72758. names.push(value + '');
  72759. });
  72760. dataArr = idxArr;
  72761. }
  72762. var dimType = ({category: 'ordinal', time: 'time'})[axisType] || 'number';
  72763. var data = this._data = new List([{name: 'value', type: dimType}], this);
  72764. data.initData(dataArr, names);
  72765. },
  72766. getData: function () {
  72767. return this._data;
  72768. },
  72769. /**
  72770. * @public
  72771. * @return {Array.<string>} categoreis
  72772. */
  72773. getCategories: function () {
  72774. if (this.get('axisType') === 'category') {
  72775. return this._names.slice();
  72776. }
  72777. }
  72778. });
  72779. /*
  72780. * Licensed to the Apache Software Foundation (ASF) under one
  72781. * or more contributor license agreements. See the NOTICE file
  72782. * distributed with this work for additional information
  72783. * regarding copyright ownership. The ASF licenses this file
  72784. * to you under the Apache License, Version 2.0 (the
  72785. * "License"); you may not use this file except in compliance
  72786. * with the License. You may obtain a copy of the License at
  72787. *
  72788. * http://www.apache.org/licenses/LICENSE-2.0
  72789. *
  72790. * Unless required by applicable law or agreed to in writing,
  72791. * software distributed under the License is distributed on an
  72792. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72793. * KIND, either express or implied. See the License for the
  72794. * specific language governing permissions and limitations
  72795. * under the License.
  72796. */
  72797. var SliderTimelineModel = TimelineModel.extend({
  72798. type: 'timeline.slider',
  72799. /**
  72800. * @protected
  72801. */
  72802. defaultOption: {
  72803. backgroundColor: 'rgba(0,0,0,0)', // 时间轴背景颜色
  72804. borderColor: '#ccc', // 时间轴边框颜色
  72805. borderWidth: 0, // 时间轴边框线宽,单位px,默认为0(无边框)
  72806. orient: 'horizontal', // 'vertical'
  72807. inverse: false,
  72808. tooltip: { // boolean or Object
  72809. trigger: 'item' // data item may also have tootip attr.
  72810. },
  72811. symbol: 'emptyCircle',
  72812. symbolSize: 10,
  72813. lineStyle: {
  72814. show: true,
  72815. width: 2,
  72816. color: '#304654'
  72817. },
  72818. label: { // 文本标签
  72819. position: 'auto', // auto left right top bottom
  72820. // When using number, label position is not
  72821. // restricted by viewRect.
  72822. // positive: right/bottom, negative: left/top
  72823. show: true,
  72824. interval: 'auto',
  72825. rotate: 0,
  72826. // formatter: null,
  72827. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72828. color: '#304654'
  72829. },
  72830. itemStyle: {
  72831. color: '#304654',
  72832. borderWidth: 1
  72833. },
  72834. checkpointStyle: {
  72835. symbol: 'circle',
  72836. symbolSize: 13,
  72837. color: '#c23531',
  72838. borderWidth: 5,
  72839. borderColor: 'rgba(194,53,49, 0.5)',
  72840. animation: true,
  72841. animationDuration: 300,
  72842. animationEasing: 'quinticInOut'
  72843. },
  72844. controlStyle: {
  72845. show: true,
  72846. showPlayBtn: true,
  72847. showPrevBtn: true,
  72848. showNextBtn: true,
  72849. itemSize: 22,
  72850. itemGap: 12,
  72851. position: 'left', // 'left' 'right' 'top' 'bottom'
  72852. 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
  72853. 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
  72854. 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
  72855. 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
  72856. color: '#304654',
  72857. borderColor: '#304654',
  72858. borderWidth: 1
  72859. },
  72860. emphasis: {
  72861. label: {
  72862. show: true,
  72863. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  72864. color: '#c23531'
  72865. },
  72866. itemStyle: {
  72867. color: '#c23531'
  72868. },
  72869. controlStyle: {
  72870. color: '#c23531',
  72871. borderColor: '#c23531',
  72872. borderWidth: 2
  72873. }
  72874. },
  72875. data: []
  72876. }
  72877. });
  72878. mixin(SliderTimelineModel, dataFormatMixin);
  72879. /*
  72880. * Licensed to the Apache Software Foundation (ASF) under one
  72881. * or more contributor license agreements. See the NOTICE file
  72882. * distributed with this work for additional information
  72883. * regarding copyright ownership. The ASF licenses this file
  72884. * to you under the Apache License, Version 2.0 (the
  72885. * "License"); you may not use this file except in compliance
  72886. * with the License. You may obtain a copy of the License at
  72887. *
  72888. * http://www.apache.org/licenses/LICENSE-2.0
  72889. *
  72890. * Unless required by applicable law or agreed to in writing,
  72891. * software distributed under the License is distributed on an
  72892. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72893. * KIND, either express or implied. See the License for the
  72894. * specific language governing permissions and limitations
  72895. * under the License.
  72896. */
  72897. var TimelineView = Component.extend({
  72898. type: 'timeline'
  72899. });
  72900. /*
  72901. * Licensed to the Apache Software Foundation (ASF) under one
  72902. * or more contributor license agreements. See the NOTICE file
  72903. * distributed with this work for additional information
  72904. * regarding copyright ownership. The ASF licenses this file
  72905. * to you under the Apache License, Version 2.0 (the
  72906. * "License"); you may not use this file except in compliance
  72907. * with the License. You may obtain a copy of the License at
  72908. *
  72909. * http://www.apache.org/licenses/LICENSE-2.0
  72910. *
  72911. * Unless required by applicable law or agreed to in writing,
  72912. * software distributed under the License is distributed on an
  72913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72914. * KIND, either express or implied. See the License for the
  72915. * specific language governing permissions and limitations
  72916. * under the License.
  72917. */
  72918. /**
  72919. * Extend axis 2d
  72920. * @constructor module:echarts/coord/cartesian/Axis2D
  72921. * @extends {module:echarts/coord/cartesian/Axis}
  72922. * @param {string} dim
  72923. * @param {*} scale
  72924. * @param {Array.<number>} coordExtent
  72925. * @param {string} axisType
  72926. * @param {string} position
  72927. */
  72928. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  72929. Axis.call(this, dim, scale, coordExtent);
  72930. /**
  72931. * Axis type
  72932. * - 'category'
  72933. * - 'value'
  72934. * - 'time'
  72935. * - 'log'
  72936. * @type {string}
  72937. */
  72938. this.type = axisType || 'value';
  72939. /**
  72940. * Axis model
  72941. * @param {module:echarts/component/TimelineModel}
  72942. */
  72943. this.model = null;
  72944. };
  72945. TimelineAxis.prototype = {
  72946. constructor: TimelineAxis,
  72947. /**
  72948. * @override
  72949. */
  72950. getLabelModel: function () {
  72951. return this.model.getModel('label');
  72952. },
  72953. /**
  72954. * @override
  72955. */
  72956. isHorizontal: function () {
  72957. return this.model.get('orient') === 'horizontal';
  72958. }
  72959. };
  72960. inherits(TimelineAxis, Axis);
  72961. /*
  72962. * Licensed to the Apache Software Foundation (ASF) under one
  72963. * or more contributor license agreements. See the NOTICE file
  72964. * distributed with this work for additional information
  72965. * regarding copyright ownership. The ASF licenses this file
  72966. * to you under the Apache License, Version 2.0 (the
  72967. * "License"); you may not use this file except in compliance
  72968. * with the License. You may obtain a copy of the License at
  72969. *
  72970. * http://www.apache.org/licenses/LICENSE-2.0
  72971. *
  72972. * Unless required by applicable law or agreed to in writing,
  72973. * software distributed under the License is distributed on an
  72974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72975. * KIND, either express or implied. See the License for the
  72976. * specific language governing permissions and limitations
  72977. * under the License.
  72978. */
  72979. var bind$6 = bind;
  72980. var each$27 = each$1;
  72981. var PI$4 = Math.PI;
  72982. TimelineView.extend({
  72983. type: 'timeline.slider',
  72984. init: function (ecModel, api) {
  72985. this.api = api;
  72986. /**
  72987. * @private
  72988. * @type {module:echarts/component/timeline/TimelineAxis}
  72989. */
  72990. this._axis;
  72991. /**
  72992. * @private
  72993. * @type {module:zrender/core/BoundingRect}
  72994. */
  72995. this._viewRect;
  72996. /**
  72997. * @type {number}
  72998. */
  72999. this._timer;
  73000. /**
  73001. * @type {module:zrender/Element}
  73002. */
  73003. this._currentPointer;
  73004. /**
  73005. * @type {module:zrender/container/Group}
  73006. */
  73007. this._mainGroup;
  73008. /**
  73009. * @type {module:zrender/container/Group}
  73010. */
  73011. this._labelGroup;
  73012. },
  73013. /**
  73014. * @override
  73015. */
  73016. render: function (timelineModel, ecModel, api, payload) {
  73017. this.model = timelineModel;
  73018. this.api = api;
  73019. this.ecModel = ecModel;
  73020. this.group.removeAll();
  73021. if (timelineModel.get('show', true)) {
  73022. var layoutInfo = this._layout(timelineModel, api);
  73023. var mainGroup = this._createGroup('mainGroup');
  73024. var labelGroup = this._createGroup('labelGroup');
  73025. /**
  73026. * @private
  73027. * @type {module:echarts/component/timeline/TimelineAxis}
  73028. */
  73029. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  73030. timelineModel.formatTooltip = function (dataIndex) {
  73031. return encodeHTML(axis.scale.getLabel(dataIndex));
  73032. };
  73033. each$27(
  73034. ['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'],
  73035. function (name) {
  73036. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  73037. },
  73038. this
  73039. );
  73040. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  73041. this._position(layoutInfo, timelineModel);
  73042. }
  73043. this._doPlayStop();
  73044. },
  73045. /**
  73046. * @override
  73047. */
  73048. remove: function () {
  73049. this._clearTimer();
  73050. this.group.removeAll();
  73051. },
  73052. /**
  73053. * @override
  73054. */
  73055. dispose: function () {
  73056. this._clearTimer();
  73057. },
  73058. _layout: function (timelineModel, api) {
  73059. var labelPosOpt = timelineModel.get('label.position');
  73060. var orient = timelineModel.get('orient');
  73061. var viewRect = getViewRect$4(timelineModel, api);
  73062. // Auto label offset.
  73063. if (labelPosOpt == null || labelPosOpt === 'auto') {
  73064. labelPosOpt = orient === 'horizontal'
  73065. ? ((viewRect.y + viewRect.height / 2) < api.getHeight() / 2 ? '-' : '+')
  73066. : ((viewRect.x + viewRect.width / 2) < api.getWidth() / 2 ? '+' : '-');
  73067. }
  73068. else if (isNaN(labelPosOpt)) {
  73069. labelPosOpt = ({
  73070. horizontal: {top: '-', bottom: '+'},
  73071. vertical: {left: '-', right: '+'}
  73072. })[orient][labelPosOpt];
  73073. }
  73074. var labelAlignMap = {
  73075. horizontal: 'center',
  73076. vertical: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'left' : 'right'
  73077. };
  73078. var labelBaselineMap = {
  73079. horizontal: (labelPosOpt >= 0 || labelPosOpt === '+') ? 'top' : 'bottom',
  73080. vertical: 'middle'
  73081. };
  73082. var rotationMap = {
  73083. horizontal: 0,
  73084. vertical: PI$4 / 2
  73085. };
  73086. // Position
  73087. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  73088. var controlModel = timelineModel.getModel('controlStyle');
  73089. var showControl = controlModel.get('show', true);
  73090. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  73091. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  73092. var sizePlusGap = controlSize + controlGap;
  73093. // Special label rotate.
  73094. var labelRotation = timelineModel.get('label.rotate') || 0;
  73095. labelRotation = labelRotation * PI$4 / 180; // To radian.
  73096. var playPosition;
  73097. var prevBtnPosition;
  73098. var nextBtnPosition;
  73099. var axisExtent;
  73100. var controlPosition = controlModel.get('position', true);
  73101. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  73102. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  73103. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  73104. var xLeft = 0;
  73105. var xRight = mainLength;
  73106. // position[0] means left, position[1] means middle.
  73107. if (controlPosition === 'left' || controlPosition === 'bottom') {
  73108. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  73109. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  73110. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73111. }
  73112. else { // 'top' 'right'
  73113. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73114. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  73115. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  73116. }
  73117. axisExtent = [xLeft, xRight];
  73118. if (timelineModel.get('inverse')) {
  73119. axisExtent.reverse();
  73120. }
  73121. return {
  73122. viewRect: viewRect,
  73123. mainLength: mainLength,
  73124. orient: orient,
  73125. rotation: rotationMap[orient],
  73126. labelRotation: labelRotation,
  73127. labelPosOpt: labelPosOpt,
  73128. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  73129. labelBaseline: timelineModel.get('label.verticalAlign')
  73130. || timelineModel.get('label.baseline')
  73131. || labelBaselineMap[orient],
  73132. // Based on mainGroup.
  73133. playPosition: playPosition,
  73134. prevBtnPosition: prevBtnPosition,
  73135. nextBtnPosition: nextBtnPosition,
  73136. axisExtent: axisExtent,
  73137. controlSize: controlSize,
  73138. controlGap: controlGap
  73139. };
  73140. },
  73141. _position: function (layoutInfo, timelineModel) {
  73142. // Position is be called finally, because bounding rect is needed for
  73143. // adapt content to fill viewRect (auto adapt offset).
  73144. // Timeline may be not all in the viewRect when 'offset' is specified
  73145. // as a number, because it is more appropriate that label aligns at
  73146. // 'offset' but not the other edge defined by viewRect.
  73147. var mainGroup = this._mainGroup;
  73148. var labelGroup = this._labelGroup;
  73149. var viewRect = layoutInfo.viewRect;
  73150. if (layoutInfo.orient === 'vertical') {
  73151. // transform to horizontal, inverse rotate by left-top point.
  73152. var m = create$1();
  73153. var rotateOriginX = viewRect.x;
  73154. var rotateOriginY = viewRect.y + viewRect.height;
  73155. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  73156. rotate(m, m, -PI$4 / 2);
  73157. translate(m, m, [rotateOriginX, rotateOriginY]);
  73158. viewRect = viewRect.clone();
  73159. viewRect.applyTransform(m);
  73160. }
  73161. var viewBound = getBound(viewRect);
  73162. var mainBound = getBound(mainGroup.getBoundingRect());
  73163. var labelBound = getBound(labelGroup.getBoundingRect());
  73164. var mainPosition = mainGroup.position;
  73165. var labelsPosition = labelGroup.position;
  73166. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  73167. var labelPosOpt = layoutInfo.labelPosOpt;
  73168. if (isNaN(labelPosOpt)) { // '+' or '-'
  73169. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  73170. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73171. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  73172. }
  73173. else {
  73174. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  73175. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  73176. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  73177. }
  73178. mainGroup.attr('position', mainPosition);
  73179. labelGroup.attr('position', labelsPosition);
  73180. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  73181. setOrigin(mainGroup);
  73182. setOrigin(labelGroup);
  73183. function setOrigin(targetGroup) {
  73184. var pos = targetGroup.position;
  73185. targetGroup.origin = [
  73186. viewBound[0][0] - pos[0],
  73187. viewBound[1][0] - pos[1]
  73188. ];
  73189. }
  73190. function getBound(rect) {
  73191. // [[xmin, xmax], [ymin, ymax]]
  73192. return [
  73193. [rect.x, rect.x + rect.width],
  73194. [rect.y, rect.y + rect.height]
  73195. ];
  73196. }
  73197. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  73198. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  73199. }
  73200. },
  73201. _createAxis: function (layoutInfo, timelineModel) {
  73202. var data = timelineModel.getData();
  73203. var axisType = timelineModel.get('axisType');
  73204. var scale = createScaleByModel(timelineModel, axisType);
  73205. // Customize scale. The `tickValue` is `dataIndex`.
  73206. scale.getTicks = function () {
  73207. return data.mapArray(['value'], function (value) {
  73208. return value;
  73209. });
  73210. };
  73211. var dataExtent = data.getDataExtent('value');
  73212. scale.setExtent(dataExtent[0], dataExtent[1]);
  73213. scale.niceTicks();
  73214. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  73215. axis.model = timelineModel;
  73216. return axis;
  73217. },
  73218. _createGroup: function (name) {
  73219. var newGroup = this['_' + name] = new Group();
  73220. this.group.add(newGroup);
  73221. return newGroup;
  73222. },
  73223. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  73224. var axisExtent = axis.getExtent();
  73225. if (!timelineModel.get('lineStyle.show')) {
  73226. return;
  73227. }
  73228. group.add(new Line({
  73229. shape: {
  73230. x1: axisExtent[0], y1: 0,
  73231. x2: axisExtent[1], y2: 0
  73232. },
  73233. style: extend(
  73234. {lineCap: 'round'},
  73235. timelineModel.getModel('lineStyle').getLineStyle()
  73236. ),
  73237. silent: true,
  73238. z2: 1
  73239. }));
  73240. },
  73241. /**
  73242. * @private
  73243. */
  73244. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  73245. var data = timelineModel.getData();
  73246. // Show all ticks, despite ignoring strategy.
  73247. var ticks = axis.scale.getTicks();
  73248. // The value is dataIndex, see the costomized scale.
  73249. each$27(ticks, function (value) {
  73250. var tickCoord = axis.dataToCoord(value);
  73251. var itemModel = data.getItemModel(value);
  73252. var itemStyleModel = itemModel.getModel('itemStyle');
  73253. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  73254. var symbolOpt = {
  73255. position: [tickCoord, 0],
  73256. onclick: bind$6(this._changeTimeline, this, value)
  73257. };
  73258. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  73259. setHoverStyle(el, hoverStyleModel.getItemStyle());
  73260. if (itemModel.get('tooltip')) {
  73261. el.dataIndex = value;
  73262. el.dataModel = timelineModel;
  73263. }
  73264. else {
  73265. el.dataIndex = el.dataModel = null;
  73266. }
  73267. }, this);
  73268. },
  73269. /**
  73270. * @private
  73271. */
  73272. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  73273. var labelModel = axis.getLabelModel();
  73274. if (!labelModel.get('show')) {
  73275. return;
  73276. }
  73277. var data = timelineModel.getData();
  73278. var labels = axis.getViewLabels();
  73279. each$27(labels, function (labelItem) {
  73280. // The tickValue is dataIndex, see the costomized scale.
  73281. var dataIndex = labelItem.tickValue;
  73282. var itemModel = data.getItemModel(dataIndex);
  73283. var normalLabelModel = itemModel.getModel('label');
  73284. var hoverLabelModel = itemModel.getModel('emphasis.label');
  73285. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  73286. var textEl = new Text({
  73287. position: [tickCoord, 0],
  73288. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  73289. onclick: bind$6(this._changeTimeline, this, dataIndex),
  73290. silent: false
  73291. });
  73292. setTextStyle(textEl.style, normalLabelModel, {
  73293. text: labelItem.formattedLabel,
  73294. textAlign: layoutInfo.labelAlign,
  73295. textVerticalAlign: layoutInfo.labelBaseline
  73296. });
  73297. group.add(textEl);
  73298. setHoverStyle(
  73299. textEl, setTextStyle({}, hoverLabelModel)
  73300. );
  73301. }, this);
  73302. },
  73303. /**
  73304. * @private
  73305. */
  73306. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  73307. var controlSize = layoutInfo.controlSize;
  73308. var rotation = layoutInfo.rotation;
  73309. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  73310. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  73311. var rect = [0, -controlSize / 2, controlSize, controlSize];
  73312. var playState = timelineModel.getPlayState();
  73313. var inverse = timelineModel.get('inverse', true);
  73314. makeBtn(
  73315. layoutInfo.nextBtnPosition,
  73316. 'controlStyle.nextIcon',
  73317. bind$6(this._changeTimeline, this, inverse ? '-' : '+')
  73318. );
  73319. makeBtn(
  73320. layoutInfo.prevBtnPosition,
  73321. 'controlStyle.prevIcon',
  73322. bind$6(this._changeTimeline, this, inverse ? '+' : '-')
  73323. );
  73324. makeBtn(
  73325. layoutInfo.playPosition,
  73326. 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'),
  73327. bind$6(this._handlePlayClick, this, !playState),
  73328. true
  73329. );
  73330. function makeBtn(position, iconPath, onclick, willRotate) {
  73331. if (!position) {
  73332. return;
  73333. }
  73334. var opt = {
  73335. position: position,
  73336. origin: [controlSize / 2, 0],
  73337. rotation: willRotate ? -rotation : 0,
  73338. rectHover: true,
  73339. style: itemStyle,
  73340. onclick: onclick
  73341. };
  73342. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  73343. group.add(btn);
  73344. setHoverStyle(btn, hoverStyle);
  73345. }
  73346. },
  73347. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  73348. var data = timelineModel.getData();
  73349. var currentIndex = timelineModel.getCurrentIndex();
  73350. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  73351. var me = this;
  73352. var callback = {
  73353. onCreate: function (pointer) {
  73354. pointer.draggable = true;
  73355. pointer.drift = bind$6(me._handlePointerDrag, me);
  73356. pointer.ondragend = bind$6(me._handlePointerDragend, me);
  73357. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  73358. },
  73359. onUpdate: function (pointer) {
  73360. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  73361. }
  73362. };
  73363. // Reuse when exists, for animation and drag.
  73364. this._currentPointer = giveSymbol(
  73365. pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback
  73366. );
  73367. },
  73368. _handlePlayClick: function (nextState) {
  73369. this._clearTimer();
  73370. this.api.dispatchAction({
  73371. type: 'timelinePlayChange',
  73372. playState: nextState,
  73373. from: this.uid
  73374. });
  73375. },
  73376. _handlePointerDrag: function (dx, dy, e) {
  73377. this._clearTimer();
  73378. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  73379. },
  73380. _handlePointerDragend: function (e) {
  73381. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  73382. },
  73383. _pointerChangeTimeline: function (mousePos, trigger) {
  73384. var toCoord = this._toAxisCoord(mousePos)[0];
  73385. var axis = this._axis;
  73386. var axisExtent = asc(axis.getExtent().slice());
  73387. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  73388. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  73389. this._currentPointer.position[0] = toCoord;
  73390. this._currentPointer.dirty();
  73391. var targetDataIndex = this._findNearestTick(toCoord);
  73392. var timelineModel = this.model;
  73393. if (trigger || (
  73394. targetDataIndex !== timelineModel.getCurrentIndex()
  73395. && timelineModel.get('realtime')
  73396. )) {
  73397. this._changeTimeline(targetDataIndex);
  73398. }
  73399. },
  73400. _doPlayStop: function () {
  73401. this._clearTimer();
  73402. if (this.model.getPlayState()) {
  73403. this._timer = setTimeout(
  73404. bind$6(handleFrame, this),
  73405. this.model.get('playInterval')
  73406. );
  73407. }
  73408. function handleFrame() {
  73409. // Do not cache
  73410. var timelineModel = this.model;
  73411. this._changeTimeline(
  73412. timelineModel.getCurrentIndex()
  73413. + (timelineModel.get('rewind', true) ? -1 : 1)
  73414. );
  73415. }
  73416. },
  73417. _toAxisCoord: function (vertex) {
  73418. var trans = this._mainGroup.getLocalTransform();
  73419. return applyTransform$1(vertex, trans, true);
  73420. },
  73421. _findNearestTick: function (axisCoord) {
  73422. var data = this.model.getData();
  73423. var dist = Infinity;
  73424. var targetDataIndex;
  73425. var axis = this._axis;
  73426. data.each(['value'], function (value, dataIndex) {
  73427. var coord = axis.dataToCoord(value);
  73428. var d = Math.abs(coord - axisCoord);
  73429. if (d < dist) {
  73430. dist = d;
  73431. targetDataIndex = dataIndex;
  73432. }
  73433. });
  73434. return targetDataIndex;
  73435. },
  73436. _clearTimer: function () {
  73437. if (this._timer) {
  73438. clearTimeout(this._timer);
  73439. this._timer = null;
  73440. }
  73441. },
  73442. _changeTimeline: function (nextIndex) {
  73443. var currentIndex = this.model.getCurrentIndex();
  73444. if (nextIndex === '+') {
  73445. nextIndex = currentIndex + 1;
  73446. }
  73447. else if (nextIndex === '-') {
  73448. nextIndex = currentIndex - 1;
  73449. }
  73450. this.api.dispatchAction({
  73451. type: 'timelineChange',
  73452. currentIndex: nextIndex,
  73453. from: this.uid
  73454. });
  73455. }
  73456. });
  73457. function getViewRect$4(model, api) {
  73458. return getLayoutRect(
  73459. model.getBoxLayoutParams(),
  73460. {
  73461. width: api.getWidth(),
  73462. height: api.getHeight()
  73463. },
  73464. model.get('padding')
  73465. );
  73466. }
  73467. function makeIcon(timelineModel, objPath, rect, opts) {
  73468. var icon = makePath(
  73469. timelineModel.get(objPath).replace(/^path:\/\//, ''),
  73470. clone(opts || {}),
  73471. new BoundingRect(rect[0], rect[1], rect[2], rect[3]),
  73472. 'center'
  73473. );
  73474. return icon;
  73475. }
  73476. /**
  73477. * Create symbol or update symbol
  73478. * opt: basic position and event handlers
  73479. */
  73480. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  73481. var color = itemStyleModel.get('color');
  73482. if (!symbol) {
  73483. var symbolType = hostModel.get('symbol');
  73484. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  73485. symbol.setStyle('strokeNoScale', true);
  73486. group.add(symbol);
  73487. callback && callback.onCreate(symbol);
  73488. }
  73489. else {
  73490. symbol.setColor(color);
  73491. group.add(symbol); // Group may be new, also need to add.
  73492. callback && callback.onUpdate(symbol);
  73493. }
  73494. // Style
  73495. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  73496. symbol.setStyle(itemStyle);
  73497. // Transform and events.
  73498. opt = merge({
  73499. rectHover: true,
  73500. z2: 100
  73501. }, opt, true);
  73502. var symbolSize = hostModel.get('symbolSize');
  73503. symbolSize = symbolSize instanceof Array
  73504. ? symbolSize.slice()
  73505. : [+symbolSize, +symbolSize];
  73506. symbolSize[0] /= 2;
  73507. symbolSize[1] /= 2;
  73508. opt.scale = symbolSize;
  73509. var symbolOffset = hostModel.get('symbolOffset');
  73510. if (symbolOffset) {
  73511. var pos = opt.position = opt.position || [0, 0];
  73512. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  73513. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  73514. }
  73515. var symbolRotate = hostModel.get('symbolRotate');
  73516. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  73517. symbol.attr(opt);
  73518. // FIXME
  73519. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  73520. // getBoundingRect will return wrong result.
  73521. // (This is supposed to be resolved in zrender, but it is a little difficult to
  73522. // leverage performance and auto updateTransform)
  73523. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  73524. symbol.updateTransform();
  73525. return symbol;
  73526. }
  73527. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  73528. if (pointer.dragging) {
  73529. return;
  73530. }
  73531. var pointerModel = timelineModel.getModel('checkpointStyle');
  73532. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  73533. if (noAnimation || !pointerModel.get('animation', true)) {
  73534. pointer.attr({position: [toCoord, 0]});
  73535. }
  73536. else {
  73537. pointer.stopAnimation(true);
  73538. pointer.animateTo(
  73539. {position: [toCoord, 0]},
  73540. pointerModel.get('animationDuration', true),
  73541. pointerModel.get('animationEasing', true)
  73542. );
  73543. }
  73544. }
  73545. /*
  73546. * Licensed to the Apache Software Foundation (ASF) under one
  73547. * or more contributor license agreements. See the NOTICE file
  73548. * distributed with this work for additional information
  73549. * regarding copyright ownership. The ASF licenses this file
  73550. * to you under the Apache License, Version 2.0 (the
  73551. * "License"); you may not use this file except in compliance
  73552. * with the License. You may obtain a copy of the License at
  73553. *
  73554. * http://www.apache.org/licenses/LICENSE-2.0
  73555. *
  73556. * Unless required by applicable law or agreed to in writing,
  73557. * software distributed under the License is distributed on an
  73558. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73559. * KIND, either express or implied. See the License for the
  73560. * specific language governing permissions and limitations
  73561. * under the License.
  73562. */
  73563. /**
  73564. * DataZoom component entry
  73565. */
  73566. registerPreprocessor(preprocessor$3);
  73567. /*
  73568. * Licensed to the Apache Software Foundation (ASF) under one
  73569. * or more contributor license agreements. See the NOTICE file
  73570. * distributed with this work for additional information
  73571. * regarding copyright ownership. The ASF licenses this file
  73572. * to you under the Apache License, Version 2.0 (the
  73573. * "License"); you may not use this file except in compliance
  73574. * with the License. You may obtain a copy of the License at
  73575. *
  73576. * http://www.apache.org/licenses/LICENSE-2.0
  73577. *
  73578. * Unless required by applicable law or agreed to in writing,
  73579. * software distributed under the License is distributed on an
  73580. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73581. * KIND, either express or implied. See the License for the
  73582. * specific language governing permissions and limitations
  73583. * under the License.
  73584. */
  73585. var ToolboxModel = extendComponentModel({
  73586. type: 'toolbox',
  73587. layoutMode: {
  73588. type: 'box',
  73589. ignoreSize: true
  73590. },
  73591. optionUpdated: function () {
  73592. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  73593. each$1(this.option.feature, function (featureOpt, featureName) {
  73594. var Feature = get$1(featureName);
  73595. Feature && merge(featureOpt, Feature.defaultOption);
  73596. });
  73597. },
  73598. defaultOption: {
  73599. show: true,
  73600. z: 6,
  73601. zlevel: 0,
  73602. orient: 'horizontal',
  73603. left: 'right',
  73604. top: 'top',
  73605. // right
  73606. // bottom
  73607. backgroundColor: 'transparent',
  73608. borderColor: '#ccc',
  73609. borderRadius: 0,
  73610. borderWidth: 0,
  73611. padding: 5,
  73612. itemSize: 15,
  73613. itemGap: 8,
  73614. showTitle: true,
  73615. iconStyle: {
  73616. borderColor: '#666',
  73617. color: 'none'
  73618. },
  73619. emphasis: {
  73620. iconStyle: {
  73621. borderColor: '#3E98C5'
  73622. }
  73623. }
  73624. // textStyle: {},
  73625. // feature
  73626. }
  73627. });
  73628. /*
  73629. * Licensed to the Apache Software Foundation (ASF) under one
  73630. * or more contributor license agreements. See the NOTICE file
  73631. * distributed with this work for additional information
  73632. * regarding copyright ownership. The ASF licenses this file
  73633. * to you under the Apache License, Version 2.0 (the
  73634. * "License"); you may not use this file except in compliance
  73635. * with the License. You may obtain a copy of the License at
  73636. *
  73637. * http://www.apache.org/licenses/LICENSE-2.0
  73638. *
  73639. * Unless required by applicable law or agreed to in writing,
  73640. * software distributed under the License is distributed on an
  73641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73642. * KIND, either express or implied. See the License for the
  73643. * specific language governing permissions and limitations
  73644. * under the License.
  73645. */
  73646. extendComponentView({
  73647. type: 'toolbox',
  73648. render: function (toolboxModel, ecModel, api, payload) {
  73649. var group = this.group;
  73650. group.removeAll();
  73651. if (!toolboxModel.get('show')) {
  73652. return;
  73653. }
  73654. var itemSize = +toolboxModel.get('itemSize');
  73655. var featureOpts = toolboxModel.get('feature') || {};
  73656. var features = this._features || (this._features = {});
  73657. var featureNames = [];
  73658. each$1(featureOpts, function (opt, name) {
  73659. featureNames.push(name);
  73660. });
  73661. (new DataDiffer(this._featureNames || [], featureNames))
  73662. .add(processFeature)
  73663. .update(processFeature)
  73664. .remove(curry(processFeature, null))
  73665. .execute();
  73666. // Keep for diff.
  73667. this._featureNames = featureNames;
  73668. function processFeature(newIndex, oldIndex) {
  73669. var featureName = featureNames[newIndex];
  73670. var oldName = featureNames[oldIndex];
  73671. var featureOpt = featureOpts[featureName];
  73672. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  73673. var feature;
  73674. if (featureName && !oldName) { // Create
  73675. if (isUserFeatureName(featureName)) {
  73676. feature = {
  73677. model: featureModel,
  73678. onclick: featureModel.option.onclick,
  73679. featureName: featureName
  73680. };
  73681. }
  73682. else {
  73683. var Feature = get$1(featureName);
  73684. if (!Feature) {
  73685. return;
  73686. }
  73687. feature = new Feature(featureModel, ecModel, api);
  73688. }
  73689. features[featureName] = feature;
  73690. }
  73691. else {
  73692. feature = features[oldName];
  73693. // If feature does not exsit.
  73694. if (!feature) {
  73695. return;
  73696. }
  73697. feature.model = featureModel;
  73698. feature.ecModel = ecModel;
  73699. feature.api = api;
  73700. }
  73701. if (!featureName && oldName) {
  73702. feature.dispose && feature.dispose(ecModel, api);
  73703. return;
  73704. }
  73705. if (!featureModel.get('show') || feature.unusable) {
  73706. feature.remove && feature.remove(ecModel, api);
  73707. return;
  73708. }
  73709. createIconPaths(featureModel, feature, featureName);
  73710. featureModel.setIconStatus = function (iconName, status) {
  73711. var option = this.option;
  73712. var iconPaths = this.iconPaths;
  73713. option.iconStatus = option.iconStatus || {};
  73714. option.iconStatus[iconName] = status;
  73715. // FIXME
  73716. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  73717. };
  73718. if (feature.render) {
  73719. feature.render(featureModel, ecModel, api, payload);
  73720. }
  73721. }
  73722. function createIconPaths(featureModel, feature, featureName) {
  73723. var iconStyleModel = featureModel.getModel('iconStyle');
  73724. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle');
  73725. // If one feature has mutiple icon. they are orginaized as
  73726. // {
  73727. // icon: {
  73728. // foo: '',
  73729. // bar: ''
  73730. // },
  73731. // title: {
  73732. // foo: '',
  73733. // bar: ''
  73734. // }
  73735. // }
  73736. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  73737. var titles = featureModel.get('title') || {};
  73738. if (typeof icons === 'string') {
  73739. var icon = icons;
  73740. var title = titles;
  73741. icons = {};
  73742. titles = {};
  73743. icons[featureName] = icon;
  73744. titles[featureName] = title;
  73745. }
  73746. var iconPaths = featureModel.iconPaths = {};
  73747. each$1(icons, function (iconStr, iconName) {
  73748. var path = createIcon(
  73749. iconStr,
  73750. {},
  73751. {
  73752. x: -itemSize / 2,
  73753. y: -itemSize / 2,
  73754. width: itemSize,
  73755. height: itemSize
  73756. }
  73757. );
  73758. path.setStyle(iconStyleModel.getItemStyle());
  73759. path.hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73760. setHoverStyle(path);
  73761. if (toolboxModel.get('showTitle')) {
  73762. path.__title = titles[iconName];
  73763. path.on('mouseover', function () {
  73764. // Should not reuse above hoverStyle, which might be modified.
  73765. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73766. path.setStyle({
  73767. text: titles[iconName],
  73768. textPosition: hoverStyle.textPosition || 'bottom',
  73769. textFill: hoverStyle.fill || hoverStyle.stroke || '#000',
  73770. textAlign: hoverStyle.textAlign || 'center'
  73771. });
  73772. })
  73773. .on('mouseout', function () {
  73774. path.setStyle({
  73775. textFill: null
  73776. });
  73777. });
  73778. }
  73779. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  73780. group.add(path);
  73781. path.on('click', bind(
  73782. feature.onclick, feature, ecModel, api, iconName
  73783. ));
  73784. iconPaths[iconName] = path;
  73785. });
  73786. }
  73787. layout$3(group, toolboxModel, api);
  73788. // Render background after group is layout
  73789. // FIXME
  73790. group.add(makeBackground(group.getBoundingRect(), toolboxModel));
  73791. // Adjust icon title positions to avoid them out of screen
  73792. group.eachChild(function (icon) {
  73793. var titleText = icon.__title;
  73794. var hoverStyle = icon.hoverStyle;
  73795. // May be background element
  73796. if (hoverStyle && titleText) {
  73797. var rect = getBoundingRect(
  73798. titleText, makeFont(hoverStyle)
  73799. );
  73800. var offsetX = icon.position[0] + group.position[0];
  73801. var offsetY = icon.position[1] + group.position[1] + itemSize;
  73802. var needPutOnTop = false;
  73803. if (offsetY + rect.height > api.getHeight()) {
  73804. hoverStyle.textPosition = 'top';
  73805. needPutOnTop = true;
  73806. }
  73807. var topOffset = needPutOnTop ? (-5 - rect.height) : (itemSize + 8);
  73808. if (offsetX + rect.width / 2 > api.getWidth()) {
  73809. hoverStyle.textPosition = ['100%', topOffset];
  73810. hoverStyle.textAlign = 'right';
  73811. }
  73812. else if (offsetX - rect.width / 2 < 0) {
  73813. hoverStyle.textPosition = [0, topOffset];
  73814. hoverStyle.textAlign = 'left';
  73815. }
  73816. }
  73817. });
  73818. },
  73819. updateView: function (toolboxModel, ecModel, api, payload) {
  73820. each$1(this._features, function (feature) {
  73821. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  73822. });
  73823. },
  73824. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  73825. // zrUtil.each(this._features, function (feature) {
  73826. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  73827. // });
  73828. // },
  73829. remove: function (ecModel, api) {
  73830. each$1(this._features, function (feature) {
  73831. feature.remove && feature.remove(ecModel, api);
  73832. });
  73833. this.group.removeAll();
  73834. },
  73835. dispose: function (ecModel, api) {
  73836. each$1(this._features, function (feature) {
  73837. feature.dispose && feature.dispose(ecModel, api);
  73838. });
  73839. }
  73840. });
  73841. function isUserFeatureName(featureName) {
  73842. return featureName.indexOf('my') === 0;
  73843. }
  73844. /*
  73845. * Licensed to the Apache Software Foundation (ASF) under one
  73846. * or more contributor license agreements. See the NOTICE file
  73847. * distributed with this work for additional information
  73848. * regarding copyright ownership. The ASF licenses this file
  73849. * to you under the Apache License, Version 2.0 (the
  73850. * "License"); you may not use this file except in compliance
  73851. * with the License. You may obtain a copy of the License at
  73852. *
  73853. * http://www.apache.org/licenses/LICENSE-2.0
  73854. *
  73855. * Unless required by applicable law or agreed to in writing,
  73856. * software distributed under the License is distributed on an
  73857. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73858. * KIND, either express or implied. See the License for the
  73859. * specific language governing permissions and limitations
  73860. * under the License.
  73861. */
  73862. var saveAsImageLang = lang.toolbox.saveAsImage;
  73863. function SaveAsImage(model) {
  73864. this.model = model;
  73865. }
  73866. SaveAsImage.defaultOption = {
  73867. show: true,
  73868. 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',
  73869. title: saveAsImageLang.title,
  73870. type: 'png',
  73871. // Default use option.backgroundColor
  73872. // backgroundColor: '#fff',
  73873. name: '',
  73874. excludeComponents: ['toolbox'],
  73875. pixelRatio: 1,
  73876. lang: saveAsImageLang.lang.slice()
  73877. };
  73878. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  73879. var proto$4 = SaveAsImage.prototype;
  73880. proto$4.onclick = function (ecModel, api) {
  73881. var model = this.model;
  73882. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  73883. var $a = document.createElement('a');
  73884. var type = model.get('type', true) || 'png';
  73885. $a.download = title + '.' + type;
  73886. $a.target = '_blank';
  73887. var url = api.getConnectedDataURL({
  73888. type: type,
  73889. backgroundColor: model.get('backgroundColor', true)
  73890. || ecModel.get('backgroundColor') || '#fff',
  73891. excludeComponents: model.get('excludeComponents'),
  73892. pixelRatio: model.get('pixelRatio')
  73893. });
  73894. $a.href = url;
  73895. // Chrome and Firefox
  73896. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  73897. var evt = new MouseEvent('click', {
  73898. view: window,
  73899. bubbles: true,
  73900. cancelable: false
  73901. });
  73902. $a.dispatchEvent(evt);
  73903. }
  73904. // IE
  73905. else {
  73906. if (window.navigator.msSaveOrOpenBlob) {
  73907. var bstr = atob(url.split(',')[1]);
  73908. var n = bstr.length;
  73909. var u8arr = new Uint8Array(n);
  73910. while(n--) {
  73911. u8arr[n] = bstr.charCodeAt(n);
  73912. }
  73913. var blob = new Blob([u8arr]);
  73914. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  73915. }
  73916. else {
  73917. var lang$$1 = model.get('lang');
  73918. var html = '' +
  73919. '<body style="margin:0;">' +
  73920. '<img src="' + url + '" style="max-width:100%;" title="' + ((lang$$1 && lang$$1[0]) || '') + '" />' +
  73921. '</body>';
  73922. var tab = window.open();
  73923. tab.document.write(html);
  73924. }
  73925. }
  73926. };
  73927. register$1(
  73928. 'saveAsImage', SaveAsImage
  73929. );
  73930. /*
  73931. * Licensed to the Apache Software Foundation (ASF) under one
  73932. * or more contributor license agreements. See the NOTICE file
  73933. * distributed with this work for additional information
  73934. * regarding copyright ownership. The ASF licenses this file
  73935. * to you under the Apache License, Version 2.0 (the
  73936. * "License"); you may not use this file except in compliance
  73937. * with the License. You may obtain a copy of the License at
  73938. *
  73939. * http://www.apache.org/licenses/LICENSE-2.0
  73940. *
  73941. * Unless required by applicable law or agreed to in writing,
  73942. * software distributed under the License is distributed on an
  73943. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73944. * KIND, either express or implied. See the License for the
  73945. * specific language governing permissions and limitations
  73946. * under the License.
  73947. */
  73948. var magicTypeLang = lang.toolbox.magicType;
  73949. function MagicType(model) {
  73950. this.model = model;
  73951. }
  73952. MagicType.defaultOption = {
  73953. show: true,
  73954. type: [],
  73955. // Icon group
  73956. icon: {
  73957. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  73958. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  73959. 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
  73960. tiled: 'M2.3,2.2h22.8V25H2.3V2.2z M35,2.2h22.8V25H35V2.2zM2.3,35h22.8v22.8H2.3V35z M35,35h22.8v22.8H35V35z'
  73961. },
  73962. // `line`, `bar`, `stack`, `tiled`
  73963. title: clone(magicTypeLang.title),
  73964. option: {},
  73965. seriesIndex: {}
  73966. };
  73967. var proto$5 = MagicType.prototype;
  73968. proto$5.getIcons = function () {
  73969. var model = this.model;
  73970. var availableIcons = model.get('icon');
  73971. var icons = {};
  73972. each$1(model.get('type'), function (type) {
  73973. if (availableIcons[type]) {
  73974. icons[type] = availableIcons[type];
  73975. }
  73976. });
  73977. return icons;
  73978. };
  73979. var seriesOptGenreator = {
  73980. 'line': function (seriesType, seriesId, seriesModel, model) {
  73981. if (seriesType === 'bar') {
  73982. return merge({
  73983. id: seriesId,
  73984. type: 'line',
  73985. // Preserve data related option
  73986. data: seriesModel.get('data'),
  73987. stack: seriesModel.get('stack'),
  73988. markPoint: seriesModel.get('markPoint'),
  73989. markLine: seriesModel.get('markLine')
  73990. }, model.get('option.line') || {}, true);
  73991. }
  73992. },
  73993. 'bar': function (seriesType, seriesId, seriesModel, model) {
  73994. if (seriesType === 'line') {
  73995. return merge({
  73996. id: seriesId,
  73997. type: 'bar',
  73998. // Preserve data related option
  73999. data: seriesModel.get('data'),
  74000. stack: seriesModel.get('stack'),
  74001. markPoint: seriesModel.get('markPoint'),
  74002. markLine: seriesModel.get('markLine')
  74003. }, model.get('option.bar') || {}, true);
  74004. }
  74005. },
  74006. 'stack': function (seriesType, seriesId, seriesModel, model) {
  74007. if (seriesType === 'line' || seriesType === 'bar') {
  74008. return merge({
  74009. id: seriesId,
  74010. stack: '__ec_magicType_stack__'
  74011. }, model.get('option.stack') || {}, true);
  74012. }
  74013. },
  74014. 'tiled': function (seriesType, seriesId, seriesModel, model) {
  74015. if (seriesType === 'line' || seriesType === 'bar') {
  74016. return merge({
  74017. id: seriesId,
  74018. stack: ''
  74019. }, model.get('option.tiled') || {}, true);
  74020. }
  74021. }
  74022. };
  74023. var radioTypes = [
  74024. ['line', 'bar'],
  74025. ['stack', 'tiled']
  74026. ];
  74027. proto$5.onclick = function (ecModel, api, type) {
  74028. var model = this.model;
  74029. var seriesIndex = model.get('seriesIndex.' + type);
  74030. // Not supported magicType
  74031. if (!seriesOptGenreator[type]) {
  74032. return;
  74033. }
  74034. var newOption = {
  74035. series: []
  74036. };
  74037. var generateNewSeriesTypes = function (seriesModel) {
  74038. var seriesType = seriesModel.subType;
  74039. var seriesId = seriesModel.id;
  74040. var newSeriesOpt = seriesOptGenreator[type](
  74041. seriesType, seriesId, seriesModel, model
  74042. );
  74043. if (newSeriesOpt) {
  74044. // PENDING If merge original option?
  74045. defaults(newSeriesOpt, seriesModel.option);
  74046. newOption.series.push(newSeriesOpt);
  74047. }
  74048. // Modify boundaryGap
  74049. var coordSys = seriesModel.coordinateSystem;
  74050. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  74051. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  74052. if (categoryAxis) {
  74053. var axisDim = categoryAxis.dim;
  74054. var axisType = axisDim + 'Axis';
  74055. var axisModel = ecModel.queryComponents({
  74056. mainType: axisType,
  74057. index: seriesModel.get(name + 'Index'),
  74058. id: seriesModel.get(name + 'Id')
  74059. })[0];
  74060. var axisIndex = axisModel.componentIndex;
  74061. newOption[axisType] = newOption[axisType] || [];
  74062. for (var i = 0; i <= axisIndex; i++) {
  74063. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  74064. }
  74065. newOption[axisType][axisIndex].boundaryGap = type === 'bar' ? true : false;
  74066. }
  74067. }
  74068. };
  74069. each$1(radioTypes, function (radio) {
  74070. if (indexOf(radio, type) >= 0) {
  74071. each$1(radio, function (item) {
  74072. model.setIconStatus(item, 'normal');
  74073. });
  74074. }
  74075. });
  74076. model.setIconStatus(type, 'emphasis');
  74077. ecModel.eachComponent(
  74078. {
  74079. mainType: 'series',
  74080. query: seriesIndex == null ? null : {
  74081. seriesIndex: seriesIndex
  74082. }
  74083. }, generateNewSeriesTypes
  74084. );
  74085. api.dispatchAction({
  74086. type: 'changeMagicType',
  74087. currentType: type,
  74088. newOption: newOption
  74089. });
  74090. };
  74091. registerAction({
  74092. type: 'changeMagicType',
  74093. event: 'magicTypeChanged',
  74094. update: 'prepareAndUpdate'
  74095. }, function (payload, ecModel) {
  74096. ecModel.mergeOption(payload.newOption);
  74097. });
  74098. register$1('magicType', MagicType);
  74099. /*
  74100. * Licensed to the Apache Software Foundation (ASF) under one
  74101. * or more contributor license agreements. See the NOTICE file
  74102. * distributed with this work for additional information
  74103. * regarding copyright ownership. The ASF licenses this file
  74104. * to you under the Apache License, Version 2.0 (the
  74105. * "License"); you may not use this file except in compliance
  74106. * with the License. You may obtain a copy of the License at
  74107. *
  74108. * http://www.apache.org/licenses/LICENSE-2.0
  74109. *
  74110. * Unless required by applicable law or agreed to in writing,
  74111. * software distributed under the License is distributed on an
  74112. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74113. * KIND, either express or implied. See the License for the
  74114. * specific language governing permissions and limitations
  74115. * under the License.
  74116. */
  74117. var dataViewLang = lang.toolbox.dataView;
  74118. var BLOCK_SPLITER = new Array(60).join('-');
  74119. var ITEM_SPLITER = '\t';
  74120. /**
  74121. * Group series into two types
  74122. * 1. on category axis, like line, bar
  74123. * 2. others, like scatter, pie
  74124. * @param {module:echarts/model/Global} ecModel
  74125. * @return {Object}
  74126. * @inner
  74127. */
  74128. function groupSeries(ecModel) {
  74129. var seriesGroupByCategoryAxis = {};
  74130. var otherSeries = [];
  74131. var meta = [];
  74132. ecModel.eachRawSeries(function (seriesModel) {
  74133. var coordSys = seriesModel.coordinateSystem;
  74134. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  74135. var baseAxis = coordSys.getBaseAxis();
  74136. if (baseAxis.type === 'category') {
  74137. var key = baseAxis.dim + '_' + baseAxis.index;
  74138. if (!seriesGroupByCategoryAxis[key]) {
  74139. seriesGroupByCategoryAxis[key] = {
  74140. categoryAxis: baseAxis,
  74141. valueAxis: coordSys.getOtherAxis(baseAxis),
  74142. series: []
  74143. };
  74144. meta.push({
  74145. axisDim: baseAxis.dim,
  74146. axisIndex: baseAxis.index
  74147. });
  74148. }
  74149. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  74150. }
  74151. else {
  74152. otherSeries.push(seriesModel);
  74153. }
  74154. }
  74155. else {
  74156. otherSeries.push(seriesModel);
  74157. }
  74158. });
  74159. return {
  74160. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  74161. other: otherSeries,
  74162. meta: meta
  74163. };
  74164. }
  74165. /**
  74166. * Assemble content of series on cateogory axis
  74167. * @param {Array.<module:echarts/model/Series>} series
  74168. * @return {string}
  74169. * @inner
  74170. */
  74171. function assembleSeriesWithCategoryAxis(series) {
  74172. var tables = [];
  74173. each$1(series, function (group, key) {
  74174. var categoryAxis = group.categoryAxis;
  74175. var valueAxis = group.valueAxis;
  74176. var valueAxisDim = valueAxis.dim;
  74177. var headers = [' '].concat(map(group.series, function (series) {
  74178. return series.name;
  74179. }));
  74180. var columns = [categoryAxis.model.getCategories()];
  74181. each$1(group.series, function (series) {
  74182. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  74183. return val;
  74184. }));
  74185. });
  74186. // Assemble table content
  74187. var lines = [headers.join(ITEM_SPLITER)];
  74188. for (var i = 0; i < columns[0].length; i++) {
  74189. var items = [];
  74190. for (var j = 0; j < columns.length; j++) {
  74191. items.push(columns[j][i]);
  74192. }
  74193. lines.push(items.join(ITEM_SPLITER));
  74194. }
  74195. tables.push(lines.join('\n'));
  74196. });
  74197. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  74198. }
  74199. /**
  74200. * Assemble content of other series
  74201. * @param {Array.<module:echarts/model/Series>} series
  74202. * @return {string}
  74203. * @inner
  74204. */
  74205. function assembleOtherSeries(series) {
  74206. return map(series, function (series) {
  74207. var data = series.getRawData();
  74208. var lines = [series.name];
  74209. var vals = [];
  74210. data.each(data.dimensions, function () {
  74211. var argLen = arguments.length;
  74212. var dataIndex = arguments[argLen - 1];
  74213. var name = data.getName(dataIndex);
  74214. for (var i = 0; i < argLen - 1; i++) {
  74215. vals[i] = arguments[i];
  74216. }
  74217. lines.push((name ? (name + ITEM_SPLITER) : '') + vals.join(ITEM_SPLITER));
  74218. });
  74219. return lines.join('\n');
  74220. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  74221. }
  74222. /**
  74223. * @param {module:echarts/model/Global}
  74224. * @return {Object}
  74225. * @inner
  74226. */
  74227. function getContentFromModel(ecModel) {
  74228. var result = groupSeries(ecModel);
  74229. return {
  74230. value: filter([
  74231. assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis),
  74232. assembleOtherSeries(result.other)
  74233. ], function (str) {
  74234. return str.replace(/[\n\t\s]/g, '');
  74235. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  74236. meta: result.meta
  74237. };
  74238. }
  74239. function trim$1(str) {
  74240. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  74241. }
  74242. /**
  74243. * If a block is tsv format
  74244. */
  74245. function isTSVFormat(block) {
  74246. // Simple method to find out if a block is tsv format
  74247. var firstLine = block.slice(0, block.indexOf('\n'));
  74248. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  74249. return true;
  74250. }
  74251. }
  74252. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  74253. /**
  74254. * @param {string} tsv
  74255. * @return {Object}
  74256. */
  74257. function parseTSVContents(tsv) {
  74258. var tsvLines = tsv.split(/\n+/g);
  74259. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  74260. var categories = [];
  74261. var series = map(headers, function (header) {
  74262. return {
  74263. name: header,
  74264. data: []
  74265. };
  74266. });
  74267. for (var i = 0; i < tsvLines.length; i++) {
  74268. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  74269. categories.push(items.shift());
  74270. for (var j = 0; j < items.length; j++) {
  74271. series[j] && (series[j].data[i] = items[j]);
  74272. }
  74273. }
  74274. return {
  74275. series: series,
  74276. categories: categories
  74277. };
  74278. }
  74279. /**
  74280. * @param {string} str
  74281. * @return {Array.<Object>}
  74282. * @inner
  74283. */
  74284. function parseListContents(str) {
  74285. var lines = str.split(/\n+/g);
  74286. var seriesName = trim$1(lines.shift());
  74287. var data = [];
  74288. for (var i = 0; i < lines.length; i++) {
  74289. var items = trim$1(lines[i]).split(itemSplitRegex);
  74290. var name = '';
  74291. var value;
  74292. var hasName = false;
  74293. if (isNaN(items[0])) { // First item is name
  74294. hasName = true;
  74295. name = items[0];
  74296. items = items.slice(1);
  74297. data[i] = {
  74298. name: name,
  74299. value: []
  74300. };
  74301. value = data[i].value;
  74302. }
  74303. else {
  74304. value = data[i] = [];
  74305. }
  74306. for (var j = 0; j < items.length; j++) {
  74307. value.push(+items[j]);
  74308. }
  74309. if (value.length === 1) {
  74310. hasName ? (data[i].value = value[0]) : (data[i] = value[0]);
  74311. }
  74312. }
  74313. return {
  74314. name: seriesName,
  74315. data: data
  74316. };
  74317. }
  74318. /**
  74319. * @param {string} str
  74320. * @param {Array.<Object>} blockMetaList
  74321. * @return {Object}
  74322. * @inner
  74323. */
  74324. function parseContents(str, blockMetaList) {
  74325. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  74326. var newOption = {
  74327. series: []
  74328. };
  74329. each$1(blocks, function (block, idx) {
  74330. if (isTSVFormat(block)) {
  74331. var result = parseTSVContents(block);
  74332. var blockMeta = blockMetaList[idx];
  74333. var axisKey = blockMeta.axisDim + 'Axis';
  74334. if (blockMeta) {
  74335. newOption[axisKey] = newOption[axisKey] || [];
  74336. newOption[axisKey][blockMeta.axisIndex] = {
  74337. data: result.categories
  74338. };
  74339. newOption.series = newOption.series.concat(result.series);
  74340. }
  74341. }
  74342. else {
  74343. var result = parseListContents(block);
  74344. newOption.series.push(result);
  74345. }
  74346. });
  74347. return newOption;
  74348. }
  74349. /**
  74350. * @alias {module:echarts/component/toolbox/feature/DataView}
  74351. * @constructor
  74352. * @param {module:echarts/model/Model} model
  74353. */
  74354. function DataView(model) {
  74355. this._dom = null;
  74356. this.model = model;
  74357. }
  74358. DataView.defaultOption = {
  74359. show: true,
  74360. readOnly: false,
  74361. optionToContent: null,
  74362. contentToOption: null,
  74363. 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',
  74364. title: clone(dataViewLang.title),
  74365. lang: clone(dataViewLang.lang),
  74366. backgroundColor: '#fff',
  74367. textColor: '#000',
  74368. textareaColor: '#fff',
  74369. textareaBorderColor: '#333',
  74370. buttonColor: '#c23531',
  74371. buttonTextColor: '#fff'
  74372. };
  74373. DataView.prototype.onclick = function (ecModel, api) {
  74374. var container = api.getDom();
  74375. var model = this.model;
  74376. if (this._dom) {
  74377. container.removeChild(this._dom);
  74378. }
  74379. var root = document.createElement('div');
  74380. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  74381. root.style.backgroundColor = model.get('backgroundColor') || '#fff';
  74382. // Create elements
  74383. var header = document.createElement('h4');
  74384. var lang$$1 = model.get('lang') || [];
  74385. header.innerHTML = lang$$1[0] || model.get('title');
  74386. header.style.cssText = 'margin: 10px 20px;';
  74387. header.style.color = model.get('textColor');
  74388. var viewMain = document.createElement('div');
  74389. var textarea = document.createElement('textarea');
  74390. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  74391. var optionToContent = model.get('optionToContent');
  74392. var contentToOption = model.get('contentToOption');
  74393. var result = getContentFromModel(ecModel);
  74394. if (typeof optionToContent === 'function') {
  74395. var htmlOrDom = optionToContent(api.getOption());
  74396. if (typeof htmlOrDom === 'string') {
  74397. viewMain.innerHTML = htmlOrDom;
  74398. }
  74399. else if (isDom(htmlOrDom)) {
  74400. viewMain.appendChild(htmlOrDom);
  74401. }
  74402. }
  74403. else {
  74404. // Use default textarea
  74405. viewMain.appendChild(textarea);
  74406. textarea.readOnly = model.get('readOnly');
  74407. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  74408. textarea.style.color = model.get('textColor');
  74409. textarea.style.borderColor = model.get('textareaBorderColor');
  74410. textarea.style.backgroundColor = model.get('textareaColor');
  74411. textarea.value = result.value;
  74412. }
  74413. var blockMetaList = result.meta;
  74414. var buttonContainer = document.createElement('div');
  74415. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  74416. var buttonStyle = 'float:right;margin-right:20px;border:none;'
  74417. + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  74418. var closeButton = document.createElement('div');
  74419. var refreshButton = document.createElement('div');
  74420. buttonStyle += ';background-color:' + model.get('buttonColor');
  74421. buttonStyle += ';color:' + model.get('buttonTextColor');
  74422. var self = this;
  74423. function close() {
  74424. container.removeChild(root);
  74425. self._dom = null;
  74426. }
  74427. addEventListener(closeButton, 'click', close);
  74428. addEventListener(refreshButton, 'click', function () {
  74429. var newOption;
  74430. try {
  74431. if (typeof contentToOption === 'function') {
  74432. newOption = contentToOption(viewMain, api.getOption());
  74433. }
  74434. else {
  74435. newOption = parseContents(textarea.value, blockMetaList);
  74436. }
  74437. }
  74438. catch (e) {
  74439. close();
  74440. throw new Error('Data view format error ' + e);
  74441. }
  74442. if (newOption) {
  74443. api.dispatchAction({
  74444. type: 'changeDataView',
  74445. newOption: newOption
  74446. });
  74447. }
  74448. close();
  74449. });
  74450. closeButton.innerHTML = lang$$1[1];
  74451. refreshButton.innerHTML = lang$$1[2];
  74452. refreshButton.style.cssText = buttonStyle;
  74453. closeButton.style.cssText = buttonStyle;
  74454. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  74455. buttonContainer.appendChild(closeButton);
  74456. // http://stackoverflow.com/questions/6637341/use-tab-to-indent-in-textarea
  74457. addEventListener(textarea, 'keydown', function (e) {
  74458. if ((e.keyCode || e.which) === 9) {
  74459. // get caret position/selection
  74460. var val = this.value;
  74461. var start = this.selectionStart;
  74462. var end = this.selectionEnd;
  74463. // set textarea value to: text before caret + tab + text after caret
  74464. this.value = val.substring(0, start) + ITEM_SPLITER + val.substring(end);
  74465. // put caret at right position again
  74466. this.selectionStart = this.selectionEnd = start + 1;
  74467. // prevent the focus lose
  74468. stop(e);
  74469. }
  74470. });
  74471. root.appendChild(header);
  74472. root.appendChild(viewMain);
  74473. root.appendChild(buttonContainer);
  74474. viewMain.style.height = (container.clientHeight - 80) + 'px';
  74475. container.appendChild(root);
  74476. this._dom = root;
  74477. };
  74478. DataView.prototype.remove = function (ecModel, api) {
  74479. this._dom && api.getDom().removeChild(this._dom);
  74480. };
  74481. DataView.prototype.dispose = function (ecModel, api) {
  74482. this.remove(ecModel, api);
  74483. };
  74484. /**
  74485. * @inner
  74486. */
  74487. function tryMergeDataOption(newData, originalData) {
  74488. return map(newData, function (newVal, idx) {
  74489. var original = originalData && originalData[idx];
  74490. if (isObject$1(original) && !isArray(original)) {
  74491. if (isObject$1(newVal) && !isArray(newVal)) {
  74492. newVal = newVal.value;
  74493. }
  74494. // Original data has option
  74495. return defaults({
  74496. value: newVal
  74497. }, original);
  74498. }
  74499. else {
  74500. return newVal;
  74501. }
  74502. });
  74503. }
  74504. register$1('dataView', DataView);
  74505. registerAction({
  74506. type: 'changeDataView',
  74507. event: 'dataViewChanged',
  74508. update: 'prepareAndUpdate'
  74509. }, function (payload, ecModel) {
  74510. var newSeriesOptList = [];
  74511. each$1(payload.newOption.series, function (seriesOpt) {
  74512. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  74513. if (!seriesModel) {
  74514. // New created series
  74515. // Geuss the series type
  74516. newSeriesOptList.push(extend({
  74517. // Default is scatter
  74518. type: 'scatter'
  74519. }, seriesOpt));
  74520. }
  74521. else {
  74522. var originalData = seriesModel.get('data');
  74523. newSeriesOptList.push({
  74524. name: seriesOpt.name,
  74525. data: tryMergeDataOption(seriesOpt.data, originalData)
  74526. });
  74527. }
  74528. });
  74529. ecModel.mergeOption(defaults({
  74530. series: newSeriesOptList
  74531. }, payload.newOption));
  74532. });
  74533. /*
  74534. * Licensed to the Apache Software Foundation (ASF) under one
  74535. * or more contributor license agreements. See the NOTICE file
  74536. * distributed with this work for additional information
  74537. * regarding copyright ownership. The ASF licenses this file
  74538. * to you under the Apache License, Version 2.0 (the
  74539. * "License"); you may not use this file except in compliance
  74540. * with the License. You may obtain a copy of the License at
  74541. *
  74542. * http://www.apache.org/licenses/LICENSE-2.0
  74543. *
  74544. * Unless required by applicable law or agreed to in writing,
  74545. * software distributed under the License is distributed on an
  74546. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74547. * KIND, either express or implied. See the License for the
  74548. * specific language governing permissions and limitations
  74549. * under the License.
  74550. */
  74551. var each$29 = each$1;
  74552. var ATTR$2 = '\0_ec_hist_store';
  74553. /**
  74554. * @param {module:echarts/model/Global} ecModel
  74555. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  74556. */
  74557. function push(ecModel, newSnapshot) {
  74558. var store = giveStore$1(ecModel);
  74559. // If previous dataZoom can not be found,
  74560. // complete an range with current range.
  74561. each$29(newSnapshot, function (batchItem, dataZoomId) {
  74562. var i = store.length - 1;
  74563. for (; i >= 0; i--) {
  74564. var snapshot = store[i];
  74565. if (snapshot[dataZoomId]) {
  74566. break;
  74567. }
  74568. }
  74569. if (i < 0) {
  74570. // No origin range set, create one by current range.
  74571. var dataZoomModel = ecModel.queryComponents(
  74572. {mainType: 'dataZoom', subType: 'select', id: dataZoomId}
  74573. )[0];
  74574. if (dataZoomModel) {
  74575. var percentRange = dataZoomModel.getPercentRange();
  74576. store[0][dataZoomId] = {
  74577. dataZoomId: dataZoomId,
  74578. start: percentRange[0],
  74579. end: percentRange[1]
  74580. };
  74581. }
  74582. }
  74583. });
  74584. store.push(newSnapshot);
  74585. }
  74586. /**
  74587. * @param {module:echarts/model/Global} ecModel
  74588. * @return {Object} snapshot
  74589. */
  74590. function pop(ecModel) {
  74591. var store = giveStore$1(ecModel);
  74592. var head = store[store.length - 1];
  74593. store.length > 1 && store.pop();
  74594. // Find top for all dataZoom.
  74595. var snapshot = {};
  74596. each$29(head, function (batchItem, dataZoomId) {
  74597. for (var i = store.length - 1; i >= 0; i--) {
  74598. var batchItem = store[i][dataZoomId];
  74599. if (batchItem) {
  74600. snapshot[dataZoomId] = batchItem;
  74601. break;
  74602. }
  74603. }
  74604. });
  74605. return snapshot;
  74606. }
  74607. /**
  74608. * @param {module:echarts/model/Global} ecModel
  74609. */
  74610. function clear$1(ecModel) {
  74611. ecModel[ATTR$2] = null;
  74612. }
  74613. /**
  74614. * @param {module:echarts/model/Global} ecModel
  74615. * @return {number} records. always >= 1.
  74616. */
  74617. function count(ecModel) {
  74618. return giveStore$1(ecModel).length;
  74619. }
  74620. /**
  74621. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  74622. * History length of each dataZoom may be different.
  74623. * this._history[0] is used to store origin range.
  74624. * @type {Array.<Object>}
  74625. */
  74626. function giveStore$1(ecModel) {
  74627. var store = ecModel[ATTR$2];
  74628. if (!store) {
  74629. store = ecModel[ATTR$2] = [{}];
  74630. }
  74631. return store;
  74632. }
  74633. /*
  74634. * Licensed to the Apache Software Foundation (ASF) under one
  74635. * or more contributor license agreements. See the NOTICE file
  74636. * distributed with this work for additional information
  74637. * regarding copyright ownership. The ASF licenses this file
  74638. * to you under the Apache License, Version 2.0 (the
  74639. * "License"); you may not use this file except in compliance
  74640. * with the License. You may obtain a copy of the License at
  74641. *
  74642. * http://www.apache.org/licenses/LICENSE-2.0
  74643. *
  74644. * Unless required by applicable law or agreed to in writing,
  74645. * software distributed under the License is distributed on an
  74646. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74647. * KIND, either express or implied. See the License for the
  74648. * specific language governing permissions and limitations
  74649. * under the License.
  74650. */
  74651. DataZoomModel.extend({
  74652. type: 'dataZoom.select'
  74653. });
  74654. /*
  74655. * Licensed to the Apache Software Foundation (ASF) under one
  74656. * or more contributor license agreements. See the NOTICE file
  74657. * distributed with this work for additional information
  74658. * regarding copyright ownership. The ASF licenses this file
  74659. * to you under the Apache License, Version 2.0 (the
  74660. * "License"); you may not use this file except in compliance
  74661. * with the License. You may obtain a copy of the License at
  74662. *
  74663. * http://www.apache.org/licenses/LICENSE-2.0
  74664. *
  74665. * Unless required by applicable law or agreed to in writing,
  74666. * software distributed under the License is distributed on an
  74667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74668. * KIND, either express or implied. See the License for the
  74669. * specific language governing permissions and limitations
  74670. * under the License.
  74671. */
  74672. DataZoomView.extend({
  74673. type: 'dataZoom.select'
  74674. });
  74675. /*
  74676. * Licensed to the Apache Software Foundation (ASF) under one
  74677. * or more contributor license agreements. See the NOTICE file
  74678. * distributed with this work for additional information
  74679. * regarding copyright ownership. The ASF licenses this file
  74680. * to you under the Apache License, Version 2.0 (the
  74681. * "License"); you may not use this file except in compliance
  74682. * with the License. You may obtain a copy of the License at
  74683. *
  74684. * http://www.apache.org/licenses/LICENSE-2.0
  74685. *
  74686. * Unless required by applicable law or agreed to in writing,
  74687. * software distributed under the License is distributed on an
  74688. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74689. * KIND, either express or implied. See the License for the
  74690. * specific language governing permissions and limitations
  74691. * under the License.
  74692. */
  74693. /**
  74694. * DataZoom component entry
  74695. */
  74696. /*
  74697. * Licensed to the Apache Software Foundation (ASF) under one
  74698. * or more contributor license agreements. See the NOTICE file
  74699. * distributed with this work for additional information
  74700. * regarding copyright ownership. The ASF licenses this file
  74701. * to you under the Apache License, Version 2.0 (the
  74702. * "License"); you may not use this file except in compliance
  74703. * with the License. You may obtain a copy of the License at
  74704. *
  74705. * http://www.apache.org/licenses/LICENSE-2.0
  74706. *
  74707. * Unless required by applicable law or agreed to in writing,
  74708. * software distributed under the License is distributed on an
  74709. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74710. * KIND, either express or implied. See the License for the
  74711. * specific language governing permissions and limitations
  74712. * under the License.
  74713. */
  74714. // Use dataZoomSelect
  74715. var dataZoomLang = lang.toolbox.dataZoom;
  74716. var each$28 = each$1;
  74717. // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  74718. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  74719. function DataZoom(model, ecModel, api) {
  74720. /**
  74721. * @private
  74722. * @type {module:echarts/component/helper/BrushController}
  74723. */
  74724. (this._brushController = new BrushController(api.getZr()))
  74725. .on('brush', bind(this._onBrush, this))
  74726. .mount();
  74727. /**
  74728. * @private
  74729. * @type {boolean}
  74730. */
  74731. this._isZoomActive;
  74732. }
  74733. DataZoom.defaultOption = {
  74734. show: true,
  74735. // Icon group
  74736. icon: {
  74737. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  74738. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  74739. },
  74740. // `zoom`, `back`
  74741. title: clone(dataZoomLang.title)
  74742. };
  74743. var proto$6 = DataZoom.prototype;
  74744. proto$6.render = function (featureModel, ecModel, api, payload) {
  74745. this.model = featureModel;
  74746. this.ecModel = ecModel;
  74747. this.api = api;
  74748. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  74749. updateBackBtnStatus(featureModel, ecModel);
  74750. };
  74751. proto$6.onclick = function (ecModel, api, type) {
  74752. handlers$1[type].call(this);
  74753. };
  74754. proto$6.remove = function (ecModel, api) {
  74755. this._brushController.unmount();
  74756. };
  74757. proto$6.dispose = function (ecModel, api) {
  74758. this._brushController.dispose();
  74759. };
  74760. /**
  74761. * @private
  74762. */
  74763. var handlers$1 = {
  74764. zoom: function () {
  74765. var nextActive = !this._isZoomActive;
  74766. this.api.dispatchAction({
  74767. type: 'takeGlobalCursor',
  74768. key: 'dataZoomSelect',
  74769. dataZoomSelectActive: nextActive
  74770. });
  74771. },
  74772. back: function () {
  74773. this._dispatchZoomAction(pop(this.ecModel));
  74774. }
  74775. };
  74776. /**
  74777. * @private
  74778. */
  74779. proto$6._onBrush = function (areas, opt) {
  74780. if (!opt.isEnd || !areas.length) {
  74781. return;
  74782. }
  74783. var snapshot = {};
  74784. var ecModel = this.ecModel;
  74785. this._brushController.updateCovers([]); // remove cover
  74786. var brushTargetManager = new BrushTargetManager(
  74787. retrieveAxisSetting(this.model.option), ecModel, {include: ['grid']}
  74788. );
  74789. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  74790. if (coordSys.type !== 'cartesian2d') {
  74791. return;
  74792. }
  74793. var brushType = area.brushType;
  74794. if (brushType === 'rect') {
  74795. setBatch('x', coordSys, coordRange[0]);
  74796. setBatch('y', coordSys, coordRange[1]);
  74797. }
  74798. else {
  74799. setBatch(({lineX: 'x', lineY: 'y'})[brushType], coordSys, coordRange);
  74800. }
  74801. });
  74802. push(ecModel, snapshot);
  74803. this._dispatchZoomAction(snapshot);
  74804. function setBatch(dimName, coordSys, minMax) {
  74805. var axis = coordSys.getAxis(dimName);
  74806. var axisModel = axis.model;
  74807. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel);
  74808. // Restrict range.
  74809. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  74810. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  74811. minMax = sliderMove(
  74812. 0, minMax.slice(), axis.scale.getExtent(), 0,
  74813. minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan
  74814. );
  74815. }
  74816. dataZoomModel && (snapshot[dataZoomModel.id] = {
  74817. dataZoomId: dataZoomModel.id,
  74818. startValue: minMax[0],
  74819. endValue: minMax[1]
  74820. });
  74821. }
  74822. function findDataZoom(dimName, axisModel, ecModel) {
  74823. var found;
  74824. ecModel.eachComponent({mainType: 'dataZoom', subType: 'select'}, function (dzModel) {
  74825. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  74826. has && (found = dzModel);
  74827. });
  74828. return found;
  74829. }
  74830. };
  74831. /**
  74832. * @private
  74833. */
  74834. proto$6._dispatchZoomAction = function (snapshot) {
  74835. var batch = [];
  74836. // Convert from hash map to array.
  74837. each$28(snapshot, function (batchItem, dataZoomId) {
  74838. batch.push(clone(batchItem));
  74839. });
  74840. batch.length && this.api.dispatchAction({
  74841. type: 'dataZoom',
  74842. from: this.uid,
  74843. batch: batch
  74844. });
  74845. };
  74846. function retrieveAxisSetting(option) {
  74847. var setting = {};
  74848. // Compatible with previous setting: null => all axis, false => no axis.
  74849. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  74850. setting[name] = option[name];
  74851. setting[name] == null && (setting[name] = 'all');
  74852. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  74853. });
  74854. return setting;
  74855. }
  74856. function updateBackBtnStatus(featureModel, ecModel) {
  74857. featureModel.setIconStatus(
  74858. 'back',
  74859. count(ecModel) > 1 ? 'emphasis' : 'normal'
  74860. );
  74861. }
  74862. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  74863. var zoomActive = view._isZoomActive;
  74864. if (payload && payload.type === 'takeGlobalCursor') {
  74865. zoomActive = payload.key === 'dataZoomSelect'
  74866. ? payload.dataZoomSelectActive : false;
  74867. }
  74868. view._isZoomActive = zoomActive;
  74869. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  74870. var brushTargetManager = new BrushTargetManager(
  74871. retrieveAxisSetting(featureModel.option), ecModel, {include: ['grid']}
  74872. );
  74873. view._brushController
  74874. .setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  74875. return (targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared)
  74876. ? 'lineX'
  74877. : (!targetInfo.xAxisDeclared && targetInfo.yAxisDeclared)
  74878. ? 'lineY'
  74879. : 'rect';
  74880. }))
  74881. .enableBrush(
  74882. zoomActive
  74883. ? {
  74884. brushType: 'auto',
  74885. brushStyle: {
  74886. // FIXME user customized?
  74887. lineWidth: 0,
  74888. fill: 'rgba(0,0,0,0.2)'
  74889. }
  74890. }
  74891. : false
  74892. );
  74893. }
  74894. register$1('dataZoom', DataZoom);
  74895. // Create special dataZoom option for select
  74896. // FIXME consider the case of merge option, where axes options are not exists.
  74897. registerPreprocessor(function (option) {
  74898. if (!option) {
  74899. return;
  74900. }
  74901. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  74902. if (!isArray(dataZoomOpts)) {
  74903. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  74904. }
  74905. var toolboxOpt = option.toolbox;
  74906. if (toolboxOpt) {
  74907. // Assume there is only one toolbox
  74908. if (isArray(toolboxOpt)) {
  74909. toolboxOpt = toolboxOpt[0];
  74910. }
  74911. if (toolboxOpt && toolboxOpt.feature) {
  74912. var dataZoomOpt = toolboxOpt.feature.dataZoom;
  74913. // FIXME: If add dataZoom when setOption in merge mode,
  74914. // no axis info to be added. See `test/dataZoom-extreme.html`
  74915. addForAxis('xAxis', dataZoomOpt);
  74916. addForAxis('yAxis', dataZoomOpt);
  74917. }
  74918. }
  74919. function addForAxis(axisName, dataZoomOpt) {
  74920. if (!dataZoomOpt) {
  74921. return;
  74922. }
  74923. // Try not to modify model, because it is not merged yet.
  74924. var axisIndicesName = axisName + 'Index';
  74925. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  74926. if (givenAxisIndices != null
  74927. && givenAxisIndices != 'all'
  74928. && !isArray(givenAxisIndices)
  74929. ) {
  74930. givenAxisIndices = (givenAxisIndices === false || givenAxisIndices === 'none') ? [] : [givenAxisIndices];
  74931. }
  74932. forEachComponent(axisName, function (axisOpt, axisIndex) {
  74933. if (givenAxisIndices != null
  74934. && givenAxisIndices != 'all'
  74935. && indexOf(givenAxisIndices, axisIndex) === -1
  74936. ) {
  74937. return;
  74938. }
  74939. var newOpt = {
  74940. type: 'select',
  74941. $fromToolbox: true,
  74942. // Id for merge mapping.
  74943. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  74944. };
  74945. // FIXME
  74946. // Only support one axis now.
  74947. newOpt[axisIndicesName] = axisIndex;
  74948. dataZoomOpts.push(newOpt);
  74949. });
  74950. }
  74951. function forEachComponent(mainType, cb) {
  74952. var opts = option[mainType];
  74953. if (!isArray(opts)) {
  74954. opts = opts ? [opts] : [];
  74955. }
  74956. each$28(opts, cb);
  74957. }
  74958. });
  74959. /*
  74960. * Licensed to the Apache Software Foundation (ASF) under one
  74961. * or more contributor license agreements. See the NOTICE file
  74962. * distributed with this work for additional information
  74963. * regarding copyright ownership. The ASF licenses this file
  74964. * to you under the Apache License, Version 2.0 (the
  74965. * "License"); you may not use this file except in compliance
  74966. * with the License. You may obtain a copy of the License at
  74967. *
  74968. * http://www.apache.org/licenses/LICENSE-2.0
  74969. *
  74970. * Unless required by applicable law or agreed to in writing,
  74971. * software distributed under the License is distributed on an
  74972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74973. * KIND, either express or implied. See the License for the
  74974. * specific language governing permissions and limitations
  74975. * under the License.
  74976. */
  74977. var restoreLang = lang.toolbox.restore;
  74978. function Restore(model) {
  74979. this.model = model;
  74980. }
  74981. Restore.defaultOption = {
  74982. show: true,
  74983. 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',
  74984. title: restoreLang.title
  74985. };
  74986. var proto$7 = Restore.prototype;
  74987. proto$7.onclick = function (ecModel, api, type) {
  74988. clear$1(ecModel);
  74989. api.dispatchAction({
  74990. type: 'restore',
  74991. from: this.uid
  74992. });
  74993. };
  74994. register$1('restore', Restore);
  74995. registerAction(
  74996. {type: 'restore', event: 'restore', update: 'prepareAndUpdate'},
  74997. function (payload, ecModel) {
  74998. ecModel.resetOption('recreate');
  74999. }
  75000. );
  75001. /*
  75002. * Licensed to the Apache Software Foundation (ASF) under one
  75003. * or more contributor license agreements. See the NOTICE file
  75004. * distributed with this work for additional information
  75005. * regarding copyright ownership. The ASF licenses this file
  75006. * to you under the Apache License, Version 2.0 (the
  75007. * "License"); you may not use this file except in compliance
  75008. * with the License. You may obtain a copy of the License at
  75009. *
  75010. * http://www.apache.org/licenses/LICENSE-2.0
  75011. *
  75012. * Unless required by applicable law or agreed to in writing,
  75013. * software distributed under the License is distributed on an
  75014. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75015. * KIND, either express or implied. See the License for the
  75016. * specific language governing permissions and limitations
  75017. * under the License.
  75018. */
  75019. var urn = 'urn:schemas-microsoft-com:vml';
  75020. var win = typeof window === 'undefined' ? null : window;
  75021. var vmlInited = false;
  75022. var doc = win && win.document;
  75023. function createNode(tagName) {
  75024. return doCreateNode(tagName);
  75025. }
  75026. // Avoid assign to an exported variable, for transforming to cjs.
  75027. var doCreateNode;
  75028. if (doc && !env$1.canvasSupported) {
  75029. try {
  75030. !doc.namespaces.zrvml && doc.namespaces.add('zrvml', urn);
  75031. doCreateNode = function (tagName) {
  75032. return doc.createElement('<zrvml:' + tagName + ' class="zrvml">');
  75033. };
  75034. }
  75035. catch (e) {
  75036. doCreateNode = function (tagName) {
  75037. return doc.createElement('<' + tagName + ' xmlns="' + urn + '" class="zrvml">');
  75038. };
  75039. }
  75040. }
  75041. // From raphael
  75042. function initVML() {
  75043. if (vmlInited || !doc) {
  75044. return;
  75045. }
  75046. vmlInited = true;
  75047. var styleSheets = doc.styleSheets;
  75048. if (styleSheets.length < 31) {
  75049. doc.createStyleSheet().addRule('.zrvml', 'behavior:url(#default#VML)');
  75050. }
  75051. else {
  75052. // http://msdn.microsoft.com/en-us/library/ms531194%28VS.85%29.aspx
  75053. styleSheets[0].addRule('.zrvml', 'behavior:url(#default#VML)');
  75054. }
  75055. }
  75056. // http://www.w3.org/TR/NOTE-VML
  75057. // TODO Use proxy like svg instead of overwrite brush methods
  75058. var CMD$3 = PathProxy.CMD;
  75059. var round$3 = Math.round;
  75060. var sqrt = Math.sqrt;
  75061. var abs$1 = Math.abs;
  75062. var cos = Math.cos;
  75063. var sin = Math.sin;
  75064. var mathMax$8 = Math.max;
  75065. if (!env$1.canvasSupported) {
  75066. var comma = ',';
  75067. var imageTransformPrefix = 'progid:DXImageTransform.Microsoft';
  75068. var Z = 21600;
  75069. var Z2 = Z / 2;
  75070. var ZLEVEL_BASE = 100000;
  75071. var Z_BASE$1 = 1000;
  75072. var initRootElStyle = function (el) {
  75073. el.style.cssText = 'position:absolute;left:0;top:0;width:1px;height:1px;';
  75074. el.coordsize = Z + ',' + Z;
  75075. el.coordorigin = '0,0';
  75076. };
  75077. var encodeHtmlAttribute = function (s) {
  75078. return String(s).replace(/&/g, '&amp;').replace(/"/g, '&quot;');
  75079. };
  75080. var rgb2Str = function (r, g, b) {
  75081. return 'rgb(' + [r, g, b].join(',') + ')';
  75082. };
  75083. var append = function (parent, child) {
  75084. if (child && parent && child.parentNode !== parent) {
  75085. parent.appendChild(child);
  75086. }
  75087. };
  75088. var remove = function (parent, child) {
  75089. if (child && parent && child.parentNode === parent) {
  75090. parent.removeChild(child);
  75091. }
  75092. };
  75093. var getZIndex = function (zlevel, z, z2) {
  75094. // z 的取值范围为 [0, 1000]
  75095. return (parseFloat(zlevel) || 0) * ZLEVEL_BASE + (parseFloat(z) || 0) * Z_BASE$1 + z2;
  75096. };
  75097. var parsePercent$3 = function (value, maxValue) {
  75098. if (typeof value === 'string') {
  75099. if (value.lastIndexOf('%') >= 0) {
  75100. return parseFloat(value) / 100 * maxValue;
  75101. }
  75102. return parseFloat(value);
  75103. }
  75104. return value;
  75105. };
  75106. /***************************************************
  75107. * PATH
  75108. **************************************************/
  75109. var setColorAndOpacity = function (el, color, opacity) {
  75110. var colorArr = parse(color);
  75111. opacity = +opacity;
  75112. if (isNaN(opacity)) {
  75113. opacity = 1;
  75114. }
  75115. if (colorArr) {
  75116. el.color = rgb2Str(colorArr[0], colorArr[1], colorArr[2]);
  75117. el.opacity = opacity * colorArr[3];
  75118. }
  75119. };
  75120. var getColorAndAlpha = function (color) {
  75121. var colorArr = parse(color);
  75122. return [
  75123. rgb2Str(colorArr[0], colorArr[1], colorArr[2]),
  75124. colorArr[3]
  75125. ];
  75126. };
  75127. var updateFillNode = function (el, style, zrEl) {
  75128. // TODO pattern
  75129. var fill = style.fill;
  75130. if (fill != null) {
  75131. // Modified from excanvas
  75132. if (fill instanceof Gradient) {
  75133. var gradientType;
  75134. var angle = 0;
  75135. var focus = [0, 0];
  75136. // additional offset
  75137. var shift = 0;
  75138. // scale factor for offset
  75139. var expansion = 1;
  75140. var rect = zrEl.getBoundingRect();
  75141. var rectWidth = rect.width;
  75142. var rectHeight = rect.height;
  75143. if (fill.type === 'linear') {
  75144. gradientType = 'gradient';
  75145. var transform = zrEl.transform;
  75146. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  75147. var p1 = [fill.x2 * rectWidth, fill.y2 * rectHeight];
  75148. if (transform) {
  75149. applyTransform(p0, p0, transform);
  75150. applyTransform(p1, p1, transform);
  75151. }
  75152. var dx = p1[0] - p0[0];
  75153. var dy = p1[1] - p0[1];
  75154. angle = Math.atan2(dx, dy) * 180 / Math.PI;
  75155. // The angle should be a non-negative number.
  75156. if (angle < 0) {
  75157. angle += 360;
  75158. }
  75159. // Very small angles produce an unexpected result because they are
  75160. // converted to a scientific notation string.
  75161. if (angle < 1e-6) {
  75162. angle = 0;
  75163. }
  75164. }
  75165. else {
  75166. gradientType = 'gradientradial';
  75167. var p0 = [fill.x * rectWidth, fill.y * rectHeight];
  75168. var transform = zrEl.transform;
  75169. var scale$$1 = zrEl.scale;
  75170. var width = rectWidth;
  75171. var height = rectHeight;
  75172. focus = [
  75173. // Percent in bounding rect
  75174. (p0[0] - rect.x) / width,
  75175. (p0[1] - rect.y) / height
  75176. ];
  75177. if (transform) {
  75178. applyTransform(p0, p0, transform);
  75179. }
  75180. width /= scale$$1[0] * Z;
  75181. height /= scale$$1[1] * Z;
  75182. var dimension = mathMax$8(width, height);
  75183. shift = 2 * 0 / dimension;
  75184. expansion = 2 * fill.r / dimension - shift;
  75185. }
  75186. // We need to sort the color stops in ascending order by offset,
  75187. // otherwise IE won't interpret it correctly.
  75188. var stops = fill.colorStops.slice();
  75189. stops.sort(function(cs1, cs2) {
  75190. return cs1.offset - cs2.offset;
  75191. });
  75192. var length$$1 = stops.length;
  75193. // Color and alpha list of first and last stop
  75194. var colorAndAlphaList = [];
  75195. var colors = [];
  75196. for (var i = 0; i < length$$1; i++) {
  75197. var stop = stops[i];
  75198. var colorAndAlpha = getColorAndAlpha(stop.color);
  75199. colors.push(stop.offset * expansion + shift + ' ' + colorAndAlpha[0]);
  75200. if (i === 0 || i === length$$1 - 1) {
  75201. colorAndAlphaList.push(colorAndAlpha);
  75202. }
  75203. }
  75204. if (length$$1 >= 2) {
  75205. var color1 = colorAndAlphaList[0][0];
  75206. var color2 = colorAndAlphaList[1][0];
  75207. var opacity1 = colorAndAlphaList[0][1] * style.opacity;
  75208. var opacity2 = colorAndAlphaList[1][1] * style.opacity;
  75209. el.type = gradientType;
  75210. el.method = 'none';
  75211. el.focus = '100%';
  75212. el.angle = angle;
  75213. el.color = color1;
  75214. el.color2 = color2;
  75215. el.colors = colors.join(',');
  75216. // When colors attribute is used, the meanings of opacity and o:opacity2
  75217. // are reversed.
  75218. el.opacity = opacity2;
  75219. // FIXME g_o_:opacity ?
  75220. el.opacity2 = opacity1;
  75221. }
  75222. if (gradientType === 'radial') {
  75223. el.focusposition = focus.join(',');
  75224. }
  75225. }
  75226. else {
  75227. // FIXME Change from Gradient fill to color fill
  75228. setColorAndOpacity(el, fill, style.opacity);
  75229. }
  75230. }
  75231. };
  75232. var updateStrokeNode = function (el, style) {
  75233. // if (style.lineJoin != null) {
  75234. // el.joinstyle = style.lineJoin;
  75235. // }
  75236. // if (style.miterLimit != null) {
  75237. // el.miterlimit = style.miterLimit * Z;
  75238. // }
  75239. // if (style.lineCap != null) {
  75240. // el.endcap = style.lineCap;
  75241. // }
  75242. if (style.lineDash != null) {
  75243. el.dashstyle = style.lineDash.join(' ');
  75244. }
  75245. if (style.stroke != null && !(style.stroke instanceof Gradient)) {
  75246. setColorAndOpacity(el, style.stroke, style.opacity);
  75247. }
  75248. };
  75249. var updateFillAndStroke = function (vmlEl, type, style, zrEl) {
  75250. var isFill = type == 'fill';
  75251. var el = vmlEl.getElementsByTagName(type)[0];
  75252. // Stroke must have lineWidth
  75253. if (style[type] != null && style[type] !== 'none' && (isFill || (!isFill && style.lineWidth))) {
  75254. vmlEl[isFill ? 'filled' : 'stroked'] = 'true';
  75255. // FIXME Remove before updating, or set `colors` will throw error
  75256. if (style[type] instanceof Gradient) {
  75257. remove(vmlEl, el);
  75258. }
  75259. if (!el) {
  75260. el = createNode(type);
  75261. }
  75262. isFill ? updateFillNode(el, style, zrEl) : updateStrokeNode(el, style);
  75263. append(vmlEl, el);
  75264. }
  75265. else {
  75266. vmlEl[isFill ? 'filled' : 'stroked'] = 'false';
  75267. remove(vmlEl, el);
  75268. }
  75269. };
  75270. var points$3 = [[], [], []];
  75271. var pathDataToString = function (path, m) {
  75272. var M = CMD$3.M;
  75273. var C = CMD$3.C;
  75274. var L = CMD$3.L;
  75275. var A = CMD$3.A;
  75276. var Q = CMD$3.Q;
  75277. var str = [];
  75278. var nPoint;
  75279. var cmdStr;
  75280. var cmd;
  75281. var i;
  75282. var xi;
  75283. var yi;
  75284. var data = path.data;
  75285. var dataLength = path.len();
  75286. for (i = 0; i < dataLength;) {
  75287. cmd = data[i++];
  75288. cmdStr = '';
  75289. nPoint = 0;
  75290. switch (cmd) {
  75291. case M:
  75292. cmdStr = ' m ';
  75293. nPoint = 1;
  75294. xi = data[i++];
  75295. yi = data[i++];
  75296. points$3[0][0] = xi;
  75297. points$3[0][1] = yi;
  75298. break;
  75299. case L:
  75300. cmdStr = ' l ';
  75301. nPoint = 1;
  75302. xi = data[i++];
  75303. yi = data[i++];
  75304. points$3[0][0] = xi;
  75305. points$3[0][1] = yi;
  75306. break;
  75307. case Q:
  75308. case C:
  75309. cmdStr = ' c ';
  75310. nPoint = 3;
  75311. var x1 = data[i++];
  75312. var y1 = data[i++];
  75313. var x2 = data[i++];
  75314. var y2 = data[i++];
  75315. var x3;
  75316. var y3;
  75317. if (cmd === Q) {
  75318. // Convert quadratic to cubic using degree elevation
  75319. x3 = x2;
  75320. y3 = y2;
  75321. x2 = (x2 + 2 * x1) / 3;
  75322. y2 = (y2 + 2 * y1) / 3;
  75323. x1 = (xi + 2 * x1) / 3;
  75324. y1 = (yi + 2 * y1) / 3;
  75325. }
  75326. else {
  75327. x3 = data[i++];
  75328. y3 = data[i++];
  75329. }
  75330. points$3[0][0] = x1;
  75331. points$3[0][1] = y1;
  75332. points$3[1][0] = x2;
  75333. points$3[1][1] = y2;
  75334. points$3[2][0] = x3;
  75335. points$3[2][1] = y3;
  75336. xi = x3;
  75337. yi = y3;
  75338. break;
  75339. case A:
  75340. var x = 0;
  75341. var y = 0;
  75342. var sx = 1;
  75343. var sy = 1;
  75344. var angle = 0;
  75345. if (m) {
  75346. // Extract SRT from matrix
  75347. x = m[4];
  75348. y = m[5];
  75349. sx = sqrt(m[0] * m[0] + m[1] * m[1]);
  75350. sy = sqrt(m[2] * m[2] + m[3] * m[3]);
  75351. angle = Math.atan2(-m[1] / sy, m[0] / sx);
  75352. }
  75353. var cx = data[i++];
  75354. var cy = data[i++];
  75355. var rx = data[i++];
  75356. var ry = data[i++];
  75357. var startAngle = data[i++] + angle;
  75358. var endAngle = data[i++] + startAngle + angle;
  75359. // FIXME
  75360. // var psi = data[i++];
  75361. i++;
  75362. var clockwise = data[i++];
  75363. var x0 = cx + cos(startAngle) * rx;
  75364. var y0 = cy + sin(startAngle) * ry;
  75365. var x1 = cx + cos(endAngle) * rx;
  75366. var y1 = cy + sin(endAngle) * ry;
  75367. var type = clockwise ? ' wa ' : ' at ';
  75368. if (Math.abs(x0 - x1) < 1e-4) {
  75369. // IE won't render arches drawn counter clockwise if x0 == x1.
  75370. if (Math.abs(endAngle - startAngle) > 1e-2) {
  75371. // Offset x0 by 1/80 of a pixel. Use something
  75372. // that can be represented in binary
  75373. if (clockwise) {
  75374. x0 += 270 / Z;
  75375. }
  75376. }
  75377. else {
  75378. // Avoid case draw full circle
  75379. if (Math.abs(y0 - cy) < 1e-4) {
  75380. if ((clockwise && x0 < cx) || (!clockwise && x0 > cx)) {
  75381. y1 -= 270 / Z;
  75382. }
  75383. else {
  75384. y1 += 270 / Z;
  75385. }
  75386. }
  75387. else if ((clockwise && y0 < cy) || (!clockwise && y0 > cy)) {
  75388. x1 += 270 / Z;
  75389. }
  75390. else {
  75391. x1 -= 270 / Z;
  75392. }
  75393. }
  75394. }
  75395. str.push(
  75396. type,
  75397. round$3(((cx - rx) * sx + x) * Z - Z2), comma,
  75398. round$3(((cy - ry) * sy + y) * Z - Z2), comma,
  75399. round$3(((cx + rx) * sx + x) * Z - Z2), comma,
  75400. round$3(((cy + ry) * sy + y) * Z - Z2), comma,
  75401. round$3((x0 * sx + x) * Z - Z2), comma,
  75402. round$3((y0 * sy + y) * Z - Z2), comma,
  75403. round$3((x1 * sx + x) * Z - Z2), comma,
  75404. round$3((y1 * sy + y) * Z - Z2)
  75405. );
  75406. xi = x1;
  75407. yi = y1;
  75408. break;
  75409. case CMD$3.R:
  75410. var p0 = points$3[0];
  75411. var p1 = points$3[1];
  75412. // x0, y0
  75413. p0[0] = data[i++];
  75414. p0[1] = data[i++];
  75415. // x1, y1
  75416. p1[0] = p0[0] + data[i++];
  75417. p1[1] = p0[1] + data[i++];
  75418. if (m) {
  75419. applyTransform(p0, p0, m);
  75420. applyTransform(p1, p1, m);
  75421. }
  75422. p0[0] = round$3(p0[0] * Z - Z2);
  75423. p1[0] = round$3(p1[0] * Z - Z2);
  75424. p0[1] = round$3(p0[1] * Z - Z2);
  75425. p1[1] = round$3(p1[1] * Z - Z2);
  75426. str.push(
  75427. // x0, y0
  75428. ' m ', p0[0], comma, p0[1],
  75429. // x1, y0
  75430. ' l ', p1[0], comma, p0[1],
  75431. // x1, y1
  75432. ' l ', p1[0], comma, p1[1],
  75433. // x0, y1
  75434. ' l ', p0[0], comma, p1[1]
  75435. );
  75436. break;
  75437. case CMD$3.Z:
  75438. // FIXME Update xi, yi
  75439. str.push(' x ');
  75440. }
  75441. if (nPoint > 0) {
  75442. str.push(cmdStr);
  75443. for (var k = 0; k < nPoint; k++) {
  75444. var p = points$3[k];
  75445. m && applyTransform(p, p, m);
  75446. // 不 round 会非常慢
  75447. str.push(
  75448. round$3(p[0] * Z - Z2), comma, round$3(p[1] * Z - Z2),
  75449. k < nPoint - 1 ? comma : ''
  75450. );
  75451. }
  75452. }
  75453. }
  75454. return str.join('');
  75455. };
  75456. // Rewrite the original path method
  75457. Path.prototype.brushVML = function (vmlRoot) {
  75458. var style = this.style;
  75459. var vmlEl = this._vmlEl;
  75460. if (!vmlEl) {
  75461. vmlEl = createNode('shape');
  75462. initRootElStyle(vmlEl);
  75463. this._vmlEl = vmlEl;
  75464. }
  75465. updateFillAndStroke(vmlEl, 'fill', style, this);
  75466. updateFillAndStroke(vmlEl, 'stroke', style, this);
  75467. var m = this.transform;
  75468. var needTransform = m != null;
  75469. var strokeEl = vmlEl.getElementsByTagName('stroke')[0];
  75470. if (strokeEl) {
  75471. var lineWidth = style.lineWidth;
  75472. // Get the line scale.
  75473. // Determinant of this.m_ means how much the area is enlarged by the
  75474. // transformation. So its square root can be used as a scale factor
  75475. // for width.
  75476. if (needTransform && !style.strokeNoScale) {
  75477. var det = m[0] * m[3] - m[1] * m[2];
  75478. lineWidth *= sqrt(abs$1(det));
  75479. }
  75480. strokeEl.weight = lineWidth + 'px';
  75481. }
  75482. var path = this.path || (this.path = new PathProxy());
  75483. if (this.__dirtyPath) {
  75484. path.beginPath();
  75485. this.buildPath(path, this.shape);
  75486. path.toStatic();
  75487. this.__dirtyPath = false;
  75488. }
  75489. vmlEl.path = pathDataToString(path, this.transform);
  75490. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75491. // Append to root
  75492. append(vmlRoot, vmlEl);
  75493. // Text
  75494. if (style.text != null) {
  75495. this.drawRectText(vmlRoot, this.getBoundingRect());
  75496. }
  75497. else {
  75498. this.removeRectText(vmlRoot);
  75499. }
  75500. };
  75501. Path.prototype.onRemove = function (vmlRoot) {
  75502. remove(vmlRoot, this._vmlEl);
  75503. this.removeRectText(vmlRoot);
  75504. };
  75505. Path.prototype.onAdd = function (vmlRoot) {
  75506. append(vmlRoot, this._vmlEl);
  75507. this.appendRectText(vmlRoot);
  75508. };
  75509. /***************************************************
  75510. * IMAGE
  75511. **************************************************/
  75512. var isImage = function (img) {
  75513. // FIXME img instanceof Image 如果 img 是一个字符串的时候,IE8 下会报错
  75514. return (typeof img === 'object') && img.tagName && img.tagName.toUpperCase() === 'IMG';
  75515. // return img instanceof Image;
  75516. };
  75517. // Rewrite the original path method
  75518. ZImage.prototype.brushVML = function (vmlRoot) {
  75519. var style = this.style;
  75520. var image = style.image;
  75521. // Image original width, height
  75522. var ow;
  75523. var oh;
  75524. if (isImage(image)) {
  75525. var src = image.src;
  75526. if (src === this._imageSrc) {
  75527. ow = this._imageWidth;
  75528. oh = this._imageHeight;
  75529. }
  75530. else {
  75531. var imageRuntimeStyle = image.runtimeStyle;
  75532. var oldRuntimeWidth = imageRuntimeStyle.width;
  75533. var oldRuntimeHeight = imageRuntimeStyle.height;
  75534. imageRuntimeStyle.width = 'auto';
  75535. imageRuntimeStyle.height = 'auto';
  75536. // get the original size
  75537. ow = image.width;
  75538. oh = image.height;
  75539. // and remove overides
  75540. imageRuntimeStyle.width = oldRuntimeWidth;
  75541. imageRuntimeStyle.height = oldRuntimeHeight;
  75542. // Caching image original width, height and src
  75543. this._imageSrc = src;
  75544. this._imageWidth = ow;
  75545. this._imageHeight = oh;
  75546. }
  75547. image = src;
  75548. }
  75549. else {
  75550. if (image === this._imageSrc) {
  75551. ow = this._imageWidth;
  75552. oh = this._imageHeight;
  75553. }
  75554. }
  75555. if (!image) {
  75556. return;
  75557. }
  75558. var x = style.x || 0;
  75559. var y = style.y || 0;
  75560. var dw = style.width;
  75561. var dh = style.height;
  75562. var sw = style.sWidth;
  75563. var sh = style.sHeight;
  75564. var sx = style.sx || 0;
  75565. var sy = style.sy || 0;
  75566. var hasCrop = sw && sh;
  75567. var vmlEl = this._vmlEl;
  75568. if (!vmlEl) {
  75569. // FIXME 使用 group 在 left, top 都不是 0 的时候就无法显示了。
  75570. // vmlEl = vmlCore.createNode('group');
  75571. vmlEl = doc.createElement('div');
  75572. initRootElStyle(vmlEl);
  75573. this._vmlEl = vmlEl;
  75574. }
  75575. var vmlElStyle = vmlEl.style;
  75576. var hasRotation = false;
  75577. var m;
  75578. var scaleX = 1;
  75579. var scaleY = 1;
  75580. if (this.transform) {
  75581. m = this.transform;
  75582. scaleX = sqrt(m[0] * m[0] + m[1] * m[1]);
  75583. scaleY = sqrt(m[2] * m[2] + m[3] * m[3]);
  75584. hasRotation = m[1] || m[2];
  75585. }
  75586. if (hasRotation) {
  75587. // If filters are necessary (rotation exists), create them
  75588. // filters are bog-slow, so only create them if abbsolutely necessary
  75589. // The following check doesn't account for skews (which don't exist
  75590. // in the canvas spec (yet) anyway.
  75591. // From excanvas
  75592. var p0 = [x, y];
  75593. var p1 = [x + dw, y];
  75594. var p2 = [x, y + dh];
  75595. var p3 = [x + dw, y + dh];
  75596. applyTransform(p0, p0, m);
  75597. applyTransform(p1, p1, m);
  75598. applyTransform(p2, p2, m);
  75599. applyTransform(p3, p3, m);
  75600. var maxX = mathMax$8(p0[0], p1[0], p2[0], p3[0]);
  75601. var maxY = mathMax$8(p0[1], p1[1], p2[1], p3[1]);
  75602. var transformFilter = [];
  75603. transformFilter.push('M11=', m[0] / scaleX, comma,
  75604. 'M12=', m[2] / scaleY, comma,
  75605. 'M21=', m[1] / scaleX, comma,
  75606. 'M22=', m[3] / scaleY, comma,
  75607. 'Dx=', round$3(x * scaleX + m[4]), comma,
  75608. 'Dy=', round$3(y * scaleY + m[5]));
  75609. vmlElStyle.padding = '0 ' + round$3(maxX) + 'px ' + round$3(maxY) + 'px 0';
  75610. // FIXME DXImageTransform 在 IE11 的兼容模式下不起作用
  75611. vmlElStyle.filter = imageTransformPrefix + '.Matrix('
  75612. + transformFilter.join('') + ', SizingMethod=clip)';
  75613. }
  75614. else {
  75615. if (m) {
  75616. x = x * scaleX + m[4];
  75617. y = y * scaleY + m[5];
  75618. }
  75619. vmlElStyle.filter = '';
  75620. vmlElStyle.left = round$3(x) + 'px';
  75621. vmlElStyle.top = round$3(y) + 'px';
  75622. }
  75623. var imageEl = this._imageEl;
  75624. var cropEl = this._cropEl;
  75625. if (!imageEl) {
  75626. imageEl = doc.createElement('div');
  75627. this._imageEl = imageEl;
  75628. }
  75629. var imageELStyle = imageEl.style;
  75630. if (hasCrop) {
  75631. // Needs know image original width and height
  75632. if (! (ow && oh)) {
  75633. var tmpImage = new Image();
  75634. var self = this;
  75635. tmpImage.onload = function () {
  75636. tmpImage.onload = null;
  75637. ow = tmpImage.width;
  75638. oh = tmpImage.height;
  75639. // Adjust image width and height to fit the ratio destinationSize / sourceSize
  75640. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  75641. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  75642. // Caching image original width, height and src
  75643. self._imageWidth = ow;
  75644. self._imageHeight = oh;
  75645. self._imageSrc = image;
  75646. };
  75647. tmpImage.src = image;
  75648. }
  75649. else {
  75650. imageELStyle.width = round$3(scaleX * ow * dw / sw) + 'px';
  75651. imageELStyle.height = round$3(scaleY * oh * dh / sh) + 'px';
  75652. }
  75653. if (! cropEl) {
  75654. cropEl = doc.createElement('div');
  75655. cropEl.style.overflow = 'hidden';
  75656. this._cropEl = cropEl;
  75657. }
  75658. var cropElStyle = cropEl.style;
  75659. cropElStyle.width = round$3((dw + sx * dw / sw) * scaleX);
  75660. cropElStyle.height = round$3((dh + sy * dh / sh) * scaleY);
  75661. cropElStyle.filter = imageTransformPrefix + '.Matrix(Dx='
  75662. + (-sx * dw / sw * scaleX) + ',Dy=' + (-sy * dh / sh * scaleY) + ')';
  75663. if (! cropEl.parentNode) {
  75664. vmlEl.appendChild(cropEl);
  75665. }
  75666. if (imageEl.parentNode != cropEl) {
  75667. cropEl.appendChild(imageEl);
  75668. }
  75669. }
  75670. else {
  75671. imageELStyle.width = round$3(scaleX * dw) + 'px';
  75672. imageELStyle.height = round$3(scaleY * dh) + 'px';
  75673. vmlEl.appendChild(imageEl);
  75674. if (cropEl && cropEl.parentNode) {
  75675. vmlEl.removeChild(cropEl);
  75676. this._cropEl = null;
  75677. }
  75678. }
  75679. var filterStr = '';
  75680. var alpha = style.opacity;
  75681. if (alpha < 1) {
  75682. filterStr += '.Alpha(opacity=' + round$3(alpha * 100) + ') ';
  75683. }
  75684. filterStr += imageTransformPrefix + '.AlphaImageLoader(src=' + image + ', SizingMethod=scale)';
  75685. imageELStyle.filter = filterStr;
  75686. vmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75687. // Append to root
  75688. append(vmlRoot, vmlEl);
  75689. // Text
  75690. if (style.text != null) {
  75691. this.drawRectText(vmlRoot, this.getBoundingRect());
  75692. }
  75693. };
  75694. ZImage.prototype.onRemove = function (vmlRoot) {
  75695. remove(vmlRoot, this._vmlEl);
  75696. this._vmlEl = null;
  75697. this._cropEl = null;
  75698. this._imageEl = null;
  75699. this.removeRectText(vmlRoot);
  75700. };
  75701. ZImage.prototype.onAdd = function (vmlRoot) {
  75702. append(vmlRoot, this._vmlEl);
  75703. this.appendRectText(vmlRoot);
  75704. };
  75705. /***************************************************
  75706. * TEXT
  75707. **************************************************/
  75708. var DEFAULT_STYLE_NORMAL = 'normal';
  75709. var fontStyleCache = {};
  75710. var fontStyleCacheCount = 0;
  75711. var MAX_FONT_CACHE_SIZE = 100;
  75712. var fontEl = document.createElement('div');
  75713. var getFontStyle = function (fontString) {
  75714. var fontStyle = fontStyleCache[fontString];
  75715. if (!fontStyle) {
  75716. // Clear cache
  75717. if (fontStyleCacheCount > MAX_FONT_CACHE_SIZE) {
  75718. fontStyleCacheCount = 0;
  75719. fontStyleCache = {};
  75720. }
  75721. var style = fontEl.style;
  75722. var fontFamily;
  75723. try {
  75724. style.font = fontString;
  75725. fontFamily = style.fontFamily.split(',')[0];
  75726. }
  75727. catch (e) {
  75728. }
  75729. fontStyle = {
  75730. style: style.fontStyle || DEFAULT_STYLE_NORMAL,
  75731. variant: style.fontVariant || DEFAULT_STYLE_NORMAL,
  75732. weight: style.fontWeight || DEFAULT_STYLE_NORMAL,
  75733. size: parseFloat(style.fontSize || 12) | 0,
  75734. family: fontFamily || 'Microsoft YaHei'
  75735. };
  75736. fontStyleCache[fontString] = fontStyle;
  75737. fontStyleCacheCount++;
  75738. }
  75739. return fontStyle;
  75740. };
  75741. var textMeasureEl;
  75742. // Overwrite measure text method
  75743. $override$1('measureText', function (text, textFont) {
  75744. var doc$$1 = doc;
  75745. if (!textMeasureEl) {
  75746. textMeasureEl = doc$$1.createElement('div');
  75747. textMeasureEl.style.cssText = 'position:absolute;top:-20000px;left:0;'
  75748. + 'padding:0;margin:0;border:none;white-space:pre;';
  75749. doc.body.appendChild(textMeasureEl);
  75750. }
  75751. try {
  75752. textMeasureEl.style.font = textFont;
  75753. } catch (ex) {
  75754. // Ignore failures to set to invalid font.
  75755. }
  75756. textMeasureEl.innerHTML = '';
  75757. // Don't use innerHTML or innerText because they allow markup/whitespace.
  75758. textMeasureEl.appendChild(doc$$1.createTextNode(text));
  75759. return {
  75760. width: textMeasureEl.offsetWidth
  75761. };
  75762. });
  75763. var tmpRect$2 = new BoundingRect();
  75764. var drawRectText = function (vmlRoot, rect, textRect, fromTextEl) {
  75765. var style = this.style;
  75766. // Optimize, avoid normalize every time.
  75767. this.__dirty && normalizeTextStyle(style, true);
  75768. var text = style.text;
  75769. // Convert to string
  75770. text != null && (text += '');
  75771. if (!text) {
  75772. return;
  75773. }
  75774. // Convert rich text to plain text. Rich text is not supported in
  75775. // IE8-, but tags in rich text template will be removed.
  75776. if (style.rich) {
  75777. var contentBlock = parseRichText(text, style);
  75778. text = [];
  75779. for (var i = 0; i < contentBlock.lines.length; i++) {
  75780. var tokens = contentBlock.lines[i].tokens;
  75781. var textLine = [];
  75782. for (var j = 0; j < tokens.length; j++) {
  75783. textLine.push(tokens[j].text);
  75784. }
  75785. text.push(textLine.join(''));
  75786. }
  75787. text = text.join('\n');
  75788. }
  75789. var x;
  75790. var y;
  75791. var align = style.textAlign;
  75792. var verticalAlign = style.textVerticalAlign;
  75793. var fontStyle = getFontStyle(style.font);
  75794. // FIXME encodeHtmlAttribute ?
  75795. var font = fontStyle.style + ' ' + fontStyle.variant + ' ' + fontStyle.weight + ' '
  75796. + fontStyle.size + 'px "' + fontStyle.family + '"';
  75797. textRect = textRect || getBoundingRect(text, font, align, verticalAlign);
  75798. // Transform rect to view space
  75799. var m = this.transform;
  75800. // Ignore transform for text in other element
  75801. if (m && !fromTextEl) {
  75802. tmpRect$2.copy(rect);
  75803. tmpRect$2.applyTransform(m);
  75804. rect = tmpRect$2;
  75805. }
  75806. if (!fromTextEl) {
  75807. var textPosition = style.textPosition;
  75808. var distance$$1 = style.textDistance;
  75809. // Text position represented by coord
  75810. if (textPosition instanceof Array) {
  75811. x = rect.x + parsePercent$3(textPosition[0], rect.width);
  75812. y = rect.y + parsePercent$3(textPosition[1], rect.height);
  75813. align = align || 'left';
  75814. }
  75815. else {
  75816. var res = adjustTextPositionOnRect(
  75817. textPosition, rect, distance$$1
  75818. );
  75819. x = res.x;
  75820. y = res.y;
  75821. // Default align and baseline when has textPosition
  75822. align = align || res.textAlign;
  75823. verticalAlign = verticalAlign || res.textVerticalAlign;
  75824. }
  75825. }
  75826. else {
  75827. x = rect.x;
  75828. y = rect.y;
  75829. }
  75830. x = adjustTextX(x, textRect.width, align);
  75831. y = adjustTextY(y, textRect.height, verticalAlign);
  75832. // Force baseline 'middle'
  75833. y += textRect.height / 2;
  75834. // var fontSize = fontStyle.size;
  75835. // 1.75 is an arbitrary number, as there is no info about the text baseline
  75836. // switch (baseline) {
  75837. // case 'hanging':
  75838. // case 'top':
  75839. // y += fontSize / 1.75;
  75840. // break;
  75841. // case 'middle':
  75842. // break;
  75843. // default:
  75844. // // case null:
  75845. // // case 'alphabetic':
  75846. // // case 'ideographic':
  75847. // // case 'bottom':
  75848. // y -= fontSize / 2.25;
  75849. // break;
  75850. // }
  75851. // switch (align) {
  75852. // case 'left':
  75853. // break;
  75854. // case 'center':
  75855. // x -= textRect.width / 2;
  75856. // break;
  75857. // case 'right':
  75858. // x -= textRect.width;
  75859. // break;
  75860. // case 'end':
  75861. // align = elementStyle.direction == 'ltr' ? 'right' : 'left';
  75862. // break;
  75863. // case 'start':
  75864. // align = elementStyle.direction == 'rtl' ? 'right' : 'left';
  75865. // break;
  75866. // default:
  75867. // align = 'left';
  75868. // }
  75869. var createNode$$1 = createNode;
  75870. var textVmlEl = this._textVmlEl;
  75871. var pathEl;
  75872. var textPathEl;
  75873. var skewEl;
  75874. if (!textVmlEl) {
  75875. textVmlEl = createNode$$1('line');
  75876. pathEl = createNode$$1('path');
  75877. textPathEl = createNode$$1('textpath');
  75878. skewEl = createNode$$1('skew');
  75879. // FIXME Why here is not cammel case
  75880. // Align 'center' seems wrong
  75881. textPathEl.style['v-text-align'] = 'left';
  75882. initRootElStyle(textVmlEl);
  75883. pathEl.textpathok = true;
  75884. textPathEl.on = true;
  75885. textVmlEl.from = '0 0';
  75886. textVmlEl.to = '1000 0.05';
  75887. append(textVmlEl, skewEl);
  75888. append(textVmlEl, pathEl);
  75889. append(textVmlEl, textPathEl);
  75890. this._textVmlEl = textVmlEl;
  75891. }
  75892. else {
  75893. // 这里是在前面 appendChild 保证顺序的前提下
  75894. skewEl = textVmlEl.firstChild;
  75895. pathEl = skewEl.nextSibling;
  75896. textPathEl = pathEl.nextSibling;
  75897. }
  75898. var coords = [x, y];
  75899. var textVmlElStyle = textVmlEl.style;
  75900. // Ignore transform for text in other element
  75901. if (m && fromTextEl) {
  75902. applyTransform(coords, coords, m);
  75903. skewEl.on = true;
  75904. skewEl.matrix = m[0].toFixed(3) + comma + m[2].toFixed(3) + comma +
  75905. m[1].toFixed(3) + comma + m[3].toFixed(3) + ',0,0';
  75906. // Text position
  75907. skewEl.offset = (round$3(coords[0]) || 0) + ',' + (round$3(coords[1]) || 0);
  75908. // Left top point as origin
  75909. skewEl.origin = '0 0';
  75910. textVmlElStyle.left = '0px';
  75911. textVmlElStyle.top = '0px';
  75912. }
  75913. else {
  75914. skewEl.on = false;
  75915. textVmlElStyle.left = round$3(x) + 'px';
  75916. textVmlElStyle.top = round$3(y) + 'px';
  75917. }
  75918. textPathEl.string = encodeHtmlAttribute(text);
  75919. // TODO
  75920. try {
  75921. textPathEl.style.font = font;
  75922. }
  75923. // Error font format
  75924. catch (e) {}
  75925. updateFillAndStroke(textVmlEl, 'fill', {
  75926. fill: style.textFill,
  75927. opacity: style.opacity
  75928. }, this);
  75929. updateFillAndStroke(textVmlEl, 'stroke', {
  75930. stroke: style.textStroke,
  75931. opacity: style.opacity,
  75932. lineDash: style.lineDash
  75933. }, this);
  75934. textVmlEl.style.zIndex = getZIndex(this.zlevel, this.z, this.z2);
  75935. // Attached to root
  75936. append(vmlRoot, textVmlEl);
  75937. };
  75938. var removeRectText = function (vmlRoot) {
  75939. remove(vmlRoot, this._textVmlEl);
  75940. this._textVmlEl = null;
  75941. };
  75942. var appendRectText = function (vmlRoot) {
  75943. append(vmlRoot, this._textVmlEl);
  75944. };
  75945. var list = [RectText, Displayable, ZImage, Path, Text];
  75946. // In case Displayable has been mixed in RectText
  75947. for (var i$3 = 0; i$3 < list.length; i$3++) {
  75948. var proto$8 = list[i$3].prototype;
  75949. proto$8.drawRectText = drawRectText;
  75950. proto$8.removeRectText = removeRectText;
  75951. proto$8.appendRectText = appendRectText;
  75952. }
  75953. Text.prototype.brushVML = function (vmlRoot) {
  75954. var style = this.style;
  75955. if (style.text != null) {
  75956. this.drawRectText(vmlRoot, {
  75957. x: style.x || 0, y: style.y || 0,
  75958. width: 0, height: 0
  75959. }, this.getBoundingRect(), true);
  75960. }
  75961. else {
  75962. this.removeRectText(vmlRoot);
  75963. }
  75964. };
  75965. Text.prototype.onRemove = function (vmlRoot) {
  75966. this.removeRectText(vmlRoot);
  75967. };
  75968. Text.prototype.onAdd = function (vmlRoot) {
  75969. this.appendRectText(vmlRoot);
  75970. };
  75971. }
  75972. /**
  75973. * VML Painter.
  75974. *
  75975. * @module zrender/vml/Painter
  75976. */
  75977. function parseInt10$1(val) {
  75978. return parseInt(val, 10);
  75979. }
  75980. /**
  75981. * @alias module:zrender/vml/Painter
  75982. */
  75983. function VMLPainter(root, storage) {
  75984. initVML();
  75985. this.root = root;
  75986. this.storage = storage;
  75987. var vmlViewport = document.createElement('div');
  75988. var vmlRoot = document.createElement('div');
  75989. vmlViewport.style.cssText = 'display:inline-block;overflow:hidden;position:relative;width:300px;height:150px;';
  75990. vmlRoot.style.cssText = 'position:absolute;left:0;top:0;';
  75991. root.appendChild(vmlViewport);
  75992. this._vmlRoot = vmlRoot;
  75993. this._vmlViewport = vmlViewport;
  75994. this.resize();
  75995. // Modify storage
  75996. var oldDelFromStorage = storage.delFromStorage;
  75997. var oldAddToStorage = storage.addToStorage;
  75998. storage.delFromStorage = function (el) {
  75999. oldDelFromStorage.call(storage, el);
  76000. if (el) {
  76001. el.onRemove && el.onRemove(vmlRoot);
  76002. }
  76003. };
  76004. storage.addToStorage = function (el) {
  76005. // Displayable already has a vml node
  76006. el.onAdd && el.onAdd(vmlRoot);
  76007. oldAddToStorage.call(storage, el);
  76008. };
  76009. this._firstPaint = true;
  76010. }
  76011. VMLPainter.prototype = {
  76012. constructor: VMLPainter,
  76013. getType: function () {
  76014. return 'vml';
  76015. },
  76016. /**
  76017. * @return {HTMLDivElement}
  76018. */
  76019. getViewportRoot: function () {
  76020. return this._vmlViewport;
  76021. },
  76022. getViewportRootOffset: function () {
  76023. var viewportRoot = this.getViewportRoot();
  76024. if (viewportRoot) {
  76025. return {
  76026. offsetLeft: viewportRoot.offsetLeft || 0,
  76027. offsetTop: viewportRoot.offsetTop || 0
  76028. };
  76029. }
  76030. },
  76031. /**
  76032. * 刷新
  76033. */
  76034. refresh: function () {
  76035. var list = this.storage.getDisplayList(true, true);
  76036. this._paintList(list);
  76037. },
  76038. _paintList: function (list) {
  76039. var vmlRoot = this._vmlRoot;
  76040. for (var i = 0; i < list.length; i++) {
  76041. var el = list[i];
  76042. if (el.invisible || el.ignore) {
  76043. if (!el.__alreadyNotVisible) {
  76044. el.onRemove(vmlRoot);
  76045. }
  76046. // Set as already invisible
  76047. el.__alreadyNotVisible = true;
  76048. }
  76049. else {
  76050. if (el.__alreadyNotVisible) {
  76051. el.onAdd(vmlRoot);
  76052. }
  76053. el.__alreadyNotVisible = false;
  76054. if (el.__dirty) {
  76055. el.beforeBrush && el.beforeBrush();
  76056. (el.brushVML || el.brush).call(el, vmlRoot);
  76057. el.afterBrush && el.afterBrush();
  76058. }
  76059. }
  76060. el.__dirty = false;
  76061. }
  76062. if (this._firstPaint) {
  76063. // Detached from document at first time
  76064. // to avoid page refreshing too many times
  76065. // FIXME 如果每次都先 removeChild 可能会导致一些填充和描边的效果改变
  76066. this._vmlViewport.appendChild(vmlRoot);
  76067. this._firstPaint = false;
  76068. }
  76069. },
  76070. resize: function (width, height) {
  76071. var width = width == null ? this._getWidth() : width;
  76072. var height = height == null ? this._getHeight() : height;
  76073. if (this._width != width || this._height != height) {
  76074. this._width = width;
  76075. this._height = height;
  76076. var vmlViewportStyle = this._vmlViewport.style;
  76077. vmlViewportStyle.width = width + 'px';
  76078. vmlViewportStyle.height = height + 'px';
  76079. }
  76080. },
  76081. dispose: function () {
  76082. this.root.innerHTML = '';
  76083. this._vmlRoot =
  76084. this._vmlViewport =
  76085. this.storage = null;
  76086. },
  76087. getWidth: function () {
  76088. return this._width;
  76089. },
  76090. getHeight: function () {
  76091. return this._height;
  76092. },
  76093. clear: function () {
  76094. if (this._vmlViewport) {
  76095. this.root.removeChild(this._vmlViewport);
  76096. }
  76097. },
  76098. _getWidth: function () {
  76099. var root = this.root;
  76100. var stl = root.currentStyle;
  76101. return ((root.clientWidth || parseInt10$1(stl.width))
  76102. - parseInt10$1(stl.paddingLeft)
  76103. - parseInt10$1(stl.paddingRight)) | 0;
  76104. },
  76105. _getHeight: function () {
  76106. var root = this.root;
  76107. var stl = root.currentStyle;
  76108. return ((root.clientHeight || parseInt10$1(stl.height))
  76109. - parseInt10$1(stl.paddingTop)
  76110. - parseInt10$1(stl.paddingBottom)) | 0;
  76111. }
  76112. };
  76113. // Not supported methods
  76114. function createMethodNotSupport(method) {
  76115. return function () {
  76116. zrLog('In IE8.0 VML mode painter not support method "' + method + '"');
  76117. };
  76118. }
  76119. // Unsupported methods
  76120. each$1([
  76121. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer', 'eachOtherLayer', 'getLayers',
  76122. 'modLayer', 'delLayer', 'clearLayer', 'toDataURL', 'pathToImage'
  76123. ], function (name) {
  76124. VMLPainter.prototype[name] = createMethodNotSupport(name);
  76125. });
  76126. registerPainter('vml', VMLPainter);
  76127. var svgURI = 'http://www.w3.org/2000/svg';
  76128. function createElement(name) {
  76129. return document.createElementNS(svgURI, name);
  76130. }
  76131. // TODO
  76132. // 1. shadow
  76133. // 2. Image: sx, sy, sw, sh
  76134. var CMD$4 = PathProxy.CMD;
  76135. var arrayJoin = Array.prototype.join;
  76136. var NONE = 'none';
  76137. var mathRound = Math.round;
  76138. var mathSin$3 = Math.sin;
  76139. var mathCos$3 = Math.cos;
  76140. var PI$5 = Math.PI;
  76141. var PI2$7 = Math.PI * 2;
  76142. var degree = 180 / PI$5;
  76143. var EPSILON$4 = 1e-4;
  76144. function round4(val) {
  76145. return mathRound(val * 1e4) / 1e4;
  76146. }
  76147. function isAroundZero$1(val) {
  76148. return val < EPSILON$4 && val > -EPSILON$4;
  76149. }
  76150. function pathHasFill(style, isText) {
  76151. var fill = isText ? style.textFill : style.fill;
  76152. return fill != null && fill !== NONE;
  76153. }
  76154. function pathHasStroke(style, isText) {
  76155. var stroke = isText ? style.textStroke : style.stroke;
  76156. return stroke != null && stroke !== NONE;
  76157. }
  76158. function setTransform(svgEl, m) {
  76159. if (m) {
  76160. attr(svgEl, 'transform', 'matrix(' + arrayJoin.call(m, ',') + ')');
  76161. }
  76162. }
  76163. function attr(el, key, val) {
  76164. if (!val || val.type !== 'linear' && val.type !== 'radial') {
  76165. // Don't set attribute for gradient, since it need new dom nodes
  76166. if (typeof val === 'string' && val.indexOf('NaN') > -1) {
  76167. console.log(val);
  76168. }
  76169. el.setAttribute(key, val);
  76170. }
  76171. }
  76172. function attrXLink(el, key, val) {
  76173. el.setAttributeNS('http://www.w3.org/1999/xlink', key, val);
  76174. }
  76175. function bindStyle(svgEl, style, isText) {
  76176. if (pathHasFill(style, isText)) {
  76177. var fill = isText ? style.textFill : style.fill;
  76178. fill = fill === 'transparent' ? NONE : fill;
  76179. /**
  76180. * FIXME:
  76181. * This is a temporary fix for Chrome's clipping bug
  76182. * that happens when a clip-path is referring another one.
  76183. * This fix should be used before Chrome's bug is fixed.
  76184. * For an element that has clip-path, and fill is none,
  76185. * set it to be "rgba(0, 0, 0, 0.002)" will hide the element.
  76186. * Otherwise, it will show black fill color.
  76187. * 0.002 is used because this won't work for alpha values smaller
  76188. * than 0.002.
  76189. *
  76190. * See
  76191. * https://bugs.chromium.org/p/chromium/issues/detail?id=659790
  76192. * for more information.
  76193. */
  76194. if (svgEl.getAttribute('clip-path') !== 'none' && fill === NONE) {
  76195. fill = 'rgba(0, 0, 0, 0.002)';
  76196. }
  76197. attr(svgEl, 'fill', fill);
  76198. attr(svgEl, 'fill-opacity', style.opacity);
  76199. }
  76200. else {
  76201. attr(svgEl, 'fill', NONE);
  76202. }
  76203. if (pathHasStroke(style, isText)) {
  76204. var stroke = isText ? style.textStroke : style.stroke;
  76205. stroke = stroke === 'transparent' ? NONE : stroke;
  76206. attr(svgEl, 'stroke', stroke);
  76207. var strokeWidth = isText
  76208. ? style.textStrokeWidth
  76209. : style.lineWidth;
  76210. var strokeScale = !isText && style.strokeNoScale
  76211. ? style.host.getLineScale()
  76212. : 1;
  76213. attr(svgEl, 'stroke-width', strokeWidth / strokeScale);
  76214. // stroke then fill for text; fill then stroke for others
  76215. attr(svgEl, 'paint-order', isText ? 'stroke' : 'fill');
  76216. attr(svgEl, 'stroke-opacity', style.opacity);
  76217. var lineDash = style.lineDash;
  76218. if (lineDash) {
  76219. attr(svgEl, 'stroke-dasharray', style.lineDash.join(','));
  76220. attr(svgEl, 'stroke-dashoffset', mathRound(style.lineDashOffset || 0));
  76221. }
  76222. else {
  76223. attr(svgEl, 'stroke-dasharray', '');
  76224. }
  76225. // PENDING
  76226. style.lineCap && attr(svgEl, 'stroke-linecap', style.lineCap);
  76227. style.lineJoin && attr(svgEl, 'stroke-linejoin', style.lineJoin);
  76228. style.miterLimit && attr(svgEl, 'stroke-miterlimit', style.miterLimit);
  76229. }
  76230. else {
  76231. attr(svgEl, 'stroke', NONE);
  76232. }
  76233. }
  76234. /***************************************************
  76235. * PATH
  76236. **************************************************/
  76237. function pathDataToString$1(path) {
  76238. var str = [];
  76239. var data = path.data;
  76240. var dataLength = path.len();
  76241. for (var i = 0; i < dataLength;) {
  76242. var cmd = data[i++];
  76243. var cmdStr = '';
  76244. var nData = 0;
  76245. switch (cmd) {
  76246. case CMD$4.M:
  76247. cmdStr = 'M';
  76248. nData = 2;
  76249. break;
  76250. case CMD$4.L:
  76251. cmdStr = 'L';
  76252. nData = 2;
  76253. break;
  76254. case CMD$4.Q:
  76255. cmdStr = 'Q';
  76256. nData = 4;
  76257. break;
  76258. case CMD$4.C:
  76259. cmdStr = 'C';
  76260. nData = 6;
  76261. break;
  76262. case CMD$4.A:
  76263. var cx = data[i++];
  76264. var cy = data[i++];
  76265. var rx = data[i++];
  76266. var ry = data[i++];
  76267. var theta = data[i++];
  76268. var dTheta = data[i++];
  76269. var psi = data[i++];
  76270. var clockwise = data[i++];
  76271. var dThetaPositive = Math.abs(dTheta);
  76272. var isCircle = isAroundZero$1(dThetaPositive - PI2$7)
  76273. && !isAroundZero$1(dThetaPositive);
  76274. var large = false;
  76275. if (dThetaPositive >= PI2$7) {
  76276. large = true;
  76277. }
  76278. else if (isAroundZero$1(dThetaPositive)) {
  76279. large = false;
  76280. }
  76281. else {
  76282. large = (dTheta > -PI$5 && dTheta < 0 || dTheta > PI$5)
  76283. === !!clockwise;
  76284. }
  76285. var x0 = round4(cx + rx * mathCos$3(theta));
  76286. var y0 = round4(cy + ry * mathSin$3(theta));
  76287. // It will not draw if start point and end point are exactly the same
  76288. // We need to shift the end point with a small value
  76289. // FIXME A better way to draw circle ?
  76290. if (isCircle) {
  76291. if (clockwise) {
  76292. dTheta = PI2$7 - 1e-4;
  76293. }
  76294. else {
  76295. dTheta = -PI2$7 + 1e-4;
  76296. }
  76297. large = true;
  76298. if (i === 9) {
  76299. // Move to (x0, y0) only when CMD.A comes at the
  76300. // first position of a shape.
  76301. // For instance, when drawing a ring, CMD.A comes
  76302. // after CMD.M, so it's unnecessary to move to
  76303. // (x0, y0).
  76304. str.push('M', x0, y0);
  76305. }
  76306. }
  76307. var x = round4(cx + rx * mathCos$3(theta + dTheta));
  76308. var y = round4(cy + ry * mathSin$3(theta + dTheta));
  76309. // FIXME Ellipse
  76310. str.push('A', round4(rx), round4(ry),
  76311. mathRound(psi * degree), +large, +clockwise, x, y);
  76312. break;
  76313. case CMD$4.Z:
  76314. cmdStr = 'Z';
  76315. break;
  76316. case CMD$4.R:
  76317. var x = round4(data[i++]);
  76318. var y = round4(data[i++]);
  76319. var w = round4(data[i++]);
  76320. var h = round4(data[i++]);
  76321. str.push(
  76322. 'M', x, y,
  76323. 'L', x + w, y,
  76324. 'L', x + w, y + h,
  76325. 'L', x, y + h,
  76326. 'L', x, y
  76327. );
  76328. break;
  76329. }
  76330. cmdStr && str.push(cmdStr);
  76331. for (var j = 0; j < nData; j++) {
  76332. // PENDING With scale
  76333. str.push(round4(data[i++]));
  76334. }
  76335. }
  76336. return str.join(' ');
  76337. }
  76338. var svgPath = {};
  76339. svgPath.brush = function (el) {
  76340. var style = el.style;
  76341. var svgEl = el.__svgEl;
  76342. if (!svgEl) {
  76343. svgEl = createElement('path');
  76344. el.__svgEl = svgEl;
  76345. }
  76346. if (!el.path) {
  76347. el.createPathProxy();
  76348. }
  76349. var path = el.path;
  76350. if (el.__dirtyPath) {
  76351. path.beginPath();
  76352. el.buildPath(path, el.shape);
  76353. el.__dirtyPath = false;
  76354. var pathStr = pathDataToString$1(path);
  76355. if (pathStr.indexOf('NaN') < 0) {
  76356. // Ignore illegal path, which may happen such in out-of-range
  76357. // data in Calendar series.
  76358. attr(svgEl, 'd', pathStr);
  76359. }
  76360. }
  76361. bindStyle(svgEl, style);
  76362. setTransform(svgEl, el.transform);
  76363. if (style.text != null) {
  76364. svgTextDrawRectText(el, el.getBoundingRect());
  76365. }
  76366. };
  76367. /***************************************************
  76368. * IMAGE
  76369. **************************************************/
  76370. var svgImage = {};
  76371. svgImage.brush = function (el) {
  76372. var style = el.style;
  76373. var image = style.image;
  76374. if (image instanceof HTMLImageElement) {
  76375. var src = image.src;
  76376. image = src;
  76377. }
  76378. if (! image) {
  76379. return;
  76380. }
  76381. var x = style.x || 0;
  76382. var y = style.y || 0;
  76383. var dw = style.width;
  76384. var dh = style.height;
  76385. var svgEl = el.__svgEl;
  76386. if (! svgEl) {
  76387. svgEl = createElement('image');
  76388. el.__svgEl = svgEl;
  76389. }
  76390. if (image !== el.__imageSrc) {
  76391. attrXLink(svgEl, 'href', image);
  76392. // Caching image src
  76393. el.__imageSrc = image;
  76394. }
  76395. attr(svgEl, 'width', dw);
  76396. attr(svgEl, 'height', dh);
  76397. attr(svgEl, 'x', x);
  76398. attr(svgEl, 'y', y);
  76399. setTransform(svgEl, el.transform);
  76400. if (style.text != null) {
  76401. svgTextDrawRectText(el, el.getBoundingRect());
  76402. }
  76403. };
  76404. /***************************************************
  76405. * TEXT
  76406. **************************************************/
  76407. var svgText = {};
  76408. var tmpRect$3 = new BoundingRect();
  76409. var svgTextDrawRectText = function (el, rect, textRect) {
  76410. var style = el.style;
  76411. el.__dirty && normalizeTextStyle(style, true);
  76412. var text = style.text;
  76413. // Convert to string
  76414. if (text == null) {
  76415. // Draw no text only when text is set to null, but not ''
  76416. return;
  76417. }
  76418. else {
  76419. text += '';
  76420. }
  76421. var textSvgEl = el.__textSvgEl;
  76422. if (! textSvgEl) {
  76423. textSvgEl = createElement('text');
  76424. el.__textSvgEl = textSvgEl;
  76425. }
  76426. var x;
  76427. var y;
  76428. var textPosition = style.textPosition;
  76429. var distance = style.textDistance;
  76430. var align = style.textAlign || 'left';
  76431. if (typeof style.fontSize === 'number') {
  76432. style.fontSize += 'px';
  76433. }
  76434. var font = style.font
  76435. || [
  76436. style.fontStyle || '',
  76437. style.fontWeight || '',
  76438. style.fontSize || '',
  76439. style.fontFamily || ''
  76440. ].join(' ')
  76441. || DEFAULT_FONT;
  76442. var verticalAlign = getVerticalAlignForSvg(style.textVerticalAlign);
  76443. textRect = getBoundingRect(text, font, align,
  76444. verticalAlign);
  76445. var lineHeight = textRect.lineHeight;
  76446. // Text position represented by coord
  76447. if (textPosition instanceof Array) {
  76448. x = rect.x + textPosition[0];
  76449. y = rect.y + textPosition[1];
  76450. }
  76451. else {
  76452. var newPos = adjustTextPositionOnRect(
  76453. textPosition, rect, distance
  76454. );
  76455. x = newPos.x;
  76456. y = newPos.y;
  76457. verticalAlign = getVerticalAlignForSvg(newPos.textVerticalAlign);
  76458. align = newPos.textAlign;
  76459. }
  76460. attr(textSvgEl, 'alignment-baseline', verticalAlign);
  76461. if (font) {
  76462. textSvgEl.style.font = font;
  76463. }
  76464. var textPadding = style.textPadding;
  76465. // Make baseline top
  76466. attr(textSvgEl, 'x', x);
  76467. attr(textSvgEl, 'y', y);
  76468. bindStyle(textSvgEl, style, true);
  76469. if (el instanceof Text || el.style.transformText) {
  76470. // Transform text with element
  76471. setTransform(textSvgEl, el.transform);
  76472. }
  76473. else {
  76474. if (el.transform) {
  76475. tmpRect$3.copy(rect);
  76476. tmpRect$3.applyTransform(el.transform);
  76477. rect = tmpRect$3;
  76478. }
  76479. else {
  76480. var pos = el.transformCoordToGlobal(rect.x, rect.y);
  76481. rect.x = pos[0];
  76482. rect.y = pos[1];
  76483. }
  76484. // Text rotation, but no element transform
  76485. var origin = style.textOrigin;
  76486. if (origin === 'center') {
  76487. x = textRect.width / 2 + x;
  76488. y = textRect.height / 2 + y;
  76489. }
  76490. else if (origin) {
  76491. x = origin[0] + x;
  76492. y = origin[1] + y;
  76493. }
  76494. var rotate$$1 = -style.textRotation || 0;
  76495. var transform = create$1();
  76496. // Apply textRotate to element matrix
  76497. rotate(transform, el.transform, rotate$$1);
  76498. setTransform(textSvgEl, transform);
  76499. }
  76500. var textLines = text.split('\n');
  76501. var nTextLines = textLines.length;
  76502. var textAnchor = align;
  76503. // PENDING
  76504. if (textAnchor === 'left') {
  76505. textAnchor = 'start';
  76506. textPadding && (x += textPadding[3]);
  76507. }
  76508. else if (textAnchor === 'right') {
  76509. textAnchor = 'end';
  76510. textPadding && (x -= textPadding[1]);
  76511. }
  76512. else if (textAnchor === 'center') {
  76513. textAnchor = 'middle';
  76514. textPadding && (x += (textPadding[3] - textPadding[1]) / 2);
  76515. }
  76516. var dy = 0;
  76517. if (verticalAlign === 'baseline') {
  76518. dy = -textRect.height + lineHeight;
  76519. textPadding && (dy -= textPadding[2]);
  76520. }
  76521. else if (verticalAlign === 'middle') {
  76522. dy = (-textRect.height + lineHeight) / 2;
  76523. textPadding && (y += (textPadding[0] - textPadding[2]) / 2);
  76524. }
  76525. else {
  76526. textPadding && (dy += textPadding[0]);
  76527. }
  76528. // Font may affect position of each tspan elements
  76529. if (el.__text !== text || el.__textFont !== font) {
  76530. var tspanList = el.__tspanList || [];
  76531. el.__tspanList = tspanList;
  76532. for (var i = 0; i < nTextLines; i++) {
  76533. // Using cached tspan elements
  76534. var tspan = tspanList[i];
  76535. if (! tspan) {
  76536. tspan = tspanList[i] = createElement('tspan');
  76537. textSvgEl.appendChild(tspan);
  76538. attr(tspan, 'alignment-baseline', verticalAlign);
  76539. attr(tspan, 'text-anchor', textAnchor);
  76540. }
  76541. else {
  76542. tspan.innerHTML = '';
  76543. }
  76544. attr(tspan, 'x', x);
  76545. attr(tspan, 'y', y + i * lineHeight + dy);
  76546. tspan.appendChild(document.createTextNode(textLines[i]));
  76547. }
  76548. // Remove unsed tspan elements
  76549. for (; i < tspanList.length; i++) {
  76550. textSvgEl.removeChild(tspanList[i]);
  76551. }
  76552. tspanList.length = nTextLines;
  76553. el.__text = text;
  76554. el.__textFont = font;
  76555. }
  76556. else if (el.__tspanList.length) {
  76557. // Update span x and y
  76558. var len = el.__tspanList.length;
  76559. for (var i = 0; i < len; ++i) {
  76560. var tspan = el.__tspanList[i];
  76561. if (tspan) {
  76562. attr(tspan, 'x', x);
  76563. attr(tspan, 'y', y + i * lineHeight + dy);
  76564. }
  76565. }
  76566. }
  76567. };
  76568. function getVerticalAlignForSvg(verticalAlign) {
  76569. if (verticalAlign === 'middle') {
  76570. return 'middle';
  76571. }
  76572. else if (verticalAlign === 'bottom') {
  76573. return 'baseline';
  76574. }
  76575. else {
  76576. return 'hanging';
  76577. }
  76578. }
  76579. svgText.drawRectText = svgTextDrawRectText;
  76580. svgText.brush = function (el) {
  76581. var style = el.style;
  76582. if (style.text != null) {
  76583. // 强制设置 textPosition
  76584. style.textPosition = [0, 0];
  76585. svgTextDrawRectText(el, {
  76586. x: style.x || 0, y: style.y || 0,
  76587. width: 0, height: 0
  76588. }, el.getBoundingRect());
  76589. }
  76590. };
  76591. // Myers' Diff Algorithm
  76592. // Modified from https://github.com/kpdecker/jsdiff/blob/master/src/diff/base.js
  76593. function Diff() {}
  76594. Diff.prototype = {
  76595. diff: function (oldArr, newArr, equals) {
  76596. if (!equals) {
  76597. equals = function (a, b) {
  76598. return a === b;
  76599. };
  76600. }
  76601. this.equals = equals;
  76602. var self = this;
  76603. oldArr = oldArr.slice();
  76604. newArr = newArr.slice();
  76605. // Allow subclasses to massage the input prior to running
  76606. var newLen = newArr.length;
  76607. var oldLen = oldArr.length;
  76608. var editLength = 1;
  76609. var maxEditLength = newLen + oldLen;
  76610. var bestPath = [{ newPos: -1, components: [] }];
  76611. // Seed editLength = 0, i.e. the content starts with the same values
  76612. var oldPos = this.extractCommon(bestPath[0], newArr, oldArr, 0);
  76613. if (bestPath[0].newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  76614. var indices = [];
  76615. for (var i = 0; i < newArr.length; i++) {
  76616. indices.push(i);
  76617. }
  76618. // Identity per the equality and tokenizer
  76619. return [{
  76620. indices: indices, count: newArr.length
  76621. }];
  76622. }
  76623. // Main worker method. checks all permutations of a given edit length for acceptance.
  76624. function execEditLength() {
  76625. for (var diagonalPath = -1 * editLength; diagonalPath <= editLength; diagonalPath += 2) {
  76626. var basePath;
  76627. var addPath = bestPath[diagonalPath - 1];
  76628. var removePath = bestPath[diagonalPath + 1];
  76629. var oldPos = (removePath ? removePath.newPos : 0) - diagonalPath;
  76630. if (addPath) {
  76631. // No one else is going to attempt to use this value, clear it
  76632. bestPath[diagonalPath - 1] = undefined;
  76633. }
  76634. var canAdd = addPath && addPath.newPos + 1 < newLen;
  76635. var canRemove = removePath && 0 <= oldPos && oldPos < oldLen;
  76636. if (!canAdd && !canRemove) {
  76637. // If this path is a terminal then prune
  76638. bestPath[diagonalPath] = undefined;
  76639. continue;
  76640. }
  76641. // Select the diagonal that we want to branch from. We select the prior
  76642. // path whose position in the new string is the farthest from the origin
  76643. // and does not pass the bounds of the diff graph
  76644. if (!canAdd || (canRemove && addPath.newPos < removePath.newPos)) {
  76645. basePath = clonePath(removePath);
  76646. self.pushComponent(basePath.components, undefined, true);
  76647. }
  76648. else {
  76649. basePath = addPath; // No need to clone, we've pulled it from the list
  76650. basePath.newPos++;
  76651. self.pushComponent(basePath.components, true, undefined);
  76652. }
  76653. oldPos = self.extractCommon(basePath, newArr, oldArr, diagonalPath);
  76654. // If we have hit the end of both strings, then we are done
  76655. if (basePath.newPos + 1 >= newLen && oldPos + 1 >= oldLen) {
  76656. return buildValues(self, basePath.components, newArr, oldArr);
  76657. }
  76658. else {
  76659. // Otherwise track this path as a potential candidate and continue.
  76660. bestPath[diagonalPath] = basePath;
  76661. }
  76662. }
  76663. editLength++;
  76664. }
  76665. while (editLength <= maxEditLength) {
  76666. var ret = execEditLength();
  76667. if (ret) {
  76668. return ret;
  76669. }
  76670. }
  76671. },
  76672. pushComponent: function (components, added, removed) {
  76673. var last = components[components.length - 1];
  76674. if (last && last.added === added && last.removed === removed) {
  76675. // We need to clone here as the component clone operation is just
  76676. // as shallow array clone
  76677. components[components.length - 1] = {count: last.count + 1, added: added, removed: removed };
  76678. }
  76679. else {
  76680. components.push({count: 1, added: added, removed: removed });
  76681. }
  76682. },
  76683. extractCommon: function (basePath, newArr, oldArr, diagonalPath) {
  76684. var newLen = newArr.length;
  76685. var oldLen = oldArr.length;
  76686. var newPos = basePath.newPos;
  76687. var oldPos = newPos - diagonalPath;
  76688. var commonCount = 0;
  76689. while (newPos + 1 < newLen && oldPos + 1 < oldLen && this.equals(newArr[newPos + 1], oldArr[oldPos + 1])) {
  76690. newPos++;
  76691. oldPos++;
  76692. commonCount++;
  76693. }
  76694. if (commonCount) {
  76695. basePath.components.push({count: commonCount});
  76696. }
  76697. basePath.newPos = newPos;
  76698. return oldPos;
  76699. },
  76700. tokenize: function (value) {
  76701. return value.slice();
  76702. },
  76703. join: function (value) {
  76704. return value.slice();
  76705. }
  76706. };
  76707. function buildValues(diff, components, newArr, oldArr) {
  76708. var componentPos = 0;
  76709. var componentLen = components.length;
  76710. var newPos = 0;
  76711. var oldPos = 0;
  76712. for (; componentPos < componentLen; componentPos++) {
  76713. var component = components[componentPos];
  76714. if (!component.removed) {
  76715. var indices = [];
  76716. for (var i = newPos; i < newPos + component.count; i++) {
  76717. indices.push(i);
  76718. }
  76719. component.indices = indices;
  76720. newPos += component.count;
  76721. // Common case
  76722. if (!component.added) {
  76723. oldPos += component.count;
  76724. }
  76725. }
  76726. else {
  76727. var indices = [];
  76728. for (var i = oldPos; i < oldPos + component.count; i++) {
  76729. indices.push(i);
  76730. }
  76731. component.indices = indices;
  76732. oldPos += component.count;
  76733. }
  76734. }
  76735. return components;
  76736. }
  76737. function clonePath(path) {
  76738. return { newPos: path.newPos, components: path.components.slice(0) };
  76739. }
  76740. var arrayDiff = new Diff();
  76741. var arrayDiff$1 = function (oldArr, newArr, callback) {
  76742. return arrayDiff.diff(oldArr, newArr, callback);
  76743. };
  76744. /**
  76745. * @file Manages elements that can be defined in <defs> in SVG,
  76746. * e.g., gradients, clip path, etc.
  76747. * @author Zhang Wenli
  76748. */
  76749. var MARK_UNUSED = '0';
  76750. var MARK_USED = '1';
  76751. /**
  76752. * Manages elements that can be defined in <defs> in SVG,
  76753. * e.g., gradients, clip path, etc.
  76754. *
  76755. * @class
  76756. * @param {number} zrId zrender instance id
  76757. * @param {SVGElement} svgRoot root of SVG document
  76758. * @param {string|string[]} tagNames possible tag names
  76759. * @param {string} markLabel label name to make if the element
  76760. * is used
  76761. */
  76762. function Definable(
  76763. zrId,
  76764. svgRoot,
  76765. tagNames,
  76766. markLabel,
  76767. domName
  76768. ) {
  76769. this._zrId = zrId;
  76770. this._svgRoot = svgRoot;
  76771. this._tagNames = typeof tagNames === 'string' ? [tagNames] : tagNames;
  76772. this._markLabel = markLabel;
  76773. this._domName = domName || '_dom';
  76774. this.nextId = 0;
  76775. }
  76776. Definable.prototype.createElement = createElement;
  76777. /**
  76778. * Get the <defs> tag for svgRoot; optionally creates one if not exists.
  76779. *
  76780. * @param {boolean} isForceCreating if need to create when not exists
  76781. * @return {SVGDefsElement} SVG <defs> element, null if it doesn't
  76782. * exist and isForceCreating is false
  76783. */
  76784. Definable.prototype.getDefs = function (isForceCreating) {
  76785. var svgRoot = this._svgRoot;
  76786. var defs = this._svgRoot.getElementsByTagName('defs');
  76787. if (defs.length === 0) {
  76788. // Not exist
  76789. if (isForceCreating) {
  76790. defs = svgRoot.insertBefore(
  76791. this.createElement('defs'), // Create new tag
  76792. svgRoot.firstChild // Insert in the front of svg
  76793. );
  76794. if (!defs.contains) {
  76795. // IE doesn't support contains method
  76796. defs.contains = function (el) {
  76797. var children = defs.children;
  76798. if (!children) {
  76799. return false;
  76800. }
  76801. for (var i = children.length - 1; i >= 0; --i) {
  76802. if (children[i] === el) {
  76803. return true;
  76804. }
  76805. }
  76806. return false;
  76807. };
  76808. }
  76809. return defs;
  76810. }
  76811. else {
  76812. return null;
  76813. }
  76814. }
  76815. else {
  76816. return defs[0];
  76817. }
  76818. };
  76819. /**
  76820. * Update DOM element if necessary.
  76821. *
  76822. * @param {Object|string} element style element. e.g., for gradient,
  76823. * it may be '#ccc' or {type: 'linear', ...}
  76824. * @param {Function|undefined} onUpdate update callback
  76825. */
  76826. Definable.prototype.update = function (element, onUpdate) {
  76827. if (!element) {
  76828. return;
  76829. }
  76830. var defs = this.getDefs(false);
  76831. if (element[this._domName] && defs.contains(element[this._domName])) {
  76832. // Update DOM
  76833. if (typeof onUpdate === 'function') {
  76834. onUpdate(element);
  76835. }
  76836. }
  76837. else {
  76838. // No previous dom, create new
  76839. var dom = this.add(element);
  76840. if (dom) {
  76841. element[this._domName] = dom;
  76842. }
  76843. }
  76844. };
  76845. /**
  76846. * Add gradient dom to defs
  76847. *
  76848. * @param {SVGElement} dom DOM to be added to <defs>
  76849. */
  76850. Definable.prototype.addDom = function (dom) {
  76851. var defs = this.getDefs(true);
  76852. defs.appendChild(dom);
  76853. };
  76854. /**
  76855. * Remove DOM of a given element.
  76856. *
  76857. * @param {SVGElement} element element to remove dom
  76858. */
  76859. Definable.prototype.removeDom = function (element) {
  76860. var defs = this.getDefs(false);
  76861. if (defs && element[this._domName]) {
  76862. defs.removeChild(element[this._domName]);
  76863. element[this._domName] = null;
  76864. }
  76865. };
  76866. /**
  76867. * Get DOMs of this element.
  76868. *
  76869. * @return {HTMLDomElement} doms of this defineable elements in <defs>
  76870. */
  76871. Definable.prototype.getDoms = function () {
  76872. var defs = this.getDefs(false);
  76873. if (!defs) {
  76874. // No dom when defs is not defined
  76875. return [];
  76876. }
  76877. var doms = [];
  76878. each$1(this._tagNames, function (tagName) {
  76879. var tags = defs.getElementsByTagName(tagName);
  76880. // Note that tags is HTMLCollection, which is array-like
  76881. // rather than real array.
  76882. // So `doms.concat(tags)` add tags as one object.
  76883. doms = doms.concat([].slice.call(tags));
  76884. });
  76885. return doms;
  76886. };
  76887. /**
  76888. * Mark DOMs to be unused before painting, and clear unused ones at the end
  76889. * of the painting.
  76890. */
  76891. Definable.prototype.markAllUnused = function () {
  76892. var doms = this.getDoms();
  76893. var that = this;
  76894. each$1(doms, function (dom) {
  76895. dom[that._markLabel] = MARK_UNUSED;
  76896. });
  76897. };
  76898. /**
  76899. * Mark a single DOM to be used.
  76900. *
  76901. * @param {SVGElement} dom DOM to mark
  76902. */
  76903. Definable.prototype.markUsed = function (dom) {
  76904. if (dom) {
  76905. dom[this._markLabel] = MARK_USED;
  76906. }
  76907. };
  76908. /**
  76909. * Remove unused DOMs defined in <defs>
  76910. */
  76911. Definable.prototype.removeUnused = function () {
  76912. var defs = this.getDefs(false);
  76913. if (!defs) {
  76914. // Nothing to remove
  76915. return;
  76916. }
  76917. var doms = this.getDoms();
  76918. var that = this;
  76919. each$1(doms, function (dom) {
  76920. if (dom[that._markLabel] !== MARK_USED) {
  76921. // Remove gradient
  76922. defs.removeChild(dom);
  76923. }
  76924. });
  76925. };
  76926. /**
  76927. * Get SVG proxy.
  76928. *
  76929. * @param {Displayable} displayable displayable element
  76930. * @return {Path|Image|Text} svg proxy of given element
  76931. */
  76932. Definable.prototype.getSvgProxy = function (displayable) {
  76933. if (displayable instanceof Path) {
  76934. return svgPath;
  76935. }
  76936. else if (displayable instanceof ZImage) {
  76937. return svgImage;
  76938. }
  76939. else if (displayable instanceof Text) {
  76940. return svgText;
  76941. }
  76942. else {
  76943. return svgPath;
  76944. }
  76945. };
  76946. /**
  76947. * Get text SVG element.
  76948. *
  76949. * @param {Displayable} displayable displayable element
  76950. * @return {SVGElement} SVG element of text
  76951. */
  76952. Definable.prototype.getTextSvgElement = function (displayable) {
  76953. return displayable.__textSvgEl;
  76954. };
  76955. /**
  76956. * Get SVG element.
  76957. *
  76958. * @param {Displayable} displayable displayable element
  76959. * @return {SVGElement} SVG element
  76960. */
  76961. Definable.prototype.getSvgElement = function (displayable) {
  76962. return displayable.__svgEl;
  76963. };
  76964. /**
  76965. * @file Manages SVG gradient elements.
  76966. * @author Zhang Wenli
  76967. */
  76968. /**
  76969. * Manages SVG gradient elements.
  76970. *
  76971. * @class
  76972. * @extends Definable
  76973. * @param {number} zrId zrender instance id
  76974. * @param {SVGElement} svgRoot root of SVG document
  76975. */
  76976. function GradientManager(zrId, svgRoot) {
  76977. Definable.call(
  76978. this,
  76979. zrId,
  76980. svgRoot,
  76981. ['linearGradient', 'radialGradient'],
  76982. '__gradient_in_use__'
  76983. );
  76984. }
  76985. inherits(GradientManager, Definable);
  76986. /**
  76987. * Create new gradient DOM for fill or stroke if not exist,
  76988. * but will not update gradient if exists.
  76989. *
  76990. * @param {SvgElement} svgElement SVG element to paint
  76991. * @param {Displayable} displayable zrender displayable element
  76992. */
  76993. GradientManager.prototype.addWithoutUpdate = function (
  76994. svgElement,
  76995. displayable
  76996. ) {
  76997. if (displayable && displayable.style) {
  76998. var that = this;
  76999. each$1(['fill', 'stroke'], function (fillOrStroke) {
  77000. if (displayable.style[fillOrStroke]
  77001. && (displayable.style[fillOrStroke].type === 'linear'
  77002. || displayable.style[fillOrStroke].type === 'radial')
  77003. ) {
  77004. var gradient = displayable.style[fillOrStroke];
  77005. var defs = that.getDefs(true);
  77006. // Create dom in <defs> if not exists
  77007. var dom;
  77008. if (gradient._dom) {
  77009. // Gradient exists
  77010. dom = gradient._dom;
  77011. if (!defs.contains(gradient._dom)) {
  77012. // _dom is no longer in defs, recreate
  77013. that.addDom(dom);
  77014. }
  77015. }
  77016. else {
  77017. // New dom
  77018. dom = that.add(gradient);
  77019. }
  77020. that.markUsed(displayable);
  77021. var id = dom.getAttribute('id');
  77022. svgElement.setAttribute(fillOrStroke, 'url(#' + id + ')');
  77023. }
  77024. });
  77025. }
  77026. };
  77027. /**
  77028. * Add a new gradient tag in <defs>
  77029. *
  77030. * @param {Gradient} gradient zr gradient instance
  77031. * @return {SVGLinearGradientElement | SVGRadialGradientElement}
  77032. * created DOM
  77033. */
  77034. GradientManager.prototype.add = function (gradient) {
  77035. var dom;
  77036. if (gradient.type === 'linear') {
  77037. dom = this.createElement('linearGradient');
  77038. }
  77039. else if (gradient.type === 'radial') {
  77040. dom = this.createElement('radialGradient');
  77041. }
  77042. else {
  77043. zrLog('Illegal gradient type.');
  77044. return null;
  77045. }
  77046. // Set dom id with gradient id, since each gradient instance
  77047. // will have no more than one dom element.
  77048. // id may exists before for those dirty elements, in which case
  77049. // id should remain the same, and other attributes should be
  77050. // updated.
  77051. gradient.id = gradient.id || this.nextId++;
  77052. dom.setAttribute('id', 'zr' + this._zrId
  77053. + '-gradient-' + gradient.id);
  77054. this.updateDom(gradient, dom);
  77055. this.addDom(dom);
  77056. return dom;
  77057. };
  77058. /**
  77059. * Update gradient.
  77060. *
  77061. * @param {Gradient} gradient zr gradient instance
  77062. */
  77063. GradientManager.prototype.update = function (gradient) {
  77064. var that = this;
  77065. Definable.prototype.update.call(this, gradient, function () {
  77066. var type = gradient.type;
  77067. var tagName = gradient._dom.tagName;
  77068. if (type === 'linear' && tagName === 'linearGradient'
  77069. || type === 'radial' && tagName === 'radialGradient'
  77070. ) {
  77071. // Gradient type is not changed, update gradient
  77072. that.updateDom(gradient, gradient._dom);
  77073. }
  77074. else {
  77075. // Remove and re-create if type is changed
  77076. that.removeDom(gradient);
  77077. that.add(gradient);
  77078. }
  77079. });
  77080. };
  77081. /**
  77082. * Update gradient dom
  77083. *
  77084. * @param {Gradient} gradient zr gradient instance
  77085. * @param {SVGLinearGradientElement | SVGRadialGradientElement} dom
  77086. * DOM to update
  77087. */
  77088. GradientManager.prototype.updateDom = function (gradient, dom) {
  77089. if (gradient.type === 'linear') {
  77090. dom.setAttribute('x1', gradient.x);
  77091. dom.setAttribute('y1', gradient.y);
  77092. dom.setAttribute('x2', gradient.x2);
  77093. dom.setAttribute('y2', gradient.y2);
  77094. }
  77095. else if (gradient.type === 'radial') {
  77096. dom.setAttribute('cx', gradient.x);
  77097. dom.setAttribute('cy', gradient.y);
  77098. dom.setAttribute('r', gradient.r);
  77099. }
  77100. else {
  77101. zrLog('Illegal gradient type.');
  77102. return;
  77103. }
  77104. if (gradient.global) {
  77105. // x1, x2, y1, y2 in range of 0 to canvas width or height
  77106. dom.setAttribute('gradientUnits', 'userSpaceOnUse');
  77107. }
  77108. else {
  77109. // x1, x2, y1, y2 in range of 0 to 1
  77110. dom.setAttribute('gradientUnits', 'objectBoundingBox');
  77111. }
  77112. // Remove color stops if exists
  77113. dom.innerHTML = '';
  77114. // Add color stops
  77115. var colors = gradient.colorStops;
  77116. for (var i = 0, len = colors.length; i < len; ++i) {
  77117. var stop = this.createElement('stop');
  77118. stop.setAttribute('offset', colors[i].offset * 100 + '%');
  77119. stop.setAttribute('stop-color', colors[i].color);
  77120. dom.appendChild(stop);
  77121. }
  77122. // Store dom element in gradient, to avoid creating multiple
  77123. // dom instances for the same gradient element
  77124. gradient._dom = dom;
  77125. };
  77126. /**
  77127. * Mark a single gradient to be used
  77128. *
  77129. * @param {Displayable} displayable displayable element
  77130. */
  77131. GradientManager.prototype.markUsed = function (displayable) {
  77132. if (displayable.style) {
  77133. var gradient = displayable.style.fill;
  77134. if (gradient && gradient._dom) {
  77135. Definable.prototype.markUsed.call(this, gradient._dom);
  77136. }
  77137. gradient = displayable.style.stroke;
  77138. if (gradient && gradient._dom) {
  77139. Definable.prototype.markUsed.call(this, gradient._dom);
  77140. }
  77141. }
  77142. };
  77143. /**
  77144. * @file Manages SVG clipPath elements.
  77145. * @author Zhang Wenli
  77146. */
  77147. /**
  77148. * Manages SVG clipPath elements.
  77149. *
  77150. * @class
  77151. * @extends Definable
  77152. * @param {number} zrId zrender instance id
  77153. * @param {SVGElement} svgRoot root of SVG document
  77154. */
  77155. function ClippathManager(zrId, svgRoot) {
  77156. Definable.call(this, zrId, svgRoot, 'clipPath', '__clippath_in_use__');
  77157. }
  77158. inherits(ClippathManager, Definable);
  77159. /**
  77160. * Update clipPath.
  77161. *
  77162. * @param {Displayable} displayable displayable element
  77163. */
  77164. ClippathManager.prototype.update = function (displayable) {
  77165. var svgEl = this.getSvgElement(displayable);
  77166. if (svgEl) {
  77167. this.updateDom(svgEl, displayable.__clipPaths, false);
  77168. }
  77169. var textEl = this.getTextSvgElement(displayable);
  77170. if (textEl) {
  77171. // Make another clipPath for text, since it's transform
  77172. // matrix is not the same with svgElement
  77173. this.updateDom(textEl, displayable.__clipPaths, true);
  77174. }
  77175. this.markUsed(displayable);
  77176. };
  77177. /**
  77178. * Create an SVGElement of displayable and create a <clipPath> of its
  77179. * clipPath
  77180. *
  77181. * @param {Displayable} parentEl parent element
  77182. * @param {ClipPath[]} clipPaths clipPaths of parent element
  77183. * @param {boolean} isText if parent element is Text
  77184. */
  77185. ClippathManager.prototype.updateDom = function (
  77186. parentEl,
  77187. clipPaths,
  77188. isText
  77189. ) {
  77190. if (clipPaths && clipPaths.length > 0) {
  77191. // Has clipPath, create <clipPath> with the first clipPath
  77192. var defs = this.getDefs(true);
  77193. var clipPath = clipPaths[0];
  77194. var clipPathEl;
  77195. var id;
  77196. var dom = isText ? '_textDom' : '_dom';
  77197. if (clipPath[dom]) {
  77198. // Use a dom that is already in <defs>
  77199. id = clipPath[dom].getAttribute('id');
  77200. clipPathEl = clipPath[dom];
  77201. // Use a dom that is already in <defs>
  77202. if (!defs.contains(clipPathEl)) {
  77203. // This happens when set old clipPath that has
  77204. // been previously removed
  77205. defs.appendChild(clipPathEl);
  77206. }
  77207. }
  77208. else {
  77209. // New <clipPath>
  77210. id = 'zr' + this._zrId + '-clip-' + this.nextId;
  77211. ++this.nextId;
  77212. clipPathEl = this.createElement('clipPath');
  77213. clipPathEl.setAttribute('id', id);
  77214. defs.appendChild(clipPathEl);
  77215. clipPath[dom] = clipPathEl;
  77216. }
  77217. // Build path and add to <clipPath>
  77218. var svgProxy = this.getSvgProxy(clipPath);
  77219. if (clipPath.transform
  77220. && clipPath.parent.invTransform
  77221. && !isText
  77222. ) {
  77223. /**
  77224. * If a clipPath has a parent with transform, the transform
  77225. * of parent should not be considered when setting transform
  77226. * of clipPath. So we need to transform back from parent's
  77227. * transform, which is done by multiplying parent's inverse
  77228. * transform.
  77229. */
  77230. // Store old transform
  77231. var transform = Array.prototype.slice.call(
  77232. clipPath.transform
  77233. );
  77234. // Transform back from parent, and brush path
  77235. mul$1(
  77236. clipPath.transform,
  77237. clipPath.parent.invTransform,
  77238. clipPath.transform
  77239. );
  77240. svgProxy.brush(clipPath);
  77241. // Set back transform of clipPath
  77242. clipPath.transform = transform;
  77243. }
  77244. else {
  77245. svgProxy.brush(clipPath);
  77246. }
  77247. var pathEl = this.getSvgElement(clipPath);
  77248. clipPathEl.innerHTML = '';
  77249. /**
  77250. * Use `cloneNode()` here to appendChild to multiple parents,
  77251. * which may happend when Text and other shapes are using the same
  77252. * clipPath. Since Text will create an extra clipPath DOM due to
  77253. * different transform rules.
  77254. */
  77255. clipPathEl.appendChild(pathEl.cloneNode());
  77256. parentEl.setAttribute('clip-path', 'url(#' + id + ')');
  77257. if (clipPaths.length > 1) {
  77258. // Make the other clipPaths recursively
  77259. this.updateDom(clipPathEl, clipPaths.slice(1), isText);
  77260. }
  77261. }
  77262. else {
  77263. // No clipPath
  77264. if (parentEl) {
  77265. parentEl.setAttribute('clip-path', 'none');
  77266. }
  77267. }
  77268. };
  77269. /**
  77270. * Mark a single clipPath to be used
  77271. *
  77272. * @param {Displayable} displayable displayable element
  77273. */
  77274. ClippathManager.prototype.markUsed = function (displayable) {
  77275. var that = this;
  77276. if (displayable.__clipPaths && displayable.__clipPaths.length > 0) {
  77277. each$1(displayable.__clipPaths, function (clipPath) {
  77278. if (clipPath._dom) {
  77279. Definable.prototype.markUsed.call(that, clipPath._dom);
  77280. }
  77281. if (clipPath._textDom) {
  77282. Definable.prototype.markUsed.call(that, clipPath._textDom);
  77283. }
  77284. });
  77285. }
  77286. };
  77287. /**
  77288. * @file Manages SVG shadow elements.
  77289. * @author Zhang Wenli
  77290. */
  77291. /**
  77292. * Manages SVG shadow elements.
  77293. *
  77294. * @class
  77295. * @extends Definable
  77296. * @param {number} zrId zrender instance id
  77297. * @param {SVGElement} svgRoot root of SVG document
  77298. */
  77299. function ShadowManager(zrId, svgRoot) {
  77300. Definable.call(
  77301. this,
  77302. zrId,
  77303. svgRoot,
  77304. ['filter'],
  77305. '__filter_in_use__',
  77306. '_shadowDom'
  77307. );
  77308. }
  77309. inherits(ShadowManager, Definable);
  77310. /**
  77311. * Create new shadow DOM for fill or stroke if not exist,
  77312. * but will not update shadow if exists.
  77313. *
  77314. * @param {SvgElement} svgElement SVG element to paint
  77315. * @param {Displayable} displayable zrender displayable element
  77316. */
  77317. ShadowManager.prototype.addWithoutUpdate = function (
  77318. svgElement,
  77319. displayable
  77320. ) {
  77321. if (displayable && hasShadow(displayable.style)) {
  77322. var style = displayable.style;
  77323. // Create dom in <defs> if not exists
  77324. var dom;
  77325. if (style._shadowDom) {
  77326. // Gradient exists
  77327. dom = style._shadowDom;
  77328. var defs = this.getDefs(true);
  77329. if (!defs.contains(style._shadowDom)) {
  77330. // _shadowDom is no longer in defs, recreate
  77331. this.addDom(dom);
  77332. }
  77333. }
  77334. else {
  77335. // New dom
  77336. dom = this.add(displayable);
  77337. }
  77338. this.markUsed(displayable);
  77339. var id = dom.getAttribute('id');
  77340. svgElement.style.filter = 'url(#' + id + ')';
  77341. }
  77342. };
  77343. /**
  77344. * Add a new shadow tag in <defs>
  77345. *
  77346. * @param {Displayable} displayable zrender displayable element
  77347. * @return {SVGFilterElement} created DOM
  77348. */
  77349. ShadowManager.prototype.add = function (displayable) {
  77350. var dom = this.createElement('filter');
  77351. var style = displayable.style;
  77352. // Set dom id with shadow id, since each shadow instance
  77353. // will have no more than one dom element.
  77354. // id may exists before for those dirty elements, in which case
  77355. // id should remain the same, and other attributes should be
  77356. // updated.
  77357. style._shadowDomId = style._shadowDomId || this.nextId++;
  77358. dom.setAttribute('id', 'zr' + this._zrId
  77359. + '-shadow-' + style._shadowDomId);
  77360. this.updateDom(displayable, dom);
  77361. this.addDom(dom);
  77362. return dom;
  77363. };
  77364. /**
  77365. * Update shadow.
  77366. *
  77367. * @param {Displayable} displayable zrender displayable element
  77368. */
  77369. ShadowManager.prototype.update = function (svgElement, displayable) {
  77370. var style = displayable.style;
  77371. if (hasShadow(style)) {
  77372. var that = this;
  77373. Definable.prototype.update.call(this, displayable, function (style) {
  77374. that.updateDom(displayable, style._shadowDom);
  77375. });
  77376. }
  77377. else {
  77378. // Remove shadow
  77379. this.remove(svgElement, style);
  77380. }
  77381. };
  77382. /**
  77383. * Remove DOM and clear parent filter
  77384. */
  77385. ShadowManager.prototype.remove = function (svgElement, style) {
  77386. if (style._shadowDomId != null) {
  77387. this.removeDom(style);
  77388. svgElement.style.filter = '';
  77389. }
  77390. };
  77391. /**
  77392. * Update shadow dom
  77393. *
  77394. * @param {Displayable} displayable zrender displayable element
  77395. * @param {SVGFilterElement} dom DOM to update
  77396. */
  77397. ShadowManager.prototype.updateDom = function (displayable, dom) {
  77398. var domChild = dom.getElementsByTagName('feDropShadow');
  77399. if (domChild.length === 0) {
  77400. domChild = this.createElement('feDropShadow');
  77401. }
  77402. else {
  77403. domChild = domChild[0];
  77404. }
  77405. var style = displayable.style;
  77406. var scaleX = displayable.scale ? (displayable.scale[0] || 1) : 1;
  77407. var scaleY = displayable.scale ? (displayable.scale[1] || 1) : 1;
  77408. // TODO: textBoxShadowBlur is not supported yet
  77409. var offsetX, offsetY, blur, color;
  77410. if (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY) {
  77411. offsetX = style.shadowOffsetX || 0;
  77412. offsetY = style.shadowOffsetY || 0;
  77413. blur = style.shadowBlur;
  77414. color = style.shadowColor;
  77415. }
  77416. else if (style.textShadowBlur) {
  77417. offsetX = style.textShadowOffsetX || 0;
  77418. offsetY = style.textShadowOffsetY || 0;
  77419. blur = style.textShadowBlur;
  77420. color = style.textShadowColor;
  77421. }
  77422. else {
  77423. // Remove shadow
  77424. this.removeDom(dom, style);
  77425. return;
  77426. }
  77427. domChild.setAttribute('dx', offsetX / scaleX);
  77428. domChild.setAttribute('dy', offsetY / scaleY);
  77429. domChild.setAttribute('flood-color', color);
  77430. // Divide by two here so that it looks the same as in canvas
  77431. // See: https://html.spec.whatwg.org/multipage/canvas.html#dom-context-2d-shadowblur
  77432. var stdDx = blur / 2 / scaleX;
  77433. var stdDy = blur / 2 / scaleY;
  77434. var stdDeviation = stdDx + ' ' + stdDy;
  77435. domChild.setAttribute('stdDeviation', stdDeviation);
  77436. // Fix filter clipping problem
  77437. dom.setAttribute('x', '-100%');
  77438. dom.setAttribute('y', '-100%');
  77439. dom.setAttribute('width', Math.ceil(blur / 2 * 200) + '%');
  77440. dom.setAttribute('height', Math.ceil(blur / 2 * 200) + '%');
  77441. dom.appendChild(domChild);
  77442. // Store dom element in shadow, to avoid creating multiple
  77443. // dom instances for the same shadow element
  77444. style._shadowDom = dom;
  77445. };
  77446. /**
  77447. * Mark a single shadow to be used
  77448. *
  77449. * @param {Displayable} displayable displayable element
  77450. */
  77451. ShadowManager.prototype.markUsed = function (displayable) {
  77452. var style = displayable.style;
  77453. if (style && style._shadowDom) {
  77454. Definable.prototype.markUsed.call(this, style._shadowDom);
  77455. }
  77456. };
  77457. function hasShadow(style) {
  77458. // TODO: textBoxShadowBlur is not supported yet
  77459. return style
  77460. && (style.shadowBlur || style.shadowOffsetX || style.shadowOffsetY
  77461. || style.textShadowBlur || style.textShadowOffsetX
  77462. || style.textShadowOffsetY);
  77463. }
  77464. /**
  77465. * SVG Painter
  77466. * @module zrender/svg/Painter
  77467. */
  77468. function parseInt10$2(val) {
  77469. return parseInt(val, 10);
  77470. }
  77471. function getSvgProxy(el) {
  77472. if (el instanceof Path) {
  77473. return svgPath;
  77474. }
  77475. else if (el instanceof ZImage) {
  77476. return svgImage;
  77477. }
  77478. else if (el instanceof Text) {
  77479. return svgText;
  77480. }
  77481. else {
  77482. return svgPath;
  77483. }
  77484. }
  77485. function checkParentAvailable(parent, child) {
  77486. return child && parent && child.parentNode !== parent;
  77487. }
  77488. function insertAfter(parent, child, prevSibling) {
  77489. if (checkParentAvailable(parent, child) && prevSibling) {
  77490. var nextSibling = prevSibling.nextSibling;
  77491. nextSibling ? parent.insertBefore(child, nextSibling)
  77492. : parent.appendChild(child);
  77493. }
  77494. }
  77495. function prepend(parent, child) {
  77496. if (checkParentAvailable(parent, child)) {
  77497. var firstChild = parent.firstChild;
  77498. firstChild ? parent.insertBefore(child, firstChild)
  77499. : parent.appendChild(child);
  77500. }
  77501. }
  77502. function remove$1(parent, child) {
  77503. if (child && parent && child.parentNode === parent) {
  77504. parent.removeChild(child);
  77505. }
  77506. }
  77507. function getTextSvgElement(displayable) {
  77508. return displayable.__textSvgEl;
  77509. }
  77510. function getSvgElement(displayable) {
  77511. return displayable.__svgEl;
  77512. }
  77513. /**
  77514. * @alias module:zrender/svg/Painter
  77515. * @constructor
  77516. * @param {HTMLElement} root 绘图容器
  77517. * @param {module:zrender/Storage} storage
  77518. * @param {Object} opts
  77519. */
  77520. var SVGPainter = function (root, storage, opts, zrId) {
  77521. this.root = root;
  77522. this.storage = storage;
  77523. this._opts = opts = extend({}, opts || {});
  77524. var svgRoot = createElement('svg');
  77525. svgRoot.setAttribute('xmlns', 'http://www.w3.org/2000/svg');
  77526. svgRoot.setAttribute('version', '1.1');
  77527. svgRoot.setAttribute('baseProfile', 'full');
  77528. svgRoot.style.cssText = 'user-select:none;position:absolute;left:0;top:0;';
  77529. this.gradientManager = new GradientManager(zrId, svgRoot);
  77530. this.clipPathManager = new ClippathManager(zrId, svgRoot);
  77531. this.shadowManager = new ShadowManager(zrId, svgRoot);
  77532. var viewport = document.createElement('div');
  77533. viewport.style.cssText = 'overflow:hidden;position:relative';
  77534. this._svgRoot = svgRoot;
  77535. this._viewport = viewport;
  77536. root.appendChild(viewport);
  77537. viewport.appendChild(svgRoot);
  77538. this.resize(opts.width, opts.height);
  77539. this._visibleList = [];
  77540. };
  77541. SVGPainter.prototype = {
  77542. constructor: SVGPainter,
  77543. getType: function () {
  77544. return 'svg';
  77545. },
  77546. getViewportRoot: function () {
  77547. return this._viewport;
  77548. },
  77549. getViewportRootOffset: function () {
  77550. var viewportRoot = this.getViewportRoot();
  77551. if (viewportRoot) {
  77552. return {
  77553. offsetLeft: viewportRoot.offsetLeft || 0,
  77554. offsetTop: viewportRoot.offsetTop || 0
  77555. };
  77556. }
  77557. },
  77558. refresh: function () {
  77559. var list = this.storage.getDisplayList(true);
  77560. this._paintList(list);
  77561. },
  77562. setBackgroundColor: function (backgroundColor) {
  77563. // TODO gradient
  77564. this._viewport.style.background = backgroundColor;
  77565. },
  77566. _paintList: function (list) {
  77567. this.gradientManager.markAllUnused();
  77568. this.clipPathManager.markAllUnused();
  77569. this.shadowManager.markAllUnused();
  77570. var svgRoot = this._svgRoot;
  77571. var visibleList = this._visibleList;
  77572. var listLen = list.length;
  77573. var newVisibleList = [];
  77574. var i;
  77575. for (i = 0; i < listLen; i++) {
  77576. var displayable = list[i];
  77577. var svgProxy = getSvgProxy(displayable);
  77578. var svgElement = getSvgElement(displayable)
  77579. || getTextSvgElement(displayable);
  77580. if (!displayable.invisible) {
  77581. if (displayable.__dirty) {
  77582. svgProxy && svgProxy.brush(displayable);
  77583. // Update clipPath
  77584. this.clipPathManager.update(displayable);
  77585. // Update gradient and shadow
  77586. if (displayable.style) {
  77587. this.gradientManager
  77588. .update(displayable.style.fill);
  77589. this.gradientManager
  77590. .update(displayable.style.stroke);
  77591. this.shadowManager
  77592. .update(svgElement, displayable);
  77593. }
  77594. displayable.__dirty = false;
  77595. }
  77596. newVisibleList.push(displayable);
  77597. }
  77598. }
  77599. var diff = arrayDiff$1(visibleList, newVisibleList);
  77600. var prevSvgElement;
  77601. // First do remove, in case element moved to the head and do remove
  77602. // after add
  77603. for (i = 0; i < diff.length; i++) {
  77604. var item = diff[i];
  77605. if (item.removed) {
  77606. for (var k = 0; k < item.count; k++) {
  77607. var displayable = visibleList[item.indices[k]];
  77608. var svgElement = getSvgElement(displayable);
  77609. var textSvgElement = getTextSvgElement(displayable);
  77610. remove$1(svgRoot, svgElement);
  77611. remove$1(svgRoot, textSvgElement);
  77612. }
  77613. }
  77614. }
  77615. for (i = 0; i < diff.length; i++) {
  77616. var item = diff[i];
  77617. if (item.added) {
  77618. for (var k = 0; k < item.count; k++) {
  77619. var displayable = newVisibleList[item.indices[k]];
  77620. var svgElement = getSvgElement(displayable);
  77621. var textSvgElement = getTextSvgElement(displayable);
  77622. prevSvgElement
  77623. ? insertAfter(svgRoot, svgElement, prevSvgElement)
  77624. : prepend(svgRoot, svgElement);
  77625. if (svgElement) {
  77626. insertAfter(svgRoot, textSvgElement, svgElement);
  77627. }
  77628. else if (prevSvgElement) {
  77629. insertAfter(
  77630. svgRoot, textSvgElement, prevSvgElement
  77631. );
  77632. }
  77633. else {
  77634. prepend(svgRoot, textSvgElement);
  77635. }
  77636. // Insert text
  77637. insertAfter(svgRoot, textSvgElement, svgElement);
  77638. prevSvgElement = textSvgElement || svgElement
  77639. || prevSvgElement;
  77640. this.gradientManager
  77641. .addWithoutUpdate(svgElement, displayable);
  77642. this.shadowManager
  77643. .addWithoutUpdate(prevSvgElement, displayable);
  77644. this.clipPathManager.markUsed(displayable);
  77645. }
  77646. }
  77647. else if (!item.removed) {
  77648. for (var k = 0; k < item.count; k++) {
  77649. var displayable = newVisibleList[item.indices[k]];
  77650. prevSvgElement
  77651. = svgElement
  77652. = getTextSvgElement(displayable)
  77653. || getSvgElement(displayable)
  77654. || prevSvgElement;
  77655. this.gradientManager.markUsed(displayable);
  77656. this.gradientManager
  77657. .addWithoutUpdate(svgElement, displayable);
  77658. this.shadowManager.markUsed(displayable);
  77659. this.shadowManager
  77660. .addWithoutUpdate(svgElement, displayable);
  77661. this.clipPathManager.markUsed(displayable);
  77662. }
  77663. }
  77664. }
  77665. this.gradientManager.removeUnused();
  77666. this.clipPathManager.removeUnused();
  77667. this.shadowManager.removeUnused();
  77668. this._visibleList = newVisibleList;
  77669. },
  77670. _getDefs: function (isForceCreating) {
  77671. var svgRoot = this._svgRoot;
  77672. var defs = this._svgRoot.getElementsByTagName('defs');
  77673. if (defs.length === 0) {
  77674. // Not exist
  77675. if (isForceCreating) {
  77676. var defs = svgRoot.insertBefore(
  77677. createElement('defs'), // Create new tag
  77678. svgRoot.firstChild // Insert in the front of svg
  77679. );
  77680. if (!defs.contains) {
  77681. // IE doesn't support contains method
  77682. defs.contains = function (el) {
  77683. var children = defs.children;
  77684. if (!children) {
  77685. return false;
  77686. }
  77687. for (var i = children.length - 1; i >= 0; --i) {
  77688. if (children[i] === el) {
  77689. return true;
  77690. }
  77691. }
  77692. return false;
  77693. };
  77694. }
  77695. return defs;
  77696. }
  77697. else {
  77698. return null;
  77699. }
  77700. }
  77701. else {
  77702. return defs[0];
  77703. }
  77704. },
  77705. resize: function (width, height) {
  77706. var viewport = this._viewport;
  77707. // FIXME Why ?
  77708. viewport.style.display = 'none';
  77709. // Save input w/h
  77710. var opts = this._opts;
  77711. width != null && (opts.width = width);
  77712. height != null && (opts.height = height);
  77713. width = this._getSize(0);
  77714. height = this._getSize(1);
  77715. viewport.style.display = '';
  77716. if (this._width !== width || this._height !== height) {
  77717. this._width = width;
  77718. this._height = height;
  77719. var viewportStyle = viewport.style;
  77720. viewportStyle.width = width + 'px';
  77721. viewportStyle.height = height + 'px';
  77722. var svgRoot = this._svgRoot;
  77723. // Set width by 'svgRoot.width = width' is invalid
  77724. svgRoot.setAttribute('width', width);
  77725. svgRoot.setAttribute('height', height);
  77726. }
  77727. },
  77728. /**
  77729. * 获取绘图区域宽度
  77730. */
  77731. getWidth: function () {
  77732. return this._width;
  77733. },
  77734. /**
  77735. * 获取绘图区域高度
  77736. */
  77737. getHeight: function () {
  77738. return this._height;
  77739. },
  77740. _getSize: function (whIdx) {
  77741. var opts = this._opts;
  77742. var wh = ['width', 'height'][whIdx];
  77743. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  77744. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  77745. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  77746. if (opts[wh] != null && opts[wh] !== 'auto') {
  77747. return parseFloat(opts[wh]);
  77748. }
  77749. var root = this.root;
  77750. // IE8 does not support getComputedStyle, but it use VML.
  77751. var stl = document.defaultView.getComputedStyle(root);
  77752. return (
  77753. (root[cwh] || parseInt10$2(stl[wh]) || parseInt10$2(root.style[wh]))
  77754. - (parseInt10$2(stl[plt]) || 0)
  77755. - (parseInt10$2(stl[prb]) || 0)
  77756. ) | 0;
  77757. },
  77758. dispose: function () {
  77759. this.root.innerHTML = '';
  77760. this._svgRoot
  77761. = this._viewport
  77762. = this.storage
  77763. = null;
  77764. },
  77765. clear: function () {
  77766. if (this._viewport) {
  77767. this.root.removeChild(this._viewport);
  77768. }
  77769. },
  77770. pathToDataUrl: function () {
  77771. this.refresh();
  77772. var html = this._svgRoot.outerHTML;
  77773. return 'data:image/svg+xml;charset=UTF-8,' + html;
  77774. }
  77775. };
  77776. // Not supported methods
  77777. function createMethodNotSupport$1(method) {
  77778. return function () {
  77779. zrLog('In SVG mode painter not support method "' + method + '"');
  77780. };
  77781. }
  77782. // Unsuppoted methods
  77783. each$1([
  77784. 'getLayer', 'insertLayer', 'eachLayer', 'eachBuiltinLayer',
  77785. 'eachOtherLayer', 'getLayers', 'modLayer', 'delLayer', 'clearLayer',
  77786. 'toDataURL', 'pathToImage'
  77787. ], function (name) {
  77788. SVGPainter.prototype[name] = createMethodNotSupport$1(name);
  77789. });
  77790. registerPainter('svg', SVGPainter);
  77791. /*
  77792. * Licensed to the Apache Software Foundation (ASF) under one
  77793. * or more contributor license agreements. See the NOTICE file
  77794. * distributed with this work for additional information
  77795. * regarding copyright ownership. The ASF licenses this file
  77796. * to you under the Apache License, Version 2.0 (the
  77797. * "License"); you may not use this file except in compliance
  77798. * with the License. You may obtain a copy of the License at
  77799. *
  77800. * http://www.apache.org/licenses/LICENSE-2.0
  77801. *
  77802. * Unless required by applicable law or agreed to in writing,
  77803. * software distributed under the License is distributed on an
  77804. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  77805. * KIND, either express or implied. See the License for the
  77806. * specific language governing permissions and limitations
  77807. * under the License.
  77808. */
  77809. // Import all charts and components
  77810. exports.version = version;
  77811. exports.dependencies = dependencies;
  77812. exports.PRIORITY = PRIORITY;
  77813. exports.init = init;
  77814. exports.connect = connect;
  77815. exports.disConnect = disConnect;
  77816. exports.disconnect = disconnect;
  77817. exports.dispose = dispose;
  77818. exports.getInstanceByDom = getInstanceByDom;
  77819. exports.getInstanceById = getInstanceById;
  77820. exports.registerTheme = registerTheme;
  77821. exports.registerPreprocessor = registerPreprocessor;
  77822. exports.registerProcessor = registerProcessor;
  77823. exports.registerPostUpdate = registerPostUpdate;
  77824. exports.registerAction = registerAction;
  77825. exports.registerCoordinateSystem = registerCoordinateSystem;
  77826. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  77827. exports.registerLayout = registerLayout;
  77828. exports.registerVisual = registerVisual;
  77829. exports.registerLoading = registerLoading;
  77830. exports.extendComponentModel = extendComponentModel;
  77831. exports.extendComponentView = extendComponentView;
  77832. exports.extendSeriesModel = extendSeriesModel;
  77833. exports.extendChartView = extendChartView;
  77834. exports.setCanvasCreator = setCanvasCreator;
  77835. exports.registerMap = registerMap;
  77836. exports.getMap = getMap;
  77837. exports.dataTool = dataTool;
  77838. exports.zrender = zrender;
  77839. exports.graphic = graphic;
  77840. exports.number = number;
  77841. exports.format = format;
  77842. exports.throttle = throttle;
  77843. exports.helper = helper;
  77844. exports.matrix = matrix;
  77845. exports.vector = vector;
  77846. exports.color = color;
  77847. exports.parseGeoJSON = parseGeoJson$1;
  77848. exports.parseGeoJson = parseGeoJson;
  77849. exports.util = ecUtil;
  77850. exports.List = List;
  77851. exports.Model = Model;
  77852. exports.Axis = Axis;
  77853. exports.env = env$1;
  77854. })));
  77855. //# sourceMappingURL=echarts.js.map