echarts.js 2.5 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183351843518535186351873518835189351903519135192351933519435195351963519735198351993520035201352023520335204352053520635207352083520935210352113521235213352143521535216352173521835219352203522135222352233522435225352263522735228352293523035231352323523335234352353523635237352383523935240352413524235243352443524535246352473524835249352503525135252352533525435255352563525735258352593526035261352623526335264352653526635267352683526935270352713527235273352743527535276352773527835279352803528135282352833528435285352863528735288352893529035291352923529335294352953529635297352983529935300353013530235303353043530535306353073530835309353103531135312353133531435315353163531735318353193532035321353223532335324353253532635327353283532935330353313533235333353343533535336353373533835339353403534135342353433534435345353463534735348353493535035351353523535335354353553535635357353583535935360353613536235363353643536535366353673536835369353703537135372353733537435375353763537735378353793538035381353823538335384353853538635387353883538935390353913539235393353943539535396353973539835399354003540135402354033540435405354063540735408354093541035411354123541335414354153541635417354183541935420354213542235423354243542535426354273542835429354303543135432354333543435435354363543735438354393544035441354423544335444354453544635447354483544935450354513545235453354543545535456354573545835459354603546135462354633546435465354663546735468354693547035471354723547335474354753547635477354783547935480354813548235483354843548535486354873548835489354903549135492354933549435495354963549735498354993550035501355023550335504355053550635507355083550935510355113551235513355143551535516355173551835519355203552135522355233552435525355263552735528355293553035531355323553335534355353553635537355383553935540355413554235543355443554535546355473554835549355503555135552355533555435555355563555735558355593556035561355623556335564355653556635567355683556935570355713557235573355743557535576355773557835579355803558135582355833558435585355863558735588355893559035591355923559335594355953559635597355983559935600356013560235603356043560535606356073560835609356103561135612356133561435615356163561735618356193562035621356223562335624356253562635627356283562935630356313563235633356343563535636356373563835639356403564135642356433564435645356463564735648356493565035651356523565335654356553565635657356583565935660356613566235663356643566535666356673566835669356703567135672356733567435675356763567735678356793568035681356823568335684356853568635687356883568935690356913569235693356943569535696356973569835699357003570135702357033570435705357063570735708357093571035711357123571335714357153571635717357183571935720357213572235723357243572535726357273572835729357303573135732357333573435735357363573735738357393574035741357423574335744357453574635747357483574935750357513575235753357543575535756357573575835759357603576135762357633576435765357663576735768357693577035771357723577335774357753577635777357783577935780357813578235783357843578535786357873578835789357903579135792357933579435795357963579735798357993580035801358023580335804358053580635807358083580935810358113581235813358143581535816358173581835819358203582135822358233582435825358263582735828358293583035831358323583335834358353583635837358383583935840358413584235843358443584535846358473584835849358503585135852358533585435855358563585735858358593586035861358623586335864358653586635867358683586935870358713587235873358743587535876358773587835879358803588135882358833588435885358863588735888358893589035891358923589335894358953589635897358983589935900359013590235903359043590535906359073590835909359103591135912359133591435915359163591735918359193592035921359223592335924359253592635927359283592935930359313593235933359343593535936359373593835939359403594135942359433594435945359463594735948359493595035951359523595335954359553595635957359583595935960359613596235963359643596535966359673596835969359703597135972359733597435975359763597735978359793598035981359823598335984359853598635987359883598935990359913599235993359943599535996359973599835999360003600136002360033600436005360063600736008360093601036011360123601336014360153601636017360183601936020360213602236023360243602536026360273602836029360303603136032360333603436035360363603736038360393604036041360423604336044360453604636047360483604936050360513605236053360543605536056360573605836059360603606136062360633606436065360663606736068360693607036071360723607336074360753607636077360783607936080360813608236083360843608536086360873608836089360903609136092360933609436095360963609736098360993610036101361023610336104361053610636107361083610936110361113611236113361143611536116361173611836119361203612136122361233612436125361263612736128361293613036131361323613336134361353613636137361383613936140361413614236143361443614536146361473614836149361503615136152361533615436155361563615736158361593616036161361623616336164361653616636167361683616936170361713617236173361743617536176361773617836179361803618136182361833618436185361863618736188361893619036191361923619336194361953619636197361983619936200362013620236203362043620536206362073620836209362103621136212362133621436215362163621736218362193622036221362223622336224362253622636227362283622936230362313623236233362343623536236362373623836239362403624136242362433624436245362463624736248362493625036251362523625336254362553625636257362583625936260362613626236263362643626536266362673626836269362703627136272362733627436275362763627736278362793628036281362823628336284362853628636287362883628936290362913629236293362943629536296362973629836299363003630136302363033630436305363063630736308363093631036311363123631336314363153631636317363183631936320363213632236323363243632536326363273632836329363303633136332363333633436335363363633736338363393634036341363423634336344363453634636347363483634936350363513635236353363543635536356363573635836359363603636136362363633636436365363663636736368363693637036371363723637336374363753637636377363783637936380363813638236383363843638536386363873638836389363903639136392363933639436395363963639736398363993640036401364023640336404364053640636407364083640936410364113641236413364143641536416364173641836419364203642136422364233642436425364263642736428364293643036431364323643336434364353643636437364383643936440364413644236443364443644536446364473644836449364503645136452364533645436455364563645736458364593646036461364623646336464364653646636467364683646936470364713647236473364743647536476364773647836479364803648136482364833648436485364863648736488364893649036491364923649336494364953649636497364983649936500365013650236503365043650536506365073650836509365103651136512365133651436515365163651736518365193652036521365223652336524365253652636527365283652936530365313653236533365343653536536365373653836539365403654136542365433654436545365463654736548365493655036551365523655336554365553655636557365583655936560365613656236563365643656536566365673656836569365703657136572365733657436575365763657736578365793658036581365823658336584365853658636587365883658936590365913659236593365943659536596365973659836599366003660136602366033660436605366063660736608366093661036611366123661336614366153661636617366183661936620366213662236623366243662536626366273662836629366303663136632366333663436635366363663736638366393664036641366423664336644366453664636647366483664936650366513665236653366543665536656366573665836659366603666136662366633666436665366663666736668366693667036671366723667336674366753667636677366783667936680366813668236683366843668536686366873668836689366903669136692366933669436695366963669736698366993670036701367023670336704367053670636707367083670936710367113671236713367143671536716367173671836719367203672136722367233672436725367263672736728367293673036731367323673336734367353673636737367383673936740367413674236743367443674536746367473674836749367503675136752367533675436755367563675736758367593676036761367623676336764367653676636767367683676936770367713677236773367743677536776367773677836779367803678136782367833678436785367863678736788367893679036791367923679336794367953679636797367983679936800368013680236803368043680536806368073680836809368103681136812368133681436815368163681736818368193682036821368223682336824368253682636827368283682936830368313683236833368343683536836368373683836839368403684136842368433684436845368463684736848368493685036851368523685336854368553685636857368583685936860368613686236863368643686536866368673686836869368703687136872368733687436875368763687736878368793688036881368823688336884368853688636887368883688936890368913689236893368943689536896368973689836899369003690136902369033690436905369063690736908369093691036911369123691336914369153691636917369183691936920369213692236923369243692536926369273692836929369303693136932369333693436935369363693736938369393694036941369423694336944369453694636947369483694936950369513695236953369543695536956369573695836959369603696136962369633696436965369663696736968369693697036971369723697336974369753697636977369783697936980369813698236983369843698536986369873698836989369903699136992369933699436995369963699736998369993700037001370023700337004370053700637007370083700937010370113701237013370143701537016370173701837019370203702137022370233702437025370263702737028370293703037031370323703337034370353703637037370383703937040370413704237043370443704537046370473704837049370503705137052370533705437055370563705737058370593706037061370623706337064370653706637067370683706937070370713707237073370743707537076370773707837079370803708137082370833708437085370863708737088370893709037091370923709337094370953709637097370983709937100371013710237103371043710537106371073710837109371103711137112371133711437115371163711737118371193712037121371223712337124371253712637127371283712937130371313713237133371343713537136371373713837139371403714137142371433714437145371463714737148371493715037151371523715337154371553715637157371583715937160371613716237163371643716537166371673716837169371703717137172371733717437175371763717737178371793718037181371823718337184371853718637187371883718937190371913719237193371943719537196371973719837199372003720137202372033720437205372063720737208372093721037211372123721337214372153721637217372183721937220372213722237223372243722537226372273722837229372303723137232372333723437235372363723737238372393724037241372423724337244372453724637247372483724937250372513725237253372543725537256372573725837259372603726137262372633726437265372663726737268372693727037271372723727337274372753727637277372783727937280372813728237283372843728537286372873728837289372903729137292372933729437295372963729737298372993730037301373023730337304373053730637307373083730937310373113731237313373143731537316373173731837319373203732137322373233732437325373263732737328373293733037331373323733337334373353733637337373383733937340373413734237343373443734537346373473734837349373503735137352373533735437355373563735737358373593736037361373623736337364373653736637367373683736937370373713737237373373743737537376373773737837379373803738137382373833738437385373863738737388373893739037391373923739337394373953739637397373983739937400374013740237403374043740537406374073740837409374103741137412374133741437415374163741737418374193742037421374223742337424374253742637427374283742937430374313743237433374343743537436374373743837439374403744137442374433744437445374463744737448374493745037451374523745337454374553745637457374583745937460374613746237463374643746537466374673746837469374703747137472374733747437475374763747737478374793748037481374823748337484374853748637487374883748937490374913749237493374943749537496374973749837499375003750137502375033750437505375063750737508375093751037511375123751337514375153751637517375183751937520375213752237523375243752537526375273752837529375303753137532375333753437535375363753737538375393754037541375423754337544375453754637547375483754937550375513755237553375543755537556375573755837559375603756137562375633756437565375663756737568375693757037571375723757337574375753757637577375783757937580375813758237583375843758537586375873758837589375903759137592375933759437595375963759737598375993760037601376023760337604376053760637607376083760937610376113761237613376143761537616376173761837619376203762137622376233762437625376263762737628376293763037631376323763337634376353763637637376383763937640376413764237643376443764537646376473764837649376503765137652376533765437655376563765737658376593766037661376623766337664376653766637667376683766937670376713767237673376743767537676376773767837679376803768137682376833768437685376863768737688376893769037691376923769337694376953769637697376983769937700377013770237703377043770537706377073770837709377103771137712377133771437715377163771737718377193772037721377223772337724377253772637727377283772937730377313773237733377343773537736377373773837739377403774137742377433774437745377463774737748377493775037751377523775337754377553775637757377583775937760377613776237763377643776537766377673776837769377703777137772377733777437775377763777737778377793778037781377823778337784377853778637787377883778937790377913779237793377943779537796377973779837799378003780137802378033780437805378063780737808378093781037811378123781337814378153781637817378183781937820378213782237823378243782537826378273782837829378303783137832378333783437835378363783737838378393784037841378423784337844378453784637847378483784937850378513785237853378543785537856378573785837859378603786137862378633786437865378663786737868378693787037871378723787337874378753787637877378783787937880378813788237883378843788537886378873788837889378903789137892378933789437895378963789737898378993790037901379023790337904379053790637907379083790937910379113791237913379143791537916379173791837919379203792137922379233792437925379263792737928379293793037931379323793337934379353793637937379383793937940379413794237943379443794537946379473794837949379503795137952379533795437955379563795737958379593796037961379623796337964379653796637967379683796937970379713797237973379743797537976379773797837979379803798137982379833798437985379863798737988379893799037991379923799337994379953799637997379983799938000380013800238003380043800538006380073800838009380103801138012380133801438015380163801738018380193802038021380223802338024380253802638027380283802938030380313803238033380343803538036380373803838039380403804138042380433804438045380463804738048380493805038051380523805338054380553805638057380583805938060380613806238063380643806538066380673806838069380703807138072380733807438075380763807738078380793808038081380823808338084380853808638087380883808938090380913809238093380943809538096380973809838099381003810138102381033810438105381063810738108381093811038111381123811338114381153811638117381183811938120381213812238123381243812538126381273812838129381303813138132381333813438135381363813738138381393814038141381423814338144381453814638147381483814938150381513815238153381543815538156381573815838159381603816138162381633816438165381663816738168381693817038171381723817338174381753817638177381783817938180381813818238183381843818538186381873818838189381903819138192381933819438195381963819738198381993820038201382023820338204382053820638207382083820938210382113821238213382143821538216382173821838219382203822138222382233822438225382263822738228382293823038231382323823338234382353823638237382383823938240382413824238243382443824538246382473824838249382503825138252382533825438255382563825738258382593826038261382623826338264382653826638267382683826938270382713827238273382743827538276382773827838279382803828138282382833828438285382863828738288382893829038291382923829338294382953829638297382983829938300383013830238303383043830538306383073830838309383103831138312383133831438315383163831738318383193832038321383223832338324383253832638327383283832938330383313833238333383343833538336383373833838339383403834138342383433834438345383463834738348383493835038351383523835338354383553835638357383583835938360383613836238363383643836538366383673836838369383703837138372383733837438375383763837738378383793838038381383823838338384383853838638387383883838938390383913839238393383943839538396383973839838399384003840138402384033840438405384063840738408384093841038411384123841338414384153841638417384183841938420384213842238423384243842538426384273842838429384303843138432384333843438435384363843738438384393844038441384423844338444384453844638447384483844938450384513845238453384543845538456384573845838459384603846138462384633846438465384663846738468384693847038471384723847338474384753847638477384783847938480384813848238483384843848538486384873848838489384903849138492384933849438495384963849738498384993850038501385023850338504385053850638507385083850938510385113851238513385143851538516385173851838519385203852138522385233852438525385263852738528385293853038531385323853338534385353853638537385383853938540385413854238543385443854538546385473854838549385503855138552385533855438555385563855738558385593856038561385623856338564385653856638567385683856938570385713857238573385743857538576385773857838579385803858138582385833858438585385863858738588385893859038591385923859338594385953859638597385983859938600386013860238603386043860538606386073860838609386103861138612386133861438615386163861738618386193862038621386223862338624386253862638627386283862938630386313863238633386343863538636386373863838639386403864138642386433864438645386463864738648386493865038651386523865338654386553865638657386583865938660386613866238663386643866538666386673866838669386703867138672386733867438675386763867738678386793868038681386823868338684386853868638687386883868938690386913869238693386943869538696386973869838699387003870138702387033870438705387063870738708387093871038711387123871338714387153871638717387183871938720387213872238723387243872538726387273872838729387303873138732387333873438735387363873738738387393874038741387423874338744387453874638747387483874938750387513875238753387543875538756387573875838759387603876138762387633876438765387663876738768387693877038771387723877338774387753877638777387783877938780387813878238783387843878538786387873878838789387903879138792387933879438795387963879738798387993880038801388023880338804388053880638807388083880938810388113881238813388143881538816388173881838819388203882138822388233882438825388263882738828388293883038831388323883338834388353883638837388383883938840388413884238843388443884538846388473884838849388503885138852388533885438855388563885738858388593886038861388623886338864388653886638867388683886938870388713887238873388743887538876388773887838879388803888138882388833888438885388863888738888388893889038891388923889338894388953889638897388983889938900389013890238903389043890538906389073890838909389103891138912389133891438915389163891738918389193892038921389223892338924389253892638927389283892938930389313893238933389343893538936389373893838939389403894138942389433894438945389463894738948389493895038951389523895338954389553895638957389583895938960389613896238963389643896538966389673896838969389703897138972389733897438975389763897738978389793898038981389823898338984389853898638987389883898938990389913899238993389943899538996389973899838999390003900139002390033900439005390063900739008390093901039011390123901339014390153901639017390183901939020390213902239023390243902539026390273902839029390303903139032390333903439035390363903739038390393904039041390423904339044390453904639047390483904939050390513905239053390543905539056390573905839059390603906139062390633906439065390663906739068390693907039071390723907339074390753907639077390783907939080390813908239083390843908539086390873908839089390903909139092390933909439095390963909739098390993910039101391023910339104391053910639107391083910939110391113911239113391143911539116391173911839119391203912139122391233912439125391263912739128391293913039131391323913339134391353913639137391383913939140391413914239143391443914539146391473914839149391503915139152391533915439155391563915739158391593916039161391623916339164391653916639167391683916939170391713917239173391743917539176391773917839179391803918139182391833918439185391863918739188391893919039191391923919339194391953919639197391983919939200392013920239203392043920539206392073920839209392103921139212392133921439215392163921739218392193922039221392223922339224392253922639227392283922939230392313923239233392343923539236392373923839239392403924139242392433924439245392463924739248392493925039251392523925339254392553925639257392583925939260392613926239263392643926539266392673926839269392703927139272392733927439275392763927739278392793928039281392823928339284392853928639287392883928939290392913929239293392943929539296392973929839299393003930139302393033930439305393063930739308393093931039311393123931339314393153931639317393183931939320393213932239323393243932539326393273932839329393303933139332393333933439335393363933739338393393934039341393423934339344393453934639347393483934939350393513935239353393543935539356393573935839359393603936139362393633936439365393663936739368393693937039371393723937339374393753937639377393783937939380393813938239383393843938539386393873938839389393903939139392393933939439395393963939739398393993940039401394023940339404394053940639407394083940939410394113941239413394143941539416394173941839419394203942139422394233942439425394263942739428394293943039431394323943339434394353943639437394383943939440394413944239443394443944539446394473944839449394503945139452394533945439455394563945739458394593946039461394623946339464394653946639467394683946939470394713947239473394743947539476394773947839479394803948139482394833948439485394863948739488394893949039491394923949339494394953949639497394983949939500395013950239503395043950539506395073950839509395103951139512395133951439515395163951739518395193952039521395223952339524395253952639527395283952939530395313953239533395343953539536395373953839539395403954139542395433954439545395463954739548395493955039551395523955339554395553955639557395583955939560395613956239563395643956539566395673956839569395703957139572395733957439575395763957739578395793958039581395823958339584395853958639587395883958939590395913959239593395943959539596395973959839599396003960139602396033960439605396063960739608396093961039611396123961339614396153961639617396183961939620396213962239623396243962539626396273962839629396303963139632396333963439635396363963739638396393964039641396423964339644396453964639647396483964939650396513965239653396543965539656396573965839659396603966139662396633966439665396663966739668396693967039671396723967339674396753967639677396783967939680396813968239683396843968539686396873968839689396903969139692396933969439695396963969739698396993970039701397023970339704397053970639707397083970939710397113971239713397143971539716397173971839719397203972139722397233972439725397263972739728397293973039731397323973339734397353973639737397383973939740397413974239743397443974539746397473974839749397503975139752397533975439755397563975739758397593976039761397623976339764397653976639767397683976939770397713977239773397743977539776397773977839779397803978139782397833978439785397863978739788397893979039791397923979339794397953979639797397983979939800398013980239803398043980539806398073980839809398103981139812398133981439815398163981739818398193982039821398223982339824398253982639827398283982939830398313983239833398343983539836398373983839839398403984139842398433984439845398463984739848398493985039851398523985339854398553985639857398583985939860398613986239863398643986539866398673986839869398703987139872398733987439875398763987739878398793988039881398823988339884398853988639887398883988939890398913989239893398943989539896398973989839899399003990139902399033990439905399063990739908399093991039911399123991339914399153991639917399183991939920399213992239923399243992539926399273992839929399303993139932399333993439935399363993739938399393994039941399423994339944399453994639947399483994939950399513995239953399543995539956399573995839959399603996139962399633996439965399663996739968399693997039971399723997339974399753997639977399783997939980399813998239983399843998539986399873998839989399903999139992399933999439995399963999739998399994000040001400024000340004400054000640007400084000940010400114001240013400144001540016400174001840019400204002140022400234002440025400264002740028400294003040031400324003340034400354003640037400384003940040400414004240043400444004540046400474004840049400504005140052400534005440055400564005740058400594006040061400624006340064400654006640067400684006940070400714007240073400744007540076400774007840079400804008140082400834008440085400864008740088400894009040091400924009340094400954009640097400984009940100401014010240103401044010540106401074010840109401104011140112401134011440115401164011740118401194012040121401224012340124401254012640127401284012940130401314013240133401344013540136401374013840139401404014140142401434014440145401464014740148401494015040151401524015340154401554015640157401584015940160401614016240163401644016540166401674016840169401704017140172401734017440175401764017740178401794018040181401824018340184401854018640187401884018940190401914019240193401944019540196401974019840199402004020140202402034020440205402064020740208402094021040211402124021340214402154021640217402184021940220402214022240223402244022540226402274022840229402304023140232402334023440235402364023740238402394024040241402424024340244402454024640247402484024940250402514025240253402544025540256402574025840259402604026140262402634026440265402664026740268402694027040271402724027340274402754027640277402784027940280402814028240283402844028540286402874028840289402904029140292402934029440295402964029740298402994030040301403024030340304403054030640307403084030940310403114031240313403144031540316403174031840319403204032140322403234032440325403264032740328403294033040331403324033340334403354033640337403384033940340403414034240343403444034540346403474034840349403504035140352403534035440355403564035740358403594036040361403624036340364403654036640367403684036940370403714037240373403744037540376403774037840379403804038140382403834038440385403864038740388403894039040391403924039340394403954039640397403984039940400404014040240403404044040540406404074040840409404104041140412404134041440415404164041740418404194042040421404224042340424404254042640427404284042940430404314043240433404344043540436404374043840439404404044140442404434044440445404464044740448404494045040451404524045340454404554045640457404584045940460404614046240463404644046540466404674046840469404704047140472404734047440475404764047740478404794048040481404824048340484404854048640487404884048940490404914049240493404944049540496404974049840499405004050140502405034050440505405064050740508405094051040511405124051340514405154051640517405184051940520405214052240523405244052540526405274052840529405304053140532405334053440535405364053740538405394054040541405424054340544405454054640547405484054940550405514055240553405544055540556405574055840559405604056140562405634056440565405664056740568405694057040571405724057340574405754057640577405784057940580405814058240583405844058540586405874058840589405904059140592405934059440595405964059740598405994060040601406024060340604406054060640607406084060940610406114061240613406144061540616406174061840619406204062140622406234062440625406264062740628406294063040631406324063340634406354063640637406384063940640406414064240643406444064540646406474064840649406504065140652406534065440655406564065740658406594066040661406624066340664406654066640667406684066940670406714067240673406744067540676406774067840679406804068140682406834068440685406864068740688406894069040691406924069340694406954069640697406984069940700407014070240703407044070540706407074070840709407104071140712407134071440715407164071740718407194072040721407224072340724407254072640727407284072940730407314073240733407344073540736407374073840739407404074140742407434074440745407464074740748407494075040751407524075340754407554075640757407584075940760407614076240763407644076540766407674076840769407704077140772407734077440775407764077740778407794078040781407824078340784407854078640787407884078940790407914079240793407944079540796407974079840799408004080140802408034080440805408064080740808408094081040811408124081340814408154081640817408184081940820408214082240823408244082540826408274082840829408304083140832408334083440835408364083740838408394084040841408424084340844408454084640847408484084940850408514085240853408544085540856408574085840859408604086140862408634086440865408664086740868408694087040871408724087340874408754087640877408784087940880408814088240883408844088540886408874088840889408904089140892408934089440895408964089740898408994090040901409024090340904409054090640907409084090940910409114091240913409144091540916409174091840919409204092140922409234092440925409264092740928409294093040931409324093340934409354093640937409384093940940409414094240943409444094540946409474094840949409504095140952409534095440955409564095740958409594096040961409624096340964409654096640967409684096940970409714097240973409744097540976409774097840979409804098140982409834098440985409864098740988409894099040991409924099340994409954099640997409984099941000410014100241003410044100541006410074100841009410104101141012410134101441015410164101741018410194102041021410224102341024410254102641027410284102941030410314103241033410344103541036410374103841039410404104141042410434104441045410464104741048410494105041051410524105341054410554105641057410584105941060410614106241063410644106541066410674106841069410704107141072410734107441075410764107741078410794108041081410824108341084410854108641087410884108941090410914109241093410944109541096410974109841099411004110141102411034110441105411064110741108411094111041111411124111341114411154111641117411184111941120411214112241123411244112541126411274112841129411304113141132411334113441135411364113741138411394114041141411424114341144411454114641147411484114941150411514115241153411544115541156411574115841159411604116141162411634116441165411664116741168411694117041171411724117341174411754117641177411784117941180411814118241183411844118541186411874118841189411904119141192411934119441195411964119741198411994120041201412024120341204412054120641207412084120941210412114121241213412144121541216412174121841219412204122141222412234122441225412264122741228412294123041231412324123341234412354123641237412384123941240412414124241243412444124541246412474124841249412504125141252412534125441255412564125741258412594126041261412624126341264412654126641267412684126941270412714127241273412744127541276412774127841279412804128141282412834128441285412864128741288412894129041291412924129341294412954129641297412984129941300413014130241303413044130541306413074130841309413104131141312413134131441315413164131741318413194132041321413224132341324413254132641327413284132941330413314133241333413344133541336413374133841339413404134141342413434134441345413464134741348413494135041351413524135341354413554135641357413584135941360413614136241363413644136541366413674136841369413704137141372413734137441375413764137741378413794138041381413824138341384413854138641387413884138941390413914139241393413944139541396413974139841399414004140141402414034140441405414064140741408414094141041411414124141341414414154141641417414184141941420414214142241423414244142541426414274142841429414304143141432414334143441435414364143741438414394144041441414424144341444414454144641447414484144941450414514145241453414544145541456414574145841459414604146141462414634146441465414664146741468414694147041471414724147341474414754147641477414784147941480414814148241483414844148541486414874148841489414904149141492414934149441495414964149741498414994150041501415024150341504415054150641507415084150941510415114151241513415144151541516415174151841519415204152141522415234152441525415264152741528415294153041531415324153341534415354153641537415384153941540415414154241543415444154541546415474154841549415504155141552415534155441555415564155741558415594156041561415624156341564415654156641567415684156941570415714157241573415744157541576415774157841579415804158141582415834158441585415864158741588415894159041591415924159341594415954159641597415984159941600416014160241603416044160541606416074160841609416104161141612416134161441615416164161741618416194162041621416224162341624416254162641627416284162941630416314163241633416344163541636416374163841639416404164141642416434164441645416464164741648416494165041651416524165341654416554165641657416584165941660416614166241663416644166541666416674166841669416704167141672416734167441675416764167741678416794168041681416824168341684416854168641687416884168941690416914169241693416944169541696416974169841699417004170141702417034170441705417064170741708417094171041711417124171341714417154171641717417184171941720417214172241723417244172541726417274172841729417304173141732417334173441735417364173741738417394174041741417424174341744417454174641747417484174941750417514175241753417544175541756417574175841759417604176141762417634176441765417664176741768417694177041771417724177341774417754177641777417784177941780417814178241783417844178541786417874178841789417904179141792417934179441795417964179741798417994180041801418024180341804418054180641807418084180941810418114181241813418144181541816418174181841819418204182141822418234182441825418264182741828418294183041831418324183341834418354183641837418384183941840418414184241843418444184541846418474184841849418504185141852418534185441855418564185741858418594186041861418624186341864418654186641867418684186941870418714187241873418744187541876418774187841879418804188141882418834188441885418864188741888418894189041891418924189341894418954189641897418984189941900419014190241903419044190541906419074190841909419104191141912419134191441915419164191741918419194192041921419224192341924419254192641927419284192941930419314193241933419344193541936419374193841939419404194141942419434194441945419464194741948419494195041951419524195341954419554195641957419584195941960419614196241963419644196541966419674196841969419704197141972419734197441975419764197741978419794198041981419824198341984419854198641987419884198941990419914199241993419944199541996419974199841999420004200142002420034200442005420064200742008420094201042011420124201342014420154201642017420184201942020420214202242023420244202542026420274202842029420304203142032420334203442035420364203742038420394204042041420424204342044420454204642047420484204942050420514205242053420544205542056420574205842059420604206142062420634206442065420664206742068420694207042071420724207342074420754207642077420784207942080420814208242083420844208542086420874208842089420904209142092420934209442095420964209742098420994210042101421024210342104421054210642107421084210942110421114211242113421144211542116421174211842119421204212142122421234212442125421264212742128421294213042131421324213342134421354213642137421384213942140421414214242143421444214542146421474214842149421504215142152421534215442155421564215742158421594216042161421624216342164421654216642167421684216942170421714217242173421744217542176421774217842179421804218142182421834218442185421864218742188421894219042191421924219342194421954219642197421984219942200422014220242203422044220542206422074220842209422104221142212422134221442215422164221742218422194222042221422224222342224422254222642227422284222942230422314223242233422344223542236422374223842239422404224142242422434224442245422464224742248422494225042251422524225342254422554225642257422584225942260422614226242263422644226542266422674226842269422704227142272422734227442275422764227742278422794228042281422824228342284422854228642287422884228942290422914229242293422944229542296422974229842299423004230142302423034230442305423064230742308423094231042311423124231342314423154231642317423184231942320423214232242323423244232542326423274232842329423304233142332423334233442335423364233742338423394234042341423424234342344423454234642347423484234942350423514235242353423544235542356423574235842359423604236142362423634236442365423664236742368423694237042371423724237342374423754237642377423784237942380423814238242383423844238542386423874238842389423904239142392423934239442395423964239742398423994240042401424024240342404424054240642407424084240942410424114241242413424144241542416424174241842419424204242142422424234242442425424264242742428424294243042431424324243342434424354243642437424384243942440424414244242443424444244542446424474244842449424504245142452424534245442455424564245742458424594246042461424624246342464424654246642467424684246942470424714247242473424744247542476424774247842479424804248142482424834248442485424864248742488424894249042491424924249342494424954249642497424984249942500425014250242503425044250542506425074250842509425104251142512425134251442515425164251742518425194252042521425224252342524425254252642527425284252942530425314253242533425344253542536425374253842539425404254142542425434254442545425464254742548425494255042551425524255342554425554255642557425584255942560425614256242563425644256542566425674256842569425704257142572425734257442575425764257742578425794258042581425824258342584425854258642587425884258942590425914259242593425944259542596425974259842599426004260142602426034260442605426064260742608426094261042611426124261342614426154261642617426184261942620426214262242623426244262542626426274262842629426304263142632426334263442635426364263742638426394264042641426424264342644426454264642647426484264942650426514265242653426544265542656426574265842659426604266142662426634266442665426664266742668426694267042671426724267342674426754267642677426784267942680426814268242683426844268542686426874268842689426904269142692426934269442695426964269742698426994270042701427024270342704427054270642707427084270942710427114271242713427144271542716427174271842719427204272142722427234272442725427264272742728427294273042731427324273342734427354273642737427384273942740427414274242743427444274542746427474274842749427504275142752427534275442755427564275742758427594276042761427624276342764427654276642767427684276942770427714277242773427744277542776427774277842779427804278142782427834278442785427864278742788427894279042791427924279342794427954279642797427984279942800428014280242803428044280542806428074280842809428104281142812428134281442815428164281742818428194282042821428224282342824428254282642827428284282942830428314283242833428344283542836428374283842839428404284142842428434284442845428464284742848428494285042851428524285342854428554285642857428584285942860428614286242863428644286542866428674286842869428704287142872428734287442875428764287742878428794288042881428824288342884428854288642887428884288942890428914289242893428944289542896428974289842899429004290142902429034290442905429064290742908429094291042911429124291342914429154291642917429184291942920429214292242923429244292542926429274292842929429304293142932429334293442935429364293742938429394294042941429424294342944429454294642947429484294942950429514295242953429544295542956429574295842959429604296142962429634296442965429664296742968429694297042971429724297342974429754297642977429784297942980429814298242983429844298542986429874298842989429904299142992429934299442995429964299742998429994300043001430024300343004430054300643007430084300943010430114301243013430144301543016430174301843019430204302143022430234302443025430264302743028430294303043031430324303343034430354303643037430384303943040430414304243043430444304543046430474304843049430504305143052430534305443055430564305743058430594306043061430624306343064430654306643067430684306943070430714307243073430744307543076430774307843079430804308143082430834308443085430864308743088430894309043091430924309343094430954309643097430984309943100431014310243103431044310543106431074310843109431104311143112431134311443115431164311743118431194312043121431224312343124431254312643127431284312943130431314313243133431344313543136431374313843139431404314143142431434314443145431464314743148431494315043151431524315343154431554315643157431584315943160431614316243163431644316543166431674316843169431704317143172431734317443175431764317743178431794318043181431824318343184431854318643187431884318943190431914319243193431944319543196431974319843199432004320143202432034320443205432064320743208432094321043211432124321343214432154321643217432184321943220432214322243223432244322543226432274322843229432304323143232432334323443235432364323743238432394324043241432424324343244432454324643247432484324943250432514325243253432544325543256432574325843259432604326143262432634326443265432664326743268432694327043271432724327343274432754327643277432784327943280432814328243283432844328543286432874328843289432904329143292432934329443295432964329743298432994330043301433024330343304433054330643307433084330943310433114331243313433144331543316433174331843319433204332143322433234332443325433264332743328433294333043331433324333343334433354333643337433384333943340433414334243343433444334543346433474334843349433504335143352433534335443355433564335743358433594336043361433624336343364433654336643367433684336943370433714337243373433744337543376433774337843379433804338143382433834338443385433864338743388433894339043391433924339343394433954339643397433984339943400434014340243403434044340543406434074340843409434104341143412434134341443415434164341743418434194342043421434224342343424434254342643427434284342943430434314343243433434344343543436434374343843439434404344143442434434344443445434464344743448434494345043451434524345343454434554345643457434584345943460434614346243463434644346543466434674346843469434704347143472434734347443475434764347743478434794348043481434824348343484434854348643487434884348943490434914349243493434944349543496434974349843499435004350143502435034350443505435064350743508435094351043511435124351343514435154351643517435184351943520435214352243523435244352543526435274352843529435304353143532435334353443535435364353743538435394354043541435424354343544435454354643547435484354943550435514355243553435544355543556435574355843559435604356143562435634356443565435664356743568435694357043571435724357343574435754357643577435784357943580435814358243583435844358543586435874358843589435904359143592435934359443595435964359743598435994360043601436024360343604436054360643607436084360943610436114361243613436144361543616436174361843619436204362143622436234362443625436264362743628436294363043631436324363343634436354363643637436384363943640436414364243643436444364543646436474364843649436504365143652436534365443655436564365743658436594366043661436624366343664436654366643667436684366943670436714367243673436744367543676436774367843679436804368143682436834368443685436864368743688436894369043691436924369343694436954369643697436984369943700437014370243703437044370543706437074370843709437104371143712437134371443715437164371743718437194372043721437224372343724437254372643727437284372943730437314373243733437344373543736437374373843739437404374143742437434374443745437464374743748437494375043751437524375343754437554375643757437584375943760437614376243763437644376543766437674376843769437704377143772437734377443775437764377743778437794378043781437824378343784437854378643787437884378943790437914379243793437944379543796437974379843799438004380143802438034380443805438064380743808438094381043811438124381343814438154381643817438184381943820438214382243823438244382543826438274382843829438304383143832438334383443835438364383743838438394384043841438424384343844438454384643847438484384943850438514385243853438544385543856438574385843859438604386143862438634386443865438664386743868438694387043871438724387343874438754387643877438784387943880438814388243883438844388543886438874388843889438904389143892438934389443895438964389743898438994390043901439024390343904439054390643907439084390943910439114391243913439144391543916439174391843919439204392143922439234392443925439264392743928439294393043931439324393343934439354393643937439384393943940439414394243943439444394543946439474394843949439504395143952439534395443955439564395743958439594396043961439624396343964439654396643967439684396943970439714397243973439744397543976439774397843979439804398143982439834398443985439864398743988439894399043991439924399343994439954399643997439984399944000440014400244003440044400544006440074400844009440104401144012440134401444015440164401744018440194402044021440224402344024440254402644027440284402944030440314403244033440344403544036440374403844039440404404144042440434404444045440464404744048440494405044051440524405344054440554405644057440584405944060440614406244063440644406544066440674406844069440704407144072440734407444075440764407744078440794408044081440824408344084440854408644087440884408944090440914409244093440944409544096440974409844099441004410144102441034410444105441064410744108441094411044111441124411344114441154411644117441184411944120441214412244123441244412544126441274412844129441304413144132441334413444135441364413744138441394414044141441424414344144441454414644147441484414944150441514415244153441544415544156441574415844159441604416144162441634416444165441664416744168441694417044171441724417344174441754417644177441784417944180441814418244183441844418544186441874418844189441904419144192441934419444195441964419744198441994420044201442024420344204442054420644207442084420944210442114421244213442144421544216442174421844219442204422144222442234422444225442264422744228442294423044231442324423344234442354423644237442384423944240442414424244243442444424544246442474424844249442504425144252442534425444255442564425744258442594426044261442624426344264442654426644267442684426944270442714427244273442744427544276442774427844279442804428144282442834428444285442864428744288442894429044291442924429344294442954429644297442984429944300443014430244303443044430544306443074430844309443104431144312443134431444315443164431744318443194432044321443224432344324443254432644327443284432944330443314433244333443344433544336443374433844339443404434144342443434434444345443464434744348443494435044351443524435344354443554435644357443584435944360443614436244363443644436544366443674436844369443704437144372443734437444375443764437744378443794438044381443824438344384443854438644387443884438944390443914439244393443944439544396443974439844399444004440144402444034440444405444064440744408444094441044411444124441344414444154441644417444184441944420444214442244423444244442544426444274442844429444304443144432444334443444435444364443744438444394444044441444424444344444444454444644447444484444944450444514445244453444544445544456444574445844459444604446144462444634446444465444664446744468444694447044471444724447344474444754447644477444784447944480444814448244483444844448544486444874448844489444904449144492444934449444495444964449744498444994450044501445024450344504445054450644507445084450944510445114451244513445144451544516445174451844519445204452144522445234452444525445264452744528445294453044531445324453344534445354453644537445384453944540445414454244543445444454544546445474454844549445504455144552445534455444555445564455744558445594456044561445624456344564445654456644567445684456944570445714457244573445744457544576445774457844579445804458144582445834458444585445864458744588445894459044591445924459344594445954459644597445984459944600446014460244603446044460544606446074460844609446104461144612446134461444615446164461744618446194462044621446224462344624446254462644627446284462944630446314463244633446344463544636446374463844639446404464144642446434464444645446464464744648446494465044651446524465344654446554465644657446584465944660446614466244663446644466544666446674466844669446704467144672446734467444675446764467744678446794468044681446824468344684446854468644687446884468944690446914469244693446944469544696446974469844699447004470144702447034470444705447064470744708447094471044711447124471344714447154471644717447184471944720447214472244723447244472544726447274472844729447304473144732447334473444735447364473744738447394474044741447424474344744447454474644747447484474944750447514475244753447544475544756447574475844759447604476144762447634476444765447664476744768447694477044771447724477344774447754477644777447784477944780447814478244783447844478544786447874478844789447904479144792447934479444795447964479744798447994480044801448024480344804448054480644807448084480944810448114481244813448144481544816448174481844819448204482144822448234482444825448264482744828448294483044831448324483344834448354483644837448384483944840448414484244843448444484544846448474484844849448504485144852448534485444855448564485744858448594486044861448624486344864448654486644867448684486944870448714487244873448744487544876448774487844879448804488144882448834488444885448864488744888448894489044891448924489344894448954489644897448984489944900449014490244903449044490544906449074490844909449104491144912449134491444915449164491744918449194492044921449224492344924449254492644927449284492944930449314493244933449344493544936449374493844939449404494144942449434494444945449464494744948449494495044951449524495344954449554495644957449584495944960449614496244963449644496544966449674496844969449704497144972449734497444975449764497744978449794498044981449824498344984449854498644987449884498944990449914499244993449944499544996449974499844999450004500145002450034500445005450064500745008450094501045011450124501345014450154501645017450184501945020450214502245023450244502545026450274502845029450304503145032450334503445035450364503745038450394504045041450424504345044450454504645047450484504945050450514505245053450544505545056450574505845059450604506145062450634506445065450664506745068450694507045071450724507345074450754507645077450784507945080450814508245083450844508545086450874508845089450904509145092450934509445095450964509745098450994510045101451024510345104451054510645107451084510945110451114511245113451144511545116451174511845119451204512145122451234512445125451264512745128451294513045131451324513345134451354513645137451384513945140451414514245143451444514545146451474514845149451504515145152451534515445155451564515745158451594516045161451624516345164451654516645167451684516945170451714517245173451744517545176451774517845179451804518145182451834518445185451864518745188451894519045191451924519345194451954519645197451984519945200452014520245203452044520545206452074520845209452104521145212452134521445215452164521745218452194522045221452224522345224452254522645227452284522945230452314523245233452344523545236452374523845239452404524145242452434524445245452464524745248452494525045251452524525345254452554525645257452584525945260452614526245263452644526545266452674526845269452704527145272452734527445275452764527745278452794528045281452824528345284452854528645287452884528945290452914529245293452944529545296452974529845299453004530145302453034530445305453064530745308453094531045311453124531345314453154531645317453184531945320453214532245323453244532545326453274532845329453304533145332453334533445335453364533745338453394534045341453424534345344453454534645347453484534945350453514535245353453544535545356453574535845359453604536145362453634536445365453664536745368453694537045371453724537345374453754537645377453784537945380453814538245383453844538545386453874538845389453904539145392453934539445395453964539745398453994540045401454024540345404454054540645407454084540945410454114541245413454144541545416454174541845419454204542145422454234542445425454264542745428454294543045431454324543345434454354543645437454384543945440454414544245443454444544545446454474544845449454504545145452454534545445455454564545745458454594546045461454624546345464454654546645467454684546945470454714547245473454744547545476454774547845479454804548145482454834548445485454864548745488454894549045491454924549345494454954549645497454984549945500455014550245503455044550545506455074550845509455104551145512455134551445515455164551745518455194552045521455224552345524455254552645527455284552945530455314553245533455344553545536455374553845539455404554145542455434554445545455464554745548455494555045551455524555345554455554555645557455584555945560455614556245563455644556545566455674556845569455704557145572455734557445575455764557745578455794558045581455824558345584455854558645587455884558945590455914559245593455944559545596455974559845599456004560145602456034560445605456064560745608456094561045611456124561345614456154561645617456184561945620456214562245623456244562545626456274562845629456304563145632456334563445635456364563745638456394564045641456424564345644456454564645647456484564945650456514565245653456544565545656456574565845659456604566145662456634566445665456664566745668456694567045671456724567345674456754567645677456784567945680456814568245683456844568545686456874568845689456904569145692456934569445695456964569745698456994570045701457024570345704457054570645707457084570945710457114571245713457144571545716457174571845719457204572145722457234572445725457264572745728457294573045731457324573345734457354573645737457384573945740457414574245743457444574545746457474574845749457504575145752457534575445755457564575745758457594576045761457624576345764457654576645767457684576945770457714577245773457744577545776457774577845779457804578145782457834578445785457864578745788457894579045791457924579345794457954579645797457984579945800458014580245803458044580545806458074580845809458104581145812458134581445815458164581745818458194582045821458224582345824458254582645827458284582945830458314583245833458344583545836458374583845839458404584145842458434584445845458464584745848458494585045851458524585345854458554585645857458584585945860458614586245863458644586545866458674586845869458704587145872458734587445875458764587745878458794588045881458824588345884458854588645887458884588945890458914589245893458944589545896458974589845899459004590145902459034590445905459064590745908459094591045911459124591345914459154591645917459184591945920459214592245923459244592545926459274592845929459304593145932459334593445935459364593745938459394594045941459424594345944459454594645947459484594945950459514595245953459544595545956459574595845959459604596145962459634596445965459664596745968459694597045971459724597345974459754597645977459784597945980459814598245983459844598545986459874598845989459904599145992459934599445995459964599745998459994600046001460024600346004460054600646007460084600946010460114601246013460144601546016460174601846019460204602146022460234602446025460264602746028460294603046031460324603346034460354603646037460384603946040460414604246043460444604546046460474604846049460504605146052460534605446055460564605746058460594606046061460624606346064460654606646067460684606946070460714607246073460744607546076460774607846079460804608146082460834608446085460864608746088460894609046091460924609346094460954609646097460984609946100461014610246103461044610546106461074610846109461104611146112461134611446115461164611746118461194612046121461224612346124461254612646127461284612946130461314613246133461344613546136461374613846139461404614146142461434614446145461464614746148461494615046151461524615346154461554615646157461584615946160461614616246163461644616546166461674616846169461704617146172461734617446175461764617746178461794618046181461824618346184461854618646187461884618946190461914619246193461944619546196461974619846199462004620146202462034620446205462064620746208462094621046211462124621346214462154621646217462184621946220462214622246223462244622546226462274622846229462304623146232462334623446235462364623746238462394624046241462424624346244462454624646247462484624946250462514625246253462544625546256462574625846259462604626146262462634626446265462664626746268462694627046271462724627346274462754627646277462784627946280462814628246283462844628546286462874628846289462904629146292462934629446295462964629746298462994630046301463024630346304463054630646307463084630946310463114631246313463144631546316463174631846319463204632146322463234632446325463264632746328463294633046331463324633346334463354633646337463384633946340463414634246343463444634546346463474634846349463504635146352463534635446355463564635746358463594636046361463624636346364463654636646367463684636946370463714637246373463744637546376463774637846379463804638146382463834638446385463864638746388463894639046391463924639346394463954639646397463984639946400464014640246403464044640546406464074640846409464104641146412464134641446415464164641746418464194642046421464224642346424464254642646427464284642946430464314643246433464344643546436464374643846439464404644146442464434644446445464464644746448464494645046451464524645346454464554645646457464584645946460464614646246463464644646546466464674646846469464704647146472464734647446475464764647746478464794648046481464824648346484464854648646487464884648946490464914649246493464944649546496464974649846499465004650146502465034650446505465064650746508465094651046511465124651346514465154651646517465184651946520465214652246523465244652546526465274652846529465304653146532465334653446535465364653746538465394654046541465424654346544465454654646547465484654946550465514655246553465544655546556465574655846559465604656146562465634656446565465664656746568465694657046571465724657346574465754657646577465784657946580465814658246583465844658546586465874658846589465904659146592465934659446595465964659746598465994660046601466024660346604466054660646607466084660946610466114661246613466144661546616466174661846619466204662146622466234662446625466264662746628466294663046631466324663346634466354663646637466384663946640466414664246643466444664546646466474664846649466504665146652466534665446655466564665746658466594666046661466624666346664466654666646667466684666946670466714667246673466744667546676466774667846679466804668146682466834668446685466864668746688466894669046691466924669346694466954669646697466984669946700467014670246703467044670546706467074670846709467104671146712467134671446715467164671746718467194672046721467224672346724467254672646727467284672946730467314673246733467344673546736467374673846739467404674146742467434674446745467464674746748467494675046751467524675346754467554675646757467584675946760467614676246763467644676546766467674676846769467704677146772467734677446775467764677746778467794678046781467824678346784467854678646787467884678946790467914679246793467944679546796467974679846799468004680146802468034680446805468064680746808468094681046811468124681346814468154681646817468184681946820468214682246823468244682546826468274682846829468304683146832468334683446835468364683746838468394684046841468424684346844468454684646847468484684946850468514685246853468544685546856468574685846859468604686146862468634686446865468664686746868468694687046871468724687346874468754687646877468784687946880468814688246883468844688546886468874688846889468904689146892468934689446895468964689746898468994690046901469024690346904469054690646907469084690946910469114691246913469144691546916469174691846919469204692146922469234692446925469264692746928469294693046931469324693346934469354693646937469384693946940469414694246943469444694546946469474694846949469504695146952469534695446955469564695746958469594696046961469624696346964469654696646967469684696946970469714697246973469744697546976469774697846979469804698146982469834698446985469864698746988469894699046991469924699346994469954699646997469984699947000470014700247003470044700547006470074700847009470104701147012470134701447015470164701747018470194702047021470224702347024470254702647027470284702947030470314703247033470344703547036470374703847039470404704147042470434704447045470464704747048470494705047051470524705347054470554705647057470584705947060470614706247063470644706547066470674706847069470704707147072470734707447075470764707747078470794708047081470824708347084470854708647087470884708947090470914709247093470944709547096470974709847099471004710147102471034710447105471064710747108471094711047111471124711347114471154711647117471184711947120471214712247123471244712547126471274712847129471304713147132471334713447135471364713747138471394714047141471424714347144471454714647147471484714947150471514715247153471544715547156471574715847159471604716147162471634716447165471664716747168471694717047171471724717347174471754717647177471784717947180471814718247183471844718547186471874718847189471904719147192471934719447195471964719747198471994720047201472024720347204472054720647207472084720947210472114721247213472144721547216472174721847219472204722147222472234722447225472264722747228472294723047231472324723347234472354723647237472384723947240472414724247243472444724547246472474724847249472504725147252472534725447255472564725747258472594726047261472624726347264472654726647267472684726947270472714727247273472744727547276472774727847279472804728147282472834728447285472864728747288472894729047291472924729347294472954729647297472984729947300473014730247303473044730547306473074730847309473104731147312473134731447315473164731747318473194732047321473224732347324473254732647327473284732947330473314733247333473344733547336473374733847339473404734147342473434734447345473464734747348473494735047351473524735347354473554735647357473584735947360473614736247363473644736547366473674736847369473704737147372473734737447375473764737747378473794738047381473824738347384473854738647387473884738947390473914739247393473944739547396473974739847399474004740147402474034740447405474064740747408474094741047411474124741347414474154741647417474184741947420474214742247423474244742547426474274742847429474304743147432474334743447435474364743747438474394744047441474424744347444474454744647447474484744947450474514745247453474544745547456474574745847459474604746147462474634746447465474664746747468474694747047471474724747347474474754747647477474784747947480474814748247483474844748547486474874748847489474904749147492474934749447495474964749747498474994750047501475024750347504475054750647507475084750947510475114751247513475144751547516475174751847519475204752147522475234752447525475264752747528475294753047531475324753347534475354753647537475384753947540475414754247543475444754547546475474754847549475504755147552475534755447555475564755747558475594756047561475624756347564475654756647567475684756947570475714757247573475744757547576475774757847579475804758147582475834758447585475864758747588475894759047591475924759347594475954759647597475984759947600476014760247603476044760547606476074760847609476104761147612476134761447615476164761747618476194762047621476224762347624476254762647627476284762947630476314763247633476344763547636476374763847639476404764147642476434764447645476464764747648476494765047651476524765347654476554765647657476584765947660476614766247663476644766547666476674766847669476704767147672476734767447675476764767747678476794768047681476824768347684476854768647687476884768947690476914769247693476944769547696476974769847699477004770147702477034770447705477064770747708477094771047711477124771347714477154771647717477184771947720477214772247723477244772547726477274772847729477304773147732477334773447735477364773747738477394774047741477424774347744477454774647747477484774947750477514775247753477544775547756477574775847759477604776147762477634776447765477664776747768477694777047771477724777347774477754777647777477784777947780477814778247783477844778547786477874778847789477904779147792477934779447795477964779747798477994780047801478024780347804478054780647807478084780947810478114781247813478144781547816478174781847819478204782147822478234782447825478264782747828478294783047831478324783347834478354783647837478384783947840478414784247843478444784547846478474784847849478504785147852478534785447855478564785747858478594786047861478624786347864478654786647867478684786947870478714787247873478744787547876478774787847879478804788147882478834788447885478864788747888478894789047891478924789347894478954789647897478984789947900479014790247903479044790547906479074790847909479104791147912479134791447915479164791747918479194792047921479224792347924479254792647927479284792947930479314793247933479344793547936479374793847939479404794147942479434794447945479464794747948479494795047951479524795347954479554795647957479584795947960479614796247963479644796547966479674796847969479704797147972479734797447975479764797747978479794798047981479824798347984479854798647987479884798947990479914799247993479944799547996479974799847999480004800148002480034800448005480064800748008480094801048011480124801348014480154801648017480184801948020480214802248023480244802548026480274802848029480304803148032480334803448035480364803748038480394804048041480424804348044480454804648047480484804948050480514805248053480544805548056480574805848059480604806148062480634806448065480664806748068480694807048071480724807348074480754807648077480784807948080480814808248083480844808548086480874808848089480904809148092480934809448095480964809748098480994810048101481024810348104481054810648107481084810948110481114811248113481144811548116481174811848119481204812148122481234812448125481264812748128481294813048131481324813348134481354813648137481384813948140481414814248143481444814548146481474814848149481504815148152481534815448155481564815748158481594816048161481624816348164481654816648167481684816948170481714817248173481744817548176481774817848179481804818148182481834818448185481864818748188481894819048191481924819348194481954819648197481984819948200482014820248203482044820548206482074820848209482104821148212482134821448215482164821748218482194822048221482224822348224482254822648227482284822948230482314823248233482344823548236482374823848239482404824148242482434824448245482464824748248482494825048251482524825348254482554825648257482584825948260482614826248263482644826548266482674826848269482704827148272482734827448275482764827748278482794828048281482824828348284482854828648287482884828948290482914829248293482944829548296482974829848299483004830148302483034830448305483064830748308483094831048311483124831348314483154831648317483184831948320483214832248323483244832548326483274832848329483304833148332483334833448335483364833748338483394834048341483424834348344483454834648347483484834948350483514835248353483544835548356483574835848359483604836148362483634836448365483664836748368483694837048371483724837348374483754837648377483784837948380483814838248383483844838548386483874838848389483904839148392483934839448395483964839748398483994840048401484024840348404484054840648407484084840948410484114841248413484144841548416484174841848419484204842148422484234842448425484264842748428484294843048431484324843348434484354843648437484384843948440484414844248443484444844548446484474844848449484504845148452484534845448455484564845748458484594846048461484624846348464484654846648467484684846948470484714847248473484744847548476484774847848479484804848148482484834848448485484864848748488484894849048491484924849348494484954849648497484984849948500485014850248503485044850548506485074850848509485104851148512485134851448515485164851748518485194852048521485224852348524485254852648527485284852948530485314853248533485344853548536485374853848539485404854148542485434854448545485464854748548485494855048551485524855348554485554855648557485584855948560485614856248563485644856548566485674856848569485704857148572485734857448575485764857748578485794858048581485824858348584485854858648587485884858948590485914859248593485944859548596485974859848599486004860148602486034860448605486064860748608486094861048611486124861348614486154861648617486184861948620486214862248623486244862548626486274862848629486304863148632486334863448635486364863748638486394864048641486424864348644486454864648647486484864948650486514865248653486544865548656486574865848659486604866148662486634866448665486664866748668486694867048671486724867348674486754867648677486784867948680486814868248683486844868548686486874868848689486904869148692486934869448695486964869748698486994870048701487024870348704487054870648707487084870948710487114871248713487144871548716487174871848719487204872148722487234872448725487264872748728487294873048731487324873348734487354873648737487384873948740487414874248743487444874548746487474874848749487504875148752487534875448755487564875748758487594876048761487624876348764487654876648767487684876948770487714877248773487744877548776487774877848779487804878148782487834878448785487864878748788487894879048791487924879348794487954879648797487984879948800488014880248803488044880548806488074880848809488104881148812488134881448815488164881748818488194882048821488224882348824488254882648827488284882948830488314883248833488344883548836488374883848839488404884148842488434884448845488464884748848488494885048851488524885348854488554885648857488584885948860488614886248863488644886548866488674886848869488704887148872488734887448875488764887748878488794888048881488824888348884488854888648887488884888948890488914889248893488944889548896488974889848899489004890148902489034890448905489064890748908489094891048911489124891348914489154891648917489184891948920489214892248923489244892548926489274892848929489304893148932489334893448935489364893748938489394894048941489424894348944489454894648947489484894948950489514895248953489544895548956489574895848959489604896148962489634896448965489664896748968489694897048971489724897348974489754897648977489784897948980489814898248983489844898548986489874898848989489904899148992489934899448995489964899748998489994900049001490024900349004490054900649007490084900949010490114901249013490144901549016490174901849019490204902149022490234902449025490264902749028490294903049031490324903349034490354903649037490384903949040490414904249043490444904549046490474904849049490504905149052490534905449055490564905749058490594906049061490624906349064490654906649067490684906949070490714907249073490744907549076490774907849079490804908149082490834908449085490864908749088490894909049091490924909349094490954909649097490984909949100491014910249103491044910549106491074910849109491104911149112491134911449115491164911749118491194912049121491224912349124491254912649127491284912949130491314913249133491344913549136491374913849139491404914149142491434914449145491464914749148491494915049151491524915349154491554915649157491584915949160491614916249163491644916549166491674916849169491704917149172491734917449175491764917749178491794918049181491824918349184491854918649187491884918949190491914919249193491944919549196491974919849199492004920149202492034920449205492064920749208492094921049211492124921349214492154921649217492184921949220492214922249223492244922549226492274922849229492304923149232492334923449235492364923749238492394924049241492424924349244492454924649247492484924949250492514925249253492544925549256492574925849259492604926149262492634926449265492664926749268492694927049271492724927349274492754927649277492784927949280492814928249283492844928549286492874928849289492904929149292492934929449295492964929749298492994930049301493024930349304493054930649307493084930949310493114931249313493144931549316493174931849319493204932149322493234932449325493264932749328493294933049331493324933349334493354933649337493384933949340493414934249343493444934549346493474934849349493504935149352493534935449355493564935749358493594936049361493624936349364493654936649367493684936949370493714937249373493744937549376493774937849379493804938149382493834938449385493864938749388493894939049391493924939349394493954939649397493984939949400494014940249403494044940549406494074940849409494104941149412494134941449415494164941749418494194942049421494224942349424494254942649427494284942949430494314943249433494344943549436494374943849439494404944149442494434944449445494464944749448494494945049451494524945349454494554945649457494584945949460494614946249463494644946549466494674946849469494704947149472494734947449475494764947749478494794948049481494824948349484494854948649487494884948949490494914949249493494944949549496494974949849499495004950149502495034950449505495064950749508495094951049511495124951349514495154951649517495184951949520495214952249523495244952549526495274952849529495304953149532495334953449535495364953749538495394954049541495424954349544495454954649547495484954949550495514955249553495544955549556495574955849559495604956149562495634956449565495664956749568495694957049571495724957349574495754957649577495784957949580495814958249583495844958549586495874958849589495904959149592495934959449595495964959749598495994960049601496024960349604496054960649607496084960949610496114961249613496144961549616496174961849619496204962149622496234962449625496264962749628496294963049631496324963349634496354963649637496384963949640496414964249643496444964549646496474964849649496504965149652496534965449655496564965749658496594966049661496624966349664496654966649667496684966949670496714967249673496744967549676496774967849679496804968149682496834968449685496864968749688496894969049691496924969349694496954969649697496984969949700497014970249703497044970549706497074970849709497104971149712497134971449715497164971749718497194972049721497224972349724497254972649727497284972949730497314973249733497344973549736497374973849739497404974149742497434974449745497464974749748497494975049751497524975349754497554975649757497584975949760497614976249763497644976549766497674976849769497704977149772497734977449775497764977749778497794978049781497824978349784497854978649787497884978949790497914979249793497944979549796497974979849799498004980149802498034980449805498064980749808498094981049811498124981349814498154981649817498184981949820498214982249823498244982549826498274982849829498304983149832498334983449835498364983749838498394984049841498424984349844498454984649847498484984949850498514985249853498544985549856498574985849859498604986149862498634986449865498664986749868498694987049871498724987349874498754987649877498784987949880498814988249883498844988549886498874988849889498904989149892498934989449895498964989749898498994990049901499024990349904499054990649907499084990949910499114991249913499144991549916499174991849919499204992149922499234992449925499264992749928499294993049931499324993349934499354993649937499384993949940499414994249943499444994549946499474994849949499504995149952499534995449955499564995749958499594996049961499624996349964499654996649967499684996949970499714997249973499744997549976499774997849979499804998149982499834998449985499864998749988499894999049991499924999349994499954999649997499984999950000500015000250003500045000550006500075000850009500105001150012500135001450015500165001750018500195002050021500225002350024500255002650027500285002950030500315003250033500345003550036500375003850039500405004150042500435004450045500465004750048500495005050051500525005350054500555005650057500585005950060500615006250063500645006550066500675006850069500705007150072500735007450075500765007750078500795008050081500825008350084500855008650087500885008950090500915009250093500945009550096500975009850099501005010150102501035010450105501065010750108501095011050111501125011350114501155011650117501185011950120501215012250123501245012550126501275012850129501305013150132501335013450135501365013750138501395014050141501425014350144501455014650147501485014950150501515015250153501545015550156501575015850159501605016150162501635016450165501665016750168501695017050171501725017350174501755017650177501785017950180501815018250183501845018550186501875018850189501905019150192501935019450195501965019750198501995020050201502025020350204502055020650207502085020950210502115021250213502145021550216502175021850219502205022150222502235022450225502265022750228502295023050231502325023350234502355023650237502385023950240502415024250243502445024550246502475024850249502505025150252502535025450255502565025750258502595026050261502625026350264502655026650267502685026950270502715027250273502745027550276502775027850279502805028150282502835028450285502865028750288502895029050291502925029350294502955029650297502985029950300503015030250303503045030550306503075030850309503105031150312503135031450315503165031750318503195032050321503225032350324503255032650327503285032950330503315033250333503345033550336503375033850339503405034150342503435034450345503465034750348503495035050351503525035350354503555035650357503585035950360503615036250363503645036550366503675036850369503705037150372503735037450375503765037750378503795038050381503825038350384503855038650387503885038950390503915039250393503945039550396503975039850399504005040150402504035040450405504065040750408504095041050411504125041350414504155041650417504185041950420504215042250423504245042550426504275042850429504305043150432504335043450435504365043750438504395044050441504425044350444504455044650447504485044950450504515045250453504545045550456504575045850459504605046150462504635046450465504665046750468504695047050471504725047350474504755047650477504785047950480504815048250483504845048550486504875048850489504905049150492504935049450495504965049750498504995050050501505025050350504505055050650507505085050950510505115051250513505145051550516505175051850519505205052150522505235052450525505265052750528505295053050531505325053350534505355053650537505385053950540505415054250543505445054550546505475054850549505505055150552505535055450555505565055750558505595056050561505625056350564505655056650567505685056950570505715057250573505745057550576505775057850579505805058150582505835058450585505865058750588505895059050591505925059350594505955059650597505985059950600506015060250603506045060550606506075060850609506105061150612506135061450615506165061750618506195062050621506225062350624506255062650627506285062950630506315063250633506345063550636506375063850639506405064150642506435064450645506465064750648506495065050651506525065350654506555065650657506585065950660506615066250663506645066550666506675066850669506705067150672506735067450675506765067750678506795068050681506825068350684506855068650687506885068950690506915069250693506945069550696506975069850699507005070150702507035070450705507065070750708507095071050711507125071350714507155071650717507185071950720507215072250723507245072550726507275072850729507305073150732507335073450735507365073750738507395074050741507425074350744507455074650747507485074950750507515075250753507545075550756507575075850759507605076150762507635076450765507665076750768507695077050771507725077350774507755077650777507785077950780507815078250783507845078550786507875078850789507905079150792507935079450795507965079750798507995080050801508025080350804508055080650807508085080950810508115081250813508145081550816508175081850819508205082150822508235082450825508265082750828508295083050831508325083350834508355083650837508385083950840508415084250843508445084550846508475084850849508505085150852508535085450855508565085750858508595086050861508625086350864508655086650867508685086950870508715087250873508745087550876508775087850879508805088150882508835088450885508865088750888508895089050891508925089350894508955089650897508985089950900509015090250903509045090550906509075090850909509105091150912509135091450915509165091750918509195092050921509225092350924509255092650927509285092950930509315093250933509345093550936509375093850939509405094150942509435094450945509465094750948509495095050951509525095350954509555095650957509585095950960509615096250963509645096550966509675096850969509705097150972509735097450975509765097750978509795098050981509825098350984509855098650987509885098950990509915099250993509945099550996509975099850999510005100151002510035100451005510065100751008510095101051011510125101351014510155101651017510185101951020510215102251023510245102551026510275102851029510305103151032510335103451035510365103751038510395104051041510425104351044510455104651047510485104951050510515105251053510545105551056510575105851059510605106151062510635106451065510665106751068510695107051071510725107351074510755107651077510785107951080510815108251083510845108551086510875108851089510905109151092510935109451095510965109751098510995110051101511025110351104511055110651107511085110951110511115111251113511145111551116511175111851119511205112151122511235112451125511265112751128511295113051131511325113351134511355113651137511385113951140511415114251143511445114551146511475114851149511505115151152511535115451155511565115751158511595116051161511625116351164511655116651167511685116951170511715117251173511745117551176511775117851179511805118151182511835118451185511865118751188511895119051191511925119351194511955119651197511985119951200512015120251203512045120551206512075120851209512105121151212512135121451215512165121751218512195122051221512225122351224512255122651227512285122951230512315123251233512345123551236512375123851239512405124151242512435124451245512465124751248512495125051251512525125351254512555125651257512585125951260512615126251263512645126551266512675126851269512705127151272512735127451275512765127751278512795128051281512825128351284512855128651287512885128951290512915129251293512945129551296512975129851299513005130151302513035130451305513065130751308513095131051311513125131351314513155131651317513185131951320513215132251323513245132551326513275132851329513305133151332513335133451335513365133751338513395134051341513425134351344513455134651347513485134951350513515135251353513545135551356513575135851359513605136151362513635136451365513665136751368513695137051371513725137351374513755137651377513785137951380513815138251383513845138551386513875138851389513905139151392513935139451395513965139751398513995140051401514025140351404514055140651407514085140951410514115141251413514145141551416514175141851419514205142151422514235142451425514265142751428514295143051431514325143351434514355143651437514385143951440514415144251443514445144551446514475144851449514505145151452514535145451455514565145751458514595146051461514625146351464514655146651467514685146951470514715147251473514745147551476514775147851479514805148151482514835148451485514865148751488514895149051491514925149351494514955149651497514985149951500515015150251503515045150551506515075150851509515105151151512515135151451515515165151751518515195152051521515225152351524515255152651527515285152951530515315153251533515345153551536515375153851539515405154151542515435154451545515465154751548515495155051551515525155351554515555155651557515585155951560515615156251563515645156551566515675156851569515705157151572515735157451575515765157751578515795158051581515825158351584515855158651587515885158951590515915159251593515945159551596515975159851599516005160151602516035160451605516065160751608516095161051611516125161351614516155161651617516185161951620516215162251623516245162551626516275162851629516305163151632516335163451635516365163751638516395164051641516425164351644516455164651647516485164951650516515165251653516545165551656516575165851659516605166151662516635166451665516665166751668516695167051671516725167351674516755167651677516785167951680516815168251683516845168551686516875168851689516905169151692516935169451695516965169751698516995170051701517025170351704517055170651707517085170951710517115171251713517145171551716517175171851719517205172151722517235172451725517265172751728517295173051731517325173351734517355173651737517385173951740517415174251743517445174551746517475174851749517505175151752517535175451755517565175751758517595176051761517625176351764517655176651767517685176951770517715177251773517745177551776517775177851779517805178151782517835178451785517865178751788517895179051791517925179351794517955179651797517985179951800518015180251803518045180551806518075180851809518105181151812518135181451815518165181751818518195182051821518225182351824518255182651827518285182951830518315183251833518345183551836518375183851839518405184151842518435184451845518465184751848518495185051851518525185351854518555185651857518585185951860518615186251863518645186551866518675186851869518705187151872518735187451875518765187751878518795188051881518825188351884518855188651887518885188951890518915189251893518945189551896518975189851899519005190151902519035190451905519065190751908519095191051911519125191351914519155191651917519185191951920519215192251923519245192551926519275192851929519305193151932519335193451935519365193751938519395194051941519425194351944519455194651947519485194951950519515195251953519545195551956519575195851959519605196151962519635196451965519665196751968519695197051971519725197351974519755197651977519785197951980519815198251983519845198551986519875198851989519905199151992519935199451995519965199751998519995200052001520025200352004520055200652007520085200952010520115201252013520145201552016520175201852019520205202152022520235202452025520265202752028520295203052031520325203352034520355203652037520385203952040520415204252043520445204552046520475204852049520505205152052520535205452055520565205752058520595206052061520625206352064520655206652067520685206952070520715207252073520745207552076520775207852079520805208152082520835208452085520865208752088520895209052091520925209352094520955209652097520985209952100521015210252103521045210552106521075210852109521105211152112521135211452115521165211752118521195212052121521225212352124521255212652127521285212952130521315213252133521345213552136521375213852139521405214152142521435214452145521465214752148521495215052151521525215352154521555215652157521585215952160521615216252163521645216552166521675216852169521705217152172521735217452175521765217752178521795218052181521825218352184521855218652187521885218952190521915219252193521945219552196521975219852199522005220152202522035220452205522065220752208522095221052211522125221352214522155221652217522185221952220522215222252223522245222552226522275222852229522305223152232522335223452235522365223752238522395224052241522425224352244522455224652247522485224952250522515225252253522545225552256522575225852259522605226152262522635226452265522665226752268522695227052271522725227352274522755227652277522785227952280522815228252283522845228552286522875228852289522905229152292522935229452295522965229752298522995230052301523025230352304523055230652307523085230952310523115231252313523145231552316523175231852319523205232152322523235232452325523265232752328523295233052331523325233352334523355233652337523385233952340523415234252343523445234552346523475234852349523505235152352523535235452355523565235752358523595236052361523625236352364523655236652367523685236952370523715237252373523745237552376523775237852379523805238152382523835238452385523865238752388523895239052391523925239352394523955239652397523985239952400524015240252403524045240552406524075240852409524105241152412524135241452415524165241752418524195242052421524225242352424524255242652427524285242952430524315243252433524345243552436524375243852439524405244152442524435244452445524465244752448524495245052451524525245352454524555245652457524585245952460524615246252463524645246552466524675246852469524705247152472524735247452475524765247752478524795248052481524825248352484524855248652487524885248952490524915249252493524945249552496524975249852499525005250152502525035250452505525065250752508525095251052511525125251352514525155251652517525185251952520525215252252523525245252552526525275252852529525305253152532525335253452535525365253752538525395254052541525425254352544525455254652547525485254952550525515255252553525545255552556525575255852559525605256152562525635256452565525665256752568525695257052571525725257352574525755257652577525785257952580525815258252583525845258552586525875258852589525905259152592525935259452595525965259752598525995260052601526025260352604526055260652607526085260952610526115261252613526145261552616526175261852619526205262152622526235262452625526265262752628526295263052631526325263352634526355263652637526385263952640526415264252643526445264552646526475264852649526505265152652526535265452655526565265752658526595266052661526625266352664526655266652667526685266952670526715267252673526745267552676526775267852679526805268152682526835268452685526865268752688526895269052691526925269352694526955269652697526985269952700527015270252703527045270552706527075270852709527105271152712527135271452715527165271752718527195272052721527225272352724527255272652727527285272952730527315273252733527345273552736527375273852739527405274152742527435274452745527465274752748527495275052751527525275352754527555275652757527585275952760527615276252763527645276552766527675276852769527705277152772527735277452775527765277752778527795278052781527825278352784527855278652787527885278952790527915279252793527945279552796527975279852799528005280152802528035280452805528065280752808528095281052811528125281352814528155281652817528185281952820528215282252823528245282552826528275282852829528305283152832528335283452835528365283752838528395284052841528425284352844528455284652847528485284952850528515285252853528545285552856528575285852859528605286152862528635286452865528665286752868528695287052871528725287352874528755287652877528785287952880528815288252883528845288552886528875288852889528905289152892528935289452895528965289752898528995290052901529025290352904529055290652907529085290952910529115291252913529145291552916529175291852919529205292152922529235292452925529265292752928529295293052931529325293352934529355293652937529385293952940529415294252943529445294552946529475294852949529505295152952529535295452955529565295752958529595296052961529625296352964529655296652967529685296952970529715297252973529745297552976529775297852979529805298152982529835298452985529865298752988529895299052991529925299352994529955299652997529985299953000530015300253003530045300553006530075300853009530105301153012530135301453015530165301753018530195302053021530225302353024530255302653027530285302953030530315303253033530345303553036530375303853039530405304153042530435304453045530465304753048530495305053051530525305353054530555305653057530585305953060530615306253063530645306553066530675306853069530705307153072530735307453075530765307753078530795308053081530825308353084530855308653087530885308953090530915309253093530945309553096530975309853099531005310153102531035310453105531065310753108531095311053111531125311353114531155311653117531185311953120531215312253123531245312553126531275312853129531305313153132531335313453135531365313753138531395314053141531425314353144531455314653147531485314953150531515315253153531545315553156531575315853159531605316153162531635316453165531665316753168531695317053171531725317353174531755317653177531785317953180531815318253183531845318553186531875318853189531905319153192531935319453195531965319753198531995320053201532025320353204532055320653207532085320953210532115321253213532145321553216532175321853219532205322153222532235322453225532265322753228532295323053231532325323353234532355323653237532385323953240532415324253243532445324553246532475324853249532505325153252532535325453255532565325753258532595326053261532625326353264532655326653267532685326953270532715327253273532745327553276532775327853279532805328153282532835328453285532865328753288532895329053291532925329353294532955329653297532985329953300533015330253303533045330553306533075330853309533105331153312533135331453315533165331753318533195332053321533225332353324533255332653327533285332953330533315333253333533345333553336533375333853339533405334153342533435334453345533465334753348533495335053351533525335353354533555335653357533585335953360533615336253363533645336553366533675336853369533705337153372533735337453375533765337753378533795338053381533825338353384533855338653387533885338953390533915339253393533945339553396533975339853399534005340153402534035340453405534065340753408534095341053411534125341353414534155341653417534185341953420534215342253423534245342553426534275342853429534305343153432534335343453435534365343753438534395344053441534425344353444534455344653447534485344953450534515345253453534545345553456534575345853459534605346153462534635346453465534665346753468534695347053471534725347353474534755347653477534785347953480534815348253483534845348553486534875348853489534905349153492534935349453495534965349753498534995350053501535025350353504535055350653507535085350953510535115351253513535145351553516535175351853519535205352153522535235352453525535265352753528535295353053531535325353353534535355353653537535385353953540535415354253543535445354553546535475354853549535505355153552535535355453555535565355753558535595356053561535625356353564535655356653567535685356953570535715357253573535745357553576535775357853579535805358153582535835358453585535865358753588535895359053591535925359353594535955359653597535985359953600536015360253603536045360553606536075360853609536105361153612536135361453615536165361753618536195362053621536225362353624536255362653627536285362953630536315363253633536345363553636536375363853639536405364153642536435364453645536465364753648536495365053651536525365353654536555365653657536585365953660536615366253663536645366553666536675366853669536705367153672536735367453675536765367753678536795368053681536825368353684536855368653687536885368953690536915369253693536945369553696536975369853699537005370153702537035370453705537065370753708537095371053711537125371353714537155371653717537185371953720537215372253723537245372553726537275372853729537305373153732537335373453735537365373753738537395374053741537425374353744537455374653747537485374953750537515375253753537545375553756537575375853759537605376153762537635376453765537665376753768537695377053771537725377353774537755377653777537785377953780537815378253783537845378553786537875378853789537905379153792537935379453795537965379753798537995380053801538025380353804538055380653807538085380953810538115381253813538145381553816538175381853819538205382153822538235382453825538265382753828538295383053831538325383353834538355383653837538385383953840538415384253843538445384553846538475384853849538505385153852538535385453855538565385753858538595386053861538625386353864538655386653867538685386953870538715387253873538745387553876538775387853879538805388153882538835388453885538865388753888538895389053891538925389353894538955389653897538985389953900539015390253903539045390553906539075390853909539105391153912539135391453915539165391753918539195392053921539225392353924539255392653927539285392953930539315393253933539345393553936539375393853939539405394153942539435394453945539465394753948539495395053951539525395353954539555395653957539585395953960539615396253963539645396553966539675396853969539705397153972539735397453975539765397753978539795398053981539825398353984539855398653987539885398953990539915399253993539945399553996539975399853999540005400154002540035400454005540065400754008540095401054011540125401354014540155401654017540185401954020540215402254023540245402554026540275402854029540305403154032540335403454035540365403754038540395404054041540425404354044540455404654047540485404954050540515405254053540545405554056540575405854059540605406154062540635406454065540665406754068540695407054071540725407354074540755407654077540785407954080540815408254083540845408554086540875408854089540905409154092540935409454095540965409754098540995410054101541025410354104541055410654107541085410954110541115411254113541145411554116541175411854119541205412154122541235412454125541265412754128541295413054131541325413354134541355413654137541385413954140541415414254143541445414554146541475414854149541505415154152541535415454155541565415754158541595416054161541625416354164541655416654167541685416954170541715417254173541745417554176541775417854179541805418154182541835418454185541865418754188541895419054191541925419354194541955419654197541985419954200542015420254203542045420554206542075420854209542105421154212542135421454215542165421754218542195422054221542225422354224542255422654227542285422954230542315423254233542345423554236542375423854239542405424154242542435424454245542465424754248542495425054251542525425354254542555425654257542585425954260542615426254263542645426554266542675426854269542705427154272542735427454275542765427754278542795428054281542825428354284542855428654287542885428954290542915429254293542945429554296542975429854299543005430154302543035430454305543065430754308543095431054311543125431354314543155431654317543185431954320543215432254323543245432554326543275432854329543305433154332543335433454335543365433754338543395434054341543425434354344543455434654347543485434954350543515435254353543545435554356543575435854359543605436154362543635436454365543665436754368543695437054371543725437354374543755437654377543785437954380543815438254383543845438554386543875438854389543905439154392543935439454395543965439754398543995440054401544025440354404544055440654407544085440954410544115441254413544145441554416544175441854419544205442154422544235442454425544265442754428544295443054431544325443354434544355443654437544385443954440544415444254443544445444554446544475444854449544505445154452544535445454455544565445754458544595446054461544625446354464544655446654467544685446954470544715447254473544745447554476544775447854479544805448154482544835448454485544865448754488544895449054491544925449354494544955449654497544985449954500545015450254503545045450554506545075450854509545105451154512545135451454515545165451754518545195452054521545225452354524545255452654527545285452954530545315453254533545345453554536545375453854539545405454154542545435454454545545465454754548545495455054551545525455354554545555455654557545585455954560545615456254563545645456554566545675456854569545705457154572545735457454575545765457754578545795458054581545825458354584545855458654587545885458954590545915459254593545945459554596545975459854599546005460154602546035460454605546065460754608546095461054611546125461354614546155461654617546185461954620546215462254623546245462554626546275462854629546305463154632546335463454635546365463754638546395464054641546425464354644546455464654647546485464954650546515465254653546545465554656546575465854659546605466154662546635466454665546665466754668546695467054671546725467354674546755467654677546785467954680546815468254683546845468554686546875468854689546905469154692546935469454695546965469754698546995470054701547025470354704547055470654707547085470954710547115471254713547145471554716547175471854719547205472154722547235472454725547265472754728547295473054731547325473354734547355473654737547385473954740547415474254743547445474554746547475474854749547505475154752547535475454755547565475754758547595476054761547625476354764547655476654767547685476954770547715477254773547745477554776547775477854779547805478154782547835478454785547865478754788547895479054791547925479354794547955479654797547985479954800548015480254803548045480554806548075480854809548105481154812548135481454815548165481754818548195482054821548225482354824548255482654827548285482954830548315483254833548345483554836548375483854839548405484154842548435484454845548465484754848548495485054851548525485354854548555485654857548585485954860548615486254863548645486554866548675486854869548705487154872548735487454875548765487754878548795488054881548825488354884548855488654887548885488954890548915489254893548945489554896548975489854899549005490154902549035490454905549065490754908549095491054911549125491354914549155491654917549185491954920549215492254923549245492554926549275492854929549305493154932549335493454935549365493754938549395494054941549425494354944549455494654947549485494954950549515495254953549545495554956549575495854959549605496154962549635496454965549665496754968549695497054971549725497354974549755497654977549785497954980549815498254983549845498554986549875498854989549905499154992549935499454995549965499754998549995500055001550025500355004550055500655007550085500955010550115501255013550145501555016550175501855019550205502155022550235502455025550265502755028550295503055031550325503355034550355503655037550385503955040550415504255043550445504555046550475504855049550505505155052550535505455055550565505755058550595506055061550625506355064550655506655067550685506955070550715507255073550745507555076550775507855079550805508155082550835508455085550865508755088550895509055091550925509355094550955509655097550985509955100551015510255103551045510555106551075510855109551105511155112551135511455115551165511755118551195512055121551225512355124551255512655127551285512955130551315513255133551345513555136551375513855139551405514155142551435514455145551465514755148551495515055151551525515355154551555515655157551585515955160551615516255163551645516555166551675516855169551705517155172551735517455175551765517755178551795518055181551825518355184551855518655187551885518955190551915519255193551945519555196551975519855199552005520155202552035520455205552065520755208552095521055211552125521355214552155521655217552185521955220552215522255223552245522555226552275522855229552305523155232552335523455235552365523755238552395524055241552425524355244552455524655247552485524955250552515525255253552545525555256552575525855259552605526155262552635526455265552665526755268552695527055271552725527355274552755527655277552785527955280552815528255283552845528555286552875528855289552905529155292552935529455295552965529755298552995530055301553025530355304553055530655307553085530955310553115531255313553145531555316553175531855319553205532155322553235532455325553265532755328553295533055331553325533355334553355533655337553385533955340553415534255343553445534555346553475534855349553505535155352553535535455355553565535755358553595536055361553625536355364553655536655367553685536955370553715537255373553745537555376553775537855379553805538155382553835538455385553865538755388553895539055391553925539355394553955539655397553985539955400554015540255403554045540555406554075540855409554105541155412554135541455415554165541755418554195542055421554225542355424554255542655427554285542955430554315543255433554345543555436554375543855439554405544155442554435544455445554465544755448554495545055451554525545355454554555545655457554585545955460554615546255463554645546555466554675546855469554705547155472554735547455475554765547755478554795548055481554825548355484554855548655487554885548955490554915549255493554945549555496554975549855499555005550155502555035550455505555065550755508555095551055511555125551355514555155551655517555185551955520555215552255523555245552555526555275552855529555305553155532555335553455535555365553755538555395554055541555425554355544555455554655547555485554955550555515555255553555545555555556555575555855559555605556155562555635556455565555665556755568555695557055571555725557355574555755557655577555785557955580555815558255583555845558555586555875558855589555905559155592555935559455595555965559755598555995560055601556025560355604556055560655607556085560955610556115561255613556145561555616556175561855619556205562155622556235562455625556265562755628556295563055631556325563355634556355563655637556385563955640556415564255643556445564555646556475564855649556505565155652556535565455655556565565755658556595566055661556625566355664556655566655667556685566955670556715567255673556745567555676556775567855679556805568155682556835568455685556865568755688556895569055691556925569355694556955569655697556985569955700557015570255703557045570555706557075570855709557105571155712557135571455715557165571755718557195572055721557225572355724557255572655727557285572955730557315573255733557345573555736557375573855739557405574155742557435574455745557465574755748557495575055751557525575355754557555575655757557585575955760557615576255763557645576555766557675576855769557705577155772557735577455775557765577755778557795578055781557825578355784557855578655787557885578955790557915579255793557945579555796557975579855799558005580155802558035580455805558065580755808558095581055811558125581355814558155581655817558185581955820558215582255823558245582555826558275582855829558305583155832558335583455835558365583755838558395584055841558425584355844558455584655847558485584955850558515585255853558545585555856558575585855859558605586155862558635586455865558665586755868558695587055871558725587355874558755587655877558785587955880558815588255883558845588555886558875588855889558905589155892558935589455895558965589755898558995590055901559025590355904559055590655907559085590955910559115591255913559145591555916559175591855919559205592155922559235592455925559265592755928559295593055931559325593355934559355593655937559385593955940559415594255943559445594555946559475594855949559505595155952559535595455955559565595755958559595596055961559625596355964559655596655967559685596955970559715597255973559745597555976559775597855979559805598155982559835598455985559865598755988559895599055991559925599355994559955599655997559985599956000560015600256003560045600556006560075600856009560105601156012560135601456015560165601756018560195602056021560225602356024560255602656027560285602956030560315603256033560345603556036560375603856039560405604156042560435604456045560465604756048560495605056051560525605356054560555605656057560585605956060560615606256063560645606556066560675606856069560705607156072560735607456075560765607756078560795608056081560825608356084560855608656087560885608956090560915609256093560945609556096560975609856099561005610156102561035610456105561065610756108561095611056111561125611356114561155611656117561185611956120561215612256123561245612556126561275612856129561305613156132561335613456135561365613756138561395614056141561425614356144561455614656147561485614956150561515615256153561545615556156561575615856159561605616156162561635616456165561665616756168561695617056171561725617356174561755617656177561785617956180561815618256183561845618556186561875618856189561905619156192561935619456195561965619756198561995620056201562025620356204562055620656207562085620956210562115621256213562145621556216562175621856219562205622156222562235622456225562265622756228562295623056231562325623356234562355623656237562385623956240562415624256243562445624556246562475624856249562505625156252562535625456255562565625756258562595626056261562625626356264562655626656267562685626956270562715627256273562745627556276562775627856279562805628156282562835628456285562865628756288562895629056291562925629356294562955629656297562985629956300563015630256303563045630556306563075630856309563105631156312563135631456315563165631756318563195632056321563225632356324563255632656327563285632956330563315633256333563345633556336563375633856339563405634156342563435634456345563465634756348563495635056351563525635356354563555635656357563585635956360563615636256363563645636556366563675636856369563705637156372563735637456375563765637756378563795638056381563825638356384563855638656387563885638956390563915639256393563945639556396563975639856399564005640156402564035640456405564065640756408564095641056411564125641356414564155641656417564185641956420564215642256423564245642556426564275642856429564305643156432564335643456435564365643756438564395644056441564425644356444564455644656447564485644956450564515645256453564545645556456564575645856459564605646156462564635646456465564665646756468564695647056471564725647356474564755647656477564785647956480564815648256483564845648556486564875648856489564905649156492564935649456495564965649756498564995650056501565025650356504565055650656507565085650956510565115651256513565145651556516565175651856519565205652156522565235652456525565265652756528565295653056531565325653356534565355653656537565385653956540565415654256543565445654556546565475654856549565505655156552565535655456555565565655756558565595656056561565625656356564565655656656567565685656956570565715657256573565745657556576565775657856579565805658156582565835658456585565865658756588565895659056591565925659356594565955659656597565985659956600566015660256603566045660556606566075660856609566105661156612566135661456615566165661756618566195662056621566225662356624566255662656627566285662956630566315663256633566345663556636566375663856639566405664156642566435664456645566465664756648566495665056651566525665356654566555665656657566585665956660566615666256663566645666556666566675666856669566705667156672566735667456675566765667756678566795668056681566825668356684566855668656687566885668956690566915669256693566945669556696566975669856699567005670156702567035670456705567065670756708567095671056711567125671356714567155671656717567185671956720567215672256723567245672556726567275672856729567305673156732567335673456735567365673756738567395674056741567425674356744567455674656747567485674956750567515675256753567545675556756567575675856759567605676156762567635676456765567665676756768567695677056771567725677356774567755677656777567785677956780567815678256783567845678556786567875678856789567905679156792567935679456795567965679756798567995680056801568025680356804568055680656807568085680956810568115681256813568145681556816568175681856819568205682156822568235682456825568265682756828568295683056831568325683356834568355683656837568385683956840568415684256843568445684556846568475684856849568505685156852568535685456855568565685756858568595686056861568625686356864568655686656867568685686956870568715687256873568745687556876568775687856879568805688156882568835688456885568865688756888568895689056891568925689356894568955689656897568985689956900569015690256903569045690556906569075690856909569105691156912569135691456915569165691756918569195692056921569225692356924569255692656927569285692956930569315693256933569345693556936569375693856939569405694156942569435694456945569465694756948569495695056951569525695356954569555695656957569585695956960569615696256963569645696556966569675696856969569705697156972569735697456975569765697756978569795698056981569825698356984569855698656987569885698956990569915699256993569945699556996569975699856999570005700157002570035700457005570065700757008570095701057011570125701357014570155701657017570185701957020570215702257023570245702557026570275702857029570305703157032570335703457035570365703757038570395704057041570425704357044570455704657047570485704957050570515705257053570545705557056570575705857059570605706157062570635706457065570665706757068570695707057071570725707357074570755707657077570785707957080570815708257083570845708557086570875708857089570905709157092570935709457095570965709757098570995710057101571025710357104571055710657107571085710957110571115711257113571145711557116571175711857119571205712157122571235712457125571265712757128571295713057131571325713357134571355713657137571385713957140571415714257143571445714557146571475714857149571505715157152571535715457155571565715757158571595716057161571625716357164571655716657167571685716957170571715717257173571745717557176571775717857179571805718157182571835718457185571865718757188571895719057191571925719357194571955719657197571985719957200572015720257203572045720557206572075720857209572105721157212572135721457215572165721757218572195722057221572225722357224572255722657227572285722957230572315723257233572345723557236572375723857239572405724157242572435724457245572465724757248572495725057251572525725357254572555725657257572585725957260572615726257263572645726557266572675726857269572705727157272572735727457275572765727757278572795728057281572825728357284572855728657287572885728957290572915729257293572945729557296572975729857299573005730157302573035730457305573065730757308573095731057311573125731357314573155731657317573185731957320573215732257323573245732557326573275732857329573305733157332573335733457335573365733757338573395734057341573425734357344573455734657347573485734957350573515735257353573545735557356573575735857359573605736157362573635736457365573665736757368573695737057371573725737357374573755737657377573785737957380573815738257383573845738557386573875738857389573905739157392573935739457395573965739757398573995740057401574025740357404574055740657407574085740957410574115741257413574145741557416574175741857419574205742157422574235742457425574265742757428574295743057431574325743357434574355743657437574385743957440574415744257443574445744557446574475744857449574505745157452574535745457455574565745757458574595746057461574625746357464574655746657467574685746957470574715747257473574745747557476574775747857479574805748157482574835748457485574865748757488574895749057491574925749357494574955749657497574985749957500575015750257503575045750557506575075750857509575105751157512575135751457515575165751757518575195752057521575225752357524575255752657527575285752957530575315753257533575345753557536575375753857539575405754157542575435754457545575465754757548575495755057551575525755357554575555755657557575585755957560575615756257563575645756557566575675756857569575705757157572575735757457575575765757757578575795758057581575825758357584575855758657587575885758957590575915759257593575945759557596575975759857599576005760157602576035760457605576065760757608576095761057611576125761357614576155761657617576185761957620576215762257623576245762557626576275762857629576305763157632576335763457635576365763757638576395764057641576425764357644576455764657647576485764957650576515765257653576545765557656576575765857659576605766157662576635766457665576665766757668576695767057671576725767357674576755767657677576785767957680576815768257683576845768557686576875768857689576905769157692576935769457695576965769757698576995770057701577025770357704577055770657707577085770957710577115771257713577145771557716577175771857719577205772157722577235772457725577265772757728577295773057731577325773357734577355773657737577385773957740577415774257743577445774557746577475774857749577505775157752577535775457755577565775757758577595776057761577625776357764577655776657767577685776957770577715777257773577745777557776577775777857779577805778157782577835778457785577865778757788577895779057791577925779357794577955779657797577985779957800578015780257803578045780557806578075780857809578105781157812578135781457815578165781757818578195782057821578225782357824578255782657827578285782957830578315783257833578345783557836578375783857839578405784157842578435784457845578465784757848578495785057851578525785357854578555785657857578585785957860578615786257863578645786557866578675786857869578705787157872578735787457875578765787757878578795788057881578825788357884578855788657887578885788957890578915789257893578945789557896578975789857899579005790157902579035790457905579065790757908579095791057911579125791357914579155791657917579185791957920579215792257923579245792557926579275792857929579305793157932579335793457935579365793757938579395794057941579425794357944579455794657947579485794957950579515795257953579545795557956579575795857959579605796157962579635796457965579665796757968579695797057971579725797357974579755797657977579785797957980579815798257983579845798557986579875798857989579905799157992579935799457995579965799757998579995800058001580025800358004580055800658007580085800958010580115801258013580145801558016580175801858019580205802158022580235802458025580265802758028580295803058031580325803358034580355803658037580385803958040580415804258043580445804558046580475804858049580505805158052580535805458055580565805758058580595806058061580625806358064580655806658067580685806958070580715807258073580745807558076580775807858079580805808158082580835808458085580865808758088580895809058091580925809358094580955809658097580985809958100581015810258103581045810558106581075810858109581105811158112581135811458115581165811758118581195812058121581225812358124581255812658127581285812958130581315813258133581345813558136581375813858139581405814158142581435814458145581465814758148581495815058151581525815358154581555815658157581585815958160581615816258163581645816558166581675816858169581705817158172581735817458175581765817758178581795818058181581825818358184581855818658187581885818958190581915819258193581945819558196581975819858199582005820158202582035820458205582065820758208582095821058211582125821358214582155821658217582185821958220582215822258223582245822558226582275822858229582305823158232582335823458235582365823758238582395824058241582425824358244582455824658247582485824958250582515825258253582545825558256582575825858259582605826158262582635826458265582665826758268582695827058271582725827358274582755827658277582785827958280582815828258283582845828558286582875828858289582905829158292582935829458295582965829758298582995830058301583025830358304583055830658307583085830958310583115831258313583145831558316583175831858319583205832158322583235832458325583265832758328583295833058331583325833358334583355833658337583385833958340583415834258343583445834558346583475834858349583505835158352583535835458355583565835758358583595836058361583625836358364583655836658367583685836958370583715837258373583745837558376583775837858379583805838158382583835838458385583865838758388583895839058391583925839358394583955839658397583985839958400584015840258403584045840558406584075840858409584105841158412584135841458415584165841758418584195842058421584225842358424584255842658427584285842958430584315843258433584345843558436584375843858439584405844158442584435844458445584465844758448584495845058451584525845358454584555845658457584585845958460584615846258463584645846558466584675846858469584705847158472584735847458475584765847758478584795848058481584825848358484584855848658487584885848958490584915849258493584945849558496584975849858499585005850158502585035850458505585065850758508585095851058511585125851358514585155851658517585185851958520585215852258523585245852558526585275852858529585305853158532585335853458535585365853758538585395854058541585425854358544585455854658547585485854958550585515855258553585545855558556585575855858559585605856158562585635856458565585665856758568585695857058571585725857358574585755857658577585785857958580585815858258583585845858558586585875858858589585905859158592585935859458595585965859758598585995860058601586025860358604586055860658607586085860958610586115861258613586145861558616586175861858619586205862158622586235862458625586265862758628586295863058631586325863358634586355863658637586385863958640586415864258643586445864558646586475864858649586505865158652586535865458655586565865758658586595866058661586625866358664586655866658667586685866958670586715867258673586745867558676586775867858679586805868158682586835868458685586865868758688586895869058691586925869358694586955869658697586985869958700587015870258703587045870558706587075870858709587105871158712587135871458715587165871758718587195872058721587225872358724587255872658727587285872958730587315873258733587345873558736587375873858739587405874158742587435874458745587465874758748587495875058751587525875358754587555875658757587585875958760587615876258763587645876558766587675876858769587705877158772587735877458775587765877758778587795878058781587825878358784587855878658787587885878958790587915879258793587945879558796587975879858799588005880158802588035880458805588065880758808588095881058811588125881358814588155881658817588185881958820588215882258823588245882558826588275882858829588305883158832588335883458835588365883758838588395884058841588425884358844588455884658847588485884958850588515885258853588545885558856588575885858859588605886158862588635886458865588665886758868588695887058871588725887358874588755887658877588785887958880588815888258883588845888558886588875888858889588905889158892588935889458895588965889758898588995890058901589025890358904589055890658907589085890958910589115891258913589145891558916589175891858919589205892158922589235892458925589265892758928589295893058931589325893358934589355893658937589385893958940589415894258943589445894558946589475894858949589505895158952589535895458955589565895758958589595896058961589625896358964589655896658967589685896958970589715897258973589745897558976589775897858979589805898158982589835898458985589865898758988589895899058991589925899358994589955899658997589985899959000590015900259003590045900559006590075900859009590105901159012590135901459015590165901759018590195902059021590225902359024590255902659027590285902959030590315903259033590345903559036590375903859039590405904159042590435904459045590465904759048590495905059051590525905359054590555905659057590585905959060590615906259063590645906559066590675906859069590705907159072590735907459075590765907759078590795908059081590825908359084590855908659087590885908959090590915909259093590945909559096590975909859099591005910159102591035910459105591065910759108591095911059111591125911359114591155911659117591185911959120591215912259123591245912559126591275912859129591305913159132591335913459135591365913759138591395914059141591425914359144591455914659147591485914959150591515915259153591545915559156591575915859159591605916159162591635916459165591665916759168591695917059171591725917359174591755917659177591785917959180591815918259183591845918559186591875918859189591905919159192591935919459195591965919759198591995920059201592025920359204592055920659207592085920959210592115921259213592145921559216592175921859219592205922159222592235922459225592265922759228592295923059231592325923359234592355923659237592385923959240592415924259243592445924559246592475924859249592505925159252592535925459255592565925759258592595926059261592625926359264592655926659267592685926959270592715927259273592745927559276592775927859279592805928159282592835928459285592865928759288592895929059291592925929359294592955929659297592985929959300593015930259303593045930559306593075930859309593105931159312593135931459315593165931759318593195932059321593225932359324593255932659327593285932959330593315933259333593345933559336593375933859339593405934159342593435934459345593465934759348593495935059351593525935359354593555935659357593585935959360593615936259363593645936559366593675936859369593705937159372593735937459375593765937759378593795938059381593825938359384593855938659387593885938959390593915939259393593945939559396593975939859399594005940159402594035940459405594065940759408594095941059411594125941359414594155941659417594185941959420594215942259423594245942559426594275942859429594305943159432594335943459435594365943759438594395944059441594425944359444594455944659447594485944959450594515945259453594545945559456594575945859459594605946159462594635946459465594665946759468594695947059471594725947359474594755947659477594785947959480594815948259483594845948559486594875948859489594905949159492594935949459495594965949759498594995950059501595025950359504595055950659507595085950959510595115951259513595145951559516595175951859519595205952159522595235952459525595265952759528595295953059531595325953359534595355953659537595385953959540595415954259543595445954559546595475954859549595505955159552595535955459555595565955759558595595956059561595625956359564595655956659567595685956959570595715957259573595745957559576595775957859579595805958159582595835958459585595865958759588595895959059591595925959359594595955959659597595985959959600596015960259603596045960559606596075960859609596105961159612596135961459615596165961759618596195962059621596225962359624596255962659627596285962959630596315963259633596345963559636596375963859639596405964159642596435964459645596465964759648596495965059651596525965359654596555965659657596585965959660596615966259663596645966559666596675966859669596705967159672596735967459675596765967759678596795968059681596825968359684596855968659687596885968959690596915969259693596945969559696596975969859699597005970159702597035970459705597065970759708597095971059711597125971359714597155971659717597185971959720597215972259723597245972559726597275972859729597305973159732597335973459735597365973759738597395974059741597425974359744597455974659747597485974959750597515975259753597545975559756597575975859759597605976159762597635976459765597665976759768597695977059771597725977359774597755977659777597785977959780597815978259783597845978559786597875978859789597905979159792597935979459795597965979759798597995980059801598025980359804598055980659807598085980959810598115981259813598145981559816598175981859819598205982159822598235982459825598265982759828598295983059831598325983359834598355983659837598385983959840598415984259843598445984559846598475984859849598505985159852598535985459855598565985759858598595986059861598625986359864598655986659867598685986959870598715987259873598745987559876598775987859879598805988159882598835988459885598865988759888598895989059891598925989359894598955989659897598985989959900599015990259903599045990559906599075990859909599105991159912599135991459915599165991759918599195992059921599225992359924599255992659927599285992959930599315993259933599345993559936599375993859939599405994159942599435994459945599465994759948599495995059951599525995359954599555995659957599585995959960599615996259963599645996559966599675996859969599705997159972599735997459975599765997759978599795998059981599825998359984599855998659987599885998959990599915999259993599945999559996599975999859999600006000160002600036000460005600066000760008600096001060011600126001360014600156001660017600186001960020600216002260023600246002560026600276002860029600306003160032600336003460035600366003760038600396004060041600426004360044600456004660047600486004960050600516005260053600546005560056600576005860059600606006160062600636006460065600666006760068600696007060071600726007360074600756007660077600786007960080600816008260083600846008560086600876008860089600906009160092600936009460095600966009760098600996010060101601026010360104601056010660107601086010960110601116011260113601146011560116601176011860119601206012160122601236012460125601266012760128601296013060131601326013360134601356013660137601386013960140601416014260143601446014560146601476014860149601506015160152601536015460155601566015760158601596016060161601626016360164601656016660167601686016960170601716017260173601746017560176601776017860179601806018160182601836018460185601866018760188601896019060191601926019360194601956019660197601986019960200602016020260203602046020560206602076020860209602106021160212602136021460215602166021760218602196022060221602226022360224602256022660227602286022960230602316023260233602346023560236602376023860239602406024160242602436024460245602466024760248602496025060251602526025360254602556025660257602586025960260602616026260263602646026560266602676026860269602706027160272602736027460275602766027760278602796028060281602826028360284602856028660287602886028960290602916029260293602946029560296602976029860299603006030160302603036030460305603066030760308603096031060311603126031360314603156031660317603186031960320603216032260323603246032560326603276032860329603306033160332603336033460335603366033760338603396034060341603426034360344603456034660347603486034960350603516035260353603546035560356603576035860359603606036160362603636036460365603666036760368603696037060371603726037360374603756037660377603786037960380603816038260383603846038560386603876038860389603906039160392603936039460395603966039760398603996040060401604026040360404604056040660407604086040960410604116041260413604146041560416604176041860419604206042160422604236042460425604266042760428604296043060431604326043360434604356043660437604386043960440604416044260443604446044560446604476044860449604506045160452604536045460455604566045760458604596046060461604626046360464604656046660467604686046960470604716047260473604746047560476604776047860479604806048160482604836048460485604866048760488604896049060491604926049360494604956049660497604986049960500605016050260503605046050560506605076050860509605106051160512605136051460515605166051760518605196052060521605226052360524605256052660527605286052960530605316053260533605346053560536605376053860539605406054160542605436054460545605466054760548605496055060551605526055360554605556055660557605586055960560605616056260563605646056560566605676056860569605706057160572605736057460575605766057760578605796058060581605826058360584605856058660587605886058960590605916059260593605946059560596605976059860599606006060160602606036060460605606066060760608606096061060611606126061360614606156061660617606186061960620606216062260623606246062560626606276062860629606306063160632606336063460635606366063760638606396064060641606426064360644606456064660647606486064960650606516065260653606546065560656606576065860659606606066160662606636066460665606666066760668606696067060671606726067360674606756067660677606786067960680606816068260683606846068560686606876068860689606906069160692606936069460695606966069760698606996070060701607026070360704607056070660707607086070960710607116071260713607146071560716607176071860719607206072160722607236072460725607266072760728607296073060731607326073360734607356073660737607386073960740607416074260743607446074560746607476074860749607506075160752607536075460755607566075760758607596076060761607626076360764607656076660767607686076960770607716077260773607746077560776607776077860779607806078160782607836078460785607866078760788607896079060791607926079360794607956079660797607986079960800608016080260803608046080560806608076080860809608106081160812608136081460815608166081760818608196082060821608226082360824608256082660827608286082960830608316083260833608346083560836608376083860839608406084160842608436084460845608466084760848608496085060851608526085360854608556085660857608586085960860608616086260863608646086560866608676086860869608706087160872608736087460875608766087760878608796088060881608826088360884608856088660887608886088960890608916089260893608946089560896608976089860899609006090160902609036090460905609066090760908609096091060911609126091360914609156091660917609186091960920609216092260923609246092560926609276092860929609306093160932609336093460935609366093760938609396094060941609426094360944609456094660947609486094960950609516095260953609546095560956609576095860959609606096160962609636096460965609666096760968609696097060971609726097360974609756097660977609786097960980609816098260983609846098560986609876098860989609906099160992609936099460995609966099760998609996100061001610026100361004610056100661007610086100961010610116101261013610146101561016610176101861019610206102161022610236102461025610266102761028610296103061031610326103361034610356103661037610386103961040610416104261043610446104561046610476104861049610506105161052610536105461055610566105761058610596106061061610626106361064610656106661067610686106961070610716107261073610746107561076610776107861079610806108161082610836108461085610866108761088610896109061091610926109361094610956109661097610986109961100611016110261103611046110561106611076110861109611106111161112611136111461115611166111761118611196112061121611226112361124611256112661127611286112961130611316113261133611346113561136611376113861139611406114161142611436114461145611466114761148611496115061151611526115361154611556115661157611586115961160611616116261163611646116561166611676116861169611706117161172611736117461175611766117761178611796118061181611826118361184611856118661187611886118961190611916119261193611946119561196611976119861199612006120161202612036120461205612066120761208612096121061211612126121361214612156121661217612186121961220612216122261223612246122561226612276122861229612306123161232612336123461235612366123761238612396124061241612426124361244612456124661247612486124961250612516125261253612546125561256612576125861259612606126161262612636126461265612666126761268612696127061271612726127361274612756127661277612786127961280612816128261283612846128561286612876128861289612906129161292612936129461295612966129761298612996130061301613026130361304613056130661307613086130961310613116131261313613146131561316613176131861319613206132161322613236132461325613266132761328613296133061331613326133361334613356133661337613386133961340613416134261343613446134561346613476134861349613506135161352613536135461355613566135761358613596136061361613626136361364613656136661367613686136961370613716137261373613746137561376613776137861379613806138161382613836138461385613866138761388613896139061391613926139361394613956139661397613986139961400614016140261403614046140561406614076140861409614106141161412614136141461415614166141761418614196142061421614226142361424614256142661427614286142961430614316143261433614346143561436614376143861439614406144161442614436144461445614466144761448614496145061451614526145361454614556145661457614586145961460614616146261463614646146561466614676146861469614706147161472614736147461475614766147761478614796148061481614826148361484614856148661487614886148961490614916149261493614946149561496614976149861499615006150161502615036150461505615066150761508615096151061511615126151361514615156151661517615186151961520615216152261523615246152561526615276152861529615306153161532615336153461535615366153761538615396154061541615426154361544615456154661547615486154961550615516155261553615546155561556615576155861559615606156161562615636156461565615666156761568615696157061571615726157361574615756157661577615786157961580615816158261583615846158561586615876158861589615906159161592615936159461595615966159761598615996160061601616026160361604616056160661607616086160961610616116161261613616146161561616616176161861619616206162161622616236162461625616266162761628616296163061631616326163361634616356163661637616386163961640616416164261643616446164561646616476164861649616506165161652616536165461655616566165761658616596166061661616626166361664616656166661667616686166961670616716167261673616746167561676616776167861679616806168161682616836168461685616866168761688616896169061691616926169361694616956169661697616986169961700617016170261703617046170561706617076170861709617106171161712617136171461715617166171761718617196172061721617226172361724617256172661727617286172961730617316173261733617346173561736617376173861739617406174161742617436174461745617466174761748617496175061751617526175361754617556175661757617586175961760617616176261763617646176561766617676176861769617706177161772617736177461775617766177761778617796178061781617826178361784617856178661787617886178961790617916179261793617946179561796617976179861799618006180161802618036180461805618066180761808618096181061811618126181361814618156181661817618186181961820618216182261823618246182561826618276182861829618306183161832618336183461835618366183761838618396184061841618426184361844618456184661847618486184961850618516185261853618546185561856618576185861859618606186161862618636186461865618666186761868618696187061871618726187361874618756187661877618786187961880618816188261883618846188561886618876188861889618906189161892618936189461895618966189761898618996190061901619026190361904619056190661907619086190961910619116191261913619146191561916619176191861919619206192161922619236192461925619266192761928619296193061931619326193361934619356193661937619386193961940619416194261943619446194561946619476194861949619506195161952619536195461955619566195761958619596196061961619626196361964619656196661967619686196961970619716197261973619746197561976619776197861979619806198161982619836198461985619866198761988619896199061991619926199361994619956199661997619986199962000620016200262003620046200562006620076200862009620106201162012620136201462015620166201762018620196202062021620226202362024620256202662027620286202962030620316203262033620346203562036620376203862039620406204162042620436204462045620466204762048620496205062051620526205362054620556205662057620586205962060620616206262063620646206562066620676206862069620706207162072620736207462075620766207762078620796208062081620826208362084620856208662087620886208962090620916209262093620946209562096620976209862099621006210162102621036210462105621066210762108621096211062111621126211362114621156211662117621186211962120621216212262123621246212562126621276212862129621306213162132621336213462135621366213762138621396214062141621426214362144621456214662147621486214962150621516215262153621546215562156621576215862159621606216162162621636216462165621666216762168621696217062171621726217362174621756217662177621786217962180621816218262183621846218562186621876218862189621906219162192621936219462195621966219762198621996220062201622026220362204622056220662207622086220962210622116221262213622146221562216622176221862219622206222162222622236222462225622266222762228622296223062231622326223362234622356223662237622386223962240622416224262243622446224562246622476224862249622506225162252622536225462255622566225762258622596226062261622626226362264622656226662267622686226962270622716227262273622746227562276622776227862279622806228162282622836228462285622866228762288622896229062291622926229362294622956229662297622986229962300623016230262303623046230562306623076230862309623106231162312623136231462315623166231762318623196232062321623226232362324623256232662327623286232962330623316233262333623346233562336623376233862339623406234162342623436234462345623466234762348623496235062351623526235362354623556235662357623586235962360623616236262363623646236562366623676236862369623706237162372623736237462375623766237762378623796238062381623826238362384623856238662387623886238962390623916239262393623946239562396623976239862399624006240162402624036240462405624066240762408624096241062411624126241362414624156241662417624186241962420624216242262423624246242562426624276242862429624306243162432624336243462435624366243762438624396244062441624426244362444624456244662447624486244962450624516245262453624546245562456624576245862459624606246162462624636246462465624666246762468624696247062471624726247362474624756247662477624786247962480624816248262483624846248562486624876248862489624906249162492624936249462495624966249762498624996250062501625026250362504625056250662507625086250962510625116251262513625146251562516625176251862519625206252162522625236252462525625266252762528625296253062531625326253362534625356253662537625386253962540625416254262543625446254562546625476254862549625506255162552625536255462555625566255762558625596256062561625626256362564625656256662567625686256962570625716257262573625746257562576625776257862579625806258162582625836258462585625866258762588625896259062591625926259362594625956259662597625986259962600626016260262603626046260562606626076260862609626106261162612626136261462615626166261762618626196262062621626226262362624626256262662627626286262962630626316263262633626346263562636626376263862639626406264162642626436264462645626466264762648626496265062651626526265362654626556265662657626586265962660626616266262663626646266562666626676266862669626706267162672626736267462675626766267762678626796268062681626826268362684626856268662687626886268962690626916269262693626946269562696626976269862699627006270162702627036270462705627066270762708627096271062711627126271362714627156271662717627186271962720627216272262723627246272562726627276272862729627306273162732627336273462735627366273762738627396274062741627426274362744627456274662747627486274962750627516275262753627546275562756627576275862759627606276162762627636276462765627666276762768627696277062771627726277362774627756277662777627786277962780627816278262783627846278562786627876278862789627906279162792627936279462795627966279762798627996280062801628026280362804628056280662807628086280962810628116281262813628146281562816628176281862819628206282162822628236282462825628266282762828628296283062831628326283362834628356283662837628386283962840628416284262843628446284562846628476284862849628506285162852628536285462855628566285762858628596286062861628626286362864628656286662867628686286962870628716287262873628746287562876628776287862879628806288162882628836288462885628866288762888628896289062891628926289362894628956289662897628986289962900629016290262903629046290562906629076290862909629106291162912629136291462915629166291762918629196292062921629226292362924629256292662927629286292962930629316293262933629346293562936629376293862939629406294162942629436294462945629466294762948629496295062951629526295362954629556295662957629586295962960629616296262963629646296562966629676296862969629706297162972629736297462975629766297762978629796298062981629826298362984629856298662987629886298962990629916299262993629946299562996629976299862999630006300163002630036300463005630066300763008630096301063011630126301363014630156301663017630186301963020630216302263023630246302563026630276302863029630306303163032630336303463035630366303763038630396304063041630426304363044630456304663047630486304963050630516305263053630546305563056630576305863059630606306163062630636306463065630666306763068630696307063071630726307363074630756307663077630786307963080630816308263083630846308563086630876308863089630906309163092630936309463095630966309763098630996310063101631026310363104631056310663107631086310963110631116311263113631146311563116631176311863119631206312163122631236312463125631266312763128631296313063131631326313363134631356313663137631386313963140631416314263143631446314563146631476314863149631506315163152631536315463155631566315763158631596316063161631626316363164631656316663167631686316963170631716317263173631746317563176631776317863179631806318163182631836318463185631866318763188631896319063191631926319363194631956319663197631986319963200632016320263203632046320563206632076320863209632106321163212632136321463215632166321763218632196322063221632226322363224632256322663227632286322963230632316323263233632346323563236632376323863239632406324163242632436324463245632466324763248632496325063251632526325363254632556325663257632586325963260632616326263263632646326563266632676326863269632706327163272632736327463275632766327763278632796328063281632826328363284632856328663287632886328963290632916329263293632946329563296632976329863299633006330163302633036330463305633066330763308633096331063311633126331363314633156331663317633186331963320633216332263323633246332563326633276332863329633306333163332633336333463335633366333763338633396334063341633426334363344633456334663347633486334963350633516335263353633546335563356633576335863359633606336163362633636336463365633666336763368633696337063371633726337363374633756337663377633786337963380633816338263383633846338563386633876338863389633906339163392633936339463395633966339763398633996340063401634026340363404634056340663407634086340963410634116341263413634146341563416634176341863419634206342163422634236342463425634266342763428634296343063431634326343363434634356343663437634386343963440634416344263443634446344563446634476344863449634506345163452634536345463455634566345763458634596346063461634626346363464634656346663467634686346963470634716347263473634746347563476634776347863479634806348163482634836348463485634866348763488634896349063491634926349363494634956349663497634986349963500635016350263503635046350563506635076350863509635106351163512635136351463515635166351763518635196352063521635226352363524635256352663527635286352963530635316353263533635346353563536635376353863539635406354163542635436354463545635466354763548635496355063551635526355363554635556355663557635586355963560635616356263563635646356563566635676356863569635706357163572635736357463575635766357763578635796358063581635826358363584635856358663587635886358963590635916359263593635946359563596635976359863599636006360163602636036360463605636066360763608636096361063611636126361363614636156361663617636186361963620636216362263623636246362563626636276362863629636306363163632636336363463635636366363763638636396364063641636426364363644636456364663647636486364963650636516365263653636546365563656636576365863659636606366163662636636366463665636666366763668636696367063671636726367363674636756367663677636786367963680636816368263683636846368563686636876368863689636906369163692636936369463695636966369763698636996370063701637026370363704637056370663707637086370963710637116371263713637146371563716637176371863719637206372163722637236372463725637266372763728637296373063731637326373363734637356373663737637386373963740637416374263743637446374563746637476374863749637506375163752637536375463755637566375763758637596376063761637626376363764637656376663767637686376963770637716377263773637746377563776637776377863779637806378163782637836378463785637866378763788637896379063791637926379363794637956379663797637986379963800638016380263803638046380563806638076380863809638106381163812638136381463815638166381763818638196382063821638226382363824638256382663827638286382963830638316383263833638346383563836638376383863839638406384163842638436384463845638466384763848638496385063851638526385363854638556385663857638586385963860638616386263863638646386563866638676386863869638706387163872638736387463875638766387763878638796388063881638826388363884638856388663887638886388963890638916389263893638946389563896638976389863899639006390163902639036390463905639066390763908639096391063911639126391363914639156391663917639186391963920639216392263923639246392563926639276392863929639306393163932639336393463935639366393763938639396394063941639426394363944639456394663947639486394963950639516395263953639546395563956639576395863959639606396163962639636396463965639666396763968639696397063971639726397363974639756397663977639786397963980639816398263983639846398563986639876398863989639906399163992639936399463995639966399763998639996400064001640026400364004640056400664007640086400964010640116401264013640146401564016640176401864019640206402164022640236402464025640266402764028640296403064031640326403364034640356403664037640386403964040640416404264043640446404564046640476404864049640506405164052640536405464055640566405764058640596406064061640626406364064640656406664067640686406964070640716407264073640746407564076640776407864079640806408164082640836408464085640866408764088640896409064091640926409364094640956409664097640986409964100641016410264103641046410564106641076410864109641106411164112641136411464115641166411764118641196412064121641226412364124641256412664127641286412964130641316413264133641346413564136641376413864139641406414164142641436414464145641466414764148641496415064151641526415364154641556415664157641586415964160641616416264163641646416564166641676416864169641706417164172641736417464175641766417764178641796418064181641826418364184641856418664187641886418964190641916419264193641946419564196641976419864199642006420164202642036420464205642066420764208642096421064211642126421364214642156421664217642186421964220642216422264223642246422564226642276422864229642306423164232642336423464235642366423764238642396424064241642426424364244642456424664247642486424964250642516425264253642546425564256642576425864259642606426164262642636426464265642666426764268642696427064271642726427364274642756427664277642786427964280642816428264283642846428564286642876428864289642906429164292642936429464295642966429764298642996430064301643026430364304643056430664307643086430964310643116431264313643146431564316643176431864319643206432164322643236432464325643266432764328643296433064331643326433364334643356433664337643386433964340643416434264343643446434564346643476434864349643506435164352643536435464355643566435764358643596436064361643626436364364643656436664367643686436964370643716437264373643746437564376643776437864379643806438164382643836438464385643866438764388643896439064391643926439364394643956439664397643986439964400644016440264403644046440564406644076440864409644106441164412644136441464415644166441764418644196442064421644226442364424644256442664427644286442964430644316443264433644346443564436644376443864439644406444164442644436444464445644466444764448644496445064451644526445364454644556445664457644586445964460644616446264463644646446564466644676446864469644706447164472644736447464475644766447764478644796448064481644826448364484644856448664487644886448964490644916449264493644946449564496644976449864499645006450164502645036450464505645066450764508645096451064511645126451364514645156451664517645186451964520645216452264523645246452564526645276452864529645306453164532645336453464535645366453764538645396454064541645426454364544645456454664547645486454964550645516455264553645546455564556645576455864559645606456164562645636456464565645666456764568645696457064571645726457364574645756457664577645786457964580645816458264583645846458564586645876458864589645906459164592645936459464595645966459764598645996460064601646026460364604646056460664607646086460964610646116461264613646146461564616646176461864619646206462164622646236462464625646266462764628646296463064631646326463364634646356463664637646386463964640646416464264643646446464564646646476464864649646506465164652646536465464655646566465764658646596466064661646626466364664646656466664667646686466964670646716467264673646746467564676646776467864679646806468164682646836468464685646866468764688646896469064691646926469364694646956469664697646986469964700647016470264703647046470564706647076470864709647106471164712647136471464715647166471764718647196472064721647226472364724647256472664727647286472964730647316473264733647346473564736647376473864739647406474164742647436474464745647466474764748647496475064751647526475364754647556475664757647586475964760647616476264763647646476564766647676476864769647706477164772647736477464775647766477764778647796478064781647826478364784647856478664787647886478964790647916479264793647946479564796647976479864799648006480164802648036480464805648066480764808648096481064811648126481364814648156481664817648186481964820648216482264823648246482564826648276482864829648306483164832648336483464835648366483764838648396484064841648426484364844648456484664847648486484964850648516485264853648546485564856648576485864859648606486164862648636486464865648666486764868648696487064871648726487364874648756487664877648786487964880648816488264883648846488564886648876488864889648906489164892648936489464895648966489764898648996490064901649026490364904649056490664907649086490964910649116491264913649146491564916649176491864919649206492164922649236492464925649266492764928649296493064931649326493364934649356493664937649386493964940649416494264943649446494564946649476494864949649506495164952649536495464955649566495764958649596496064961649626496364964649656496664967649686496964970649716497264973649746497564976649776497864979649806498164982649836498464985649866498764988649896499064991649926499364994649956499664997649986499965000650016500265003650046500565006650076500865009650106501165012650136501465015650166501765018650196502065021650226502365024650256502665027650286502965030650316503265033650346503565036650376503865039650406504165042650436504465045650466504765048650496505065051650526505365054650556505665057650586505965060650616506265063650646506565066650676506865069650706507165072650736507465075650766507765078650796508065081650826508365084650856508665087650886508965090650916509265093650946509565096650976509865099651006510165102651036510465105651066510765108651096511065111651126511365114651156511665117651186511965120651216512265123651246512565126651276512865129651306513165132651336513465135651366513765138651396514065141651426514365144651456514665147651486514965150651516515265153651546515565156651576515865159651606516165162651636516465165651666516765168651696517065171651726517365174651756517665177651786517965180651816518265183651846518565186651876518865189651906519165192651936519465195651966519765198651996520065201652026520365204652056520665207652086520965210652116521265213652146521565216652176521865219652206522165222652236522465225652266522765228652296523065231652326523365234652356523665237652386523965240652416524265243652446524565246652476524865249652506525165252652536525465255652566525765258652596526065261652626526365264652656526665267652686526965270652716527265273652746527565276652776527865279652806528165282652836528465285652866528765288652896529065291652926529365294652956529665297652986529965300653016530265303653046530565306653076530865309653106531165312653136531465315653166531765318653196532065321653226532365324653256532665327653286532965330653316533265333653346533565336653376533865339653406534165342653436534465345653466534765348653496535065351653526535365354653556535665357653586535965360653616536265363653646536565366653676536865369653706537165372653736537465375653766537765378653796538065381653826538365384653856538665387653886538965390653916539265393653946539565396653976539865399654006540165402654036540465405654066540765408654096541065411654126541365414654156541665417654186541965420654216542265423654246542565426654276542865429654306543165432654336543465435654366543765438654396544065441654426544365444654456544665447654486544965450654516545265453654546545565456654576545865459654606546165462654636546465465654666546765468654696547065471654726547365474654756547665477654786547965480654816548265483654846548565486654876548865489654906549165492654936549465495654966549765498654996550065501655026550365504655056550665507655086550965510655116551265513655146551565516655176551865519655206552165522655236552465525655266552765528655296553065531655326553365534655356553665537655386553965540655416554265543655446554565546655476554865549655506555165552655536555465555655566555765558655596556065561655626556365564655656556665567655686556965570655716557265573655746557565576655776557865579655806558165582655836558465585655866558765588655896559065591655926559365594655956559665597655986559965600656016560265603656046560565606656076560865609656106561165612656136561465615656166561765618656196562065621656226562365624656256562665627656286562965630656316563265633656346563565636656376563865639656406564165642656436564465645656466564765648656496565065651656526565365654656556565665657656586565965660656616566265663656646566565666656676566865669656706567165672656736567465675656766567765678656796568065681656826568365684656856568665687656886568965690656916569265693656946569565696656976569865699657006570165702657036570465705657066570765708657096571065711657126571365714657156571665717657186571965720657216572265723657246572565726657276572865729657306573165732657336573465735657366573765738657396574065741657426574365744657456574665747657486574965750657516575265753657546575565756657576575865759657606576165762657636576465765657666576765768657696577065771657726577365774657756577665777657786577965780657816578265783657846578565786657876578865789657906579165792657936579465795657966579765798657996580065801658026580365804658056580665807658086580965810658116581265813658146581565816658176581865819658206582165822658236582465825658266582765828658296583065831658326583365834658356583665837658386583965840658416584265843658446584565846658476584865849658506585165852658536585465855658566585765858658596586065861658626586365864658656586665867658686586965870658716587265873658746587565876658776587865879658806588165882658836588465885658866588765888658896589065891658926589365894658956589665897658986589965900659016590265903659046590565906659076590865909659106591165912659136591465915659166591765918659196592065921659226592365924659256592665927659286592965930659316593265933659346593565936659376593865939659406594165942659436594465945659466594765948659496595065951659526595365954659556595665957659586595965960659616596265963659646596565966659676596865969659706597165972659736597465975659766597765978659796598065981659826598365984659856598665987659886598965990659916599265993659946599565996659976599865999660006600166002660036600466005660066600766008660096601066011660126601366014660156601666017660186601966020660216602266023660246602566026660276602866029660306603166032660336603466035660366603766038660396604066041660426604366044660456604666047660486604966050660516605266053660546605566056660576605866059660606606166062660636606466065660666606766068660696607066071660726607366074660756607666077660786607966080660816608266083660846608566086660876608866089660906609166092660936609466095660966609766098660996610066101661026610366104661056610666107661086610966110661116611266113661146611566116661176611866119661206612166122661236612466125661266612766128661296613066131661326613366134661356613666137661386613966140661416614266143661446614566146661476614866149661506615166152661536615466155661566615766158661596616066161661626616366164661656616666167661686616966170661716617266173661746617566176661776617866179661806618166182661836618466185661866618766188661896619066191661926619366194661956619666197661986619966200662016620266203662046620566206662076620866209662106621166212662136621466215662166621766218662196622066221662226622366224662256622666227662286622966230662316623266233662346623566236662376623866239662406624166242662436624466245662466624766248662496625066251662526625366254662556625666257662586625966260662616626266263662646626566266662676626866269662706627166272662736627466275662766627766278662796628066281662826628366284662856628666287662886628966290662916629266293662946629566296662976629866299663006630166302663036630466305663066630766308663096631066311663126631366314663156631666317663186631966320663216632266323663246632566326663276632866329663306633166332663336633466335663366633766338663396634066341663426634366344663456634666347663486634966350663516635266353663546635566356663576635866359663606636166362663636636466365663666636766368663696637066371663726637366374663756637666377663786637966380663816638266383663846638566386663876638866389663906639166392663936639466395663966639766398663996640066401664026640366404664056640666407664086640966410664116641266413664146641566416664176641866419664206642166422664236642466425664266642766428664296643066431664326643366434664356643666437664386643966440664416644266443664446644566446664476644866449664506645166452664536645466455664566645766458664596646066461664626646366464664656646666467664686646966470664716647266473664746647566476664776647866479664806648166482664836648466485664866648766488664896649066491664926649366494664956649666497664986649966500665016650266503665046650566506665076650866509665106651166512665136651466515665166651766518665196652066521665226652366524665256652666527665286652966530665316653266533665346653566536665376653866539665406654166542665436654466545665466654766548665496655066551665526655366554665556655666557665586655966560665616656266563665646656566566665676656866569665706657166572665736657466575665766657766578665796658066581665826658366584665856658666587665886658966590665916659266593665946659566596665976659866599666006660166602666036660466605666066660766608666096661066611666126661366614666156661666617666186661966620666216662266623666246662566626666276662866629666306663166632666336663466635666366663766638666396664066641666426664366644666456664666647666486664966650666516665266653666546665566656666576665866659666606666166662666636666466665666666666766668666696667066671666726667366674666756667666677666786667966680666816668266683666846668566686666876668866689666906669166692666936669466695666966669766698666996670066701667026670366704667056670666707667086670966710667116671266713667146671566716667176671866719667206672166722667236672466725667266672766728667296673066731667326673366734667356673666737667386673966740667416674266743667446674566746667476674866749667506675166752667536675466755667566675766758667596676066761667626676366764667656676666767667686676966770667716677266773667746677566776667776677866779667806678166782667836678466785667866678766788667896679066791667926679366794667956679666797667986679966800668016680266803668046680566806668076680866809668106681166812668136681466815668166681766818668196682066821668226682366824668256682666827668286682966830668316683266833668346683566836668376683866839668406684166842668436684466845668466684766848668496685066851668526685366854668556685666857668586685966860668616686266863668646686566866668676686866869668706687166872668736687466875668766687766878668796688066881668826688366884668856688666887668886688966890668916689266893668946689566896668976689866899669006690166902669036690466905669066690766908669096691066911669126691366914669156691666917669186691966920669216692266923669246692566926669276692866929669306693166932669336693466935669366693766938669396694066941669426694366944669456694666947669486694966950669516695266953669546695566956669576695866959669606696166962669636696466965669666696766968669696697066971669726697366974669756697666977669786697966980669816698266983669846698566986669876698866989669906699166992669936699466995669966699766998669996700067001670026700367004670056700667007670086700967010670116701267013670146701567016670176701867019670206702167022670236702467025670266702767028670296703067031670326703367034670356703667037670386703967040670416704267043670446704567046670476704867049670506705167052670536705467055670566705767058670596706067061670626706367064670656706667067670686706967070670716707267073670746707567076670776707867079670806708167082670836708467085670866708767088670896709067091670926709367094670956709667097670986709967100671016710267103671046710567106671076710867109671106711167112671136711467115671166711767118671196712067121671226712367124671256712667127671286712967130671316713267133671346713567136671376713867139671406714167142671436714467145671466714767148671496715067151671526715367154671556715667157671586715967160671616716267163671646716567166671676716867169671706717167172671736717467175671766717767178671796718067181671826718367184671856718667187671886718967190671916719267193671946719567196671976719867199672006720167202672036720467205672066720767208672096721067211672126721367214672156721667217672186721967220672216722267223672246722567226672276722867229672306723167232672336723467235672366723767238672396724067241672426724367244672456724667247672486724967250672516725267253672546725567256672576725867259672606726167262672636726467265672666726767268672696727067271672726727367274672756727667277672786727967280672816728267283672846728567286672876728867289672906729167292672936729467295672966729767298672996730067301673026730367304673056730667307673086730967310673116731267313673146731567316673176731867319673206732167322673236732467325673266732767328673296733067331673326733367334673356733667337673386733967340673416734267343673446734567346673476734867349673506735167352673536735467355673566735767358673596736067361673626736367364673656736667367673686736967370673716737267373673746737567376673776737867379673806738167382673836738467385673866738767388673896739067391673926739367394673956739667397673986739967400674016740267403674046740567406674076740867409674106741167412674136741467415674166741767418674196742067421674226742367424674256742667427674286742967430674316743267433674346743567436674376743867439674406744167442674436744467445674466744767448674496745067451674526745367454674556745667457674586745967460674616746267463674646746567466674676746867469674706747167472674736747467475674766747767478674796748067481674826748367484674856748667487674886748967490674916749267493674946749567496674976749867499675006750167502675036750467505675066750767508675096751067511675126751367514675156751667517675186751967520675216752267523675246752567526675276752867529675306753167532675336753467535675366753767538675396754067541675426754367544675456754667547675486754967550675516755267553675546755567556675576755867559675606756167562675636756467565675666756767568675696757067571675726757367574675756757667577675786757967580675816758267583675846758567586675876758867589675906759167592675936759467595675966759767598675996760067601676026760367604676056760667607676086760967610676116761267613676146761567616676176761867619676206762167622676236762467625676266762767628676296763067631676326763367634676356763667637676386763967640676416764267643676446764567646676476764867649676506765167652676536765467655676566765767658676596766067661676626766367664676656766667667676686766967670676716767267673676746767567676676776767867679676806768167682676836768467685676866768767688676896769067691676926769367694676956769667697676986769967700677016770267703677046770567706677076770867709677106771167712677136771467715677166771767718677196772067721677226772367724677256772667727677286772967730677316773267733677346773567736677376773867739677406774167742677436774467745677466774767748677496775067751677526775367754677556775667757677586775967760677616776267763677646776567766677676776867769677706777167772677736777467775677766777767778677796778067781677826778367784677856778667787677886778967790677916779267793677946779567796677976779867799678006780167802678036780467805678066780767808678096781067811678126781367814678156781667817678186781967820678216782267823678246782567826678276782867829678306783167832678336783467835678366783767838678396784067841678426784367844678456784667847678486784967850678516785267853678546785567856678576785867859678606786167862678636786467865678666786767868678696787067871678726787367874678756787667877678786787967880678816788267883678846788567886678876788867889678906789167892678936789467895678966789767898678996790067901679026790367904679056790667907679086790967910679116791267913679146791567916679176791867919679206792167922679236792467925679266792767928679296793067931679326793367934679356793667937679386793967940679416794267943679446794567946679476794867949679506795167952679536795467955679566795767958679596796067961679626796367964679656796667967679686796967970679716797267973679746797567976679776797867979679806798167982679836798467985679866798767988679896799067991679926799367994679956799667997679986799968000680016800268003680046800568006680076800868009680106801168012680136801468015680166801768018680196802068021680226802368024680256802668027680286802968030680316803268033680346803568036680376803868039680406804168042680436804468045680466804768048680496805068051680526805368054680556805668057680586805968060680616806268063680646806568066680676806868069680706807168072680736807468075680766807768078680796808068081680826808368084680856808668087680886808968090680916809268093680946809568096680976809868099681006810168102681036810468105681066810768108681096811068111681126811368114681156811668117681186811968120681216812268123681246812568126681276812868129681306813168132681336813468135681366813768138681396814068141681426814368144681456814668147681486814968150681516815268153681546815568156681576815868159681606816168162681636816468165681666816768168681696817068171681726817368174681756817668177681786817968180681816818268183681846818568186681876818868189681906819168192681936819468195681966819768198681996820068201682026820368204682056820668207682086820968210682116821268213682146821568216682176821868219682206822168222682236822468225682266822768228682296823068231682326823368234682356823668237682386823968240682416824268243682446824568246682476824868249682506825168252682536825468255682566825768258682596826068261682626826368264682656826668267682686826968270682716827268273682746827568276682776827868279682806828168282682836828468285682866828768288682896829068291682926829368294682956829668297682986829968300683016830268303683046830568306683076830868309683106831168312683136831468315683166831768318683196832068321683226832368324683256832668327683286832968330683316833268333683346833568336683376833868339683406834168342683436834468345683466834768348683496835068351683526835368354683556835668357683586835968360683616836268363683646836568366683676836868369683706837168372683736837468375683766837768378683796838068381683826838368384683856838668387683886838968390683916839268393683946839568396683976839868399684006840168402684036840468405684066840768408684096841068411684126841368414684156841668417684186841968420684216842268423684246842568426684276842868429684306843168432684336843468435684366843768438684396844068441684426844368444684456844668447684486844968450684516845268453684546845568456684576845868459684606846168462684636846468465684666846768468684696847068471684726847368474684756847668477684786847968480684816848268483684846848568486684876848868489684906849168492684936849468495684966849768498684996850068501685026850368504685056850668507685086850968510685116851268513685146851568516685176851868519685206852168522685236852468525685266852768528685296853068531685326853368534685356853668537685386853968540685416854268543685446854568546685476854868549685506855168552685536855468555685566855768558685596856068561685626856368564685656856668567685686856968570685716857268573685746857568576685776857868579685806858168582685836858468585685866858768588685896859068591685926859368594685956859668597685986859968600686016860268603686046860568606686076860868609686106861168612686136861468615686166861768618686196862068621686226862368624686256862668627686286862968630686316863268633686346863568636686376863868639686406864168642686436864468645686466864768648686496865068651686526865368654686556865668657686586865968660686616866268663686646866568666686676866868669686706867168672686736867468675686766867768678686796868068681686826868368684686856868668687686886868968690686916869268693686946869568696686976869868699687006870168702687036870468705687066870768708687096871068711687126871368714687156871668717687186871968720687216872268723687246872568726687276872868729687306873168732687336873468735687366873768738687396874068741687426874368744687456874668747687486874968750687516875268753687546875568756687576875868759687606876168762687636876468765687666876768768687696877068771687726877368774687756877668777687786877968780687816878268783687846878568786687876878868789687906879168792687936879468795687966879768798687996880068801688026880368804688056880668807688086880968810688116881268813688146881568816688176881868819688206882168822688236882468825688266882768828688296883068831688326883368834688356883668837688386883968840688416884268843688446884568846688476884868849688506885168852688536885468855688566885768858688596886068861688626886368864688656886668867688686886968870688716887268873688746887568876688776887868879688806888168882688836888468885688866888768888688896889068891688926889368894688956889668897688986889968900689016890268903689046890568906689076890868909689106891168912689136891468915689166891768918689196892068921689226892368924689256892668927689286892968930689316893268933689346893568936689376893868939689406894168942689436894468945689466894768948689496895068951689526895368954689556895668957689586895968960689616896268963689646896568966689676896868969689706897168972689736897468975689766897768978689796898068981689826898368984689856898668987689886898968990689916899268993689946899568996689976899868999690006900169002690036900469005690066900769008690096901069011690126901369014690156901669017690186901969020690216902269023690246902569026690276902869029690306903169032690336903469035690366903769038690396904069041690426904369044690456904669047690486904969050690516905269053690546905569056690576905869059690606906169062690636906469065690666906769068690696907069071690726907369074690756907669077690786907969080690816908269083690846908569086690876908869089690906909169092690936909469095690966909769098690996910069101691026910369104691056910669107691086910969110691116911269113691146911569116691176911869119691206912169122691236912469125691266912769128691296913069131691326913369134691356913669137691386913969140691416914269143691446914569146691476914869149691506915169152691536915469155691566915769158691596916069161691626916369164691656916669167691686916969170691716917269173691746917569176691776917869179691806918169182691836918469185691866918769188691896919069191691926919369194691956919669197691986919969200692016920269203692046920569206692076920869209692106921169212692136921469215692166921769218692196922069221692226922369224692256922669227692286922969230692316923269233692346923569236692376923869239692406924169242692436924469245692466924769248692496925069251692526925369254692556925669257692586925969260692616926269263692646926569266692676926869269692706927169272692736927469275692766927769278692796928069281692826928369284692856928669287692886928969290692916929269293692946929569296692976929869299693006930169302693036930469305693066930769308693096931069311693126931369314693156931669317693186931969320693216932269323693246932569326693276932869329693306933169332693336933469335693366933769338693396934069341693426934369344693456934669347693486934969350693516935269353693546935569356693576935869359693606936169362693636936469365693666936769368693696937069371693726937369374693756937669377693786937969380693816938269383693846938569386693876938869389693906939169392693936939469395693966939769398693996940069401694026940369404694056940669407694086940969410694116941269413694146941569416694176941869419694206942169422694236942469425694266942769428694296943069431694326943369434694356943669437694386943969440694416944269443694446944569446694476944869449694506945169452694536945469455694566945769458694596946069461694626946369464694656946669467694686946969470694716947269473694746947569476694776947869479694806948169482694836948469485694866948769488694896949069491694926949369494694956949669497694986949969500695016950269503695046950569506695076950869509695106951169512695136951469515695166951769518695196952069521695226952369524695256952669527695286952969530695316953269533695346953569536695376953869539695406954169542695436954469545695466954769548695496955069551695526955369554695556955669557695586955969560695616956269563695646956569566695676956869569695706957169572695736957469575695766957769578695796958069581695826958369584695856958669587695886958969590695916959269593695946959569596695976959869599696006960169602696036960469605696066960769608696096961069611696126961369614696156961669617696186961969620696216962269623696246962569626696276962869629696306963169632696336963469635696366963769638696396964069641696426964369644696456964669647696486964969650696516965269653696546965569656696576965869659696606966169662696636966469665696666966769668696696967069671696726967369674696756967669677696786967969680696816968269683696846968569686696876968869689696906969169692696936969469695696966969769698696996970069701697026970369704697056970669707697086970969710697116971269713697146971569716697176971869719697206972169722697236972469725697266972769728697296973069731697326973369734697356973669737697386973969740697416974269743697446974569746697476974869749697506975169752697536975469755697566975769758697596976069761697626976369764697656976669767697686976969770697716977269773697746977569776697776977869779697806978169782697836978469785697866978769788697896979069791697926979369794697956979669797697986979969800698016980269803698046980569806698076980869809698106981169812698136981469815698166981769818698196982069821698226982369824698256982669827698286982969830698316983269833698346983569836698376983869839698406984169842698436984469845698466984769848698496985069851698526985369854698556985669857698586985969860698616986269863698646986569866698676986869869698706987169872698736987469875698766987769878698796988069881698826988369884698856988669887698886988969890698916989269893698946989569896698976989869899699006990169902699036990469905699066990769908699096991069911699126991369914699156991669917699186991969920699216992269923699246992569926699276992869929699306993169932699336993469935699366993769938699396994069941699426994369944699456994669947699486994969950699516995269953699546995569956699576995869959699606996169962699636996469965699666996769968699696997069971699726997369974699756997669977699786997969980699816998269983699846998569986699876998869989699906999169992699936999469995699966999769998699997000070001700027000370004700057000670007700087000970010700117001270013700147001570016700177001870019700207002170022700237002470025700267002770028700297003070031700327003370034700357003670037700387003970040700417004270043700447004570046700477004870049700507005170052700537005470055700567005770058700597006070061700627006370064700657006670067700687006970070700717007270073700747007570076700777007870079700807008170082700837008470085700867008770088700897009070091700927009370094700957009670097700987009970100701017010270103701047010570106701077010870109701107011170112701137011470115701167011770118701197012070121701227012370124701257012670127701287012970130701317013270133701347013570136701377013870139701407014170142701437014470145701467014770148701497015070151701527015370154701557015670157701587015970160701617016270163701647016570166701677016870169701707017170172701737017470175701767017770178701797018070181701827018370184701857018670187701887018970190701917019270193701947019570196701977019870199702007020170202702037020470205702067020770208702097021070211702127021370214702157021670217702187021970220702217022270223702247022570226702277022870229702307023170232702337023470235702367023770238702397024070241702427024370244702457024670247702487024970250702517025270253702547025570256702577025870259702607026170262702637026470265702667026770268702697027070271702727027370274702757027670277702787027970280702817028270283702847028570286702877028870289702907029170292702937029470295702967029770298702997030070301703027030370304703057030670307703087030970310703117031270313703147031570316703177031870319703207032170322703237032470325703267032770328703297033070331703327033370334703357033670337703387033970340703417034270343703447034570346703477034870349703507035170352703537035470355703567035770358703597036070361703627036370364703657036670367703687036970370703717037270373703747037570376703777037870379703807038170382703837038470385703867038770388703897039070391703927039370394703957039670397703987039970400704017040270403704047040570406704077040870409704107041170412704137041470415704167041770418704197042070421704227042370424704257042670427704287042970430704317043270433704347043570436704377043870439704407044170442704437044470445704467044770448704497045070451704527045370454704557045670457704587045970460704617046270463704647046570466704677046870469704707047170472704737047470475704767047770478704797048070481704827048370484704857048670487704887048970490704917049270493704947049570496704977049870499705007050170502705037050470505705067050770508705097051070511705127051370514705157051670517705187051970520705217052270523705247052570526705277052870529705307053170532705337053470535705367053770538705397054070541705427054370544705457054670547705487054970550705517055270553705547055570556705577055870559705607056170562705637056470565705667056770568705697057070571705727057370574705757057670577705787057970580705817058270583705847058570586705877058870589705907059170592705937059470595705967059770598705997060070601706027060370604706057060670607706087060970610706117061270613706147061570616706177061870619706207062170622706237062470625706267062770628706297063070631706327063370634706357063670637706387063970640706417064270643706447064570646706477064870649706507065170652706537065470655706567065770658706597066070661706627066370664706657066670667706687066970670706717067270673706747067570676706777067870679706807068170682706837068470685706867068770688706897069070691706927069370694706957069670697706987069970700707017070270703707047070570706707077070870709707107071170712707137071470715707167071770718707197072070721707227072370724707257072670727707287072970730707317073270733707347073570736707377073870739707407074170742707437074470745707467074770748707497075070751707527075370754707557075670757707587075970760707617076270763707647076570766707677076870769707707077170772707737077470775707767077770778707797078070781707827078370784707857078670787707887078970790707917079270793707947079570796707977079870799708007080170802708037080470805708067080770808708097081070811708127081370814708157081670817708187081970820708217082270823708247082570826708277082870829708307083170832708337083470835708367083770838708397084070841708427084370844708457084670847708487084970850708517085270853708547085570856708577085870859708607086170862708637086470865708667086770868708697087070871708727087370874708757087670877708787087970880708817088270883708847088570886708877088870889708907089170892708937089470895708967089770898708997090070901709027090370904709057090670907709087090970910709117091270913709147091570916709177091870919709207092170922709237092470925709267092770928709297093070931709327093370934709357093670937709387093970940709417094270943709447094570946709477094870949709507095170952709537095470955709567095770958709597096070961709627096370964709657096670967709687096970970709717097270973709747097570976709777097870979709807098170982709837098470985709867098770988709897099070991709927099370994709957099670997709987099971000710017100271003710047100571006710077100871009710107101171012710137101471015710167101771018710197102071021710227102371024710257102671027710287102971030710317103271033710347103571036710377103871039710407104171042710437104471045710467104771048710497105071051710527105371054710557105671057710587105971060710617106271063710647106571066710677106871069710707107171072710737107471075710767107771078710797108071081710827108371084710857108671087710887108971090710917109271093710947109571096710977109871099711007110171102711037110471105711067110771108711097111071111711127111371114711157111671117711187111971120711217112271123711247112571126711277112871129711307113171132711337113471135711367113771138711397114071141711427114371144711457114671147711487114971150711517115271153711547115571156711577115871159711607116171162711637116471165711667116771168711697117071171711727117371174711757117671177711787117971180711817118271183711847118571186711877118871189711907119171192711937119471195711967119771198711997120071201712027120371204712057120671207712087120971210712117121271213712147121571216712177121871219712207122171222712237122471225712267122771228712297123071231712327123371234712357123671237712387123971240712417124271243712447124571246712477124871249712507125171252712537125471255712567125771258712597126071261712627126371264712657126671267712687126971270712717127271273712747127571276712777127871279712807128171282712837128471285712867128771288712897129071291712927129371294712957129671297712987129971300713017130271303713047130571306713077130871309713107131171312713137131471315713167131771318713197132071321713227132371324713257132671327713287132971330713317133271333713347133571336713377133871339713407134171342713437134471345713467134771348713497135071351713527135371354713557135671357713587135971360713617136271363713647136571366713677136871369713707137171372713737137471375713767137771378713797138071381713827138371384713857138671387713887138971390713917139271393713947139571396713977139871399714007140171402714037140471405714067140771408714097141071411714127141371414714157141671417714187141971420714217142271423714247142571426714277142871429714307143171432714337143471435714367143771438714397144071441714427144371444714457144671447714487144971450714517145271453714547145571456714577145871459714607146171462714637146471465714667146771468714697147071471714727147371474714757147671477714787147971480714817148271483714847148571486714877148871489714907149171492714937149471495714967149771498714997150071501715027150371504715057150671507715087150971510715117151271513715147151571516715177151871519715207152171522715237152471525715267152771528715297153071531715327153371534715357153671537715387153971540715417154271543715447154571546715477154871549715507155171552715537155471555715567155771558715597156071561715627156371564715657156671567715687156971570715717157271573715747157571576715777157871579715807158171582715837158471585715867158771588715897159071591715927159371594715957159671597715987159971600716017160271603716047160571606716077160871609716107161171612716137161471615716167161771618716197162071621716227162371624716257162671627716287162971630716317163271633716347163571636716377163871639716407164171642716437164471645716467164771648716497165071651716527165371654716557165671657716587165971660716617166271663716647166571666716677166871669716707167171672716737167471675716767167771678716797168071681716827168371684716857168671687716887168971690716917169271693716947169571696716977169871699717007170171702717037170471705717067170771708717097171071711717127171371714717157171671717717187171971720717217172271723717247172571726717277172871729717307173171732717337173471735717367173771738717397174071741717427174371744717457174671747717487174971750717517175271753717547175571756717577175871759717607176171762717637176471765717667176771768717697177071771717727177371774717757177671777717787177971780717817178271783717847178571786717877178871789717907179171792717937179471795717967179771798717997180071801718027180371804718057180671807718087180971810718117181271813718147181571816718177181871819718207182171822718237182471825718267182771828718297183071831718327183371834718357183671837718387183971840718417184271843718447184571846718477184871849718507185171852718537185471855718567185771858718597186071861718627186371864718657186671867718687186971870718717187271873718747187571876718777187871879718807188171882718837188471885718867188771888718897189071891718927189371894718957189671897718987189971900719017190271903719047190571906719077190871909719107191171912719137191471915719167191771918719197192071921719227192371924719257192671927719287192971930719317193271933719347193571936719377193871939719407194171942719437194471945719467194771948719497195071951719527195371954719557195671957719587195971960719617196271963719647196571966719677196871969719707197171972719737197471975719767197771978719797198071981719827198371984719857198671987719887198971990719917199271993719947199571996719977199871999720007200172002720037200472005720067200772008720097201072011720127201372014720157201672017720187201972020720217202272023720247202572026720277202872029720307203172032720337203472035720367203772038720397204072041720427204372044720457204672047720487204972050720517205272053720547205572056720577205872059720607206172062720637206472065720667206772068720697207072071720727207372074720757207672077720787207972080720817208272083720847208572086720877208872089720907209172092720937209472095720967209772098720997210072101721027210372104721057210672107721087210972110721117211272113721147211572116721177211872119721207212172122721237212472125721267212772128721297213072131721327213372134721357213672137721387213972140721417214272143721447214572146721477214872149721507215172152721537215472155721567215772158721597216072161721627216372164721657216672167721687216972170721717217272173721747217572176721777217872179721807218172182721837218472185721867218772188721897219072191721927219372194721957219672197721987219972200722017220272203722047220572206722077220872209722107221172212722137221472215722167221772218722197222072221722227222372224722257222672227722287222972230722317223272233722347223572236722377223872239722407224172242722437224472245722467224772248722497225072251722527225372254722557225672257722587225972260722617226272263722647226572266722677226872269722707227172272722737227472275722767227772278722797228072281722827228372284722857228672287722887228972290722917229272293722947229572296722977229872299723007230172302723037230472305723067230772308723097231072311723127231372314723157231672317723187231972320723217232272323723247232572326723277232872329723307233172332723337233472335723367233772338723397234072341723427234372344723457234672347723487234972350723517235272353723547235572356723577235872359723607236172362723637236472365723667236772368723697237072371723727237372374723757237672377723787237972380723817238272383723847238572386723877238872389723907239172392723937239472395723967239772398723997240072401724027240372404724057240672407724087240972410724117241272413724147241572416724177241872419724207242172422724237242472425724267242772428724297243072431724327243372434724357243672437724387243972440724417244272443724447244572446724477244872449724507245172452724537245472455724567245772458724597246072461724627246372464724657246672467724687246972470724717247272473724747247572476724777247872479724807248172482724837248472485724867248772488724897249072491724927249372494724957249672497724987249972500725017250272503725047250572506725077250872509725107251172512725137251472515725167251772518725197252072521725227252372524725257252672527725287252972530725317253272533725347253572536725377253872539725407254172542725437254472545725467254772548725497255072551725527255372554725557255672557725587255972560725617256272563725647256572566725677256872569725707257172572725737257472575725767257772578725797258072581725827258372584725857258672587725887258972590725917259272593725947259572596725977259872599726007260172602726037260472605726067260772608726097261072611726127261372614726157261672617726187261972620726217262272623726247262572626726277262872629726307263172632726337263472635726367263772638726397264072641726427264372644726457264672647726487264972650726517265272653726547265572656726577265872659726607266172662726637266472665726667266772668726697267072671726727267372674726757267672677726787267972680726817268272683726847268572686726877268872689726907269172692726937269472695726967269772698726997270072701727027270372704727057270672707727087270972710727117271272713727147271572716727177271872719727207272172722727237272472725727267272772728727297273072731727327273372734727357273672737727387273972740727417274272743727447274572746727477274872749727507275172752727537275472755727567275772758727597276072761727627276372764727657276672767727687276972770727717277272773727747277572776727777277872779727807278172782727837278472785727867278772788727897279072791727927279372794727957279672797727987279972800728017280272803728047280572806728077280872809728107281172812728137281472815728167281772818728197282072821728227282372824728257282672827728287282972830728317283272833728347283572836728377283872839728407284172842728437284472845728467284772848728497285072851728527285372854728557285672857728587285972860728617286272863728647286572866728677286872869728707287172872728737287472875728767287772878728797288072881728827288372884728857288672887728887288972890728917289272893728947289572896728977289872899729007290172902729037290472905729067290772908729097291072911729127291372914729157291672917729187291972920729217292272923729247292572926729277292872929729307293172932729337293472935729367293772938729397294072941729427294372944729457294672947729487294972950729517295272953729547295572956729577295872959729607296172962729637296472965729667296772968729697297072971729727297372974729757297672977729787297972980729817298272983729847298572986729877298872989729907299172992729937299472995729967299772998729997300073001730027300373004730057300673007730087300973010730117301273013730147301573016730177301873019730207302173022730237302473025730267302773028730297303073031730327303373034730357303673037730387303973040730417304273043730447304573046730477304873049730507305173052730537305473055730567305773058730597306073061730627306373064730657306673067730687306973070730717307273073730747307573076730777307873079730807308173082730837308473085730867308773088730897309073091730927309373094730957309673097730987309973100731017310273103731047310573106731077310873109731107311173112731137311473115731167311773118731197312073121731227312373124731257312673127731287312973130731317313273133731347313573136731377313873139731407314173142731437314473145731467314773148731497315073151731527315373154731557315673157731587315973160731617316273163731647316573166731677316873169731707317173172731737317473175731767317773178731797318073181731827318373184731857318673187731887318973190731917319273193731947319573196731977319873199732007320173202732037320473205732067320773208732097321073211732127321373214732157321673217732187321973220732217322273223732247322573226732277322873229732307323173232732337323473235732367323773238732397324073241732427324373244732457324673247732487324973250732517325273253732547325573256732577325873259732607326173262732637326473265732667326773268732697327073271732727327373274732757327673277732787327973280732817328273283732847328573286732877328873289732907329173292732937329473295732967329773298732997330073301733027330373304733057330673307733087330973310733117331273313733147331573316733177331873319733207332173322733237332473325733267332773328733297333073331733327333373334733357333673337733387333973340733417334273343733447334573346733477334873349733507335173352733537335473355733567335773358733597336073361733627336373364733657336673367733687336973370733717337273373733747337573376733777337873379733807338173382733837338473385733867338773388733897339073391733927339373394733957339673397733987339973400734017340273403734047340573406734077340873409734107341173412734137341473415734167341773418734197342073421734227342373424734257342673427734287342973430734317343273433734347343573436734377343873439734407344173442734437344473445734467344773448734497345073451734527345373454734557345673457734587345973460734617346273463734647346573466734677346873469734707347173472734737347473475734767347773478734797348073481734827348373484734857348673487734887348973490734917349273493734947349573496734977349873499735007350173502735037350473505735067350773508735097351073511735127351373514735157351673517735187351973520735217352273523735247352573526735277352873529735307353173532735337353473535735367353773538735397354073541735427354373544735457354673547735487354973550735517355273553735547355573556735577355873559735607356173562735637356473565735667356773568735697357073571735727357373574735757357673577735787357973580735817358273583735847358573586735877358873589735907359173592735937359473595735967359773598735997360073601736027360373604736057360673607736087360973610736117361273613736147361573616736177361873619736207362173622736237362473625736267362773628736297363073631736327363373634736357363673637736387363973640736417364273643736447364573646736477364873649736507365173652736537365473655736567365773658736597366073661736627366373664736657366673667736687366973670736717367273673736747367573676736777367873679736807368173682736837368473685736867368773688736897369073691736927369373694736957369673697736987369973700737017370273703737047370573706737077370873709737107371173712737137371473715737167371773718737197372073721737227372373724737257372673727737287372973730737317373273733737347373573736737377373873739737407374173742737437374473745737467374773748737497375073751737527375373754737557375673757737587375973760737617376273763737647376573766737677376873769737707377173772737737377473775737767377773778737797378073781737827378373784737857378673787737887378973790737917379273793737947379573796737977379873799738007380173802738037380473805738067380773808738097381073811738127381373814738157381673817738187381973820738217382273823738247382573826738277382873829738307383173832738337383473835738367383773838738397384073841738427384373844738457384673847738487384973850738517385273853738547385573856738577385873859738607386173862738637386473865738667386773868738697387073871738727387373874738757387673877738787387973880738817388273883738847388573886738877388873889738907389173892738937389473895738967389773898738997390073901739027390373904739057390673907739087390973910739117391273913739147391573916739177391873919739207392173922739237392473925739267392773928739297393073931739327393373934739357393673937739387393973940739417394273943739447394573946739477394873949739507395173952739537395473955739567395773958739597396073961739627396373964739657396673967739687396973970739717397273973739747397573976739777397873979739807398173982739837398473985739867398773988739897399073991739927399373994739957399673997739987399974000740017400274003740047400574006740077400874009740107401174012740137401474015740167401774018740197402074021740227402374024740257402674027740287402974030740317403274033740347403574036740377403874039740407404174042740437404474045740467404774048740497405074051740527405374054740557405674057740587405974060740617406274063740647406574066740677406874069740707407174072740737407474075740767407774078740797408074081740827408374084740857408674087740887408974090740917409274093740947409574096740977409874099741007410174102741037410474105741067410774108741097411074111741127411374114741157411674117741187411974120741217412274123741247412574126741277412874129741307413174132741337413474135741367413774138741397414074141741427414374144741457414674147741487414974150741517415274153741547415574156741577415874159741607416174162741637416474165741667416774168741697417074171741727417374174741757417674177741787417974180741817418274183741847418574186741877418874189741907419174192741937419474195741967419774198741997420074201742027420374204742057420674207742087420974210742117421274213742147421574216742177421874219742207422174222742237422474225742267422774228742297423074231742327423374234742357423674237742387423974240742417424274243742447424574246742477424874249742507425174252742537425474255742567425774258742597426074261742627426374264742657426674267742687426974270742717427274273742747427574276742777427874279742807428174282742837428474285742867428774288742897429074291742927429374294742957429674297742987429974300743017430274303743047430574306743077430874309743107431174312743137431474315743167431774318743197432074321743227432374324743257432674327743287432974330743317433274333743347433574336743377433874339743407434174342743437434474345743467434774348743497435074351743527435374354743557435674357743587435974360743617436274363743647436574366743677436874369743707437174372743737437474375743767437774378743797438074381743827438374384743857438674387743887438974390743917439274393743947439574396743977439874399744007440174402744037440474405744067440774408744097441074411744127441374414744157441674417744187441974420744217442274423744247442574426744277442874429744307443174432744337443474435744367443774438744397444074441744427444374444744457444674447744487444974450744517445274453744547445574456744577445874459744607446174462744637446474465744667446774468744697447074471744727447374474744757447674477744787447974480744817448274483744847448574486744877448874489744907449174492744937449474495744967449774498744997450074501745027450374504745057450674507745087450974510745117451274513745147451574516745177451874519745207452174522745237452474525745267452774528745297453074531745327453374534745357453674537745387453974540745417454274543745447454574546745477454874549745507455174552745537455474555745567455774558745597456074561745627456374564745657456674567745687456974570745717457274573745747457574576745777457874579745807458174582745837458474585745867458774588745897459074591745927459374594745957459674597745987459974600746017460274603746047460574606746077460874609746107461174612746137461474615746167461774618746197462074621746227462374624746257462674627746287462974630746317463274633746347463574636746377463874639746407464174642746437464474645746467464774648746497465074651746527465374654746557465674657746587465974660746617466274663746647466574666746677466874669746707467174672746737467474675746767467774678746797468074681746827468374684746857468674687746887468974690746917469274693746947469574696746977469874699747007470174702747037470474705747067470774708747097471074711747127471374714747157471674717747187471974720747217472274723747247472574726747277472874729747307473174732747337473474735747367473774738747397474074741747427474374744747457474674747747487474974750747517475274753747547475574756747577475874759747607476174762747637476474765747667476774768747697477074771747727477374774747757477674777747787477974780747817478274783747847478574786747877478874789747907479174792747937479474795747967479774798747997480074801748027480374804748057480674807748087480974810748117481274813748147481574816748177481874819748207482174822748237482474825748267482774828748297483074831748327483374834748357483674837748387483974840748417484274843748447484574846748477484874849748507485174852748537485474855748567485774858748597486074861748627486374864748657486674867748687486974870748717487274873748747487574876748777487874879748807488174882748837488474885748867488774888748897489074891748927489374894748957489674897748987489974900749017490274903749047490574906749077490874909749107491174912749137491474915749167491774918749197492074921749227492374924749257492674927749287492974930749317493274933749347493574936749377493874939749407494174942749437494474945749467494774948749497495074951749527495374954749557495674957749587495974960749617496274963749647496574966749677496874969749707497174972749737497474975749767497774978749797498074981749827498374984749857498674987749887498974990749917499274993749947499574996749977499874999750007500175002750037500475005750067500775008750097501075011750127501375014750157501675017750187501975020750217502275023750247502575026750277502875029750307503175032750337503475035750367503775038750397504075041750427504375044750457504675047750487504975050750517505275053750547505575056750577505875059750607506175062750637506475065750667506775068750697507075071750727507375074750757507675077750787507975080750817508275083750847508575086750877508875089750907509175092750937509475095750967509775098750997510075101751027510375104751057510675107751087510975110751117511275113751147511575116751177511875119751207512175122751237512475125751267512775128751297513075131751327513375134751357513675137751387513975140751417514275143751447514575146751477514875149751507515175152751537515475155751567515775158751597516075161751627516375164751657516675167751687516975170751717517275173751747517575176751777517875179751807518175182751837518475185751867518775188751897519075191751927519375194751957519675197751987519975200752017520275203752047520575206752077520875209752107521175212752137521475215752167521775218752197522075221752227522375224752257522675227752287522975230752317523275233752347523575236752377523875239752407524175242752437524475245752467524775248752497525075251752527525375254752557525675257752587525975260752617526275263752647526575266752677526875269752707527175272752737527475275752767527775278752797528075281752827528375284752857528675287752887528975290752917529275293752947529575296752977529875299753007530175302753037530475305753067530775308753097531075311753127531375314753157531675317753187531975320753217532275323753247532575326753277532875329753307533175332753337533475335753367533775338753397534075341753427534375344753457534675347753487534975350753517535275353753547535575356753577535875359753607536175362753637536475365753667536775368753697537075371753727537375374753757537675377753787537975380753817538275383753847538575386753877538875389753907539175392753937539475395753967539775398753997540075401754027540375404754057540675407754087540975410754117541275413754147541575416754177541875419754207542175422754237542475425754267542775428754297543075431754327543375434754357543675437754387543975440754417544275443754447544575446754477544875449754507545175452754537545475455754567545775458754597546075461754627546375464754657546675467754687546975470754717547275473754747547575476754777547875479754807548175482754837548475485754867548775488754897549075491754927549375494754957549675497754987549975500755017550275503755047550575506755077550875509755107551175512755137551475515755167551775518755197552075521755227552375524755257552675527755287552975530755317553275533755347553575536755377553875539755407554175542755437554475545755467554775548755497555075551755527555375554755557555675557755587555975560755617556275563755647556575566755677556875569755707557175572755737557475575755767557775578755797558075581755827558375584755857558675587755887558975590755917559275593755947559575596755977559875599756007560175602756037560475605756067560775608756097561075611756127561375614756157561675617756187561975620756217562275623756247562575626756277562875629756307563175632756337563475635756367563775638756397564075641756427564375644756457564675647756487564975650756517565275653756547565575656756577565875659756607566175662756637566475665756667566775668756697567075671756727567375674756757567675677756787567975680756817568275683756847568575686756877568875689756907569175692756937569475695756967569775698756997570075701757027570375704757057570675707757087570975710757117571275713757147571575716757177571875719757207572175722757237572475725757267572775728757297573075731757327573375734757357573675737757387573975740757417574275743757447574575746757477574875749757507575175752757537575475755757567575775758757597576075761757627576375764757657576675767757687576975770757717577275773757747577575776757777577875779757807578175782757837578475785757867578775788757897579075791757927579375794757957579675797757987579975800758017580275803758047580575806758077580875809758107581175812758137581475815758167581775818758197582075821758227582375824758257582675827758287582975830758317583275833758347583575836758377583875839758407584175842758437584475845758467584775848758497585075851758527585375854758557585675857758587585975860758617586275863758647586575866758677586875869758707587175872758737587475875758767587775878758797588075881758827588375884758857588675887758887588975890758917589275893758947589575896758977589875899759007590175902759037590475905759067590775908759097591075911759127591375914759157591675917759187591975920759217592275923759247592575926759277592875929759307593175932759337593475935759367593775938759397594075941759427594375944759457594675947759487594975950759517595275953759547595575956759577595875959759607596175962759637596475965759667596775968759697597075971759727597375974759757597675977759787597975980759817598275983759847598575986759877598875989759907599175992759937599475995759967599775998759997600076001760027600376004760057600676007760087600976010760117601276013760147601576016760177601876019760207602176022760237602476025760267602776028760297603076031760327603376034760357603676037760387603976040760417604276043760447604576046760477604876049760507605176052760537605476055760567605776058760597606076061760627606376064760657606676067760687606976070760717607276073760747607576076760777607876079760807608176082760837608476085760867608776088760897609076091760927609376094760957609676097760987609976100761017610276103761047610576106761077610876109761107611176112761137611476115761167611776118761197612076121761227612376124761257612676127761287612976130761317613276133761347613576136761377613876139761407614176142761437614476145761467614776148761497615076151761527615376154761557615676157761587615976160761617616276163761647616576166761677616876169761707617176172761737617476175761767617776178761797618076181761827618376184761857618676187761887618976190761917619276193761947619576196761977619876199762007620176202762037620476205762067620776208762097621076211762127621376214762157621676217762187621976220762217622276223762247622576226762277622876229762307623176232762337623476235762367623776238762397624076241762427624376244762457624676247762487624976250762517625276253762547625576256762577625876259762607626176262762637626476265762667626776268762697627076271762727627376274762757627676277762787627976280762817628276283762847628576286762877628876289762907629176292762937629476295762967629776298762997630076301763027630376304763057630676307763087630976310763117631276313763147631576316763177631876319763207632176322763237632476325763267632776328763297633076331763327633376334763357633676337763387633976340763417634276343763447634576346763477634876349763507635176352763537635476355763567635776358763597636076361763627636376364763657636676367763687636976370763717637276373763747637576376763777637876379763807638176382763837638476385763867638776388763897639076391763927639376394763957639676397763987639976400764017640276403764047640576406764077640876409764107641176412764137641476415764167641776418764197642076421764227642376424764257642676427764287642976430764317643276433764347643576436764377643876439764407644176442764437644476445764467644776448764497645076451764527645376454764557645676457764587645976460764617646276463764647646576466764677646876469764707647176472764737647476475764767647776478764797648076481764827648376484764857648676487764887648976490764917649276493764947649576496764977649876499765007650176502765037650476505765067650776508765097651076511765127651376514765157651676517765187651976520765217652276523765247652576526765277652876529765307653176532765337653476535765367653776538765397654076541765427654376544765457654676547765487654976550765517655276553765547655576556765577655876559765607656176562765637656476565765667656776568765697657076571765727657376574765757657676577765787657976580765817658276583765847658576586765877658876589765907659176592765937659476595765967659776598765997660076601766027660376604766057660676607766087660976610766117661276613766147661576616766177661876619766207662176622766237662476625766267662776628766297663076631766327663376634766357663676637766387663976640766417664276643766447664576646766477664876649766507665176652766537665476655766567665776658766597666076661766627666376664766657666676667766687666976670766717667276673766747667576676766777667876679766807668176682766837668476685766867668776688766897669076691766927669376694766957669676697766987669976700767017670276703767047670576706767077670876709767107671176712767137671476715767167671776718767197672076721767227672376724767257672676727767287672976730767317673276733767347673576736767377673876739767407674176742767437674476745767467674776748767497675076751767527675376754767557675676757767587675976760767617676276763767647676576766767677676876769767707677176772767737677476775767767677776778767797678076781767827678376784767857678676787767887678976790767917679276793767947679576796767977679876799768007680176802768037680476805768067680776808768097681076811768127681376814768157681676817768187681976820768217682276823768247682576826768277682876829768307683176832768337683476835768367683776838768397684076841768427684376844768457684676847768487684976850768517685276853768547685576856768577685876859768607686176862768637686476865768667686776868768697687076871768727687376874768757687676877768787687976880768817688276883768847688576886768877688876889768907689176892768937689476895768967689776898768997690076901769027690376904769057690676907769087690976910769117691276913769147691576916769177691876919769207692176922769237692476925769267692776928769297693076931769327693376934769357693676937769387693976940769417694276943769447694576946769477694876949769507695176952769537695476955769567695776958769597696076961769627696376964769657696676967769687696976970769717697276973769747697576976769777697876979769807698176982769837698476985769867698776988769897699076991769927699376994769957699676997769987699977000770017700277003770047700577006770077700877009770107701177012770137701477015770167701777018770197702077021770227702377024770257702677027770287702977030770317703277033770347703577036770377703877039770407704177042770437704477045770467704777048770497705077051770527705377054770557705677057770587705977060770617706277063770647706577066770677706877069770707707177072770737707477075770767707777078770797708077081770827708377084770857708677087770887708977090770917709277093770947709577096770977709877099771007710177102771037710477105771067710777108771097711077111771127711377114771157711677117771187711977120771217712277123771247712577126771277712877129771307713177132771337713477135771367713777138771397714077141771427714377144771457714677147771487714977150771517715277153771547715577156771577715877159771607716177162771637716477165771667716777168771697717077171771727717377174771757717677177771787717977180771817718277183771847718577186771877718877189771907719177192771937719477195771967719777198771997720077201772027720377204772057720677207772087720977210772117721277213772147721577216772177721877219772207722177222772237722477225772267722777228772297723077231772327723377234772357723677237772387723977240772417724277243772447724577246772477724877249772507725177252772537725477255772567725777258772597726077261772627726377264772657726677267772687726977270772717727277273772747727577276772777727877279772807728177282772837728477285772867728777288772897729077291772927729377294772957729677297772987729977300773017730277303773047730577306773077730877309773107731177312773137731477315773167731777318773197732077321773227732377324773257732677327773287732977330773317733277333773347733577336773377733877339773407734177342773437734477345773467734777348773497735077351773527735377354773557735677357773587735977360773617736277363773647736577366773677736877369773707737177372773737737477375773767737777378773797738077381773827738377384773857738677387773887738977390773917739277393773947739577396773977739877399774007740177402774037740477405774067740777408774097741077411774127741377414774157741677417774187741977420774217742277423774247742577426774277742877429774307743177432774337743477435774367743777438774397744077441774427744377444774457744677447774487744977450774517745277453774547745577456774577745877459774607746177462774637746477465774667746777468774697747077471774727747377474774757747677477774787747977480774817748277483774847748577486774877748877489774907749177492774937749477495774967749777498774997750077501775027750377504775057750677507775087750977510775117751277513775147751577516775177751877519775207752177522775237752477525775267752777528775297753077531775327753377534775357753677537775387753977540775417754277543775447754577546775477754877549775507755177552775537755477555775567755777558775597756077561775627756377564775657756677567775687756977570775717757277573775747757577576775777757877579775807758177582775837758477585775867758777588775897759077591775927759377594775957759677597775987759977600776017760277603776047760577606776077760877609776107761177612776137761477615776167761777618776197762077621776227762377624776257762677627776287762977630776317763277633776347763577636776377763877639776407764177642776437764477645776467764777648776497765077651776527765377654776557765677657776587765977660776617766277663776647766577666776677766877669776707767177672776737767477675776767767777678776797768077681776827768377684776857768677687776887768977690776917769277693776947769577696776977769877699777007770177702777037770477705777067770777708777097771077711777127771377714777157771677717777187771977720777217772277723777247772577726777277772877729777307773177732777337773477735777367773777738777397774077741777427774377744777457774677747777487774977750777517775277753777547775577756777577775877759777607776177762777637776477765777667776777768777697777077771777727777377774777757777677777777787777977780777817778277783777847778577786777877778877789777907779177792777937779477795777967779777798777997780077801778027780377804778057780677807778087780977810778117781277813778147781577816778177781877819778207782177822778237782477825778267782777828778297783077831778327783377834778357783677837778387783977840778417784277843778447784577846778477784877849778507785177852778537785477855778567785777858778597786077861778627786377864778657786677867778687786977870778717787277873778747787577876778777787877879778807788177882778837788477885778867788777888778897789077891778927789377894778957789677897778987789977900779017790277903779047790577906779077790877909779107791177912779137791477915779167791777918779197792077921779227792377924779257792677927779287792977930779317793277933779347793577936779377793877939779407794177942779437794477945779467794777948779497795077951779527795377954779557795677957779587795977960779617796277963779647796577966779677796877969779707797177972779737797477975779767797777978779797798077981779827798377984779857798677987779887798977990779917799277993779947799577996779977799877999780007800178002780037800478005780067800778008780097801078011780127801378014780157801678017780187801978020780217802278023780247802578026780277802878029780307803178032780337803478035780367803778038780397804078041780427804378044780457804678047780487804978050780517805278053780547805578056780577805878059780607806178062780637806478065780667806778068780697807078071780727807378074780757807678077780787807978080780817808278083780847808578086780877808878089780907809178092780937809478095780967809778098780997810078101781027810378104781057810678107781087810978110781117811278113781147811578116781177811878119781207812178122781237812478125781267812778128781297813078131781327813378134781357813678137781387813978140781417814278143781447814578146781477814878149781507815178152781537815478155781567815778158781597816078161781627816378164781657816678167781687816978170781717817278173781747817578176781777817878179781807818178182781837818478185781867818778188781897819078191781927819378194781957819678197781987819978200782017820278203782047820578206782077820878209782107821178212782137821478215782167821778218782197822078221782227822378224782257822678227782287822978230782317823278233782347823578236782377823878239782407824178242782437824478245782467824778248782497825078251782527825378254782557825678257782587825978260782617826278263782647826578266782677826878269782707827178272782737827478275782767827778278782797828078281782827828378284782857828678287782887828978290782917829278293782947829578296782977829878299783007830178302783037830478305783067830778308783097831078311783127831378314783157831678317783187831978320783217832278323783247832578326783277832878329783307833178332783337833478335783367833778338783397834078341783427834378344783457834678347783487834978350783517835278353783547835578356783577835878359783607836178362783637836478365783667836778368783697837078371783727837378374783757837678377783787837978380783817838278383783847838578386783877838878389783907839178392783937839478395783967839778398783997840078401784027840378404784057840678407784087840978410784117841278413784147841578416784177841878419784207842178422784237842478425784267842778428784297843078431784327843378434784357843678437784387843978440784417844278443784447844578446784477844878449784507845178452784537845478455784567845778458784597846078461784627846378464784657846678467784687846978470784717847278473784747847578476784777847878479784807848178482784837848478485784867848778488784897849078491784927849378494784957849678497784987849978500785017850278503785047850578506785077850878509785107851178512785137851478515785167851778518785197852078521785227852378524785257852678527785287852978530785317853278533785347853578536785377853878539785407854178542785437854478545785467854778548785497855078551785527855378554785557855678557785587855978560785617856278563785647856578566785677856878569785707857178572785737857478575785767857778578785797858078581785827858378584785857858678587785887858978590785917859278593785947859578596785977859878599786007860178602786037860478605786067860778608786097861078611786127861378614786157861678617786187861978620786217862278623786247862578626786277862878629786307863178632786337863478635786367863778638786397864078641786427864378644786457864678647786487864978650786517865278653786547865578656786577865878659786607866178662786637866478665786667866778668786697867078671786727867378674786757867678677786787867978680786817868278683786847868578686786877868878689786907869178692786937869478695786967869778698786997870078701787027870378704787057870678707787087870978710787117871278713787147871578716787177871878719787207872178722787237872478725787267872778728787297873078731787327873378734787357873678737787387873978740787417874278743787447874578746787477874878749787507875178752787537875478755787567875778758787597876078761787627876378764787657876678767787687876978770787717877278773787747877578776787777877878779787807878178782787837878478785787867878778788787897879078791787927879378794787957879678797787987879978800788017880278803788047880578806788077880878809788107881178812788137881478815788167881778818788197882078821788227882378824788257882678827788287882978830788317883278833788347883578836788377883878839788407884178842788437884478845788467884778848788497885078851788527885378854788557885678857788587885978860788617886278863788647886578866788677886878869788707887178872788737887478875788767887778878788797888078881788827888378884788857888678887788887888978890788917889278893788947889578896788977889878899789007890178902789037890478905789067890778908789097891078911789127891378914789157891678917789187891978920789217892278923789247892578926789277892878929789307893178932789337893478935789367893778938789397894078941789427894378944789457894678947789487894978950789517895278953789547895578956789577895878959789607896178962789637896478965789667896778968789697897078971789727897378974789757897678977789787897978980789817898278983789847898578986789877898878989789907899178992789937899478995789967899778998789997900079001790027900379004790057900679007790087900979010790117901279013790147901579016790177901879019790207902179022790237902479025790267902779028790297903079031790327903379034790357903679037790387903979040790417904279043790447904579046790477904879049790507905179052790537905479055790567905779058790597906079061790627906379064790657906679067790687906979070790717907279073790747907579076790777907879079790807908179082790837908479085790867908779088790897909079091790927909379094790957909679097790987909979100791017910279103791047910579106791077910879109791107911179112791137911479115791167911779118791197912079121791227912379124791257912679127791287912979130791317913279133791347913579136791377913879139791407914179142791437914479145791467914779148791497915079151791527915379154791557915679157791587915979160791617916279163791647916579166791677916879169791707917179172791737917479175791767917779178791797918079181791827918379184791857918679187791887918979190791917919279193791947919579196791977919879199792007920179202792037920479205792067920779208792097921079211792127921379214792157921679217792187921979220792217922279223792247922579226792277922879229792307923179232792337923479235792367923779238792397924079241792427924379244792457924679247792487924979250792517925279253792547925579256792577925879259792607926179262792637926479265792667926779268792697927079271792727927379274792757927679277792787927979280792817928279283792847928579286792877928879289792907929179292792937929479295792967929779298792997930079301793027930379304793057930679307793087930979310793117931279313793147931579316793177931879319793207932179322793237932479325793267932779328793297933079331793327933379334793357933679337793387933979340793417934279343793447934579346793477934879349793507935179352793537935479355793567935779358793597936079361793627936379364793657936679367793687936979370793717937279373793747937579376793777937879379793807938179382793837938479385793867938779388793897939079391793927939379394793957939679397793987939979400794017940279403794047940579406794077940879409794107941179412794137941479415794167941779418794197942079421794227942379424794257942679427794287942979430794317943279433794347943579436794377943879439794407944179442794437944479445794467944779448794497945079451794527945379454794557945679457794587945979460794617946279463794647946579466794677946879469794707947179472794737947479475794767947779478794797948079481794827948379484794857948679487794887948979490794917949279493794947949579496794977949879499795007950179502795037950479505795067950779508795097951079511795127951379514795157951679517795187951979520795217952279523795247952579526795277952879529795307953179532795337953479535795367953779538795397954079541795427954379544795457954679547795487954979550795517955279553795547955579556795577955879559795607956179562795637956479565795667956779568795697957079571795727957379574795757957679577795787957979580795817958279583795847958579586795877958879589795907959179592795937959479595795967959779598795997960079601796027960379604796057960679607796087960979610796117961279613796147961579616796177961879619796207962179622796237962479625796267962779628796297963079631796327963379634796357963679637796387963979640796417964279643796447964579646796477964879649796507965179652796537965479655796567965779658796597966079661796627966379664796657966679667796687966979670796717967279673796747967579676796777967879679796807968179682796837968479685796867968779688796897969079691796927969379694796957969679697796987969979700797017970279703797047970579706797077970879709797107971179712797137971479715797167971779718797197972079721797227972379724797257972679727797287972979730797317973279733797347973579736797377973879739797407974179742797437974479745797467974779748797497975079751797527975379754797557975679757797587975979760797617976279763797647976579766797677976879769797707977179772797737977479775797767977779778797797978079781797827978379784797857978679787797887978979790797917979279793797947979579796797977979879799798007980179802798037980479805798067980779808798097981079811798127981379814798157981679817798187981979820798217982279823798247982579826798277982879829798307983179832798337983479835798367983779838798397984079841798427984379844798457984679847798487984979850798517985279853798547985579856798577985879859798607986179862798637986479865798667986779868798697987079871798727987379874798757987679877798787987979880798817988279883798847988579886798877988879889798907989179892798937989479895798967989779898798997990079901799027990379904799057990679907799087990979910799117991279913799147991579916799177991879919799207992179922799237992479925799267992779928799297993079931799327993379934799357993679937799387993979940799417994279943799447994579946799477994879949799507995179952799537995479955799567995779958799597996079961799627996379964799657996679967799687996979970799717997279973799747997579976799777997879979799807998179982799837998479985799867998779988799897999079991799927999379994799957999679997799987999980000800018000280003800048000580006800078000880009800108001180012800138001480015800168001780018800198002080021800228002380024800258002680027800288002980030800318003280033800348003580036800378003880039800408004180042800438004480045800468004780048800498005080051800528005380054800558005680057800588005980060800618006280063800648006580066800678006880069800708007180072800738007480075800768007780078800798008080081800828008380084800858008680087800888008980090800918009280093800948009580096800978009880099801008010180102801038010480105801068010780108801098011080111801128011380114801158011680117801188011980120801218012280123801248012580126801278012880129801308013180132801338013480135801368013780138801398014080141801428014380144801458014680147801488014980150801518015280153801548015580156801578015880159801608016180162801638016480165801668016780168801698017080171801728017380174801758017680177801788017980180801818018280183801848018580186801878018880189801908019180192801938019480195801968019780198801998020080201802028020380204802058020680207802088020980210802118021280213802148021580216802178021880219802208022180222802238022480225802268022780228802298023080231802328023380234802358023680237802388023980240802418024280243802448024580246802478024880249802508025180252802538025480255802568025780258802598026080261802628026380264802658026680267802688026980270802718027280273802748027580276802778027880279802808028180282802838028480285802868028780288802898029080291802928029380294802958029680297802988029980300803018030280303803048030580306803078030880309803108031180312803138031480315803168031780318803198032080321803228032380324803258032680327803288032980330803318033280333803348033580336803378033880339803408034180342803438034480345803468034780348803498035080351803528035380354803558035680357803588035980360803618036280363803648036580366803678036880369803708037180372803738037480375803768037780378803798038080381803828038380384803858038680387803888038980390803918039280393803948039580396803978039880399804008040180402804038040480405804068040780408804098041080411804128041380414804158041680417804188041980420804218042280423804248042580426804278042880429804308043180432804338043480435804368043780438804398044080441804428044380444804458044680447804488044980450804518045280453804548045580456804578045880459804608046180462804638046480465804668046780468804698047080471804728047380474804758047680477804788047980480804818048280483804848048580486804878048880489804908049180492804938049480495804968049780498804998050080501805028050380504805058050680507805088050980510805118051280513805148051580516805178051880519805208052180522805238052480525805268052780528805298053080531805328053380534805358053680537805388053980540805418054280543805448054580546805478054880549805508055180552805538055480555805568055780558805598056080561805628056380564805658056680567805688056980570805718057280573805748057580576805778057880579805808058180582805838058480585805868058780588805898059080591805928059380594805958059680597805988059980600806018060280603806048060580606806078060880609806108061180612806138061480615806168061780618806198062080621806228062380624806258062680627806288062980630806318063280633806348063580636806378063880639806408064180642806438064480645806468064780648806498065080651806528065380654806558065680657806588065980660806618066280663806648066580666806678066880669806708067180672806738067480675806768067780678806798068080681806828068380684806858068680687806888068980690806918069280693806948069580696806978069880699807008070180702807038070480705807068070780708807098071080711807128071380714807158071680717807188071980720807218072280723807248072580726807278072880729807308073180732807338073480735807368073780738807398074080741807428074380744807458074680747807488074980750807518075280753807548075580756807578075880759807608076180762807638076480765807668076780768807698077080771807728077380774807758077680777807788077980780807818078280783807848078580786807878078880789807908079180792807938079480795807968079780798807998080080801808028080380804808058080680807808088080980810808118081280813808148081580816808178081880819808208082180822808238082480825808268082780828808298083080831808328083380834808358083680837808388083980840808418084280843808448084580846808478084880849808508085180852808538085480855808568085780858808598086080861808628086380864808658086680867808688086980870808718087280873808748087580876808778087880879808808088180882808838088480885808868088780888808898089080891808928089380894808958089680897808988089980900809018090280903809048090580906809078090880909809108091180912809138091480915809168091780918809198092080921809228092380924809258092680927809288092980930809318093280933809348093580936809378093880939809408094180942809438094480945809468094780948809498095080951809528095380954809558095680957809588095980960809618096280963809648096580966809678096880969809708097180972809738097480975809768097780978809798098080981809828098380984809858098680987809888098980990809918099280993809948099580996809978099880999810008100181002810038100481005810068100781008810098101081011810128101381014810158101681017810188101981020810218102281023810248102581026810278102881029810308103181032810338103481035810368103781038810398104081041810428104381044810458104681047810488104981050810518105281053810548105581056810578105881059810608106181062810638106481065810668106781068810698107081071810728107381074810758107681077810788107981080810818108281083810848108581086810878108881089810908109181092810938109481095810968109781098810998110081101811028110381104811058110681107811088110981110811118111281113811148111581116811178111881119811208112181122811238112481125811268112781128811298113081131811328113381134811358113681137811388113981140811418114281143811448114581146811478114881149811508115181152811538115481155811568115781158811598116081161811628116381164811658116681167811688116981170811718117281173811748117581176811778117881179811808118181182811838118481185811868118781188811898119081191811928119381194811958119681197811988119981200812018120281203812048120581206812078120881209812108121181212812138121481215812168121781218812198122081221812228122381224812258122681227812288122981230812318123281233812348123581236812378123881239812408124181242812438124481245812468124781248812498125081251812528125381254812558125681257812588125981260812618126281263812648126581266812678126881269812708127181272812738127481275812768127781278812798128081281812828128381284812858128681287812888128981290812918129281293812948129581296812978129881299813008130181302813038130481305813068130781308813098131081311813128131381314813158131681317813188131981320813218132281323813248132581326813278132881329813308133181332813338133481335813368133781338813398134081341813428134381344813458134681347813488134981350813518135281353813548135581356813578135881359813608136181362813638136481365813668136781368813698137081371813728137381374813758137681377813788137981380813818138281383813848138581386813878138881389813908139181392813938139481395813968139781398813998140081401814028140381404814058140681407814088140981410814118141281413814148141581416814178141881419814208142181422814238142481425814268142781428814298143081431814328143381434814358143681437814388143981440814418144281443814448144581446814478144881449814508145181452814538145481455814568145781458814598146081461814628146381464814658146681467814688146981470814718147281473814748147581476814778147881479814808148181482814838148481485814868148781488814898149081491814928149381494814958149681497814988149981500815018150281503815048150581506815078150881509815108151181512815138151481515815168151781518815198152081521815228152381524815258152681527815288152981530815318153281533815348153581536815378153881539815408154181542815438154481545815468154781548815498155081551815528155381554815558155681557815588155981560815618156281563815648156581566815678156881569815708157181572815738157481575815768157781578815798158081581815828158381584815858158681587815888158981590815918159281593815948159581596815978159881599816008160181602816038160481605816068160781608816098161081611816128161381614816158161681617816188161981620816218162281623816248162581626816278162881629816308163181632816338163481635816368163781638816398164081641816428164381644816458164681647816488164981650816518165281653816548165581656816578165881659816608166181662816638166481665816668166781668816698167081671816728167381674816758167681677816788167981680816818168281683816848168581686816878168881689816908169181692816938169481695816968169781698816998170081701817028170381704817058170681707817088170981710817118171281713817148171581716817178171881719817208172181722817238172481725817268172781728817298173081731817328173381734817358173681737817388173981740817418174281743817448174581746817478174881749817508175181752817538175481755817568175781758817598176081761817628176381764817658176681767817688176981770817718177281773817748177581776817778177881779817808178181782817838178481785817868178781788817898179081791817928179381794817958179681797817988179981800818018180281803818048180581806818078180881809818108181181812818138181481815818168181781818818198182081821818228182381824818258182681827818288182981830818318183281833818348183581836818378183881839818408184181842818438184481845818468184781848818498185081851818528185381854818558185681857818588185981860818618186281863818648186581866818678186881869818708187181872818738187481875818768187781878818798188081881818828188381884818858188681887818888188981890818918189281893818948189581896818978189881899819008190181902819038190481905819068190781908819098191081911819128191381914819158191681917819188191981920819218192281923819248192581926819278192881929819308193181932819338193481935819368193781938819398194081941819428194381944819458194681947819488194981950819518195281953819548195581956819578195881959819608196181962819638196481965819668196781968819698197081971819728197381974819758197681977819788197981980819818198281983819848198581986819878198881989819908199181992819938199481995819968199781998819998200082001820028200382004820058200682007820088200982010820118201282013820148201582016820178201882019820208202182022820238202482025820268202782028820298203082031820328203382034820358203682037820388203982040820418204282043820448204582046820478204882049820508205182052820538205482055820568205782058820598206082061820628206382064820658206682067820688206982070820718207282073820748207582076820778207882079820808208182082820838208482085820868208782088820898209082091820928209382094820958209682097820988209982100821018210282103821048210582106821078210882109821108211182112821138211482115821168211782118821198212082121821228212382124821258212682127821288212982130821318213282133821348213582136821378213882139821408214182142821438214482145821468214782148821498215082151821528215382154821558215682157821588215982160821618216282163821648216582166821678216882169821708217182172821738217482175821768217782178821798218082181821828218382184821858218682187821888218982190821918219282193821948219582196821978219882199822008220182202822038220482205822068220782208822098221082211822128221382214822158221682217822188221982220822218222282223822248222582226822278222882229822308223182232822338223482235822368223782238822398224082241822428224382244822458224682247822488224982250822518225282253822548225582256822578225882259822608226182262822638226482265822668226782268822698227082271822728227382274822758227682277822788227982280822818228282283822848228582286822878228882289822908229182292822938229482295822968229782298822998230082301823028230382304823058230682307823088230982310823118231282313823148231582316823178231882319823208232182322823238232482325823268232782328823298233082331823328233382334823358233682337823388233982340823418234282343823448234582346823478234882349823508235182352823538235482355823568235782358823598236082361823628236382364823658236682367823688236982370823718237282373823748237582376823778237882379823808238182382823838238482385823868238782388823898239082391823928239382394823958239682397823988239982400824018240282403824048240582406824078240882409824108241182412824138241482415824168241782418824198242082421824228242382424824258242682427824288242982430824318243282433824348243582436824378243882439824408244182442824438244482445824468244782448824498245082451824528245382454824558245682457824588245982460824618246282463824648246582466824678246882469824708247182472824738247482475824768247782478824798248082481824828248382484824858248682487824888248982490824918249282493824948249582496824978249882499825008250182502825038250482505825068250782508825098251082511825128251382514825158251682517825188251982520825218252282523825248252582526825278252882529825308253182532825338253482535825368253782538825398254082541825428254382544825458254682547825488254982550825518255282553825548255582556825578255882559825608256182562825638256482565825668256782568825698257082571825728257382574825758257682577825788257982580825818258282583825848258582586825878258882589825908259182592825938259482595825968259782598825998260082601826028260382604826058260682607826088260982610826118261282613826148261582616826178261882619826208262182622826238262482625826268262782628826298263082631826328263382634826358263682637826388263982640826418264282643826448264582646826478264882649826508265182652826538265482655826568265782658826598266082661826628266382664826658266682667826688266982670826718267282673826748267582676826778267882679826808268182682826838268482685826868268782688826898269082691826928269382694826958269682697826988269982700827018270282703827048270582706827078270882709827108271182712827138271482715827168271782718827198272082721827228272382724827258272682727827288272982730827318273282733827348273582736827378273882739827408274182742827438274482745827468274782748827498275082751827528275382754827558275682757827588275982760827618276282763827648276582766827678276882769827708277182772827738277482775827768277782778827798278082781827828278382784827858278682787827888278982790827918279282793827948279582796827978279882799828008280182802828038280482805828068280782808828098281082811828128281382814828158281682817828188281982820828218282282823828248282582826828278282882829828308283182832828338283482835828368283782838828398284082841828428284382844828458284682847828488284982850828518285282853828548285582856828578285882859828608286182862828638286482865828668286782868828698287082871828728287382874828758287682877828788287982880828818288282883828848288582886828878288882889828908289182892828938289482895828968289782898828998290082901829028290382904829058290682907829088290982910829118291282913829148291582916829178291882919829208292182922829238292482925829268292782928829298293082931829328293382934829358293682937829388293982940829418294282943829448294582946829478294882949829508295182952829538295482955829568295782958829598296082961829628296382964829658296682967829688296982970829718297282973829748297582976829778297882979829808298182982829838298482985829868298782988829898299082991829928299382994829958299682997829988299983000830018300283003830048300583006830078300883009830108301183012830138301483015830168301783018830198302083021830228302383024830258302683027830288302983030830318303283033830348303583036830378303883039830408304183042830438304483045830468304783048830498305083051830528305383054830558305683057830588305983060830618306283063830648306583066830678306883069830708307183072830738307483075830768307783078830798308083081830828308383084830858308683087830888308983090830918309283093830948309583096830978309883099831008310183102831038310483105831068310783108831098311083111831128311383114831158311683117831188311983120831218312283123831248312583126831278312883129831308313183132831338313483135831368313783138831398314083141831428314383144831458314683147831488314983150831518315283153831548315583156831578315883159831608316183162831638316483165831668316783168831698317083171831728317383174831758317683177831788317983180831818318283183831848318583186831878318883189831908319183192831938319483195831968319783198831998320083201832028320383204832058320683207832088320983210832118321283213832148321583216832178321883219832208322183222832238322483225832268322783228832298323083231832328323383234832358323683237832388323983240832418324283243832448324583246832478324883249832508325183252832538325483255832568325783258832598326083261832628326383264832658326683267832688326983270832718327283273832748327583276832778327883279832808328183282832838328483285832868328783288832898329083291832928329383294832958329683297832988329983300833018330283303833048330583306833078330883309833108331183312833138331483315833168331783318833198332083321833228332383324833258332683327833288332983330833318333283333833348333583336833378333883339833408334183342833438334483345833468334783348833498335083351833528335383354833558335683357833588335983360833618336283363833648336583366833678336883369833708337183372833738337483375833768337783378833798338083381833828338383384833858338683387833888338983390833918339283393833948339583396833978339883399834008340183402834038340483405834068340783408834098341083411834128341383414834158341683417834188341983420834218342283423834248342583426834278342883429834308343183432834338343483435834368343783438834398344083441834428344383444834458344683447834488344983450834518345283453834548345583456834578345883459834608346183462834638346483465834668346783468834698347083471834728347383474834758347683477834788347983480834818348283483834848348583486834878348883489834908349183492834938349483495834968349783498834998350083501835028350383504835058350683507835088350983510835118351283513835148351583516835178351883519835208352183522835238352483525835268352783528835298353083531835328353383534835358353683537835388353983540835418354283543835448354583546835478354883549835508355183552835538355483555835568355783558835598356083561835628356383564835658356683567835688356983570835718357283573835748357583576835778357883579835808358183582835838358483585835868358783588835898359083591835928359383594835958359683597835988359983600836018360283603836048360583606836078360883609836108361183612836138361483615836168361783618836198362083621836228362383624836258362683627836288362983630836318363283633836348363583636836378363883639836408364183642836438364483645836468364783648836498365083651836528365383654836558365683657836588365983660836618366283663836648366583666836678366883669836708367183672836738367483675836768367783678836798368083681836828368383684836858368683687836888368983690836918369283693836948369583696836978369883699837008370183702837038370483705837068370783708837098371083711837128371383714837158371683717837188371983720837218372283723837248372583726837278372883729837308373183732837338373483735837368373783738837398374083741837428374383744837458374683747837488374983750837518375283753837548375583756837578375883759837608376183762837638376483765837668376783768837698377083771837728377383774837758377683777837788377983780837818378283783837848378583786837878378883789837908379183792837938379483795837968379783798837998380083801838028380383804838058380683807838088380983810838118381283813838148381583816838178381883819838208382183822838238382483825838268382783828838298383083831838328383383834838358383683837838388383983840838418384283843838448384583846838478384883849838508385183852838538385483855838568385783858838598386083861838628386383864838658386683867838688386983870838718387283873838748387583876838778387883879838808388183882838838388483885838868388783888838898389083891838928389383894838958389683897838988389983900839018390283903839048390583906839078390883909839108391183912839138391483915839168391783918839198392083921839228392383924839258392683927839288392983930839318393283933839348393583936839378393883939839408394183942839438394483945839468394783948839498395083951839528395383954839558395683957839588395983960839618396283963839648396583966839678396883969839708397183972839738397483975839768397783978839798398083981839828398383984839858398683987839888398983990839918399283993839948399583996839978399883999840008400184002840038400484005840068400784008840098401084011840128401384014840158401684017840188401984020840218402284023840248402584026840278402884029840308403184032840338403484035840368403784038840398404084041840428404384044840458404684047840488404984050840518405284053840548405584056840578405884059840608406184062840638406484065840668406784068840698407084071840728407384074840758407684077840788407984080840818408284083840848408584086840878408884089840908409184092840938409484095840968409784098840998410084101841028410384104841058410684107841088410984110841118411284113841148411584116841178411884119841208412184122841238412484125841268412784128841298413084131841328413384134841358413684137841388413984140841418414284143841448414584146841478414884149841508415184152841538415484155841568415784158841598416084161841628416384164841658416684167841688416984170841718417284173841748417584176841778417884179841808418184182841838418484185841868418784188841898419084191841928419384194841958419684197841988419984200842018420284203842048420584206842078420884209842108421184212842138421484215842168421784218842198422084221842228422384224842258422684227842288422984230842318423284233842348423584236842378423884239842408424184242842438424484245842468424784248842498425084251842528425384254842558425684257842588425984260842618426284263842648426584266842678426884269842708427184272842738427484275842768427784278842798428084281842828428384284842858428684287842888428984290842918429284293842948429584296842978429884299843008430184302843038430484305843068430784308843098431084311843128431384314843158431684317843188431984320843218432284323843248432584326843278432884329843308433184332843338433484335843368433784338843398434084341843428434384344843458434684347843488434984350843518435284353843548435584356843578435884359843608436184362843638436484365843668436784368843698437084371843728437384374843758437684377843788437984380843818438284383843848438584386843878438884389843908439184392843938439484395843968439784398843998440084401844028440384404844058440684407844088440984410844118441284413844148441584416844178441884419844208442184422844238442484425844268442784428844298443084431844328443384434844358443684437844388443984440844418444284443844448444584446844478444884449844508445184452844538445484455844568445784458844598446084461844628446384464844658446684467844688446984470844718447284473844748447584476844778447884479844808448184482844838448484485844868448784488844898449084491844928449384494844958449684497844988449984500845018450284503845048450584506845078450884509845108451184512845138451484515845168451784518845198452084521845228452384524845258452684527845288452984530845318453284533845348453584536845378453884539845408454184542845438454484545845468454784548845498455084551845528455384554845558455684557845588455984560845618456284563845648456584566845678456884569845708457184572845738457484575845768457784578845798458084581845828458384584845858458684587845888458984590845918459284593845948459584596845978459884599846008460184602846038460484605846068460784608846098461084611846128461384614846158461684617846188461984620846218462284623846248462584626846278462884629846308463184632846338463484635846368463784638846398464084641846428464384644846458464684647846488464984650846518465284653846548465584656846578465884659846608466184662846638466484665846668466784668846698467084671846728467384674846758467684677846788467984680846818468284683846848468584686846878468884689846908469184692846938469484695846968469784698846998470084701847028470384704847058470684707847088470984710847118471284713847148471584716847178471884719847208472184722847238472484725847268472784728847298473084731847328473384734847358473684737847388473984740847418474284743847448474584746847478474884749847508475184752847538475484755847568475784758847598476084761847628476384764847658476684767847688476984770847718477284773847748477584776847778477884779847808478184782847838478484785847868478784788847898479084791847928479384794847958479684797847988479984800848018480284803848048480584806848078480884809848108481184812848138481484815848168481784818848198482084821848228482384824848258482684827848288482984830848318483284833848348483584836848378483884839848408484184842848438484484845848468484784848848498485084851848528485384854848558485684857848588485984860848618486284863848648486584866848678486884869848708487184872848738487484875848768487784878848798488084881848828488384884848858488684887848888488984890848918489284893848948489584896848978489884899849008490184902849038490484905849068490784908849098491084911849128491384914849158491684917849188491984920849218492284923849248492584926849278492884929849308493184932849338493484935849368493784938849398494084941849428494384944849458494684947849488494984950849518495284953849548495584956849578495884959849608496184962849638496484965849668496784968849698497084971849728497384974849758497684977849788497984980849818498284983849848498584986849878498884989849908499184992849938499484995849968499784998849998500085001850028500385004850058500685007850088500985010850118501285013850148501585016850178501885019850208502185022850238502485025850268502785028850298503085031850328503385034850358503685037850388503985040850418504285043850448504585046850478504885049850508505185052850538505485055850568505785058850598506085061850628506385064850658506685067850688506985070850718507285073850748507585076850778507885079850808508185082850838508485085850868508785088850898509085091850928509385094850958509685097850988509985100851018510285103851048510585106851078510885109851108511185112851138511485115851168511785118851198512085121851228512385124851258512685127851288512985130851318513285133851348513585136851378513885139851408514185142851438514485145851468514785148851498515085151851528515385154851558515685157851588515985160851618516285163851648516585166851678516885169851708517185172851738517485175851768517785178851798518085181851828518385184851858518685187851888518985190851918519285193851948519585196851978519885199852008520185202852038520485205852068520785208852098521085211852128521385214852158521685217852188521985220852218522285223852248522585226852278522885229852308523185232852338523485235852368523785238852398524085241852428524385244852458524685247852488524985250852518525285253852548525585256852578525885259852608526185262852638526485265852668526785268852698527085271852728527385274852758527685277852788527985280852818528285283852848528585286852878528885289852908529185292852938529485295852968529785298852998530085301853028530385304853058530685307853088530985310853118531285313853148531585316853178531885319853208532185322853238532485325853268532785328853298533085331853328533385334853358533685337853388533985340853418534285343853448534585346853478534885349853508535185352853538535485355853568535785358853598536085361853628536385364853658536685367853688536985370853718537285373853748537585376853778537885379853808538185382853838538485385853868538785388853898539085391853928539385394853958539685397853988539985400854018540285403854048540585406854078540885409854108541185412854138541485415854168541785418854198542085421854228542385424854258542685427854288542985430854318543285433854348543585436854378543885439854408544185442854438544485445854468544785448854498545085451854528545385454854558545685457854588545985460854618546285463854648546585466854678546885469854708547185472854738547485475854768547785478854798548085481854828548385484854858548685487854888548985490854918549285493854948549585496854978549885499855008550185502855038550485505855068550785508855098551085511855128551385514855158551685517855188551985520855218552285523855248552585526855278552885529855308553185532855338553485535855368553785538855398554085541855428554385544855458554685547855488554985550855518555285553855548555585556855578555885559855608556185562855638556485565855668556785568855698557085571855728557385574855758557685577855788557985580855818558285583855848558585586855878558885589855908559185592855938559485595855968559785598855998560085601856028560385604856058560685607856088560985610856118561285613856148561585616856178561885619856208562185622856238562485625856268562785628856298563085631856328563385634856358563685637856388563985640856418564285643856448564585646856478564885649856508565185652856538565485655856568565785658856598566085661856628566385664856658566685667856688566985670856718567285673856748567585676856778567885679856808568185682856838568485685856868568785688856898569085691856928569385694856958569685697856988569985700857018570285703857048570585706857078570885709857108571185712857138571485715857168571785718857198572085721857228572385724857258572685727857288572985730857318573285733857348573585736857378573885739857408574185742857438574485745857468574785748857498575085751857528575385754857558575685757857588575985760857618576285763857648576585766857678576885769857708577185772857738577485775857768577785778857798578085781857828578385784857858578685787857888578985790857918579285793857948579585796857978579885799858008580185802858038580485805858068580785808858098581085811858128581385814858158581685817858188581985820858218582285823858248582585826858278582885829858308583185832858338583485835858368583785838858398584085841858428584385844858458584685847858488584985850858518585285853858548585585856858578585885859858608586185862858638586485865858668586785868858698587085871858728587385874858758587685877858788587985880858818588285883858848588585886858878588885889858908589185892858938589485895858968589785898858998590085901859028590385904859058590685907859088590985910859118591285913859148591585916859178591885919859208592185922859238592485925859268592785928859298593085931859328593385934859358593685937859388593985940859418594285943859448594585946859478594885949859508595185952859538595485955859568595785958859598596085961859628596385964859658596685967859688596985970859718597285973859748597585976859778597885979859808598185982859838598485985859868598785988859898599085991859928599385994859958599685997859988599986000860018600286003860048600586006860078600886009860108601186012860138601486015860168601786018860198602086021860228602386024860258602686027860288602986030860318603286033860348603586036860378603886039860408604186042860438604486045860468604786048860498605086051860528605386054860558605686057860588605986060860618606286063860648606586066860678606886069860708607186072860738607486075860768607786078860798608086081860828608386084860858608686087860888608986090860918609286093860948609586096860978609886099861008610186102861038610486105861068610786108861098611086111861128611386114861158611686117861188611986120861218612286123861248612586126861278612886129861308613186132861338613486135861368613786138861398614086141861428614386144861458614686147861488614986150861518615286153861548615586156861578615886159861608616186162861638616486165861668616786168861698617086171861728617386174861758617686177861788617986180861818618286183861848618586186861878618886189861908619186192861938619486195861968619786198861998620086201862028620386204862058620686207862088620986210862118621286213862148621586216862178621886219862208622186222862238622486225862268622786228862298623086231862328623386234862358623686237862388623986240862418624286243862448624586246862478624886249862508625186252862538625486255862568625786258862598626086261862628626386264862658626686267862688626986270862718627286273862748627586276862778627886279862808628186282862838628486285862868628786288862898629086291862928629386294862958629686297862988629986300863018630286303863048630586306863078630886309863108631186312863138631486315863168631786318863198632086321863228632386324863258632686327863288632986330863318633286333863348633586336863378633886339863408634186342863438634486345863468634786348863498635086351863528635386354863558635686357863588635986360863618636286363863648636586366863678636886369863708637186372863738637486375863768637786378863798638086381863828638386384863858638686387863888638986390863918639286393863948639586396863978639886399864008640186402864038640486405864068640786408864098641086411864128641386414864158641686417864188641986420864218642286423864248642586426864278642886429864308643186432864338643486435864368643786438864398644086441864428644386444864458644686447864488644986450864518645286453864548645586456864578645886459864608646186462864638646486465864668646786468864698647086471864728647386474864758647686477864788647986480864818648286483864848648586486864878648886489864908649186492864938649486495864968649786498864998650086501865028650386504865058650686507865088650986510865118651286513865148651586516865178651886519865208652186522865238652486525865268652786528865298653086531865328653386534865358653686537865388653986540865418654286543865448654586546865478654886549865508655186552865538655486555865568655786558865598656086561865628656386564865658656686567865688656986570865718657286573865748657586576865778657886579865808658186582865838658486585865868658786588865898659086591865928659386594865958659686597865988659986600866018660286603866048660586606866078660886609866108661186612866138661486615866168661786618866198662086621866228662386624866258662686627866288662986630866318663286633866348663586636866378663886639866408664186642866438664486645866468664786648866498665086651866528665386654866558665686657866588665986660866618666286663866648666586666866678666886669866708667186672866738667486675866768667786678866798668086681866828668386684866858668686687866888668986690866918669286693866948669586696866978669886699867008670186702867038670486705867068670786708867098671086711867128671386714867158671686717867188671986720867218672286723867248672586726867278672886729867308673186732867338673486735867368673786738867398674086741867428674386744867458674686747867488674986750867518675286753867548675586756867578675886759867608676186762867638676486765867668676786768867698677086771867728677386774867758677686777867788677986780867818678286783867848678586786867878678886789867908679186792867938679486795867968679786798867998680086801868028680386804868058680686807868088680986810868118681286813868148681586816868178681886819868208682186822868238682486825868268682786828868298683086831868328683386834868358683686837868388683986840868418684286843868448684586846868478684886849868508685186852868538685486855868568685786858868598686086861868628686386864868658686686867868688686986870868718687286873868748687586876868778687886879868808688186882868838688486885868868688786888868898689086891868928689386894868958689686897868988689986900869018690286903869048690586906869078690886909869108691186912869138691486915869168691786918869198692086921869228692386924869258692686927869288692986930869318693286933869348693586936869378693886939869408694186942869438694486945869468694786948869498695086951869528695386954869558695686957869588695986960869618696286963
  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. /**
  30. * zrender: 生成唯一id
  31. *
  32. * @author errorrik (errorrik@gmail.com)
  33. */
  34. var idStart = 0x0907;
  35. var guid = function () {
  36. return idStart++;
  37. };
  38. /**
  39. * echarts设备环境识别
  40. *
  41. * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。
  42. * @author firede[firede@firede.us]
  43. * @desc thanks zepto.
  44. */
  45. /* global wx */
  46. var env = {};
  47. if (typeof wx === 'object' && typeof wx.getSystemInfoSync === 'function') {
  48. // In Weixin Application
  49. env = {
  50. browser: {},
  51. os: {},
  52. node: false,
  53. wxa: true,
  54. // Weixin Application
  55. canvasSupported: true,
  56. svgSupported: false,
  57. touchEventsSupported: true,
  58. domSupported: false
  59. };
  60. } else if (typeof document === 'undefined' && typeof self !== 'undefined') {
  61. // In worker
  62. env = {
  63. browser: {},
  64. os: {},
  65. node: false,
  66. worker: true,
  67. canvasSupported: true,
  68. domSupported: false
  69. };
  70. } else if (typeof navigator === 'undefined') {
  71. // In node
  72. env = {
  73. browser: {},
  74. os: {},
  75. node: true,
  76. worker: false,
  77. // Assume canvas is supported
  78. canvasSupported: true,
  79. svgSupported: true,
  80. domSupported: false
  81. };
  82. } else {
  83. env = detect(navigator.userAgent);
  84. }
  85. var env$1 = env; // Zepto.js
  86. // (c) 2010-2013 Thomas Fuchs
  87. // Zepto.js may be freely distributed under the MIT license.
  88. function detect(ua) {
  89. var os = {};
  90. var browser = {}; // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/);
  91. // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/);
  92. // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/);
  93. // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/);
  94. // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/);
  95. // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/);
  96. // var touchpad = webos && ua.match(/TouchPad/);
  97. // var kindle = ua.match(/Kindle\/([\d.]+)/);
  98. // var silk = ua.match(/Silk\/([\d._]+)/);
  99. // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/);
  100. // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/);
  101. // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/);
  102. // var playbook = ua.match(/PlayBook/);
  103. // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/);
  104. var firefox = ua.match(/Firefox\/([\d.]+)/); // var safari = webkit && ua.match(/Mobile\//) && !chrome;
  105. // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome;
  106. var ie = ua.match(/MSIE\s([\d.]+)/) // IE 11 Trident/7.0; rv:11.0
  107. || ua.match(/Trident\/.+?rv:(([\d.]+))/);
  108. var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+
  109. var weChat = /micromessenger/i.test(ua); // Todo: clean this up with a better OS/browser seperation:
  110. // - discern (more) between multiple browsers on android
  111. // - decide if kindle fire in silk mode is android or not
  112. // - Firefox on Android doesn't specify the Android version
  113. // - possibly devide in os, device and browser hashes
  114. // if (browser.webkit = !!webkit) browser.version = webkit[1];
  115. // if (android) os.android = true, os.version = android[2];
  116. // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.');
  117. // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.');
  118. // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null;
  119. // if (webos) os.webos = true, os.version = webos[2];
  120. // if (touchpad) os.touchpad = true;
  121. // if (blackberry) os.blackberry = true, os.version = blackberry[2];
  122. // if (bb10) os.bb10 = true, os.version = bb10[2];
  123. // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2];
  124. // if (playbook) browser.playbook = true;
  125. // if (kindle) os.kindle = true, os.version = kindle[1];
  126. // if (silk) browser.silk = true, browser.version = silk[1];
  127. // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true;
  128. // if (chrome) browser.chrome = true, browser.version = chrome[1];
  129. if (firefox) {
  130. browser.firefox = true;
  131. browser.version = firefox[1];
  132. } // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true;
  133. // if (webview) browser.webview = true;
  134. if (ie) {
  135. browser.ie = true;
  136. browser.version = ie[1];
  137. }
  138. if (edge) {
  139. browser.edge = true;
  140. browser.version = edge[1];
  141. } // It is difficult to detect WeChat in Win Phone precisely, because ua can
  142. // not be set on win phone. So we do not consider Win Phone.
  143. if (weChat) {
  144. browser.weChat = true;
  145. } // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) ||
  146. // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/)));
  147. // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos ||
  148. // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) ||
  149. // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/))));
  150. return {
  151. browser: browser,
  152. os: os,
  153. node: false,
  154. // 原生canvas支持,改极端点了
  155. // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9)
  156. canvasSupported: !!document.createElement('canvas').getContext,
  157. svgSupported: typeof SVGRect !== 'undefined',
  158. // works on most browsers
  159. // IE10/11 does not support touch event, and MS Edge supports them but not by
  160. // default, so we dont check navigator.maxTouchPoints for them here.
  161. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge,
  162. // <http://caniuse.com/#search=pointer%20event>.
  163. pointerEventsSupported: // (1) Firefox supports pointer but not by default, only MS browsers are reliable on pointer
  164. // events currently. So we dont use that on other browsers unless tested sufficiently.
  165. // For example, in iOS 13 Mobile Chromium 78, if the touching behavior starts page
  166. // scroll, the `pointermove` event can not be fired any more. That will break some
  167. // features like "pan horizontally to move something and pan vertically to page scroll".
  168. // The horizontal pan probably be interrupted by the casually triggered page scroll.
  169. // (2) Although IE 10 supports pointer event, it use old style and is different from the
  170. // standard. So we exclude that. (IE 10 is hardly used on touch device)
  171. 'onpointerdown' in window && (browser.edge || browser.ie && browser.version >= 11),
  172. // passiveSupported: detectPassiveSupport()
  173. domSupported: typeof document !== 'undefined'
  174. };
  175. } // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md#feature-detection
  176. // function detectPassiveSupport() {
  177. // // Test via a getter in the options object to see if the passive property is accessed
  178. // var supportsPassive = false;
  179. // try {
  180. // var opts = Object.defineProperty({}, 'passive', {
  181. // get: function() {
  182. // supportsPassive = true;
  183. // }
  184. // });
  185. // window.addEventListener('testPassive', function() {}, opts);
  186. // } catch (e) {
  187. // }
  188. // return supportsPassive;
  189. // }
  190. /**
  191. * @module zrender/core/util
  192. */
  193. // 用于处理merge时无法遍历Date等对象的问题
  194. var BUILTIN_OBJECT = {
  195. '[object Function]': 1,
  196. '[object RegExp]': 1,
  197. '[object Date]': 1,
  198. '[object Error]': 1,
  199. '[object CanvasGradient]': 1,
  200. '[object CanvasPattern]': 1,
  201. // For node-canvas
  202. '[object Image]': 1,
  203. '[object Canvas]': 1
  204. };
  205. var TYPED_ARRAY = {
  206. '[object Int8Array]': 1,
  207. '[object Uint8Array]': 1,
  208. '[object Uint8ClampedArray]': 1,
  209. '[object Int16Array]': 1,
  210. '[object Uint16Array]': 1,
  211. '[object Int32Array]': 1,
  212. '[object Uint32Array]': 1,
  213. '[object Float32Array]': 1,
  214. '[object Float64Array]': 1
  215. };
  216. var objToString = Object.prototype.toString;
  217. var arrayProto = Array.prototype;
  218. var nativeForEach = arrayProto.forEach;
  219. var nativeFilter = arrayProto.filter;
  220. var nativeSlice = arrayProto.slice;
  221. var nativeMap = arrayProto.map;
  222. var nativeReduce = arrayProto.reduce; // Avoid assign to an exported variable, for transforming to cjs.
  223. var methods = {};
  224. function $override(name, fn) {
  225. // Clear ctx instance for different environment
  226. if (name === 'createCanvas') {
  227. _ctx = null;
  228. }
  229. methods[name] = fn;
  230. }
  231. /**
  232. * Those data types can be cloned:
  233. * Plain object, Array, TypedArray, number, string, null, undefined.
  234. * Those data types will be assgined using the orginal data:
  235. * BUILTIN_OBJECT
  236. * Instance of user defined class will be cloned to a plain object, without
  237. * properties in prototype.
  238. * Other data types is not supported (not sure what will happen).
  239. *
  240. * Caution: do not support clone Date, for performance consideration.
  241. * (There might be a large number of date in `series.data`).
  242. * So date should not be modified in and out of echarts.
  243. *
  244. * @param {*} source
  245. * @return {*} new
  246. */
  247. function clone(source) {
  248. if (source == null || typeof source !== 'object') {
  249. return source;
  250. }
  251. var result = source;
  252. var typeStr = objToString.call(source);
  253. if (typeStr === '[object Array]') {
  254. if (!isPrimitive(source)) {
  255. result = [];
  256. for (var i = 0, len = source.length; i < len; i++) {
  257. result[i] = clone(source[i]);
  258. }
  259. }
  260. } else if (TYPED_ARRAY[typeStr]) {
  261. if (!isPrimitive(source)) {
  262. var Ctor = source.constructor;
  263. if (source.constructor.from) {
  264. result = Ctor.from(source);
  265. } else {
  266. result = new Ctor(source.length);
  267. for (var i = 0, len = source.length; i < len; i++) {
  268. result[i] = clone(source[i]);
  269. }
  270. }
  271. }
  272. } else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) {
  273. result = {};
  274. for (var key in source) {
  275. if (source.hasOwnProperty(key)) {
  276. result[key] = clone(source[key]);
  277. }
  278. }
  279. }
  280. return result;
  281. }
  282. /**
  283. * @memberOf module:zrender/core/util
  284. * @param {*} target
  285. * @param {*} source
  286. * @param {boolean} [overwrite=false]
  287. */
  288. function merge(target, source, overwrite) {
  289. // We should escapse that source is string
  290. // and enter for ... in ...
  291. if (!isObject$1(source) || !isObject$1(target)) {
  292. return overwrite ? clone(source) : target;
  293. }
  294. for (var key in source) {
  295. if (source.hasOwnProperty(key)) {
  296. var targetProp = target[key];
  297. var sourceProp = source[key];
  298. if (isObject$1(sourceProp) && isObject$1(targetProp) && !isArray(sourceProp) && !isArray(targetProp) && !isDom(sourceProp) && !isDom(targetProp) && !isBuiltInObject(sourceProp) && !isBuiltInObject(targetProp) && !isPrimitive(sourceProp) && !isPrimitive(targetProp)) {
  299. // 如果需要递归覆盖,就递归调用merge
  300. merge(targetProp, sourceProp, overwrite);
  301. } else if (overwrite || !(key in target)) {
  302. // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况
  303. // NOTE,在 target[key] 不存在的时候也是直接覆盖
  304. target[key] = clone(source[key], true);
  305. }
  306. }
  307. }
  308. return target;
  309. }
  310. /**
  311. * @param {Array} targetAndSources The first item is target, and the rests are source.
  312. * @param {boolean} [overwrite=false]
  313. * @return {*} target
  314. */
  315. function mergeAll(targetAndSources, overwrite) {
  316. var result = targetAndSources[0];
  317. for (var i = 1, len = targetAndSources.length; i < len; i++) {
  318. result = merge(result, targetAndSources[i], overwrite);
  319. }
  320. return result;
  321. }
  322. /**
  323. * @param {*} target
  324. * @param {*} source
  325. * @memberOf module:zrender/core/util
  326. */
  327. function extend(target, source) {
  328. for (var key in source) {
  329. if (source.hasOwnProperty(key)) {
  330. target[key] = source[key];
  331. }
  332. }
  333. return target;
  334. }
  335. /**
  336. * @param {*} target
  337. * @param {*} source
  338. * @param {boolean} [overlay=false]
  339. * @memberOf module:zrender/core/util
  340. */
  341. function defaults(target, source, overlay) {
  342. for (var key in source) {
  343. if (source.hasOwnProperty(key) && (overlay ? source[key] != null : target[key] == null)) {
  344. target[key] = source[key];
  345. }
  346. }
  347. return target;
  348. }
  349. var createCanvas = function () {
  350. return methods.createCanvas();
  351. };
  352. methods.createCanvas = function () {
  353. return document.createElement('canvas');
  354. }; // FIXME
  355. var _ctx;
  356. function getContext() {
  357. if (!_ctx) {
  358. // Use util.createCanvas instead of createCanvas
  359. // because createCanvas may be overwritten in different environment
  360. _ctx = createCanvas().getContext('2d');
  361. }
  362. return _ctx;
  363. }
  364. /**
  365. * 查询数组中元素的index
  366. * @memberOf module:zrender/core/util
  367. */
  368. function indexOf(array, value) {
  369. if (array) {
  370. if (array.indexOf) {
  371. return array.indexOf(value);
  372. }
  373. for (var i = 0, len = array.length; i < len; i++) {
  374. if (array[i] === value) {
  375. return i;
  376. }
  377. }
  378. }
  379. return -1;
  380. }
  381. /**
  382. * 构造类继承关系
  383. *
  384. * @memberOf module:zrender/core/util
  385. * @param {Function} clazz 源类
  386. * @param {Function} baseClazz 基类
  387. */
  388. function inherits(clazz, baseClazz) {
  389. var clazzPrototype = clazz.prototype;
  390. function F() {}
  391. F.prototype = baseClazz.prototype;
  392. clazz.prototype = new F();
  393. for (var prop in clazzPrototype) {
  394. if (clazzPrototype.hasOwnProperty(prop)) {
  395. clazz.prototype[prop] = clazzPrototype[prop];
  396. }
  397. }
  398. clazz.prototype.constructor = clazz;
  399. clazz.superClass = baseClazz;
  400. }
  401. /**
  402. * @memberOf module:zrender/core/util
  403. * @param {Object|Function} target
  404. * @param {Object|Function} sorce
  405. * @param {boolean} overlay
  406. */
  407. function mixin(target, source, overlay) {
  408. target = 'prototype' in target ? target.prototype : target;
  409. source = 'prototype' in source ? source.prototype : source;
  410. defaults(target, source, overlay);
  411. }
  412. /**
  413. * Consider typed array.
  414. * @param {Array|TypedArray} data
  415. */
  416. function isArrayLike(data) {
  417. if (!data) {
  418. return;
  419. }
  420. if (typeof data === 'string') {
  421. return false;
  422. }
  423. return typeof data.length === 'number';
  424. }
  425. /**
  426. * 数组或对象遍历
  427. * @memberOf module:zrender/core/util
  428. * @param {Object|Array} obj
  429. * @param {Function} cb
  430. * @param {*} [context]
  431. */
  432. function each$1(obj, cb, context) {
  433. if (!(obj && cb)) {
  434. return;
  435. }
  436. if (obj.forEach && obj.forEach === nativeForEach) {
  437. obj.forEach(cb, context);
  438. } else if (obj.length === +obj.length) {
  439. for (var i = 0, len = obj.length; i < len; i++) {
  440. cb.call(context, obj[i], i, obj);
  441. }
  442. } else {
  443. for (var key in obj) {
  444. if (obj.hasOwnProperty(key)) {
  445. cb.call(context, obj[key], key, obj);
  446. }
  447. }
  448. }
  449. }
  450. /**
  451. * 数组映射
  452. * @memberOf module:zrender/core/util
  453. * @param {Array} obj
  454. * @param {Function} cb
  455. * @param {*} [context]
  456. * @return {Array}
  457. */
  458. function map(obj, cb, context) {
  459. if (!(obj && cb)) {
  460. return;
  461. }
  462. if (obj.map && obj.map === nativeMap) {
  463. return obj.map(cb, context);
  464. } else {
  465. var result = [];
  466. for (var i = 0, len = obj.length; i < len; i++) {
  467. result.push(cb.call(context, obj[i], i, obj));
  468. }
  469. return result;
  470. }
  471. }
  472. /**
  473. * @memberOf module:zrender/core/util
  474. * @param {Array} obj
  475. * @param {Function} cb
  476. * @param {Object} [memo]
  477. * @param {*} [context]
  478. * @return {Array}
  479. */
  480. function reduce(obj, cb, memo, context) {
  481. if (!(obj && cb)) {
  482. return;
  483. }
  484. if (obj.reduce && obj.reduce === nativeReduce) {
  485. return obj.reduce(cb, memo, context);
  486. } else {
  487. for (var i = 0, len = obj.length; i < len; i++) {
  488. memo = cb.call(context, memo, obj[i], i, obj);
  489. }
  490. return memo;
  491. }
  492. }
  493. /**
  494. * 数组过滤
  495. * @memberOf module:zrender/core/util
  496. * @param {Array} obj
  497. * @param {Function} cb
  498. * @param {*} [context]
  499. * @return {Array}
  500. */
  501. function filter(obj, cb, context) {
  502. if (!(obj && cb)) {
  503. return;
  504. }
  505. if (obj.filter && obj.filter === nativeFilter) {
  506. return obj.filter(cb, context);
  507. } else {
  508. var result = [];
  509. for (var i = 0, len = obj.length; i < len; i++) {
  510. if (cb.call(context, obj[i], i, obj)) {
  511. result.push(obj[i]);
  512. }
  513. }
  514. return result;
  515. }
  516. }
  517. /**
  518. * 数组项查找
  519. * @memberOf module:zrender/core/util
  520. * @param {Array} obj
  521. * @param {Function} cb
  522. * @param {*} [context]
  523. * @return {*}
  524. */
  525. function find(obj, cb, context) {
  526. if (!(obj && cb)) {
  527. return;
  528. }
  529. for (var i = 0, len = obj.length; i < len; i++) {
  530. if (cb.call(context, obj[i], i, obj)) {
  531. return obj[i];
  532. }
  533. }
  534. }
  535. /**
  536. * @memberOf module:zrender/core/util
  537. * @param {Function} func
  538. * @param {*} context
  539. * @return {Function}
  540. */
  541. function bind(func, context) {
  542. var args = nativeSlice.call(arguments, 2);
  543. return function () {
  544. return func.apply(context, args.concat(nativeSlice.call(arguments)));
  545. };
  546. }
  547. /**
  548. * @memberOf module:zrender/core/util
  549. * @param {Function} func
  550. * @return {Function}
  551. */
  552. function curry(func) {
  553. var args = nativeSlice.call(arguments, 1);
  554. return function () {
  555. return func.apply(this, args.concat(nativeSlice.call(arguments)));
  556. };
  557. }
  558. /**
  559. * @memberOf module:zrender/core/util
  560. * @param {*} value
  561. * @return {boolean}
  562. */
  563. function isArray(value) {
  564. return objToString.call(value) === '[object Array]';
  565. }
  566. /**
  567. * @memberOf module:zrender/core/util
  568. * @param {*} value
  569. * @return {boolean}
  570. */
  571. function isFunction$1(value) {
  572. return typeof value === 'function';
  573. }
  574. /**
  575. * @memberOf module:zrender/core/util
  576. * @param {*} value
  577. * @return {boolean}
  578. */
  579. function isString(value) {
  580. return objToString.call(value) === '[object String]';
  581. }
  582. /**
  583. * @memberOf module:zrender/core/util
  584. * @param {*} value
  585. * @return {boolean}
  586. */
  587. function isObject$1(value) {
  588. // Avoid a V8 JIT bug in Chrome 19-20.
  589. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details.
  590. var type = typeof value;
  591. return type === 'function' || !!value && type === 'object';
  592. }
  593. /**
  594. * @memberOf module:zrender/core/util
  595. * @param {*} value
  596. * @return {boolean}
  597. */
  598. function isBuiltInObject(value) {
  599. return !!BUILTIN_OBJECT[objToString.call(value)];
  600. }
  601. /**
  602. * @memberOf module:zrender/core/util
  603. * @param {*} value
  604. * @return {boolean}
  605. */
  606. function isTypedArray(value) {
  607. return !!TYPED_ARRAY[objToString.call(value)];
  608. }
  609. /**
  610. * @memberOf module:zrender/core/util
  611. * @param {*} value
  612. * @return {boolean}
  613. */
  614. function isDom(value) {
  615. return typeof value === 'object' && typeof value.nodeType === 'number' && typeof value.ownerDocument === 'object';
  616. }
  617. /**
  618. * Whether is exactly NaN. Notice isNaN('a') returns true.
  619. * @param {*} value
  620. * @return {boolean}
  621. */
  622. function eqNaN(value) {
  623. /* eslint-disable-next-line no-self-compare */
  624. return value !== value;
  625. }
  626. /**
  627. * If value1 is not null, then return value1, otherwise judget rest of values.
  628. * Low performance.
  629. * @memberOf module:zrender/core/util
  630. * @return {*} Final value
  631. */
  632. function retrieve(values) {
  633. for (var i = 0, len = arguments.length; i < len; i++) {
  634. if (arguments[i] != null) {
  635. return arguments[i];
  636. }
  637. }
  638. }
  639. function retrieve2(value0, value1) {
  640. return value0 != null ? value0 : value1;
  641. }
  642. function retrieve3(value0, value1, value2) {
  643. return value0 != null ? value0 : value1 != null ? value1 : value2;
  644. }
  645. /**
  646. * @memberOf module:zrender/core/util
  647. * @param {Array} arr
  648. * @param {number} startIndex
  649. * @param {number} endIndex
  650. * @return {Array}
  651. */
  652. function slice() {
  653. return Function.call.apply(nativeSlice, arguments);
  654. }
  655. /**
  656. * Normalize css liked array configuration
  657. * e.g.
  658. * 3 => [3, 3, 3, 3]
  659. * [4, 2] => [4, 2, 4, 2]
  660. * [4, 3, 2] => [4, 3, 2, 3]
  661. * @param {number|Array.<number>} val
  662. * @return {Array.<number>}
  663. */
  664. function normalizeCssArray(val) {
  665. if (typeof val === 'number') {
  666. return [val, val, val, val];
  667. }
  668. var len = val.length;
  669. if (len === 2) {
  670. // vertical | horizontal
  671. return [val[0], val[1], val[0], val[1]];
  672. } else if (len === 3) {
  673. // top | horizontal | bottom
  674. return [val[0], val[1], val[2], val[1]];
  675. }
  676. return val;
  677. }
  678. /**
  679. * @memberOf module:zrender/core/util
  680. * @param {boolean} condition
  681. * @param {string} message
  682. */
  683. function assert$1(condition, message) {
  684. if (!condition) {
  685. throw new Error(message);
  686. }
  687. }
  688. /**
  689. * @memberOf module:zrender/core/util
  690. * @param {string} str string to be trimed
  691. * @return {string} trimed string
  692. */
  693. function trim(str) {
  694. if (str == null) {
  695. return null;
  696. } else if (typeof str.trim === 'function') {
  697. return str.trim();
  698. } else {
  699. return str.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, '');
  700. }
  701. }
  702. var primitiveKey = '__ec_primitive__';
  703. /**
  704. * Set an object as primitive to be ignored traversing children in clone or merge
  705. */
  706. function setAsPrimitive(obj) {
  707. obj[primitiveKey] = true;
  708. }
  709. function isPrimitive(obj) {
  710. return obj[primitiveKey];
  711. }
  712. /**
  713. * @constructor
  714. * @param {Object} obj Only apply `ownProperty`.
  715. */
  716. function HashMap(obj) {
  717. var isArr = isArray(obj); // Key should not be set on this, otherwise
  718. // methods get/set/... may be overrided.
  719. this.data = {};
  720. var thisMap = this;
  721. obj instanceof HashMap ? obj.each(visit) : obj && each$1(obj, visit);
  722. function visit(value, key) {
  723. isArr ? thisMap.set(value, key) : thisMap.set(key, value);
  724. }
  725. }
  726. HashMap.prototype = {
  727. constructor: HashMap,
  728. // Do not provide `has` method to avoid defining what is `has`.
  729. // (We usually treat `null` and `undefined` as the same, different
  730. // from ES6 Map).
  731. get: function (key) {
  732. return this.data.hasOwnProperty(key) ? this.data[key] : null;
  733. },
  734. set: function (key, value) {
  735. // Comparing with invocation chaining, `return value` is more commonly
  736. // used in this case: `var someVal = map.set('a', genVal());`
  737. return this.data[key] = value;
  738. },
  739. // Although util.each can be performed on this hashMap directly, user
  740. // should not use the exposed keys, who are prefixed.
  741. each: function (cb, context) {
  742. context !== void 0 && (cb = bind(cb, context));
  743. /* eslint-disable guard-for-in */
  744. for (var key in this.data) {
  745. this.data.hasOwnProperty(key) && cb(this.data[key], key);
  746. }
  747. /* eslint-enable guard-for-in */
  748. },
  749. // Do not use this method if performance sensitive.
  750. removeKey: function (key) {
  751. delete this.data[key];
  752. }
  753. };
  754. function createHashMap(obj) {
  755. return new HashMap(obj);
  756. }
  757. function concatArray(a, b) {
  758. var newArray = new a.constructor(a.length + b.length);
  759. for (var i = 0; i < a.length; i++) {
  760. newArray[i] = a[i];
  761. }
  762. var offset = a.length;
  763. for (i = 0; i < b.length; i++) {
  764. newArray[i + offset] = b[i];
  765. }
  766. return newArray;
  767. }
  768. function noop() {}
  769. var zrUtil = (Object.freeze || Object)({
  770. $override: $override,
  771. clone: clone,
  772. merge: merge,
  773. mergeAll: mergeAll,
  774. extend: extend,
  775. defaults: defaults,
  776. createCanvas: createCanvas,
  777. getContext: getContext,
  778. indexOf: indexOf,
  779. inherits: inherits,
  780. mixin: mixin,
  781. isArrayLike: isArrayLike,
  782. each: each$1,
  783. map: map,
  784. reduce: reduce,
  785. filter: filter,
  786. find: find,
  787. bind: bind,
  788. curry: curry,
  789. isArray: isArray,
  790. isFunction: isFunction$1,
  791. isString: isString,
  792. isObject: isObject$1,
  793. isBuiltInObject: isBuiltInObject,
  794. isTypedArray: isTypedArray,
  795. isDom: isDom,
  796. eqNaN: eqNaN,
  797. retrieve: retrieve,
  798. retrieve2: retrieve2,
  799. retrieve3: retrieve3,
  800. slice: slice,
  801. normalizeCssArray: normalizeCssArray,
  802. assert: assert$1,
  803. trim: trim,
  804. setAsPrimitive: setAsPrimitive,
  805. isPrimitive: isPrimitive,
  806. createHashMap: createHashMap,
  807. concatArray: concatArray,
  808. noop: noop
  809. });
  810. /* global Float32Array */
  811. var ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array;
  812. /**
  813. * 创建一个向量
  814. * @param {number} [x=0]
  815. * @param {number} [y=0]
  816. * @return {Vector2}
  817. */
  818. function create(x, y) {
  819. var out = new ArrayCtor(2);
  820. if (x == null) {
  821. x = 0;
  822. }
  823. if (y == null) {
  824. y = 0;
  825. }
  826. out[0] = x;
  827. out[1] = y;
  828. return out;
  829. }
  830. /**
  831. * 复制向量数据
  832. * @param {Vector2} out
  833. * @param {Vector2} v
  834. * @return {Vector2}
  835. */
  836. function copy(out, v) {
  837. out[0] = v[0];
  838. out[1] = v[1];
  839. return out;
  840. }
  841. /**
  842. * 克隆一个向量
  843. * @param {Vector2} v
  844. * @return {Vector2}
  845. */
  846. function clone$1(v) {
  847. var out = new ArrayCtor(2);
  848. out[0] = v[0];
  849. out[1] = v[1];
  850. return out;
  851. }
  852. /**
  853. * 设置向量的两个项
  854. * @param {Vector2} out
  855. * @param {number} a
  856. * @param {number} b
  857. * @return {Vector2} 结果
  858. */
  859. function set(out, a, b) {
  860. out[0] = a;
  861. out[1] = b;
  862. return out;
  863. }
  864. /**
  865. * 向量相加
  866. * @param {Vector2} out
  867. * @param {Vector2} v1
  868. * @param {Vector2} v2
  869. */
  870. function add(out, v1, v2) {
  871. out[0] = v1[0] + v2[0];
  872. out[1] = v1[1] + v2[1];
  873. return out;
  874. }
  875. /**
  876. * 向量缩放后相加
  877. * @param {Vector2} out
  878. * @param {Vector2} v1
  879. * @param {Vector2} v2
  880. * @param {number} a
  881. */
  882. function scaleAndAdd(out, v1, v2, a) {
  883. out[0] = v1[0] + v2[0] * a;
  884. out[1] = v1[1] + v2[1] * a;
  885. return out;
  886. }
  887. /**
  888. * 向量相减
  889. * @param {Vector2} out
  890. * @param {Vector2} v1
  891. * @param {Vector2} v2
  892. */
  893. function sub(out, v1, v2) {
  894. out[0] = v1[0] - v2[0];
  895. out[1] = v1[1] - v2[1];
  896. return out;
  897. }
  898. /**
  899. * 向量长度
  900. * @param {Vector2} v
  901. * @return {number}
  902. */
  903. function len(v) {
  904. return Math.sqrt(lenSquare(v));
  905. }
  906. var length = len; // jshint ignore:line
  907. /**
  908. * 向量长度平方
  909. * @param {Vector2} v
  910. * @return {number}
  911. */
  912. function lenSquare(v) {
  913. return v[0] * v[0] + v[1] * v[1];
  914. }
  915. var lengthSquare = lenSquare;
  916. /**
  917. * 向量乘法
  918. * @param {Vector2} out
  919. * @param {Vector2} v1
  920. * @param {Vector2} v2
  921. */
  922. function mul(out, v1, v2) {
  923. out[0] = v1[0] * v2[0];
  924. out[1] = v1[1] * v2[1];
  925. return out;
  926. }
  927. /**
  928. * 向量除法
  929. * @param {Vector2} out
  930. * @param {Vector2} v1
  931. * @param {Vector2} v2
  932. */
  933. function div(out, v1, v2) {
  934. out[0] = v1[0] / v2[0];
  935. out[1] = v1[1] / v2[1];
  936. return out;
  937. }
  938. /**
  939. * 向量点乘
  940. * @param {Vector2} v1
  941. * @param {Vector2} v2
  942. * @return {number}
  943. */
  944. function dot(v1, v2) {
  945. return v1[0] * v2[0] + v1[1] * v2[1];
  946. }
  947. /**
  948. * 向量缩放
  949. * @param {Vector2} out
  950. * @param {Vector2} v
  951. * @param {number} s
  952. */
  953. function scale(out, v, s) {
  954. out[0] = v[0] * s;
  955. out[1] = v[1] * s;
  956. return out;
  957. }
  958. /**
  959. * 向量归一化
  960. * @param {Vector2} out
  961. * @param {Vector2} v
  962. */
  963. function normalize(out, v) {
  964. var d = len(v);
  965. if (d === 0) {
  966. out[0] = 0;
  967. out[1] = 0;
  968. } else {
  969. out[0] = v[0] / d;
  970. out[1] = v[1] / d;
  971. }
  972. return out;
  973. }
  974. /**
  975. * 计算向量间距离
  976. * @param {Vector2} v1
  977. * @param {Vector2} v2
  978. * @return {number}
  979. */
  980. function distance(v1, v2) {
  981. return Math.sqrt((v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]));
  982. }
  983. var dist = distance;
  984. /**
  985. * 向量距离平方
  986. * @param {Vector2} v1
  987. * @param {Vector2} v2
  988. * @return {number}
  989. */
  990. function distanceSquare(v1, v2) {
  991. return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]);
  992. }
  993. var distSquare = distanceSquare;
  994. /**
  995. * 求负向量
  996. * @param {Vector2} out
  997. * @param {Vector2} v
  998. */
  999. function negate(out, v) {
  1000. out[0] = -v[0];
  1001. out[1] = -v[1];
  1002. return out;
  1003. }
  1004. /**
  1005. * 插值两个点
  1006. * @param {Vector2} out
  1007. * @param {Vector2} v1
  1008. * @param {Vector2} v2
  1009. * @param {number} t
  1010. */
  1011. function lerp(out, v1, v2, t) {
  1012. out[0] = v1[0] + t * (v2[0] - v1[0]);
  1013. out[1] = v1[1] + t * (v2[1] - v1[1]);
  1014. return out;
  1015. }
  1016. /**
  1017. * 矩阵左乘向量
  1018. * @param {Vector2} out
  1019. * @param {Vector2} v
  1020. * @param {Vector2} m
  1021. */
  1022. function applyTransform(out, v, m) {
  1023. var x = v[0];
  1024. var y = v[1];
  1025. out[0] = m[0] * x + m[2] * y + m[4];
  1026. out[1] = m[1] * x + m[3] * y + m[5];
  1027. return out;
  1028. }
  1029. /**
  1030. * 求两个向量最小值
  1031. * @param {Vector2} out
  1032. * @param {Vector2} v1
  1033. * @param {Vector2} v2
  1034. */
  1035. function min(out, v1, v2) {
  1036. out[0] = Math.min(v1[0], v2[0]);
  1037. out[1] = Math.min(v1[1], v2[1]);
  1038. return out;
  1039. }
  1040. /**
  1041. * 求两个向量最大值
  1042. * @param {Vector2} out
  1043. * @param {Vector2} v1
  1044. * @param {Vector2} v2
  1045. */
  1046. function max(out, v1, v2) {
  1047. out[0] = Math.max(v1[0], v2[0]);
  1048. out[1] = Math.max(v1[1], v2[1]);
  1049. return out;
  1050. }
  1051. var vector = (Object.freeze || Object)({
  1052. create: create,
  1053. copy: copy,
  1054. clone: clone$1,
  1055. set: set,
  1056. add: add,
  1057. scaleAndAdd: scaleAndAdd,
  1058. sub: sub,
  1059. len: len,
  1060. length: length,
  1061. lenSquare: lenSquare,
  1062. lengthSquare: lengthSquare,
  1063. mul: mul,
  1064. div: div,
  1065. dot: dot,
  1066. scale: scale,
  1067. normalize: normalize,
  1068. distance: distance,
  1069. dist: dist,
  1070. distanceSquare: distanceSquare,
  1071. distSquare: distSquare,
  1072. negate: negate,
  1073. lerp: lerp,
  1074. applyTransform: applyTransform,
  1075. min: min,
  1076. max: max
  1077. });
  1078. // TODO Draggable for group
  1079. // FIXME Draggable on element which has parent rotation or scale
  1080. function Draggable() {
  1081. this.on('mousedown', this._dragStart, this);
  1082. this.on('mousemove', this._drag, this);
  1083. this.on('mouseup', this._dragEnd, this); // `mosuemove` and `mouseup` can be continue to fire when dragging.
  1084. // See [Drag outside] in `Handler.js`. So we do not need to trigger
  1085. // `_dragEnd` when globalout. That would brings better user experience.
  1086. // this.on('globalout', this._dragEnd, this);
  1087. // this._dropTarget = null;
  1088. // this._draggingTarget = null;
  1089. // this._x = 0;
  1090. // this._y = 0;
  1091. }
  1092. Draggable.prototype = {
  1093. constructor: Draggable,
  1094. _dragStart: function (e) {
  1095. var draggingTarget = e.target; // Find if there is draggable in the ancestor
  1096. while (draggingTarget && !draggingTarget.draggable) {
  1097. draggingTarget = draggingTarget.parent;
  1098. }
  1099. if (draggingTarget) {
  1100. this._draggingTarget = draggingTarget;
  1101. draggingTarget.dragging = true;
  1102. this._x = e.offsetX;
  1103. this._y = e.offsetY;
  1104. this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event);
  1105. }
  1106. },
  1107. _drag: function (e) {
  1108. var draggingTarget = this._draggingTarget;
  1109. if (draggingTarget) {
  1110. var x = e.offsetX;
  1111. var y = e.offsetY;
  1112. var dx = x - this._x;
  1113. var dy = y - this._y;
  1114. this._x = x;
  1115. this._y = y;
  1116. draggingTarget.drift(dx, dy, e);
  1117. this.dispatchToElement(param(draggingTarget, e), 'drag', e.event);
  1118. var dropTarget = this.findHover(x, y, draggingTarget).target;
  1119. var lastDropTarget = this._dropTarget;
  1120. this._dropTarget = dropTarget;
  1121. if (draggingTarget !== dropTarget) {
  1122. if (lastDropTarget && dropTarget !== lastDropTarget) {
  1123. this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event);
  1124. }
  1125. if (dropTarget && dropTarget !== lastDropTarget) {
  1126. this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event);
  1127. }
  1128. }
  1129. }
  1130. },
  1131. _dragEnd: function (e) {
  1132. var draggingTarget = this._draggingTarget;
  1133. if (draggingTarget) {
  1134. draggingTarget.dragging = false;
  1135. }
  1136. this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event);
  1137. if (this._dropTarget) {
  1138. this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event);
  1139. }
  1140. this._draggingTarget = null;
  1141. this._dropTarget = null;
  1142. }
  1143. };
  1144. function param(target, e) {
  1145. return {
  1146. target: target,
  1147. topTarget: e && e.topTarget
  1148. };
  1149. }
  1150. /**
  1151. * Event Mixin
  1152. * @module zrender/mixin/Eventful
  1153. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  1154. * pissang (https://www.github.com/pissang)
  1155. */
  1156. var arrySlice = Array.prototype.slice;
  1157. /**
  1158. * Event dispatcher.
  1159. *
  1160. * @alias module:zrender/mixin/Eventful
  1161. * @constructor
  1162. * @param {Object} [eventProcessor] The object eventProcessor is the scope when
  1163. * `eventProcessor.xxx` called.
  1164. * @param {Function} [eventProcessor.normalizeQuery]
  1165. * param: {string|Object} Raw query.
  1166. * return: {string|Object} Normalized query.
  1167. * @param {Function} [eventProcessor.filter] Event will be dispatched only
  1168. * if it returns `true`.
  1169. * param: {string} eventType
  1170. * param: {string|Object} query
  1171. * return: {boolean}
  1172. * @param {Function} [eventProcessor.afterTrigger] Called after all handlers called.
  1173. * param: {string} eventType
  1174. */
  1175. var Eventful = function (eventProcessor) {
  1176. this._$handlers = {};
  1177. this._$eventProcessor = eventProcessor;
  1178. };
  1179. Eventful.prototype = {
  1180. constructor: Eventful,
  1181. /**
  1182. * The handler can only be triggered once, then removed.
  1183. *
  1184. * @param {string} event The event name.
  1185. * @param {string|Object} [query] Condition used on event filter.
  1186. * @param {Function} handler The event handler.
  1187. * @param {Object} context
  1188. */
  1189. one: function (event, query, handler, context) {
  1190. return on(this, event, query, handler, context, true);
  1191. },
  1192. /**
  1193. * Bind a handler.
  1194. *
  1195. * @param {string} event The event name.
  1196. * @param {string|Object} [query] Condition used on event filter.
  1197. * @param {Function} handler The event handler.
  1198. * @param {Object} [context]
  1199. */
  1200. on: function (event, query, handler, context) {
  1201. return on(this, event, query, handler, context, false);
  1202. },
  1203. /**
  1204. * Whether any handler has bound.
  1205. *
  1206. * @param {string} event
  1207. * @return {boolean}
  1208. */
  1209. isSilent: function (event) {
  1210. var _h = this._$handlers;
  1211. return !_h[event] || !_h[event].length;
  1212. },
  1213. /**
  1214. * Unbind a event.
  1215. *
  1216. * @param {string} [event] The event name.
  1217. * If no `event` input, "off" all listeners.
  1218. * @param {Function} [handler] The event handler.
  1219. * If no `handler` input, "off" all listeners of the `event`.
  1220. */
  1221. off: function (event, handler) {
  1222. var _h = this._$handlers;
  1223. if (!event) {
  1224. this._$handlers = {};
  1225. return this;
  1226. }
  1227. if (handler) {
  1228. if (_h[event]) {
  1229. var newList = [];
  1230. for (var i = 0, l = _h[event].length; i < l; i++) {
  1231. if (_h[event][i].h !== handler) {
  1232. newList.push(_h[event][i]);
  1233. }
  1234. }
  1235. _h[event] = newList;
  1236. }
  1237. if (_h[event] && _h[event].length === 0) {
  1238. delete _h[event];
  1239. }
  1240. } else {
  1241. delete _h[event];
  1242. }
  1243. return this;
  1244. },
  1245. /**
  1246. * Dispatch a event.
  1247. *
  1248. * @param {string} type The event name.
  1249. */
  1250. trigger: function (type) {
  1251. var _h = this._$handlers[type];
  1252. var eventProcessor = this._$eventProcessor;
  1253. if (_h) {
  1254. var args = arguments;
  1255. var argLen = args.length;
  1256. if (argLen > 3) {
  1257. args = arrySlice.call(args, 1);
  1258. }
  1259. var len = _h.length;
  1260. for (var i = 0; i < len;) {
  1261. var hItem = _h[i];
  1262. if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query)) {
  1263. i++;
  1264. continue;
  1265. } // Optimize advise from backbone
  1266. switch (argLen) {
  1267. case 1:
  1268. hItem.h.call(hItem.ctx);
  1269. break;
  1270. case 2:
  1271. hItem.h.call(hItem.ctx, args[1]);
  1272. break;
  1273. case 3:
  1274. hItem.h.call(hItem.ctx, args[1], args[2]);
  1275. break;
  1276. default:
  1277. // have more than 2 given arguments
  1278. hItem.h.apply(hItem.ctx, args);
  1279. break;
  1280. }
  1281. if (hItem.one) {
  1282. _h.splice(i, 1);
  1283. len--;
  1284. } else {
  1285. i++;
  1286. }
  1287. }
  1288. }
  1289. eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type);
  1290. return this;
  1291. },
  1292. /**
  1293. * Dispatch a event with context, which is specified at the last parameter.
  1294. *
  1295. * @param {string} type The event name.
  1296. */
  1297. triggerWithContext: function (type) {
  1298. var _h = this._$handlers[type];
  1299. var eventProcessor = this._$eventProcessor;
  1300. if (_h) {
  1301. var args = arguments;
  1302. var argLen = args.length;
  1303. if (argLen > 4) {
  1304. args = arrySlice.call(args, 1, args.length - 1);
  1305. }
  1306. var ctx = args[args.length - 1];
  1307. var len = _h.length;
  1308. for (var i = 0; i < len;) {
  1309. var hItem = _h[i];
  1310. if (eventProcessor && eventProcessor.filter && hItem.query != null && !eventProcessor.filter(type, hItem.query)) {
  1311. i++;
  1312. continue;
  1313. } // Optimize advise from backbone
  1314. switch (argLen) {
  1315. case 1:
  1316. hItem.h.call(ctx);
  1317. break;
  1318. case 2:
  1319. hItem.h.call(ctx, args[1]);
  1320. break;
  1321. case 3:
  1322. hItem.h.call(ctx, args[1], args[2]);
  1323. break;
  1324. default:
  1325. // have more than 2 given arguments
  1326. hItem.h.apply(ctx, args);
  1327. break;
  1328. }
  1329. if (hItem.one) {
  1330. _h.splice(i, 1);
  1331. len--;
  1332. } else {
  1333. i++;
  1334. }
  1335. }
  1336. }
  1337. eventProcessor && eventProcessor.afterTrigger && eventProcessor.afterTrigger(type);
  1338. return this;
  1339. }
  1340. };
  1341. function normalizeQuery(host, query) {
  1342. var eventProcessor = host._$eventProcessor;
  1343. if (query != null && eventProcessor && eventProcessor.normalizeQuery) {
  1344. query = eventProcessor.normalizeQuery(query);
  1345. }
  1346. return query;
  1347. }
  1348. function on(eventful, event, query, handler, context, isOnce) {
  1349. var _h = eventful._$handlers;
  1350. if (typeof query === 'function') {
  1351. context = handler;
  1352. handler = query;
  1353. query = null;
  1354. }
  1355. if (!handler || !event) {
  1356. return eventful;
  1357. }
  1358. query = normalizeQuery(eventful, query);
  1359. if (!_h[event]) {
  1360. _h[event] = [];
  1361. }
  1362. for (var i = 0; i < _h[event].length; i++) {
  1363. if (_h[event][i].h === handler) {
  1364. return eventful;
  1365. }
  1366. }
  1367. var wrap = {
  1368. h: handler,
  1369. one: isOnce,
  1370. query: query,
  1371. ctx: context || eventful,
  1372. // FIXME
  1373. // Do not publish this feature util it is proved that it makes sense.
  1374. callAtLast: handler.zrEventfulCallAtLast
  1375. };
  1376. var lastIndex = _h[event].length - 1;
  1377. var lastWrap = _h[event][lastIndex];
  1378. lastWrap && lastWrap.callAtLast ? _h[event].splice(lastIndex, 0, wrap) : _h[event].push(wrap);
  1379. return eventful;
  1380. } // ----------------------
  1381. /**
  1382. * The algoritm is learnt from
  1383. * https://franklinta.com/2014/09/08/computing-css-matrix3d-transforms/
  1384. * And we made some optimization for matrix inversion.
  1385. * Other similar approaches:
  1386. * "cv::getPerspectiveTransform", "Direct Linear Transformation".
  1387. */
  1388. var LN2 = Math.log(2);
  1389. function determinant(rows, rank, rowStart, rowMask, colMask, detCache) {
  1390. var cacheKey = rowMask + '-' + colMask;
  1391. var fullRank = rows.length;
  1392. if (detCache.hasOwnProperty(cacheKey)) {
  1393. return detCache[cacheKey];
  1394. }
  1395. if (rank === 1) {
  1396. // In this case the colMask must be like: `11101111`. We can find the place of `0`.
  1397. var colStart = Math.round(Math.log((1 << fullRank) - 1 & ~colMask) / LN2);
  1398. return rows[rowStart][colStart];
  1399. }
  1400. var subRowMask = rowMask | 1 << rowStart;
  1401. var subRowStart = rowStart + 1;
  1402. while (rowMask & 1 << subRowStart) {
  1403. subRowStart++;
  1404. }
  1405. var sum = 0;
  1406. for (var j = 0, colLocalIdx = 0; j < fullRank; j++) {
  1407. var colTag = 1 << j;
  1408. if (!(colTag & colMask)) {
  1409. sum += (colLocalIdx % 2 ? -1 : 1) * rows[rowStart][j] // det(subMatrix(0, j))
  1410. * determinant(rows, rank - 1, subRowStart, subRowMask, colMask | colTag, detCache);
  1411. colLocalIdx++;
  1412. }
  1413. }
  1414. detCache[cacheKey] = sum;
  1415. return sum;
  1416. }
  1417. /**
  1418. * Usage:
  1419. * ```js
  1420. * var transformer = buildTransformer(
  1421. * [10, 44, 100, 44, 100, 300, 10, 300],
  1422. * [50, 54, 130, 14, 140, 330, 14, 220]
  1423. * );
  1424. * var out = [];
  1425. * transformer && transformer([11, 33], out);
  1426. * ```
  1427. *
  1428. * Notice: `buildTransformer` may take more than 10ms in some Android device.
  1429. *
  1430. * @param {Array.<number>} src source four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1431. * @param {Array.<number>} dest destination four points, [x0, y0, x1, y1, x2, y2, x3, y3]
  1432. * @return {Function} transformer If fail, return null/undefined.
  1433. */
  1434. function buildTransformer(src, dest) {
  1435. var mA = [[src[0], src[1], 1, 0, 0, 0, -dest[0] * src[0], -dest[0] * src[1]], [0, 0, 0, src[0], src[1], 1, -dest[1] * src[0], -dest[1] * src[1]], [src[2], src[3], 1, 0, 0, 0, -dest[2] * src[2], -dest[2] * src[3]], [0, 0, 0, src[2], src[3], 1, -dest[3] * src[2], -dest[3] * src[3]], [src[4], src[5], 1, 0, 0, 0, -dest[4] * src[4], -dest[4] * src[5]], [0, 0, 0, src[4], src[5], 1, -dest[5] * src[4], -dest[5] * src[5]], [src[6], src[7], 1, 0, 0, 0, -dest[6] * src[6], -dest[6] * src[7]], [0, 0, 0, src[6], src[7], 1, -dest[7] * src[6], -dest[7] * src[7]]];
  1436. var detCache = {};
  1437. var det = determinant(mA, 8, 0, 0, 0, detCache);
  1438. if (det === 0) {
  1439. // can not make transformer when and only when
  1440. // any three of the markers are collinear.
  1441. return;
  1442. } // `invert(mA) * dest`, that is, `adj(mA) / det * dest`.
  1443. var vh = [];
  1444. for (var i = 0; i < 8; i++) {
  1445. for (var j = 0; j < 8; j++) {
  1446. vh[j] == null && (vh[j] = 0);
  1447. vh[j] += ((i + j) % 2 ? -1 : 1) * // det(subMatrix(i, j))
  1448. determinant(mA, 7, i === 0 ? 1 : 0, 1 << i, 1 << j, detCache) / det * dest[i];
  1449. }
  1450. }
  1451. return function (out, srcPointX, srcPointY) {
  1452. var pk = srcPointX * vh[6] + srcPointY * vh[7] + 1;
  1453. out[0] = (srcPointX * vh[0] + srcPointY * vh[1] + vh[2]) / pk;
  1454. out[1] = (srcPointX * vh[3] + srcPointY * vh[4] + vh[5]) / pk;
  1455. };
  1456. }
  1457. var EVENT_SAVED_PROP = '___zrEVENTSAVED';
  1458. var _calcOut$1 = [];
  1459. /**
  1460. * Transform "local coord" from `elFrom` to `elTarget`.
  1461. * "local coord": the coord based on the input `el`. The origin point is at
  1462. * the position of "left: 0; top: 0;" in the `el`.
  1463. *
  1464. * Support when CSS transform is used.
  1465. *
  1466. * Having the `out` (that is, `[outX, outY]`), we can create an DOM element
  1467. * and set the CSS style as "left: outX; top: outY;" and append it to `elTarge`
  1468. * to locate the element.
  1469. *
  1470. * For example, this code below positions a child of `document.body` on the event
  1471. * point, no matter whether `body` has `margin`/`paddin`/`transfrom`/... :
  1472. * ```js
  1473. * transformLocalCoord(out, container, document.body, event.offsetX, event.offsetY);
  1474. * if (!eqNaN(out[0])) {
  1475. * // Then locate the tip element on the event point.
  1476. * var tipEl = document.createElement('div');
  1477. * tipEl.style.cssText = 'position: absolute; left:' + out[0] + ';top:' + out[1] + ';';
  1478. * document.body.appendChild(tipEl);
  1479. * }
  1480. * ```
  1481. *
  1482. * Notice: In some env this method is not supported. If called, `out` will be `[NaN, NaN]`.
  1483. *
  1484. * @param {Array.<number>} out [inX: number, inY: number] The output..
  1485. * If can not transform, `out` will not be modified but return `false`.
  1486. * @param {HTMLElement} elFrom The `[inX, inY]` is based on elFrom.
  1487. * @param {HTMLElement} elTarget The `out` is based on elTarget.
  1488. * @param {number} inX
  1489. * @param {number} inY
  1490. * @return {boolean} Whether transform successfully.
  1491. */
  1492. function transformLocalCoord(out, elFrom, elTarget, inX, inY) {
  1493. return transformCoordWithViewport(_calcOut$1, elFrom, inX, inY, true) && transformCoordWithViewport(out, elTarget, _calcOut$1[0], _calcOut$1[1]);
  1494. }
  1495. /**
  1496. * Transform between a "viewport coord" and a "local coord".
  1497. * "viewport coord": the coord based on the left-top corner of the viewport
  1498. * of the browser.
  1499. * "local coord": the coord based on the input `el`. The origin point is at
  1500. * the position of "left: 0; top: 0;" in the `el`.
  1501. *
  1502. * Support the case when CSS transform is used on el.
  1503. *
  1504. * @param {Array.<number>} out [inX: number, inY: number] The output. If `inverse: false`,
  1505. * it represents "local coord", otherwise "vireport coord".
  1506. * If can not transform, `out` will not be modified but return `false`.
  1507. * @param {HTMLElement} el The "local coord" is based on the `el`, see comment above.
  1508. * @param {number} inX If `inverse: false`,
  1509. * it represents "vireport coord", otherwise "local coord".
  1510. * @param {number} inY If `inverse: false`,
  1511. * it represents "vireport coord", otherwise "local coord".
  1512. * @param {boolean} [inverse=false]
  1513. * `true`: from "viewport coord" to "local coord".
  1514. * `false`: from "local coord" to "viewport coord".
  1515. * @return {boolean} Whether transform successfully.
  1516. */
  1517. function transformCoordWithViewport(out, el, inX, inY, inverse) {
  1518. if (el.getBoundingClientRect && env$1.domSupported && !isCanvasEl(el)) {
  1519. var saved = el[EVENT_SAVED_PROP] || (el[EVENT_SAVED_PROP] = {});
  1520. var markers = prepareCoordMarkers(el, saved);
  1521. var transformer = preparePointerTransformer(markers, saved, inverse);
  1522. if (transformer) {
  1523. transformer(out, inX, inY);
  1524. return true;
  1525. }
  1526. }
  1527. return false;
  1528. }
  1529. function prepareCoordMarkers(el, saved) {
  1530. var markers = saved.markers;
  1531. if (markers) {
  1532. return markers;
  1533. }
  1534. markers = saved.markers = [];
  1535. var propLR = ['left', 'right'];
  1536. var propTB = ['top', 'bottom'];
  1537. for (var i = 0; i < 4; i++) {
  1538. var marker = document.createElement('div');
  1539. var stl = marker.style;
  1540. var idxLR = i % 2;
  1541. var idxTB = (i >> 1) % 2;
  1542. stl.cssText = ['position: absolute', 'visibility: hidden', 'padding: 0', 'margin: 0', 'border-width: 0', 'user-select: none', 'width:0', 'height:0', // 'width: 5px',
  1543. // 'height: 5px',
  1544. propLR[idxLR] + ':0', propTB[idxTB] + ':0', propLR[1 - idxLR] + ':auto', propTB[1 - idxTB] + ':auto', ''].join('!important;');
  1545. el.appendChild(marker);
  1546. markers.push(marker);
  1547. }
  1548. return markers;
  1549. }
  1550. function preparePointerTransformer(markers, saved, inverse) {
  1551. var transformerName = inverse ? 'invTrans' : 'trans';
  1552. var transformer = saved[transformerName];
  1553. var oldSrcCoords = saved.srcCoords;
  1554. var oldCoordTheSame = true;
  1555. var srcCoords = [];
  1556. var destCoords = [];
  1557. for (var i = 0; i < 4; i++) {
  1558. var rect = markers[i].getBoundingClientRect();
  1559. var ii = 2 * i;
  1560. var x = rect.left;
  1561. var y = rect.top;
  1562. srcCoords.push(x, y);
  1563. oldCoordTheSame = oldCoordTheSame && oldSrcCoords && x === oldSrcCoords[ii] && y === oldSrcCoords[ii + 1];
  1564. destCoords.push(markers[i].offsetLeft, markers[i].offsetTop);
  1565. } // Cache to avoid time consuming of `buildTransformer`.
  1566. return oldCoordTheSame && transformer ? transformer : (saved.srcCoords = srcCoords, saved[transformerName] = inverse ? buildTransformer(destCoords, srcCoords) : buildTransformer(srcCoords, destCoords));
  1567. }
  1568. function isCanvasEl(el) {
  1569. return el.nodeName.toUpperCase() === 'CANVAS';
  1570. }
  1571. /**
  1572. * Utilities for mouse or touch events.
  1573. */
  1574. var isDomLevel2 = typeof window !== 'undefined' && !!window.addEventListener;
  1575. var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/;
  1576. var _calcOut = [];
  1577. /**
  1578. * Get the `zrX` and `zrY`, which are relative to the top-left of
  1579. * the input `el`.
  1580. * CSS transform (2D & 3D) is supported.
  1581. *
  1582. * The strategy to fetch the coords:
  1583. * + If `calculate` is not set as `true`, users of this method should
  1584. * ensure that `el` is the same or the same size & location as `e.target`.
  1585. * Otherwise the result coords are probably not expected. Because we
  1586. * firstly try to get coords from e.offsetX/e.offsetY.
  1587. * + If `calculate` is set as `true`, the input `el` can be any element
  1588. * and we force to calculate the coords based on `el`.
  1589. * + The input `el` should be positionable (not position:static).
  1590. *
  1591. * The force `calculate` can be used in case like:
  1592. * When mousemove event triggered on ec tooltip, `e.target` is not `el`(zr painter.dom).
  1593. *
  1594. * @param {HTMLElement} el DOM element.
  1595. * @param {Event} e Mouse event or touch event.
  1596. * @param {Object} out Get `out.zrX` and `out.zrY` as the result.
  1597. * @param {boolean} [calculate=false] Whether to force calculate
  1598. * the coordinates but not use ones provided by browser.
  1599. */
  1600. function clientToLocal(el, e, out, calculate) {
  1601. out = out || {}; // According to the W3C Working Draft, offsetX and offsetY should be relative
  1602. // to the padding edge of the target element. The only browser using this convention
  1603. // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does
  1604. // not support the properties.
  1605. // (see http://www.jacklmoore.com/notes/mouse-position/)
  1606. // In zr painter.dom, padding edge equals to border edge.
  1607. if (calculate || !env$1.canvasSupported) {
  1608. calculateZrXY(el, e, out);
  1609. } // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned
  1610. // ancestor element, so we should make sure el is positioned (e.g., not position:static).
  1611. // BTW1, Webkit don't return the same results as FF in non-simple cases (like add
  1612. // zoom-factor, overflow / opacity layers, transforms ...)
  1613. // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d.
  1614. // <https://bugs.jquery.com/ticket/8523#comment:14>
  1615. // BTW3, In ff, offsetX/offsetY is always 0.
  1616. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) {
  1617. out.zrX = e.layerX;
  1618. out.zrY = e.layerY;
  1619. } // For IE6+, chrome, safari, opera. (When will ff support offsetX?)
  1620. else if (e.offsetX != null) {
  1621. out.zrX = e.offsetX;
  1622. out.zrY = e.offsetY;
  1623. } // For some other device, e.g., IOS safari.
  1624. else {
  1625. calculateZrXY(el, e, out);
  1626. }
  1627. return out;
  1628. }
  1629. function calculateZrXY(el, e, out) {
  1630. // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect.
  1631. if (env$1.domSupported && el.getBoundingClientRect) {
  1632. var ex = e.clientX;
  1633. var ey = e.clientY;
  1634. if (isCanvasEl(el)) {
  1635. // Original approach, which do not support CSS transform.
  1636. // marker can not be locationed in a canvas container
  1637. // (getBoundingClientRect is always 0). We do not support
  1638. // that input a pre-created canvas to zr while using css
  1639. // transform in iOS.
  1640. var box = el.getBoundingClientRect();
  1641. out.zrX = ex - box.left;
  1642. out.zrY = ey - box.top;
  1643. return;
  1644. } else {
  1645. if (transformCoordWithViewport(_calcOut, el, ex, ey)) {
  1646. out.zrX = _calcOut[0];
  1647. out.zrY = _calcOut[1];
  1648. return;
  1649. }
  1650. }
  1651. }
  1652. out.zrX = out.zrY = 0;
  1653. }
  1654. /**
  1655. * Find native event compat for legency IE.
  1656. * Should be called at the begining of a native event listener.
  1657. *
  1658. * @param {Event} [e] Mouse event or touch event or pointer event.
  1659. * For lagency IE, we use `window.event` is used.
  1660. * @return {Event} The native event.
  1661. */
  1662. function getNativeEvent(e) {
  1663. return e || window.event;
  1664. }
  1665. /**
  1666. * Normalize the coordinates of the input event.
  1667. *
  1668. * Get the `e.zrX` and `e.zrY`, which are relative to the top-left of
  1669. * the input `el`.
  1670. * Get `e.zrDelta` if using mouse wheel.
  1671. * Get `e.which`, see the comment inside this function.
  1672. *
  1673. * Do not calculate repeatly if `zrX` and `zrY` already exist.
  1674. *
  1675. * Notice: see comments in `clientToLocal`. check the relationship
  1676. * between the result coords and the parameters `el` and `calculate`.
  1677. *
  1678. * @param {HTMLElement} el DOM element.
  1679. * @param {Event} [e] See `getNativeEvent`.
  1680. * @param {boolean} [calculate=false] Whether to force calculate
  1681. * the coordinates but not use ones provided by browser.
  1682. * @return {UIEvent} The normalized native UIEvent.
  1683. */
  1684. function normalizeEvent(el, e, calculate) {
  1685. e = getNativeEvent(e);
  1686. if (e.zrX != null) {
  1687. return e;
  1688. }
  1689. var eventType = e.type;
  1690. var isTouch = eventType && eventType.indexOf('touch') >= 0;
  1691. if (!isTouch) {
  1692. clientToLocal(el, e, e, calculate);
  1693. e.zrDelta = e.wheelDelta ? e.wheelDelta / 120 : -(e.detail || 0) / 3;
  1694. } else {
  1695. var touch = eventType !== 'touchend' ? e.targetTouches[0] : e.changedTouches[0];
  1696. touch && clientToLocal(el, touch, e, calculate);
  1697. } // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0;
  1698. // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js
  1699. // If e.which has been defined, it may be readonly,
  1700. // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which
  1701. var button = e.button;
  1702. if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) {
  1703. e.which = button & 1 ? 1 : button & 2 ? 3 : button & 4 ? 2 : 0;
  1704. } // [Caution]: `e.which` from browser is not always reliable. For example,
  1705. // when press left button and `mousemove (pointermove)` in Edge, the `e.which`
  1706. // is 65536 and the `e.button` is -1. But the `mouseup (pointerup)` and
  1707. // `mousedown (pointerdown)` is the same as Chrome does.
  1708. return e;
  1709. }
  1710. /**
  1711. * @param {HTMLElement} el
  1712. * @param {string} name
  1713. * @param {Function} handler
  1714. * @param {Object|boolean} opt If boolean, means `opt.capture`
  1715. * @param {boolean} [opt.capture=false]
  1716. * @param {boolean} [opt.passive=false]
  1717. */
  1718. function addEventListener(el, name, handler, opt) {
  1719. if (isDomLevel2) {
  1720. // Reproduct the console warning:
  1721. // [Violation] Added non-passive event listener to a scroll-blocking <some> event.
  1722. // Consider marking event handler as 'passive' to make the page more responsive.
  1723. // Just set console log level: verbose in chrome dev tool.
  1724. // then the warning log will be printed when addEventListener called.
  1725. // See https://github.com/WICG/EventListenerOptions/blob/gh-pages/explainer.md
  1726. // We have not yet found a neat way to using passive. Because in zrender the dom event
  1727. // listener delegate all of the upper events of element. Some of those events need
  1728. // to prevent default. For example, the feature `preventDefaultMouseMove` of echarts.
  1729. // Before passive can be adopted, these issues should be considered:
  1730. // (1) Whether and how a zrender user specifies an event listener passive. And by default,
  1731. // passive or not.
  1732. // (2) How to tread that some zrender event listener is passive, and some is not. If
  1733. // we use other way but not preventDefault of mousewheel and touchmove, browser
  1734. // compatibility should be handled.
  1735. // var opts = (env.passiveSupported && name === 'mousewheel')
  1736. // ? {passive: true}
  1737. // // By default, the third param of el.addEventListener is `capture: false`.
  1738. // : void 0;
  1739. // el.addEventListener(name, handler /* , opts */);
  1740. el.addEventListener(name, handler, opt);
  1741. } else {
  1742. // For simplicity, do not implement `setCapture` for IE9-.
  1743. el.attachEvent('on' + name, handler);
  1744. }
  1745. }
  1746. /**
  1747. * Parameter are the same as `addEventListener`.
  1748. *
  1749. * Notice that if a listener is registered twice, one with capture and one without,
  1750. * remove each one separately. Removal of a capturing listener does not affect a
  1751. * non-capturing version of the same listener, and vice versa.
  1752. */
  1753. function removeEventListener(el, name, handler, opt) {
  1754. if (isDomLevel2) {
  1755. el.removeEventListener(name, handler, opt);
  1756. } else {
  1757. el.detachEvent('on' + name, handler);
  1758. }
  1759. }
  1760. /**
  1761. * preventDefault and stopPropagation.
  1762. * Notice: do not use this method in zrender. It can only be
  1763. * used by upper applications if necessary.
  1764. *
  1765. * @param {Event} e A mouse or touch event.
  1766. */
  1767. var stop = isDomLevel2 ? function (e) {
  1768. e.preventDefault();
  1769. e.stopPropagation();
  1770. e.cancelBubble = true;
  1771. } : function (e) {
  1772. e.returnValue = false;
  1773. e.cancelBubble = true;
  1774. };
  1775. /**
  1776. * This method only works for mouseup and mousedown. The functionality is restricted
  1777. * for fault tolerance, See the `e.which` compatibility above.
  1778. *
  1779. * @param {MouseEvent} e
  1780. * @return {boolean}
  1781. */
  1782. function isMiddleOrRightButtonOnMouseUpDown(e) {
  1783. return e.which === 2 || e.which === 3;
  1784. }
  1785. /**
  1786. * To be removed.
  1787. * @deprecated
  1788. */
  1789. // For backward compatibility
  1790. /**
  1791. * Only implements needed gestures for mobile.
  1792. */
  1793. var GestureMgr = function () {
  1794. /**
  1795. * @private
  1796. * @type {Array.<Object>}
  1797. */
  1798. this._track = [];
  1799. };
  1800. GestureMgr.prototype = {
  1801. constructor: GestureMgr,
  1802. recognize: function (event, target, root) {
  1803. this._doTrack(event, target, root);
  1804. return this._recognize(event);
  1805. },
  1806. clear: function () {
  1807. this._track.length = 0;
  1808. return this;
  1809. },
  1810. _doTrack: function (event, target, root) {
  1811. var touches = event.touches;
  1812. if (!touches) {
  1813. return;
  1814. }
  1815. var trackItem = {
  1816. points: [],
  1817. touches: [],
  1818. target: target,
  1819. event: event
  1820. };
  1821. for (var i = 0, len = touches.length; i < len; i++) {
  1822. var touch = touches[i];
  1823. var pos = clientToLocal(root, touch, {});
  1824. trackItem.points.push([pos.zrX, pos.zrY]);
  1825. trackItem.touches.push(touch);
  1826. }
  1827. this._track.push(trackItem);
  1828. },
  1829. _recognize: function (event) {
  1830. for (var eventName in recognizers) {
  1831. if (recognizers.hasOwnProperty(eventName)) {
  1832. var gestureInfo = recognizers[eventName](this._track, event);
  1833. if (gestureInfo) {
  1834. return gestureInfo;
  1835. }
  1836. }
  1837. }
  1838. }
  1839. };
  1840. function dist$1(pointPair) {
  1841. var dx = pointPair[1][0] - pointPair[0][0];
  1842. var dy = pointPair[1][1] - pointPair[0][1];
  1843. return Math.sqrt(dx * dx + dy * dy);
  1844. }
  1845. function center(pointPair) {
  1846. return [(pointPair[0][0] + pointPair[1][0]) / 2, (pointPair[0][1] + pointPair[1][1]) / 2];
  1847. }
  1848. var recognizers = {
  1849. pinch: function (track, event) {
  1850. var trackLen = track.length;
  1851. if (!trackLen) {
  1852. return;
  1853. }
  1854. var pinchEnd = (track[trackLen - 1] || {}).points;
  1855. var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd;
  1856. if (pinchPre && pinchPre.length > 1 && pinchEnd && pinchEnd.length > 1) {
  1857. var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre);
  1858. !isFinite(pinchScale) && (pinchScale = 1);
  1859. event.pinchScale = pinchScale;
  1860. var pinchCenter = center(pinchEnd);
  1861. event.pinchX = pinchCenter[0];
  1862. event.pinchY = pinchCenter[1];
  1863. return {
  1864. type: 'pinch',
  1865. target: track[0].target,
  1866. event: event
  1867. };
  1868. }
  1869. } // Only pinch currently.
  1870. };
  1871. /**
  1872. * [The interface between `Handler` and `HandlerProxy`]:
  1873. *
  1874. * The default `HandlerProxy` only support the common standard web environment
  1875. * (e.g., standalone browser, headless browser, embed browser in mobild APP, ...).
  1876. * But `HandlerProxy` can be replaced to support more non-standard environment
  1877. * (e.g., mini app), or to support more feature that the default `HandlerProxy`
  1878. * not provided (like echarts-gl did).
  1879. * So the interface between `Handler` and `HandlerProxy` should be stable. Do not
  1880. * make break changes util inevitable. The interface include the public methods
  1881. * of `Handler` and the events listed in `handlerNames` below, by which `HandlerProxy`
  1882. * drives `Handler`.
  1883. */
  1884. /**
  1885. * [Drag outside]:
  1886. *
  1887. * That is, triggering `mousemove` and `mouseup` event when the pointer is out of the
  1888. * zrender area when dragging. That is important for the improvement of the user experience
  1889. * when dragging something near the boundary without being terminated unexpectedly.
  1890. *
  1891. * We originally consider to introduce new events like `pagemovemove` and `pagemouseup`
  1892. * to resolve this issue. But some drawbacks of it is described in
  1893. * https://github.com/ecomfe/zrender/pull/536#issuecomment-560286899
  1894. *
  1895. * Instead, we referenced the specifications:
  1896. * https://www.w3.org/TR/touch-events/#the-touchmove-event
  1897. * https://www.w3.org/TR/2014/WD-DOM-Level-3-Events-20140925/#event-type-mousemove
  1898. * where the the mousemove/touchmove can be continue to fire if the user began a drag
  1899. * operation and the pointer has left the boundary. (for the mouse event, browsers
  1900. * only do it on `document` and when the pointer has left the boundary of the browser.)
  1901. *
  1902. * So the default `HandlerProxy` supports this feature similarly: if it is in the dragging
  1903. * state (see `pointerCapture` in `HandlerProxy`), the `mousemove` and `mouseup` continue
  1904. * to fire until release the pointer. That is implemented by listen to those event on
  1905. * `document`.
  1906. * If we implement some other `HandlerProxy` only for touch device, that would be easier.
  1907. * The touch event support this feature by default.
  1908. *
  1909. * Note:
  1910. * There might be some cases that the mouse event can not be
  1911. * received on `document`. For example,
  1912. * (A) `useCapture` is not supported and some user defined event listeners on the ancestor
  1913. * of zr dom throw Error .
  1914. * (B) `useCapture` is not supported Some user defined event listeners on the ancestor of
  1915. * zr dom call `stopPropagation`.
  1916. * In these cases, the `mousemove` event might be keep triggered event
  1917. * if the mouse is released. We try to reduce the side-effect in those cases.
  1918. * That is, do nothing (especially, `findHover`) in those cases. See `isOutsideBoundary`.
  1919. *
  1920. * Note:
  1921. * If `HandlerProxy` listens to `document` with `useCapture`, `HandlerProxy` needs to
  1922. * make sure `stopPropagation` and `preventDefault` doing nothing if and only if the event
  1923. * target is not zrender dom. Becuase it is dangerous to enable users to call them in
  1924. * `document` capture phase to prevent the propagation to any listener of the webpage.
  1925. * But they are needed to work when the pointer inside the zrender dom.
  1926. */
  1927. var SILENT = 'silent';
  1928. function makeEventPacket(eveType, targetInfo, event) {
  1929. return {
  1930. type: eveType,
  1931. event: event,
  1932. // target can only be an element that is not silent.
  1933. target: targetInfo.target,
  1934. // topTarget can be a silent element.
  1935. topTarget: targetInfo.topTarget,
  1936. cancelBubble: false,
  1937. offsetX: event.zrX,
  1938. offsetY: event.zrY,
  1939. gestureEvent: event.gestureEvent,
  1940. pinchX: event.pinchX,
  1941. pinchY: event.pinchY,
  1942. pinchScale: event.pinchScale,
  1943. wheelDelta: event.zrDelta,
  1944. zrByTouch: event.zrByTouch,
  1945. which: event.which,
  1946. stop: stopEvent
  1947. };
  1948. }
  1949. function stopEvent() {
  1950. stop(this.event);
  1951. }
  1952. function EmptyProxy() {}
  1953. EmptyProxy.prototype.dispose = function () {};
  1954. var handlerNames = ['click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu'];
  1955. /**
  1956. * @alias module:zrender/Handler
  1957. * @constructor
  1958. * @extends module:zrender/mixin/Eventful
  1959. * @param {module:zrender/Storage} storage Storage instance.
  1960. * @param {module:zrender/Painter} painter Painter instance.
  1961. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance.
  1962. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()).
  1963. */
  1964. var Handler = function (storage, painter, proxy, painterRoot) {
  1965. Eventful.call(this);
  1966. this.storage = storage;
  1967. this.painter = painter;
  1968. this.painterRoot = painterRoot;
  1969. proxy = proxy || new EmptyProxy();
  1970. /**
  1971. * Proxy of event. can be Dom, WebGLSurface, etc.
  1972. */
  1973. this.proxy = null;
  1974. /**
  1975. * {target, topTarget, x, y}
  1976. * @private
  1977. * @type {Object}
  1978. */
  1979. this._hovered = {};
  1980. /**
  1981. * @private
  1982. * @type {Date}
  1983. */
  1984. this._lastTouchMoment;
  1985. /**
  1986. * @private
  1987. * @type {number}
  1988. */
  1989. this._lastX;
  1990. /**
  1991. * @private
  1992. * @type {number}
  1993. */
  1994. this._lastY;
  1995. /**
  1996. * @private
  1997. * @type {module:zrender/core/GestureMgr}
  1998. */
  1999. this._gestureMgr;
  2000. Draggable.call(this);
  2001. this.setHandlerProxy(proxy);
  2002. };
  2003. Handler.prototype = {
  2004. constructor: Handler,
  2005. setHandlerProxy: function (proxy) {
  2006. if (this.proxy) {
  2007. this.proxy.dispose();
  2008. }
  2009. if (proxy) {
  2010. each$1(handlerNames, function (name) {
  2011. proxy.on && proxy.on(name, this[name], this);
  2012. }, this); // Attach handler
  2013. proxy.handler = this;
  2014. }
  2015. this.proxy = proxy;
  2016. },
  2017. mousemove: function (event) {
  2018. var x = event.zrX;
  2019. var y = event.zrY;
  2020. var isOutside = isOutsideBoundary(this, x, y);
  2021. var lastHovered = this._hovered;
  2022. var lastHoveredTarget = lastHovered.target; // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call
  2023. // (like 'setOption' or 'dispatchAction') in event handlers, we should find
  2024. // lastHovered again here. Otherwise 'mouseout' can not be triggered normally.
  2025. // See #6198.
  2026. if (lastHoveredTarget && !lastHoveredTarget.__zr) {
  2027. lastHovered = this.findHover(lastHovered.x, lastHovered.y);
  2028. lastHoveredTarget = lastHovered.target;
  2029. }
  2030. var hovered = this._hovered = isOutside ? {
  2031. x: x,
  2032. y: y
  2033. } : this.findHover(x, y);
  2034. var hoveredTarget = hovered.target;
  2035. var proxy = this.proxy;
  2036. proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default'); // Mouse out on previous hovered element
  2037. if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2038. this.dispatchToElement(lastHovered, 'mouseout', event);
  2039. } // Mouse moving on one element
  2040. this.dispatchToElement(hovered, 'mousemove', event); // Mouse over on a new element
  2041. if (hoveredTarget && hoveredTarget !== lastHoveredTarget) {
  2042. this.dispatchToElement(hovered, 'mouseover', event);
  2043. }
  2044. },
  2045. mouseout: function (event) {
  2046. var eventControl = event.zrEventControl;
  2047. var zrIsToLocalDOM = event.zrIsToLocalDOM;
  2048. if (eventControl !== 'only_globalout') {
  2049. this.dispatchToElement(this._hovered, 'mouseout', event);
  2050. }
  2051. if (eventControl !== 'no_globalout') {
  2052. // FIXME: if the pointer moving from the extra doms to realy "outside",
  2053. // the `globalout` should have been triggered. But currently not.
  2054. !zrIsToLocalDOM && this.trigger('globalout', {
  2055. type: 'globalout',
  2056. event: event
  2057. });
  2058. }
  2059. },
  2060. /**
  2061. * Resize
  2062. */
  2063. resize: function (event) {
  2064. this._hovered = {};
  2065. },
  2066. /**
  2067. * Dispatch event
  2068. * @param {string} eventName
  2069. * @param {event=} eventArgs
  2070. */
  2071. dispatch: function (eventName, eventArgs) {
  2072. var handler = this[eventName];
  2073. handler && handler.call(this, eventArgs);
  2074. },
  2075. /**
  2076. * Dispose
  2077. */
  2078. dispose: function () {
  2079. this.proxy.dispose();
  2080. this.storage = this.proxy = this.painter = null;
  2081. },
  2082. /**
  2083. * 设置默认的cursor style
  2084. * @param {string} [cursorStyle='default'] 例如 crosshair
  2085. */
  2086. setCursorStyle: function (cursorStyle) {
  2087. var proxy = this.proxy;
  2088. proxy.setCursor && proxy.setCursor(cursorStyle);
  2089. },
  2090. /**
  2091. * 事件分发代理
  2092. *
  2093. * @private
  2094. * @param {Object} targetInfo {target, topTarget} 目标图形元素
  2095. * @param {string} eventName 事件名称
  2096. * @param {Object} event 事件对象
  2097. */
  2098. dispatchToElement: function (targetInfo, eventName, event) {
  2099. targetInfo = targetInfo || {};
  2100. var el = targetInfo.target;
  2101. if (el && el.silent) {
  2102. return;
  2103. }
  2104. var eventHandler = 'on' + eventName;
  2105. var eventPacket = makeEventPacket(eventName, targetInfo, event);
  2106. while (el) {
  2107. el[eventHandler] && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket));
  2108. el.trigger(eventName, eventPacket);
  2109. el = el.parent;
  2110. if (eventPacket.cancelBubble) {
  2111. break;
  2112. }
  2113. }
  2114. if (!eventPacket.cancelBubble) {
  2115. // 冒泡到顶级 zrender 对象
  2116. this.trigger(eventName, eventPacket); // 分发事件到用户自定义层
  2117. // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在
  2118. this.painter && this.painter.eachOtherLayer(function (layer) {
  2119. if (typeof layer[eventHandler] === 'function') {
  2120. layer[eventHandler].call(layer, eventPacket);
  2121. }
  2122. if (layer.trigger) {
  2123. layer.trigger(eventName, eventPacket);
  2124. }
  2125. });
  2126. }
  2127. },
  2128. /**
  2129. * @private
  2130. * @param {number} x
  2131. * @param {number} y
  2132. * @param {module:zrender/graphic/Displayable} exclude
  2133. * @return {model:zrender/Element}
  2134. * @method
  2135. */
  2136. findHover: function (x, y, exclude) {
  2137. var list = this.storage.getDisplayList();
  2138. var out = {
  2139. x: x,
  2140. y: y
  2141. };
  2142. for (var i = list.length - 1; i >= 0; i--) {
  2143. var hoverCheckResult;
  2144. if (list[i] !== exclude // getDisplayList may include ignored item in VML mode
  2145. && !list[i].ignore && (hoverCheckResult = isHover(list[i], x, y))) {
  2146. !out.topTarget && (out.topTarget = list[i]);
  2147. if (hoverCheckResult !== SILENT) {
  2148. out.target = list[i];
  2149. break;
  2150. }
  2151. }
  2152. }
  2153. return out;
  2154. },
  2155. processGesture: function (event, stage) {
  2156. if (!this._gestureMgr) {
  2157. this._gestureMgr = new GestureMgr();
  2158. }
  2159. var gestureMgr = this._gestureMgr;
  2160. stage === 'start' && gestureMgr.clear();
  2161. var gestureInfo = gestureMgr.recognize(event, this.findHover(event.zrX, event.zrY, null).target, this.proxy.dom);
  2162. stage === 'end' && gestureMgr.clear(); // Do not do any preventDefault here. Upper application do that if necessary.
  2163. if (gestureInfo) {
  2164. var type = gestureInfo.type;
  2165. event.gestureEvent = type;
  2166. this.dispatchToElement({
  2167. target: gestureInfo.target
  2168. }, type, gestureInfo.event);
  2169. }
  2170. }
  2171. }; // Common handlers
  2172. each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  2173. Handler.prototype[name] = function (event) {
  2174. var x = event.zrX;
  2175. var y = event.zrY;
  2176. var isOutside = isOutsideBoundary(this, x, y);
  2177. var hovered;
  2178. var hoveredTarget;
  2179. if (name !== 'mouseup' || !isOutside) {
  2180. // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover
  2181. hovered = this.findHover(x, y);
  2182. hoveredTarget = hovered.target;
  2183. }
  2184. if (name === 'mousedown') {
  2185. this._downEl = hoveredTarget;
  2186. this._downPoint = [event.zrX, event.zrY]; // In case click triggered before mouseup
  2187. this._upEl = hoveredTarget;
  2188. } else if (name === 'mouseup') {
  2189. this._upEl = hoveredTarget;
  2190. } else if (name === 'click') {
  2191. if (this._downEl !== this._upEl // Original click event is triggered on the whole canvas element,
  2192. // including the case that `mousedown` - `mousemove` - `mouseup`,
  2193. // which should be filtered, otherwise it will bring trouble to
  2194. // pan and zoom.
  2195. || !this._downPoint // Arbitrary value
  2196. || dist(this._downPoint, [event.zrX, event.zrY]) > 4) {
  2197. return;
  2198. }
  2199. this._downPoint = null;
  2200. }
  2201. this.dispatchToElement(hovered, name, event);
  2202. };
  2203. });
  2204. function isHover(displayable, x, y) {
  2205. if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) {
  2206. var el = displayable;
  2207. var isSilent;
  2208. while (el) {
  2209. // If clipped by ancestor.
  2210. // FIXME: If clipPath has neither stroke nor fill,
  2211. // el.clipPath.contain(x, y) will always return false.
  2212. if (el.clipPath && !el.clipPath.contain(x, y)) {
  2213. return false;
  2214. }
  2215. if (el.silent) {
  2216. isSilent = true;
  2217. }
  2218. el = el.parent;
  2219. }
  2220. return isSilent ? SILENT : true;
  2221. }
  2222. return false;
  2223. }
  2224. /**
  2225. * See [Drag outside].
  2226. */
  2227. function isOutsideBoundary(handlerInstance, x, y) {
  2228. var painter = handlerInstance.painter;
  2229. return x < 0 || x > painter.getWidth() || y < 0 || y > painter.getHeight();
  2230. }
  2231. mixin(Handler, Eventful);
  2232. mixin(Handler, Draggable);
  2233. /**
  2234. * 3x2矩阵操作类
  2235. * @exports zrender/tool/matrix
  2236. */
  2237. /* global Float32Array */
  2238. var ArrayCtor$1 = typeof Float32Array === 'undefined' ? Array : Float32Array;
  2239. /**
  2240. * Create a identity matrix.
  2241. * @return {Float32Array|Array.<number>}
  2242. */
  2243. function create$1() {
  2244. var out = new ArrayCtor$1(6);
  2245. identity(out);
  2246. return out;
  2247. }
  2248. /**
  2249. * 设置矩阵为单位矩阵
  2250. * @param {Float32Array|Array.<number>} out
  2251. */
  2252. function identity(out) {
  2253. out[0] = 1;
  2254. out[1] = 0;
  2255. out[2] = 0;
  2256. out[3] = 1;
  2257. out[4] = 0;
  2258. out[5] = 0;
  2259. return out;
  2260. }
  2261. /**
  2262. * 复制矩阵
  2263. * @param {Float32Array|Array.<number>} out
  2264. * @param {Float32Array|Array.<number>} m
  2265. */
  2266. function copy$1(out, m) {
  2267. out[0] = m[0];
  2268. out[1] = m[1];
  2269. out[2] = m[2];
  2270. out[3] = m[3];
  2271. out[4] = m[4];
  2272. out[5] = m[5];
  2273. return out;
  2274. }
  2275. /**
  2276. * 矩阵相乘
  2277. * @param {Float32Array|Array.<number>} out
  2278. * @param {Float32Array|Array.<number>} m1
  2279. * @param {Float32Array|Array.<number>} m2
  2280. */
  2281. function mul$1(out, m1, m2) {
  2282. // Consider matrix.mul(m, m2, m);
  2283. // where out is the same as m2.
  2284. // So use temp variable to escape error.
  2285. var out0 = m1[0] * m2[0] + m1[2] * m2[1];
  2286. var out1 = m1[1] * m2[0] + m1[3] * m2[1];
  2287. var out2 = m1[0] * m2[2] + m1[2] * m2[3];
  2288. var out3 = m1[1] * m2[2] + m1[3] * m2[3];
  2289. var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4];
  2290. var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5];
  2291. out[0] = out0;
  2292. out[1] = out1;
  2293. out[2] = out2;
  2294. out[3] = out3;
  2295. out[4] = out4;
  2296. out[5] = out5;
  2297. return out;
  2298. }
  2299. /**
  2300. * 平移变换
  2301. * @param {Float32Array|Array.<number>} out
  2302. * @param {Float32Array|Array.<number>} a
  2303. * @param {Float32Array|Array.<number>} v
  2304. */
  2305. function translate(out, a, v) {
  2306. out[0] = a[0];
  2307. out[1] = a[1];
  2308. out[2] = a[2];
  2309. out[3] = a[3];
  2310. out[4] = a[4] + v[0];
  2311. out[5] = a[5] + v[1];
  2312. return out;
  2313. }
  2314. /**
  2315. * 旋转变换
  2316. * @param {Float32Array|Array.<number>} out
  2317. * @param {Float32Array|Array.<number>} a
  2318. * @param {number} rad
  2319. */
  2320. function rotate(out, a, rad) {
  2321. var aa = a[0];
  2322. var ac = a[2];
  2323. var atx = a[4];
  2324. var ab = a[1];
  2325. var ad = a[3];
  2326. var aty = a[5];
  2327. var st = Math.sin(rad);
  2328. var ct = Math.cos(rad);
  2329. out[0] = aa * ct + ab * st;
  2330. out[1] = -aa * st + ab * ct;
  2331. out[2] = ac * ct + ad * st;
  2332. out[3] = -ac * st + ct * ad;
  2333. out[4] = ct * atx + st * aty;
  2334. out[5] = ct * aty - st * atx;
  2335. return out;
  2336. }
  2337. /**
  2338. * 缩放变换
  2339. * @param {Float32Array|Array.<number>} out
  2340. * @param {Float32Array|Array.<number>} a
  2341. * @param {Float32Array|Array.<number>} v
  2342. */
  2343. function scale$1(out, a, v) {
  2344. var vx = v[0];
  2345. var vy = v[1];
  2346. out[0] = a[0] * vx;
  2347. out[1] = a[1] * vy;
  2348. out[2] = a[2] * vx;
  2349. out[3] = a[3] * vy;
  2350. out[4] = a[4] * vx;
  2351. out[5] = a[5] * vy;
  2352. return out;
  2353. }
  2354. /**
  2355. * 求逆矩阵
  2356. * @param {Float32Array|Array.<number>} out
  2357. * @param {Float32Array|Array.<number>} a
  2358. */
  2359. function invert(out, a) {
  2360. var aa = a[0];
  2361. var ac = a[2];
  2362. var atx = a[4];
  2363. var ab = a[1];
  2364. var ad = a[3];
  2365. var aty = a[5];
  2366. var det = aa * ad - ab * ac;
  2367. if (!det) {
  2368. return null;
  2369. }
  2370. det = 1.0 / det;
  2371. out[0] = ad * det;
  2372. out[1] = -ab * det;
  2373. out[2] = -ac * det;
  2374. out[3] = aa * det;
  2375. out[4] = (ac * aty - ad * atx) * det;
  2376. out[5] = (ab * atx - aa * aty) * det;
  2377. return out;
  2378. }
  2379. /**
  2380. * Clone a new matrix.
  2381. * @param {Float32Array|Array.<number>} a
  2382. */
  2383. function clone$2(a) {
  2384. var b = create$1();
  2385. copy$1(b, a);
  2386. return b;
  2387. }
  2388. var matrix = (Object.freeze || Object)({
  2389. create: create$1,
  2390. identity: identity,
  2391. copy: copy$1,
  2392. mul: mul$1,
  2393. translate: translate,
  2394. rotate: rotate,
  2395. scale: scale$1,
  2396. invert: invert,
  2397. clone: clone$2
  2398. });
  2399. /**
  2400. * 提供变换扩展
  2401. * @module zrender/mixin/Transformable
  2402. * @author pissang (https://www.github.com/pissang)
  2403. */
  2404. var mIdentity = identity;
  2405. var EPSILON = 5e-5;
  2406. function isNotAroundZero(val) {
  2407. return val > EPSILON || val < -EPSILON;
  2408. }
  2409. /**
  2410. * @alias module:zrender/mixin/Transformable
  2411. * @constructor
  2412. */
  2413. var Transformable = function (opts) {
  2414. opts = opts || {}; // If there are no given position, rotation, scale
  2415. if (!opts.position) {
  2416. /**
  2417. * 平移
  2418. * @type {Array.<number>}
  2419. * @default [0, 0]
  2420. */
  2421. this.position = [0, 0];
  2422. }
  2423. if (opts.rotation == null) {
  2424. /**
  2425. * 旋转
  2426. * @type {Array.<number>}
  2427. * @default 0
  2428. */
  2429. this.rotation = 0;
  2430. }
  2431. if (!opts.scale) {
  2432. /**
  2433. * 缩放
  2434. * @type {Array.<number>}
  2435. * @default [1, 1]
  2436. */
  2437. this.scale = [1, 1];
  2438. }
  2439. /**
  2440. * 旋转和缩放的原点
  2441. * @type {Array.<number>}
  2442. * @default null
  2443. */
  2444. this.origin = this.origin || null;
  2445. };
  2446. var transformableProto = Transformable.prototype;
  2447. transformableProto.transform = null;
  2448. /**
  2449. * 判断是否需要有坐标变换
  2450. * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵
  2451. */
  2452. transformableProto.needLocalTransform = function () {
  2453. return isNotAroundZero(this.rotation) || isNotAroundZero(this.position[0]) || isNotAroundZero(this.position[1]) || isNotAroundZero(this.scale[0] - 1) || isNotAroundZero(this.scale[1] - 1);
  2454. };
  2455. var scaleTmp = [];
  2456. transformableProto.updateTransform = function () {
  2457. var parent = this.parent;
  2458. var parentHasTransform = parent && parent.transform;
  2459. var needLocalTransform = this.needLocalTransform();
  2460. var m = this.transform;
  2461. if (!(needLocalTransform || parentHasTransform)) {
  2462. m && mIdentity(m);
  2463. return;
  2464. }
  2465. m = m || create$1();
  2466. if (needLocalTransform) {
  2467. this.getLocalTransform(m);
  2468. } else {
  2469. mIdentity(m);
  2470. } // 应用父节点变换
  2471. if (parentHasTransform) {
  2472. if (needLocalTransform) {
  2473. mul$1(m, parent.transform, m);
  2474. } else {
  2475. copy$1(m, parent.transform);
  2476. }
  2477. } // 保存这个变换矩阵
  2478. this.transform = m;
  2479. var globalScaleRatio = this.globalScaleRatio;
  2480. if (globalScaleRatio != null && globalScaleRatio !== 1) {
  2481. this.getGlobalScale(scaleTmp);
  2482. var relX = scaleTmp[0] < 0 ? -1 : 1;
  2483. var relY = scaleTmp[1] < 0 ? -1 : 1;
  2484. var sx = ((scaleTmp[0] - relX) * globalScaleRatio + relX) / scaleTmp[0] || 0;
  2485. var sy = ((scaleTmp[1] - relY) * globalScaleRatio + relY) / scaleTmp[1] || 0;
  2486. m[0] *= sx;
  2487. m[1] *= sx;
  2488. m[2] *= sy;
  2489. m[3] *= sy;
  2490. }
  2491. this.invTransform = this.invTransform || create$1();
  2492. invert(this.invTransform, m);
  2493. };
  2494. transformableProto.getLocalTransform = function (m) {
  2495. return Transformable.getLocalTransform(this, m);
  2496. };
  2497. /**
  2498. * 将自己的transform应用到context上
  2499. * @param {CanvasRenderingContext2D} ctx
  2500. */
  2501. transformableProto.setTransform = function (ctx) {
  2502. var m = this.transform;
  2503. var dpr = ctx.dpr || 1;
  2504. if (m) {
  2505. ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]);
  2506. } else {
  2507. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2508. }
  2509. };
  2510. transformableProto.restoreTransform = function (ctx) {
  2511. var dpr = ctx.dpr || 1;
  2512. ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
  2513. };
  2514. var tmpTransform = [];
  2515. var originTransform = create$1();
  2516. transformableProto.setLocalTransform = function (m) {
  2517. if (!m) {
  2518. // TODO return or set identity?
  2519. return;
  2520. }
  2521. var sx = m[0] * m[0] + m[1] * m[1];
  2522. var sy = m[2] * m[2] + m[3] * m[3];
  2523. var position = this.position;
  2524. var scale$$1 = this.scale;
  2525. if (isNotAroundZero(sx - 1)) {
  2526. sx = Math.sqrt(sx);
  2527. }
  2528. if (isNotAroundZero(sy - 1)) {
  2529. sy = Math.sqrt(sy);
  2530. }
  2531. if (m[0] < 0) {
  2532. sx = -sx;
  2533. }
  2534. if (m[3] < 0) {
  2535. sy = -sy;
  2536. }
  2537. position[0] = m[4];
  2538. position[1] = m[5];
  2539. scale$$1[0] = sx;
  2540. scale$$1[1] = sy;
  2541. this.rotation = Math.atan2(-m[1] / sy, m[0] / sx);
  2542. };
  2543. /**
  2544. * 分解`transform`矩阵到`position`, `rotation`, `scale`
  2545. */
  2546. transformableProto.decomposeTransform = function () {
  2547. if (!this.transform) {
  2548. return;
  2549. }
  2550. var parent = this.parent;
  2551. var m = this.transform;
  2552. if (parent && parent.transform) {
  2553. // Get local transform and decompose them to position, scale, rotation
  2554. mul$1(tmpTransform, parent.invTransform, m);
  2555. m = tmpTransform;
  2556. }
  2557. var origin = this.origin;
  2558. if (origin && (origin[0] || origin[1])) {
  2559. originTransform[4] = origin[0];
  2560. originTransform[5] = origin[1];
  2561. mul$1(tmpTransform, m, originTransform);
  2562. tmpTransform[4] -= origin[0];
  2563. tmpTransform[5] -= origin[1];
  2564. m = tmpTransform;
  2565. }
  2566. this.setLocalTransform(m);
  2567. };
  2568. /**
  2569. * Get global scale
  2570. * @return {Array.<number>}
  2571. */
  2572. transformableProto.getGlobalScale = function (out) {
  2573. var m = this.transform;
  2574. out = out || [];
  2575. if (!m) {
  2576. out[0] = 1;
  2577. out[1] = 1;
  2578. return out;
  2579. }
  2580. out[0] = Math.sqrt(m[0] * m[0] + m[1] * m[1]);
  2581. out[1] = Math.sqrt(m[2] * m[2] + m[3] * m[3]);
  2582. if (m[0] < 0) {
  2583. out[0] = -out[0];
  2584. }
  2585. if (m[3] < 0) {
  2586. out[1] = -out[1];
  2587. }
  2588. return out;
  2589. };
  2590. /**
  2591. * 变换坐标位置到 shape 的局部坐标空间
  2592. * @method
  2593. * @param {number} x
  2594. * @param {number} y
  2595. * @return {Array.<number>}
  2596. */
  2597. transformableProto.transformCoordToLocal = function (x, y) {
  2598. var v2 = [x, y];
  2599. var invTransform = this.invTransform;
  2600. if (invTransform) {
  2601. applyTransform(v2, v2, invTransform);
  2602. }
  2603. return v2;
  2604. };
  2605. /**
  2606. * 变换局部坐标位置到全局坐标空间
  2607. * @method
  2608. * @param {number} x
  2609. * @param {number} y
  2610. * @return {Array.<number>}
  2611. */
  2612. transformableProto.transformCoordToGlobal = function (x, y) {
  2613. var v2 = [x, y];
  2614. var transform = this.transform;
  2615. if (transform) {
  2616. applyTransform(v2, v2, transform);
  2617. }
  2618. return v2;
  2619. };
  2620. /**
  2621. * @static
  2622. * @param {Object} target
  2623. * @param {Array.<number>} target.origin
  2624. * @param {number} target.rotation
  2625. * @param {Array.<number>} target.position
  2626. * @param {Array.<number>} [m]
  2627. */
  2628. Transformable.getLocalTransform = function (target, m) {
  2629. m = m || [];
  2630. mIdentity(m);
  2631. var origin = target.origin;
  2632. var scale$$1 = target.scale || [1, 1];
  2633. var rotation = target.rotation || 0;
  2634. var position = target.position || [0, 0];
  2635. if (origin) {
  2636. // Translate to origin
  2637. m[4] -= origin[0];
  2638. m[5] -= origin[1];
  2639. }
  2640. scale$1(m, m, scale$$1);
  2641. if (rotation) {
  2642. rotate(m, m, rotation);
  2643. }
  2644. if (origin) {
  2645. // Translate back from origin
  2646. m[4] += origin[0];
  2647. m[5] += origin[1];
  2648. }
  2649. m[4] += position[0];
  2650. m[5] += position[1];
  2651. return m;
  2652. };
  2653. /**
  2654. * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js
  2655. * @see http://sole.github.io/tween.js/examples/03_graphs.html
  2656. * @exports zrender/animation/easing
  2657. */
  2658. var easing = {
  2659. /**
  2660. * @param {number} k
  2661. * @return {number}
  2662. */
  2663. linear: function (k) {
  2664. return k;
  2665. },
  2666. /**
  2667. * @param {number} k
  2668. * @return {number}
  2669. */
  2670. quadraticIn: function (k) {
  2671. return k * k;
  2672. },
  2673. /**
  2674. * @param {number} k
  2675. * @return {number}
  2676. */
  2677. quadraticOut: function (k) {
  2678. return k * (2 - k);
  2679. },
  2680. /**
  2681. * @param {number} k
  2682. * @return {number}
  2683. */
  2684. quadraticInOut: function (k) {
  2685. if ((k *= 2) < 1) {
  2686. return 0.5 * k * k;
  2687. }
  2688. return -0.5 * (--k * (k - 2) - 1);
  2689. },
  2690. // 三次方的缓动(t^3)
  2691. /**
  2692. * @param {number} k
  2693. * @return {number}
  2694. */
  2695. cubicIn: function (k) {
  2696. return k * k * k;
  2697. },
  2698. /**
  2699. * @param {number} k
  2700. * @return {number}
  2701. */
  2702. cubicOut: function (k) {
  2703. return --k * k * k + 1;
  2704. },
  2705. /**
  2706. * @param {number} k
  2707. * @return {number}
  2708. */
  2709. cubicInOut: function (k) {
  2710. if ((k *= 2) < 1) {
  2711. return 0.5 * k * k * k;
  2712. }
  2713. return 0.5 * ((k -= 2) * k * k + 2);
  2714. },
  2715. // 四次方的缓动(t^4)
  2716. /**
  2717. * @param {number} k
  2718. * @return {number}
  2719. */
  2720. quarticIn: function (k) {
  2721. return k * k * k * k;
  2722. },
  2723. /**
  2724. * @param {number} k
  2725. * @return {number}
  2726. */
  2727. quarticOut: function (k) {
  2728. return 1 - --k * k * k * k;
  2729. },
  2730. /**
  2731. * @param {number} k
  2732. * @return {number}
  2733. */
  2734. quarticInOut: function (k) {
  2735. if ((k *= 2) < 1) {
  2736. return 0.5 * k * k * k * k;
  2737. }
  2738. return -0.5 * ((k -= 2) * k * k * k - 2);
  2739. },
  2740. // 五次方的缓动(t^5)
  2741. /**
  2742. * @param {number} k
  2743. * @return {number}
  2744. */
  2745. quinticIn: function (k) {
  2746. return k * k * k * k * k;
  2747. },
  2748. /**
  2749. * @param {number} k
  2750. * @return {number}
  2751. */
  2752. quinticOut: function (k) {
  2753. return --k * k * k * k * k + 1;
  2754. },
  2755. /**
  2756. * @param {number} k
  2757. * @return {number}
  2758. */
  2759. quinticInOut: function (k) {
  2760. if ((k *= 2) < 1) {
  2761. return 0.5 * k * k * k * k * k;
  2762. }
  2763. return 0.5 * ((k -= 2) * k * k * k * k + 2);
  2764. },
  2765. // 正弦曲线的缓动(sin(t))
  2766. /**
  2767. * @param {number} k
  2768. * @return {number}
  2769. */
  2770. sinusoidalIn: function (k) {
  2771. return 1 - Math.cos(k * Math.PI / 2);
  2772. },
  2773. /**
  2774. * @param {number} k
  2775. * @return {number}
  2776. */
  2777. sinusoidalOut: function (k) {
  2778. return Math.sin(k * Math.PI / 2);
  2779. },
  2780. /**
  2781. * @param {number} k
  2782. * @return {number}
  2783. */
  2784. sinusoidalInOut: function (k) {
  2785. return 0.5 * (1 - Math.cos(Math.PI * k));
  2786. },
  2787. // 指数曲线的缓动(2^t)
  2788. /**
  2789. * @param {number} k
  2790. * @return {number}
  2791. */
  2792. exponentialIn: function (k) {
  2793. return k === 0 ? 0 : Math.pow(1024, k - 1);
  2794. },
  2795. /**
  2796. * @param {number} k
  2797. * @return {number}
  2798. */
  2799. exponentialOut: function (k) {
  2800. return k === 1 ? 1 : 1 - Math.pow(2, -10 * k);
  2801. },
  2802. /**
  2803. * @param {number} k
  2804. * @return {number}
  2805. */
  2806. exponentialInOut: function (k) {
  2807. if (k === 0) {
  2808. return 0;
  2809. }
  2810. if (k === 1) {
  2811. return 1;
  2812. }
  2813. if ((k *= 2) < 1) {
  2814. return 0.5 * Math.pow(1024, k - 1);
  2815. }
  2816. return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2);
  2817. },
  2818. // 圆形曲线的缓动(sqrt(1-t^2))
  2819. /**
  2820. * @param {number} k
  2821. * @return {number}
  2822. */
  2823. circularIn: function (k) {
  2824. return 1 - Math.sqrt(1 - k * k);
  2825. },
  2826. /**
  2827. * @param {number} k
  2828. * @return {number}
  2829. */
  2830. circularOut: function (k) {
  2831. return Math.sqrt(1 - --k * k);
  2832. },
  2833. /**
  2834. * @param {number} k
  2835. * @return {number}
  2836. */
  2837. circularInOut: function (k) {
  2838. if ((k *= 2) < 1) {
  2839. return -0.5 * (Math.sqrt(1 - k * k) - 1);
  2840. }
  2841. return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1);
  2842. },
  2843. // 创建类似于弹簧在停止前来回振荡的动画
  2844. /**
  2845. * @param {number} k
  2846. * @return {number}
  2847. */
  2848. elasticIn: function (k) {
  2849. var s;
  2850. var a = 0.1;
  2851. var p = 0.4;
  2852. if (k === 0) {
  2853. return 0;
  2854. }
  2855. if (k === 1) {
  2856. return 1;
  2857. }
  2858. if (!a || a < 1) {
  2859. a = 1;
  2860. s = p / 4;
  2861. } else {
  2862. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2863. }
  2864. return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
  2865. },
  2866. /**
  2867. * @param {number} k
  2868. * @return {number}
  2869. */
  2870. elasticOut: function (k) {
  2871. var s;
  2872. var a = 0.1;
  2873. var p = 0.4;
  2874. if (k === 0) {
  2875. return 0;
  2876. }
  2877. if (k === 1) {
  2878. return 1;
  2879. }
  2880. if (!a || a < 1) {
  2881. a = 1;
  2882. s = p / 4;
  2883. } else {
  2884. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2885. }
  2886. return a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1;
  2887. },
  2888. /**
  2889. * @param {number} k
  2890. * @return {number}
  2891. */
  2892. elasticInOut: function (k) {
  2893. var s;
  2894. var a = 0.1;
  2895. var p = 0.4;
  2896. if (k === 0) {
  2897. return 0;
  2898. }
  2899. if (k === 1) {
  2900. return 1;
  2901. }
  2902. if (!a || a < 1) {
  2903. a = 1;
  2904. s = p / 4;
  2905. } else {
  2906. s = p * Math.asin(1 / a) / (2 * Math.PI);
  2907. }
  2908. if ((k *= 2) < 1) {
  2909. return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p));
  2910. }
  2911. return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1;
  2912. },
  2913. // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动
  2914. /**
  2915. * @param {number} k
  2916. * @return {number}
  2917. */
  2918. backIn: function (k) {
  2919. var s = 1.70158;
  2920. return k * k * ((s + 1) * k - s);
  2921. },
  2922. /**
  2923. * @param {number} k
  2924. * @return {number}
  2925. */
  2926. backOut: function (k) {
  2927. var s = 1.70158;
  2928. return --k * k * ((s + 1) * k + s) + 1;
  2929. },
  2930. /**
  2931. * @param {number} k
  2932. * @return {number}
  2933. */
  2934. backInOut: function (k) {
  2935. var s = 1.70158 * 1.525;
  2936. if ((k *= 2) < 1) {
  2937. return 0.5 * (k * k * ((s + 1) * k - s));
  2938. }
  2939. return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2);
  2940. },
  2941. // 创建弹跳效果
  2942. /**
  2943. * @param {number} k
  2944. * @return {number}
  2945. */
  2946. bounceIn: function (k) {
  2947. return 1 - easing.bounceOut(1 - k);
  2948. },
  2949. /**
  2950. * @param {number} k
  2951. * @return {number}
  2952. */
  2953. bounceOut: function (k) {
  2954. if (k < 1 / 2.75) {
  2955. return 7.5625 * k * k;
  2956. } else if (k < 2 / 2.75) {
  2957. return 7.5625 * (k -= 1.5 / 2.75) * k + 0.75;
  2958. } else if (k < 2.5 / 2.75) {
  2959. return 7.5625 * (k -= 2.25 / 2.75) * k + 0.9375;
  2960. } else {
  2961. return 7.5625 * (k -= 2.625 / 2.75) * k + 0.984375;
  2962. }
  2963. },
  2964. /**
  2965. * @param {number} k
  2966. * @return {number}
  2967. */
  2968. bounceInOut: function (k) {
  2969. if (k < 0.5) {
  2970. return easing.bounceIn(k * 2) * 0.5;
  2971. }
  2972. return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5;
  2973. }
  2974. };
  2975. /**
  2976. * 动画主控制器
  2977. * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件
  2978. * @config life(1000) 动画时长
  2979. * @config delay(0) 动画延迟时间
  2980. * @config loop(true)
  2981. * @config gap(0) 循环的间隔时间
  2982. * @config onframe
  2983. * @config easing(optional)
  2984. * @config ondestroy(optional)
  2985. * @config onrestart(optional)
  2986. *
  2987. * TODO pause
  2988. */
  2989. function Clip(options) {
  2990. this._target = options.target; // 生命周期
  2991. this._life = options.life || 1000; // 延时
  2992. this._delay = options.delay || 0; // 开始时间
  2993. // this._startTime = new Date().getTime() + this._delay;// 单位毫秒
  2994. this._initialized = false; // 是否循环
  2995. this.loop = options.loop == null ? false : options.loop;
  2996. this.gap = options.gap || 0;
  2997. this.easing = options.easing || 'Linear';
  2998. this.onframe = options.onframe;
  2999. this.ondestroy = options.ondestroy;
  3000. this.onrestart = options.onrestart;
  3001. this._pausedTime = 0;
  3002. this._paused = false;
  3003. }
  3004. Clip.prototype = {
  3005. constructor: Clip,
  3006. step: function (globalTime, deltaTime) {
  3007. // Set startTime on first step, or _startTime may has milleseconds different between clips
  3008. // PENDING
  3009. if (!this._initialized) {
  3010. this._startTime = globalTime + this._delay;
  3011. this._initialized = true;
  3012. }
  3013. if (this._paused) {
  3014. this._pausedTime += deltaTime;
  3015. return;
  3016. }
  3017. var percent = (globalTime - this._startTime - this._pausedTime) / this._life; // 还没开始
  3018. if (percent < 0) {
  3019. return;
  3020. }
  3021. percent = Math.min(percent, 1);
  3022. var easing$$1 = this.easing;
  3023. var easingFunc = typeof easing$$1 === 'string' ? easing[easing$$1] : easing$$1;
  3024. var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent;
  3025. this.fire('frame', schedule); // 结束
  3026. if (percent === 1) {
  3027. if (this.loop) {
  3028. this.restart(globalTime); // 重新开始周期
  3029. // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件
  3030. return 'restart';
  3031. } // 动画完成将这个控制器标识为待删除
  3032. // 在Animation.update中进行批量删除
  3033. this._needsRemove = true;
  3034. return 'destroy';
  3035. }
  3036. return null;
  3037. },
  3038. restart: function (globalTime) {
  3039. var remainder = (globalTime - this._startTime - this._pausedTime) % this._life;
  3040. this._startTime = globalTime - remainder + this.gap;
  3041. this._pausedTime = 0;
  3042. this._needsRemove = false;
  3043. },
  3044. fire: function (eventType, arg) {
  3045. eventType = 'on' + eventType;
  3046. if (this[eventType]) {
  3047. this[eventType](this._target, arg);
  3048. }
  3049. },
  3050. pause: function () {
  3051. this._paused = true;
  3052. },
  3053. resume: function () {
  3054. this._paused = false;
  3055. }
  3056. };
  3057. // Simple LRU cache use doubly linked list
  3058. // @module zrender/core/LRU
  3059. /**
  3060. * Simple double linked list. Compared with array, it has O(1) remove operation.
  3061. * @constructor
  3062. */
  3063. var LinkedList = function () {
  3064. /**
  3065. * @type {module:zrender/core/LRU~Entry}
  3066. */
  3067. this.head = null;
  3068. /**
  3069. * @type {module:zrender/core/LRU~Entry}
  3070. */
  3071. this.tail = null;
  3072. this._len = 0;
  3073. };
  3074. var linkedListProto = LinkedList.prototype;
  3075. /**
  3076. * Insert a new value at the tail
  3077. * @param {} val
  3078. * @return {module:zrender/core/LRU~Entry}
  3079. */
  3080. linkedListProto.insert = function (val) {
  3081. var entry = new Entry(val);
  3082. this.insertEntry(entry);
  3083. return entry;
  3084. };
  3085. /**
  3086. * Insert an entry at the tail
  3087. * @param {module:zrender/core/LRU~Entry} entry
  3088. */
  3089. linkedListProto.insertEntry = function (entry) {
  3090. if (!this.head) {
  3091. this.head = this.tail = entry;
  3092. } else {
  3093. this.tail.next = entry;
  3094. entry.prev = this.tail;
  3095. entry.next = null;
  3096. this.tail = entry;
  3097. }
  3098. this._len++;
  3099. };
  3100. /**
  3101. * Remove entry.
  3102. * @param {module:zrender/core/LRU~Entry} entry
  3103. */
  3104. linkedListProto.remove = function (entry) {
  3105. var prev = entry.prev;
  3106. var next = entry.next;
  3107. if (prev) {
  3108. prev.next = next;
  3109. } else {
  3110. // Is head
  3111. this.head = next;
  3112. }
  3113. if (next) {
  3114. next.prev = prev;
  3115. } else {
  3116. // Is tail
  3117. this.tail = prev;
  3118. }
  3119. entry.next = entry.prev = null;
  3120. this._len--;
  3121. };
  3122. /**
  3123. * @return {number}
  3124. */
  3125. linkedListProto.len = function () {
  3126. return this._len;
  3127. };
  3128. /**
  3129. * Clear list
  3130. */
  3131. linkedListProto.clear = function () {
  3132. this.head = this.tail = null;
  3133. this._len = 0;
  3134. };
  3135. /**
  3136. * @constructor
  3137. * @param {} val
  3138. */
  3139. var Entry = function (val) {
  3140. /**
  3141. * @type {}
  3142. */
  3143. this.value = val;
  3144. /**
  3145. * @type {module:zrender/core/LRU~Entry}
  3146. */
  3147. this.next;
  3148. /**
  3149. * @type {module:zrender/core/LRU~Entry}
  3150. */
  3151. this.prev;
  3152. };
  3153. /**
  3154. * LRU Cache
  3155. * @constructor
  3156. * @alias module:zrender/core/LRU
  3157. */
  3158. var LRU = function (maxSize) {
  3159. this._list = new LinkedList();
  3160. this._map = {};
  3161. this._maxSize = maxSize || 10;
  3162. this._lastRemovedEntry = null;
  3163. };
  3164. var LRUProto = LRU.prototype;
  3165. /**
  3166. * @param {string} key
  3167. * @param {} value
  3168. * @return {} Removed value
  3169. */
  3170. LRUProto.put = function (key, value) {
  3171. var list = this._list;
  3172. var map = this._map;
  3173. var removed = null;
  3174. if (map[key] == null) {
  3175. var len = list.len(); // Reuse last removed entry
  3176. var entry = this._lastRemovedEntry;
  3177. if (len >= this._maxSize && len > 0) {
  3178. // Remove the least recently used
  3179. var leastUsedEntry = list.head;
  3180. list.remove(leastUsedEntry);
  3181. delete map[leastUsedEntry.key];
  3182. removed = leastUsedEntry.value;
  3183. this._lastRemovedEntry = leastUsedEntry;
  3184. }
  3185. if (entry) {
  3186. entry.value = value;
  3187. } else {
  3188. entry = new Entry(value);
  3189. }
  3190. entry.key = key;
  3191. list.insertEntry(entry);
  3192. map[key] = entry;
  3193. }
  3194. return removed;
  3195. };
  3196. /**
  3197. * @param {string} key
  3198. * @return {}
  3199. */
  3200. LRUProto.get = function (key) {
  3201. var entry = this._map[key];
  3202. var list = this._list;
  3203. if (entry != null) {
  3204. // Put the latest used entry in the tail
  3205. if (entry !== list.tail) {
  3206. list.remove(entry);
  3207. list.insertEntry(entry);
  3208. }
  3209. return entry.value;
  3210. }
  3211. };
  3212. /**
  3213. * Clear the cache
  3214. */
  3215. LRUProto.clear = function () {
  3216. this._list.clear();
  3217. this._map = {};
  3218. };
  3219. var kCSSColorTable = {
  3220. 'transparent': [0, 0, 0, 0],
  3221. 'aliceblue': [240, 248, 255, 1],
  3222. 'antiquewhite': [250, 235, 215, 1],
  3223. 'aqua': [0, 255, 255, 1],
  3224. 'aquamarine': [127, 255, 212, 1],
  3225. 'azure': [240, 255, 255, 1],
  3226. 'beige': [245, 245, 220, 1],
  3227. 'bisque': [255, 228, 196, 1],
  3228. 'black': [0, 0, 0, 1],
  3229. 'blanchedalmond': [255, 235, 205, 1],
  3230. 'blue': [0, 0, 255, 1],
  3231. 'blueviolet': [138, 43, 226, 1],
  3232. 'brown': [165, 42, 42, 1],
  3233. 'burlywood': [222, 184, 135, 1],
  3234. 'cadetblue': [95, 158, 160, 1],
  3235. 'chartreuse': [127, 255, 0, 1],
  3236. 'chocolate': [210, 105, 30, 1],
  3237. 'coral': [255, 127, 80, 1],
  3238. 'cornflowerblue': [100, 149, 237, 1],
  3239. 'cornsilk': [255, 248, 220, 1],
  3240. 'crimson': [220, 20, 60, 1],
  3241. 'cyan': [0, 255, 255, 1],
  3242. 'darkblue': [0, 0, 139, 1],
  3243. 'darkcyan': [0, 139, 139, 1],
  3244. 'darkgoldenrod': [184, 134, 11, 1],
  3245. 'darkgray': [169, 169, 169, 1],
  3246. 'darkgreen': [0, 100, 0, 1],
  3247. 'darkgrey': [169, 169, 169, 1],
  3248. 'darkkhaki': [189, 183, 107, 1],
  3249. 'darkmagenta': [139, 0, 139, 1],
  3250. 'darkolivegreen': [85, 107, 47, 1],
  3251. 'darkorange': [255, 140, 0, 1],
  3252. 'darkorchid': [153, 50, 204, 1],
  3253. 'darkred': [139, 0, 0, 1],
  3254. 'darksalmon': [233, 150, 122, 1],
  3255. 'darkseagreen': [143, 188, 143, 1],
  3256. 'darkslateblue': [72, 61, 139, 1],
  3257. 'darkslategray': [47, 79, 79, 1],
  3258. 'darkslategrey': [47, 79, 79, 1],
  3259. 'darkturquoise': [0, 206, 209, 1],
  3260. 'darkviolet': [148, 0, 211, 1],
  3261. 'deeppink': [255, 20, 147, 1],
  3262. 'deepskyblue': [0, 191, 255, 1],
  3263. 'dimgray': [105, 105, 105, 1],
  3264. 'dimgrey': [105, 105, 105, 1],
  3265. 'dodgerblue': [30, 144, 255, 1],
  3266. 'firebrick': [178, 34, 34, 1],
  3267. 'floralwhite': [255, 250, 240, 1],
  3268. 'forestgreen': [34, 139, 34, 1],
  3269. 'fuchsia': [255, 0, 255, 1],
  3270. 'gainsboro': [220, 220, 220, 1],
  3271. 'ghostwhite': [248, 248, 255, 1],
  3272. 'gold': [255, 215, 0, 1],
  3273. 'goldenrod': [218, 165, 32, 1],
  3274. 'gray': [128, 128, 128, 1],
  3275. 'green': [0, 128, 0, 1],
  3276. 'greenyellow': [173, 255, 47, 1],
  3277. 'grey': [128, 128, 128, 1],
  3278. 'honeydew': [240, 255, 240, 1],
  3279. 'hotpink': [255, 105, 180, 1],
  3280. 'indianred': [205, 92, 92, 1],
  3281. 'indigo': [75, 0, 130, 1],
  3282. 'ivory': [255, 255, 240, 1],
  3283. 'khaki': [240, 230, 140, 1],
  3284. 'lavender': [230, 230, 250, 1],
  3285. 'lavenderblush': [255, 240, 245, 1],
  3286. 'lawngreen': [124, 252, 0, 1],
  3287. 'lemonchiffon': [255, 250, 205, 1],
  3288. 'lightblue': [173, 216, 230, 1],
  3289. 'lightcoral': [240, 128, 128, 1],
  3290. 'lightcyan': [224, 255, 255, 1],
  3291. 'lightgoldenrodyellow': [250, 250, 210, 1],
  3292. 'lightgray': [211, 211, 211, 1],
  3293. 'lightgreen': [144, 238, 144, 1],
  3294. 'lightgrey': [211, 211, 211, 1],
  3295. 'lightpink': [255, 182, 193, 1],
  3296. 'lightsalmon': [255, 160, 122, 1],
  3297. 'lightseagreen': [32, 178, 170, 1],
  3298. 'lightskyblue': [135, 206, 250, 1],
  3299. 'lightslategray': [119, 136, 153, 1],
  3300. 'lightslategrey': [119, 136, 153, 1],
  3301. 'lightsteelblue': [176, 196, 222, 1],
  3302. 'lightyellow': [255, 255, 224, 1],
  3303. 'lime': [0, 255, 0, 1],
  3304. 'limegreen': [50, 205, 50, 1],
  3305. 'linen': [250, 240, 230, 1],
  3306. 'magenta': [255, 0, 255, 1],
  3307. 'maroon': [128, 0, 0, 1],
  3308. 'mediumaquamarine': [102, 205, 170, 1],
  3309. 'mediumblue': [0, 0, 205, 1],
  3310. 'mediumorchid': [186, 85, 211, 1],
  3311. 'mediumpurple': [147, 112, 219, 1],
  3312. 'mediumseagreen': [60, 179, 113, 1],
  3313. 'mediumslateblue': [123, 104, 238, 1],
  3314. 'mediumspringgreen': [0, 250, 154, 1],
  3315. 'mediumturquoise': [72, 209, 204, 1],
  3316. 'mediumvioletred': [199, 21, 133, 1],
  3317. 'midnightblue': [25, 25, 112, 1],
  3318. 'mintcream': [245, 255, 250, 1],
  3319. 'mistyrose': [255, 228, 225, 1],
  3320. 'moccasin': [255, 228, 181, 1],
  3321. 'navajowhite': [255, 222, 173, 1],
  3322. 'navy': [0, 0, 128, 1],
  3323. 'oldlace': [253, 245, 230, 1],
  3324. 'olive': [128, 128, 0, 1],
  3325. 'olivedrab': [107, 142, 35, 1],
  3326. 'orange': [255, 165, 0, 1],
  3327. 'orangered': [255, 69, 0, 1],
  3328. 'orchid': [218, 112, 214, 1],
  3329. 'palegoldenrod': [238, 232, 170, 1],
  3330. 'palegreen': [152, 251, 152, 1],
  3331. 'paleturquoise': [175, 238, 238, 1],
  3332. 'palevioletred': [219, 112, 147, 1],
  3333. 'papayawhip': [255, 239, 213, 1],
  3334. 'peachpuff': [255, 218, 185, 1],
  3335. 'peru': [205, 133, 63, 1],
  3336. 'pink': [255, 192, 203, 1],
  3337. 'plum': [221, 160, 221, 1],
  3338. 'powderblue': [176, 224, 230, 1],
  3339. 'purple': [128, 0, 128, 1],
  3340. 'red': [255, 0, 0, 1],
  3341. 'rosybrown': [188, 143, 143, 1],
  3342. 'royalblue': [65, 105, 225, 1],
  3343. 'saddlebrown': [139, 69, 19, 1],
  3344. 'salmon': [250, 128, 114, 1],
  3345. 'sandybrown': [244, 164, 96, 1],
  3346. 'seagreen': [46, 139, 87, 1],
  3347. 'seashell': [255, 245, 238, 1],
  3348. 'sienna': [160, 82, 45, 1],
  3349. 'silver': [192, 192, 192, 1],
  3350. 'skyblue': [135, 206, 235, 1],
  3351. 'slateblue': [106, 90, 205, 1],
  3352. 'slategray': [112, 128, 144, 1],
  3353. 'slategrey': [112, 128, 144, 1],
  3354. 'snow': [255, 250, 250, 1],
  3355. 'springgreen': [0, 255, 127, 1],
  3356. 'steelblue': [70, 130, 180, 1],
  3357. 'tan': [210, 180, 140, 1],
  3358. 'teal': [0, 128, 128, 1],
  3359. 'thistle': [216, 191, 216, 1],
  3360. 'tomato': [255, 99, 71, 1],
  3361. 'turquoise': [64, 224, 208, 1],
  3362. 'violet': [238, 130, 238, 1],
  3363. 'wheat': [245, 222, 179, 1],
  3364. 'white': [255, 255, 255, 1],
  3365. 'whitesmoke': [245, 245, 245, 1],
  3366. 'yellow': [255, 255, 0, 1],
  3367. 'yellowgreen': [154, 205, 50, 1]
  3368. };
  3369. function clampCssByte(i) {
  3370. // Clamp to integer 0 .. 255.
  3371. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3372. return i < 0 ? 0 : i > 255 ? 255 : i;
  3373. }
  3374. function clampCssAngle(i) {
  3375. // Clamp to integer 0 .. 360.
  3376. i = Math.round(i); // Seems to be what Chrome does (vs truncation).
  3377. return i < 0 ? 0 : i > 360 ? 360 : i;
  3378. }
  3379. function clampCssFloat(f) {
  3380. // Clamp to float 0.0 .. 1.0.
  3381. return f < 0 ? 0 : f > 1 ? 1 : f;
  3382. }
  3383. function parseCssInt(str) {
  3384. // int or percentage.
  3385. if (str.length && str.charAt(str.length - 1) === '%') {
  3386. return clampCssByte(parseFloat(str) / 100 * 255);
  3387. }
  3388. return clampCssByte(parseInt(str, 10));
  3389. }
  3390. function parseCssFloat(str) {
  3391. // float or percentage.
  3392. if (str.length && str.charAt(str.length - 1) === '%') {
  3393. return clampCssFloat(parseFloat(str) / 100);
  3394. }
  3395. return clampCssFloat(parseFloat(str));
  3396. }
  3397. function cssHueToRgb(m1, m2, h) {
  3398. if (h < 0) {
  3399. h += 1;
  3400. } else if (h > 1) {
  3401. h -= 1;
  3402. }
  3403. if (h * 6 < 1) {
  3404. return m1 + (m2 - m1) * h * 6;
  3405. }
  3406. if (h * 2 < 1) {
  3407. return m2;
  3408. }
  3409. if (h * 3 < 2) {
  3410. return m1 + (m2 - m1) * (2 / 3 - h) * 6;
  3411. }
  3412. return m1;
  3413. }
  3414. function lerpNumber(a, b, p) {
  3415. return a + (b - a) * p;
  3416. }
  3417. function setRgba(out, r, g, b, a) {
  3418. out[0] = r;
  3419. out[1] = g;
  3420. out[2] = b;
  3421. out[3] = a;
  3422. return out;
  3423. }
  3424. function copyRgba(out, a) {
  3425. out[0] = a[0];
  3426. out[1] = a[1];
  3427. out[2] = a[2];
  3428. out[3] = a[3];
  3429. return out;
  3430. }
  3431. var colorCache = new LRU(20);
  3432. var lastRemovedArr = null;
  3433. function putToCache(colorStr, rgbaArr) {
  3434. // Reuse removed array
  3435. if (lastRemovedArr) {
  3436. copyRgba(lastRemovedArr, rgbaArr);
  3437. }
  3438. lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || rgbaArr.slice());
  3439. }
  3440. /**
  3441. * @param {string} colorStr
  3442. * @param {Array.<number>} out
  3443. * @return {Array.<number>}
  3444. * @memberOf module:zrender/util/color
  3445. */
  3446. function parse(colorStr, rgbaArr) {
  3447. if (!colorStr) {
  3448. return;
  3449. }
  3450. rgbaArr = rgbaArr || [];
  3451. var cached = colorCache.get(colorStr);
  3452. if (cached) {
  3453. return copyRgba(rgbaArr, cached);
  3454. } // colorStr may be not string
  3455. colorStr = colorStr + ''; // Remove all whitespace, not compliant, but should just be more accepting.
  3456. var str = colorStr.replace(/ /g, '').toLowerCase(); // Color keywords (and transparent) lookup.
  3457. if (str in kCSSColorTable) {
  3458. copyRgba(rgbaArr, kCSSColorTable[str]);
  3459. putToCache(colorStr, rgbaArr);
  3460. return rgbaArr;
  3461. } // #abc and #abc123 syntax.
  3462. if (str.charAt(0) === '#') {
  3463. if (str.length === 4) {
  3464. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3465. if (!(iv >= 0 && iv <= 0xfff)) {
  3466. setRgba(rgbaArr, 0, 0, 0, 1);
  3467. return; // Covers NaN.
  3468. }
  3469. setRgba(rgbaArr, (iv & 0xf00) >> 4 | (iv & 0xf00) >> 8, iv & 0xf0 | (iv & 0xf0) >> 4, iv & 0xf | (iv & 0xf) << 4, 1);
  3470. putToCache(colorStr, rgbaArr);
  3471. return rgbaArr;
  3472. } else if (str.length === 7) {
  3473. var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing.
  3474. if (!(iv >= 0 && iv <= 0xffffff)) {
  3475. setRgba(rgbaArr, 0, 0, 0, 1);
  3476. return; // Covers NaN.
  3477. }
  3478. setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, 1);
  3479. putToCache(colorStr, rgbaArr);
  3480. return rgbaArr;
  3481. }
  3482. return;
  3483. }
  3484. var op = str.indexOf('(');
  3485. var ep = str.indexOf(')');
  3486. if (op !== -1 && ep + 1 === str.length) {
  3487. var fname = str.substr(0, op);
  3488. var params = str.substr(op + 1, ep - (op + 1)).split(',');
  3489. var alpha = 1; // To allow case fallthrough.
  3490. switch (fname) {
  3491. case 'rgba':
  3492. if (params.length !== 4) {
  3493. setRgba(rgbaArr, 0, 0, 0, 1);
  3494. return;
  3495. }
  3496. alpha = parseCssFloat(params.pop());
  3497. // jshint ignore:line
  3498. // Fall through.
  3499. case 'rgb':
  3500. if (params.length !== 3) {
  3501. setRgba(rgbaArr, 0, 0, 0, 1);
  3502. return;
  3503. }
  3504. setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha);
  3505. putToCache(colorStr, rgbaArr);
  3506. return rgbaArr;
  3507. case 'hsla':
  3508. if (params.length !== 4) {
  3509. setRgba(rgbaArr, 0, 0, 0, 1);
  3510. return;
  3511. }
  3512. params[3] = parseCssFloat(params[3]);
  3513. hsla2rgba(params, rgbaArr);
  3514. putToCache(colorStr, rgbaArr);
  3515. return rgbaArr;
  3516. case 'hsl':
  3517. if (params.length !== 3) {
  3518. setRgba(rgbaArr, 0, 0, 0, 1);
  3519. return;
  3520. }
  3521. hsla2rgba(params, rgbaArr);
  3522. putToCache(colorStr, rgbaArr);
  3523. return rgbaArr;
  3524. default:
  3525. return;
  3526. }
  3527. }
  3528. setRgba(rgbaArr, 0, 0, 0, 1);
  3529. return;
  3530. }
  3531. /**
  3532. * @param {Array.<number>} hsla
  3533. * @param {Array.<number>} rgba
  3534. * @return {Array.<number>} rgba
  3535. */
  3536. function hsla2rgba(hsla, rgba) {
  3537. var h = (parseFloat(hsla[0]) % 360 + 360) % 360 / 360; // 0 .. 1
  3538. // NOTE(deanm): According to the CSS spec s/l should only be
  3539. // percentages, but we don't bother and let float or percentage.
  3540. var s = parseCssFloat(hsla[1]);
  3541. var l = parseCssFloat(hsla[2]);
  3542. var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s;
  3543. var m1 = l * 2 - m2;
  3544. rgba = rgba || [];
  3545. setRgba(rgba, clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255), 1);
  3546. if (hsla.length === 4) {
  3547. rgba[3] = hsla[3];
  3548. }
  3549. return rgba;
  3550. }
  3551. /**
  3552. * @param {Array.<number>} rgba
  3553. * @return {Array.<number>} hsla
  3554. */
  3555. function rgba2hsla(rgba) {
  3556. if (!rgba) {
  3557. return;
  3558. } // RGB from 0 to 255
  3559. var R = rgba[0] / 255;
  3560. var G = rgba[1] / 255;
  3561. var B = rgba[2] / 255;
  3562. var vMin = Math.min(R, G, B); // Min. value of RGB
  3563. var vMax = Math.max(R, G, B); // Max. value of RGB
  3564. var delta = vMax - vMin; // Delta RGB value
  3565. var L = (vMax + vMin) / 2;
  3566. var H;
  3567. var S; // HSL results from 0 to 1
  3568. if (delta === 0) {
  3569. H = 0;
  3570. S = 0;
  3571. } else {
  3572. if (L < 0.5) {
  3573. S = delta / (vMax + vMin);
  3574. } else {
  3575. S = delta / (2 - vMax - vMin);
  3576. }
  3577. var deltaR = ((vMax - R) / 6 + delta / 2) / delta;
  3578. var deltaG = ((vMax - G) / 6 + delta / 2) / delta;
  3579. var deltaB = ((vMax - B) / 6 + delta / 2) / delta;
  3580. if (R === vMax) {
  3581. H = deltaB - deltaG;
  3582. } else if (G === vMax) {
  3583. H = 1 / 3 + deltaR - deltaB;
  3584. } else if (B === vMax) {
  3585. H = 2 / 3 + deltaG - deltaR;
  3586. }
  3587. if (H < 0) {
  3588. H += 1;
  3589. }
  3590. if (H > 1) {
  3591. H -= 1;
  3592. }
  3593. }
  3594. var hsla = [H * 360, S, L];
  3595. if (rgba[3] != null) {
  3596. hsla.push(rgba[3]);
  3597. }
  3598. return hsla;
  3599. }
  3600. /**
  3601. * @param {string} color
  3602. * @param {number} level
  3603. * @return {string}
  3604. * @memberOf module:zrender/util/color
  3605. */
  3606. function lift(color, level) {
  3607. var colorArr = parse(color);
  3608. if (colorArr) {
  3609. for (var i = 0; i < 3; i++) {
  3610. if (level < 0) {
  3611. colorArr[i] = colorArr[i] * (1 - level) | 0;
  3612. } else {
  3613. colorArr[i] = (255 - colorArr[i]) * level + colorArr[i] | 0;
  3614. }
  3615. if (colorArr[i] > 255) {
  3616. colorArr[i] = 255;
  3617. } else if (color[i] < 0) {
  3618. colorArr[i] = 0;
  3619. }
  3620. }
  3621. return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb');
  3622. }
  3623. }
  3624. /**
  3625. * @param {string} color
  3626. * @return {string}
  3627. * @memberOf module:zrender/util/color
  3628. */
  3629. function toHex(color) {
  3630. var colorArr = parse(color);
  3631. if (colorArr) {
  3632. return ((1 << 24) + (colorArr[0] << 16) + (colorArr[1] << 8) + +colorArr[2]).toString(16).slice(1);
  3633. }
  3634. }
  3635. /**
  3636. * Map value to color. Faster than lerp methods because color is represented by rgba array.
  3637. * @param {number} normalizedValue A float between 0 and 1.
  3638. * @param {Array.<Array.<number>>} colors List of rgba color array
  3639. * @param {Array.<number>} [out] Mapped gba color array
  3640. * @return {Array.<number>} will be null/undefined if input illegal.
  3641. */
  3642. function fastLerp(normalizedValue, colors, out) {
  3643. if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3644. return;
  3645. }
  3646. out = out || [];
  3647. var value = normalizedValue * (colors.length - 1);
  3648. var leftIndex = Math.floor(value);
  3649. var rightIndex = Math.ceil(value);
  3650. var leftColor = colors[leftIndex];
  3651. var rightColor = colors[rightIndex];
  3652. var dv = value - leftIndex;
  3653. out[0] = clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv));
  3654. out[1] = clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv));
  3655. out[2] = clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv));
  3656. out[3] = clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv));
  3657. return out;
  3658. }
  3659. /**
  3660. * @deprecated
  3661. */
  3662. var fastMapToColor = fastLerp;
  3663. /**
  3664. * @param {number} normalizedValue A float between 0 and 1.
  3665. * @param {Array.<string>} colors Color list.
  3666. * @param {boolean=} fullOutput Default false.
  3667. * @return {(string|Object)} Result color. If fullOutput,
  3668. * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...},
  3669. * @memberOf module:zrender/util/color
  3670. */
  3671. function lerp$1(normalizedValue, colors, fullOutput) {
  3672. if (!(colors && colors.length) || !(normalizedValue >= 0 && normalizedValue <= 1)) {
  3673. return;
  3674. }
  3675. var value = normalizedValue * (colors.length - 1);
  3676. var leftIndex = Math.floor(value);
  3677. var rightIndex = Math.ceil(value);
  3678. var leftColor = parse(colors[leftIndex]);
  3679. var rightColor = parse(colors[rightIndex]);
  3680. var dv = value - leftIndex;
  3681. var color = stringify([clampCssByte(lerpNumber(leftColor[0], rightColor[0], dv)), clampCssByte(lerpNumber(leftColor[1], rightColor[1], dv)), clampCssByte(lerpNumber(leftColor[2], rightColor[2], dv)), clampCssFloat(lerpNumber(leftColor[3], rightColor[3], dv))], 'rgba');
  3682. return fullOutput ? {
  3683. color: color,
  3684. leftIndex: leftIndex,
  3685. rightIndex: rightIndex,
  3686. value: value
  3687. } : color;
  3688. }
  3689. /**
  3690. * @deprecated
  3691. */
  3692. var mapToColor = lerp$1;
  3693. /**
  3694. * @param {string} color
  3695. * @param {number=} h 0 ~ 360, ignore when null.
  3696. * @param {number=} s 0 ~ 1, ignore when null.
  3697. * @param {number=} l 0 ~ 1, ignore when null.
  3698. * @return {string} Color string in rgba format.
  3699. * @memberOf module:zrender/util/color
  3700. */
  3701. function modifyHSL(color, h, s, l) {
  3702. color = parse(color);
  3703. if (color) {
  3704. color = rgba2hsla(color);
  3705. h != null && (color[0] = clampCssAngle(h));
  3706. s != null && (color[1] = parseCssFloat(s));
  3707. l != null && (color[2] = parseCssFloat(l));
  3708. return stringify(hsla2rgba(color), 'rgba');
  3709. }
  3710. }
  3711. /**
  3712. * @param {string} color
  3713. * @param {number=} alpha 0 ~ 1
  3714. * @return {string} Color string in rgba format.
  3715. * @memberOf module:zrender/util/color
  3716. */
  3717. function modifyAlpha(color, alpha) {
  3718. color = parse(color);
  3719. if (color && alpha != null) {
  3720. color[3] = clampCssFloat(alpha);
  3721. return stringify(color, 'rgba');
  3722. }
  3723. }
  3724. /**
  3725. * @param {Array.<number>} arrColor like [12,33,44,0.4]
  3726. * @param {string} type 'rgba', 'hsva', ...
  3727. * @return {string} Result color. (If input illegal, return undefined).
  3728. */
  3729. function stringify(arrColor, type) {
  3730. if (!arrColor || !arrColor.length) {
  3731. return;
  3732. }
  3733. var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2];
  3734. if (type === 'rgba' || type === 'hsva' || type === 'hsla') {
  3735. colorStr += ',' + arrColor[3];
  3736. }
  3737. return type + '(' + colorStr + ')';
  3738. }
  3739. var color = (Object.freeze || Object)({
  3740. parse: parse,
  3741. lift: lift,
  3742. toHex: toHex,
  3743. fastLerp: fastLerp,
  3744. fastMapToColor: fastMapToColor,
  3745. lerp: lerp$1,
  3746. mapToColor: mapToColor,
  3747. modifyHSL: modifyHSL,
  3748. modifyAlpha: modifyAlpha,
  3749. stringify: stringify
  3750. });
  3751. /**
  3752. * @module echarts/animation/Animator
  3753. */
  3754. var arraySlice = Array.prototype.slice;
  3755. function defaultGetter(target, key) {
  3756. return target[key];
  3757. }
  3758. function defaultSetter(target, key, value) {
  3759. target[key] = value;
  3760. }
  3761. /**
  3762. * @param {number} p0
  3763. * @param {number} p1
  3764. * @param {number} percent
  3765. * @return {number}
  3766. */
  3767. function interpolateNumber(p0, p1, percent) {
  3768. return (p1 - p0) * percent + p0;
  3769. }
  3770. /**
  3771. * @param {string} p0
  3772. * @param {string} p1
  3773. * @param {number} percent
  3774. * @return {string}
  3775. */
  3776. function interpolateString(p0, p1, percent) {
  3777. return percent > 0.5 ? p1 : p0;
  3778. }
  3779. /**
  3780. * @param {Array} p0
  3781. * @param {Array} p1
  3782. * @param {number} percent
  3783. * @param {Array} out
  3784. * @param {number} arrDim
  3785. */
  3786. function interpolateArray(p0, p1, percent, out, arrDim) {
  3787. var len = p0.length;
  3788. if (arrDim === 1) {
  3789. for (var i = 0; i < len; i++) {
  3790. out[i] = interpolateNumber(p0[i], p1[i], percent);
  3791. }
  3792. } else {
  3793. var len2 = len && p0[0].length;
  3794. for (var i = 0; i < len; i++) {
  3795. for (var j = 0; j < len2; j++) {
  3796. out[i][j] = interpolateNumber(p0[i][j], p1[i][j], percent);
  3797. }
  3798. }
  3799. }
  3800. } // arr0 is source array, arr1 is target array.
  3801. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1
  3802. function fillArr(arr0, arr1, arrDim) {
  3803. var arr0Len = arr0.length;
  3804. var arr1Len = arr1.length;
  3805. if (arr0Len !== arr1Len) {
  3806. // FIXME Not work for TypedArray
  3807. var isPreviousLarger = arr0Len > arr1Len;
  3808. if (isPreviousLarger) {
  3809. // Cut the previous
  3810. arr0.length = arr1Len;
  3811. } else {
  3812. // Fill the previous
  3813. for (var i = arr0Len; i < arr1Len; i++) {
  3814. arr0.push(arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]));
  3815. }
  3816. }
  3817. } // Handling NaN value
  3818. var len2 = arr0[0] && arr0[0].length;
  3819. for (var i = 0; i < arr0.length; i++) {
  3820. if (arrDim === 1) {
  3821. if (isNaN(arr0[i])) {
  3822. arr0[i] = arr1[i];
  3823. }
  3824. } else {
  3825. for (var j = 0; j < len2; j++) {
  3826. if (isNaN(arr0[i][j])) {
  3827. arr0[i][j] = arr1[i][j];
  3828. }
  3829. }
  3830. }
  3831. }
  3832. }
  3833. /**
  3834. * @param {Array} arr0
  3835. * @param {Array} arr1
  3836. * @param {number} arrDim
  3837. * @return {boolean}
  3838. */
  3839. function isArraySame(arr0, arr1, arrDim) {
  3840. if (arr0 === arr1) {
  3841. return true;
  3842. }
  3843. var len = arr0.length;
  3844. if (len !== arr1.length) {
  3845. return false;
  3846. }
  3847. if (arrDim === 1) {
  3848. for (var i = 0; i < len; i++) {
  3849. if (arr0[i] !== arr1[i]) {
  3850. return false;
  3851. }
  3852. }
  3853. } else {
  3854. var len2 = arr0[0].length;
  3855. for (var i = 0; i < len; i++) {
  3856. for (var j = 0; j < len2; j++) {
  3857. if (arr0[i][j] !== arr1[i][j]) {
  3858. return false;
  3859. }
  3860. }
  3861. }
  3862. }
  3863. return true;
  3864. }
  3865. /**
  3866. * Catmull Rom interpolate array
  3867. * @param {Array} p0
  3868. * @param {Array} p1
  3869. * @param {Array} p2
  3870. * @param {Array} p3
  3871. * @param {number} t
  3872. * @param {number} t2
  3873. * @param {number} t3
  3874. * @param {Array} out
  3875. * @param {number} arrDim
  3876. */
  3877. function catmullRomInterpolateArray(p0, p1, p2, p3, t, t2, t3, out, arrDim) {
  3878. var len = p0.length;
  3879. if (arrDim === 1) {
  3880. for (var i = 0; i < len; i++) {
  3881. out[i] = catmullRomInterpolate(p0[i], p1[i], p2[i], p3[i], t, t2, t3);
  3882. }
  3883. } else {
  3884. var len2 = p0[0].length;
  3885. for (var i = 0; i < len; i++) {
  3886. for (var j = 0; j < len2; j++) {
  3887. out[i][j] = catmullRomInterpolate(p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3);
  3888. }
  3889. }
  3890. }
  3891. }
  3892. /**
  3893. * Catmull Rom interpolate number
  3894. * @param {number} p0
  3895. * @param {number} p1
  3896. * @param {number} p2
  3897. * @param {number} p3
  3898. * @param {number} t
  3899. * @param {number} t2
  3900. * @param {number} t3
  3901. * @return {number}
  3902. */
  3903. function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) {
  3904. var v0 = (p2 - p0) * 0.5;
  3905. var v1 = (p3 - p1) * 0.5;
  3906. return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1;
  3907. }
  3908. function cloneValue(value) {
  3909. if (isArrayLike(value)) {
  3910. var len = value.length;
  3911. if (isArrayLike(value[0])) {
  3912. var ret = [];
  3913. for (var i = 0; i < len; i++) {
  3914. ret.push(arraySlice.call(value[i]));
  3915. }
  3916. return ret;
  3917. }
  3918. return arraySlice.call(value);
  3919. }
  3920. return value;
  3921. }
  3922. function rgba2String(rgba) {
  3923. rgba[0] = Math.floor(rgba[0]);
  3924. rgba[1] = Math.floor(rgba[1]);
  3925. rgba[2] = Math.floor(rgba[2]);
  3926. return 'rgba(' + rgba.join(',') + ')';
  3927. }
  3928. function getArrayDim(keyframes) {
  3929. var lastValue = keyframes[keyframes.length - 1].value;
  3930. return isArrayLike(lastValue && lastValue[0]) ? 2 : 1;
  3931. }
  3932. function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) {
  3933. var getter = animator._getter;
  3934. var setter = animator._setter;
  3935. var useSpline = easing === 'spline';
  3936. var trackLen = keyframes.length;
  3937. if (!trackLen) {
  3938. return;
  3939. } // Guess data type
  3940. var firstVal = keyframes[0].value;
  3941. var isValueArray = isArrayLike(firstVal);
  3942. var isValueColor = false;
  3943. var isValueString = false; // For vertices morphing
  3944. var arrDim = isValueArray ? getArrayDim(keyframes) : 0;
  3945. var trackMaxTime; // Sort keyframe as ascending
  3946. keyframes.sort(function (a, b) {
  3947. return a.time - b.time;
  3948. });
  3949. trackMaxTime = keyframes[trackLen - 1].time; // Percents of each keyframe
  3950. var kfPercents = []; // Value of each keyframe
  3951. var kfValues = [];
  3952. var prevValue = keyframes[0].value;
  3953. var isAllValueEqual = true;
  3954. for (var i = 0; i < trackLen; i++) {
  3955. kfPercents.push(keyframes[i].time / trackMaxTime); // Assume value is a color when it is a string
  3956. var value = keyframes[i].value; // Check if value is equal, deep check if value is array
  3957. if (!(isValueArray && isArraySame(value, prevValue, arrDim) || !isValueArray && value === prevValue)) {
  3958. isAllValueEqual = false;
  3959. }
  3960. prevValue = value; // Try converting a string to a color array
  3961. if (typeof value === 'string') {
  3962. var colorArray = parse(value);
  3963. if (colorArray) {
  3964. value = colorArray;
  3965. isValueColor = true;
  3966. } else {
  3967. isValueString = true;
  3968. }
  3969. }
  3970. kfValues.push(value);
  3971. }
  3972. if (!forceAnimate && isAllValueEqual) {
  3973. return;
  3974. }
  3975. var lastValue = kfValues[trackLen - 1]; // Polyfill array and NaN value
  3976. for (var i = 0; i < trackLen - 1; i++) {
  3977. if (isValueArray) {
  3978. fillArr(kfValues[i], lastValue, arrDim);
  3979. } else {
  3980. if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) {
  3981. kfValues[i] = lastValue;
  3982. }
  3983. }
  3984. }
  3985. isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim); // Cache the key of last frame to speed up when
  3986. // animation playback is sequency
  3987. var lastFrame = 0;
  3988. var lastFramePercent = 0;
  3989. var start;
  3990. var w;
  3991. var p0;
  3992. var p1;
  3993. var p2;
  3994. var p3;
  3995. if (isValueColor) {
  3996. var rgba = [0, 0, 0, 0];
  3997. }
  3998. var onframe = function (target, percent) {
  3999. // Find the range keyframes
  4000. // kf1-----kf2---------current--------kf3
  4001. // find kf2 and kf3 and do interpolation
  4002. var frame; // In the easing function like elasticOut, percent may less than 0
  4003. if (percent < 0) {
  4004. frame = 0;
  4005. } else if (percent < lastFramePercent) {
  4006. // Start from next key
  4007. // PENDING start from lastFrame ?
  4008. start = Math.min(lastFrame + 1, trackLen - 1);
  4009. for (frame = start; frame >= 0; frame--) {
  4010. if (kfPercents[frame] <= percent) {
  4011. break;
  4012. }
  4013. } // PENDING really need to do this ?
  4014. frame = Math.min(frame, trackLen - 2);
  4015. } else {
  4016. for (frame = lastFrame; frame < trackLen; frame++) {
  4017. if (kfPercents[frame] > percent) {
  4018. break;
  4019. }
  4020. }
  4021. frame = Math.min(frame - 1, trackLen - 2);
  4022. }
  4023. lastFrame = frame;
  4024. lastFramePercent = percent;
  4025. var range = kfPercents[frame + 1] - kfPercents[frame];
  4026. if (range === 0) {
  4027. return;
  4028. } else {
  4029. w = (percent - kfPercents[frame]) / range;
  4030. }
  4031. if (useSpline) {
  4032. p1 = kfValues[frame];
  4033. p0 = kfValues[frame === 0 ? frame : frame - 1];
  4034. p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1];
  4035. p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2];
  4036. if (isValueArray) {
  4037. catmullRomInterpolateArray(p0, p1, p2, p3, w, w * w, w * w * w, getter(target, propName), arrDim);
  4038. } else {
  4039. var value;
  4040. if (isValueColor) {
  4041. value = catmullRomInterpolateArray(p0, p1, p2, p3, w, w * w, w * w * w, rgba, 1);
  4042. value = rgba2String(rgba);
  4043. } else if (isValueString) {
  4044. // String is step(0.5)
  4045. return interpolateString(p1, p2, w);
  4046. } else {
  4047. value = catmullRomInterpolate(p0, p1, p2, p3, w, w * w, w * w * w);
  4048. }
  4049. setter(target, propName, value);
  4050. }
  4051. } else {
  4052. if (isValueArray) {
  4053. interpolateArray(kfValues[frame], kfValues[frame + 1], w, getter(target, propName), arrDim);
  4054. } else {
  4055. var value;
  4056. if (isValueColor) {
  4057. interpolateArray(kfValues[frame], kfValues[frame + 1], w, rgba, 1);
  4058. value = rgba2String(rgba);
  4059. } else if (isValueString) {
  4060. // String is step(0.5)
  4061. return interpolateString(kfValues[frame], kfValues[frame + 1], w);
  4062. } else {
  4063. value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w);
  4064. }
  4065. setter(target, propName, value);
  4066. }
  4067. }
  4068. };
  4069. var clip = new Clip({
  4070. target: animator._target,
  4071. life: trackMaxTime,
  4072. loop: animator._loop,
  4073. delay: animator._delay,
  4074. onframe: onframe,
  4075. ondestroy: oneTrackDone
  4076. });
  4077. if (easing && easing !== 'spline') {
  4078. clip.easing = easing;
  4079. }
  4080. return clip;
  4081. }
  4082. /**
  4083. * @alias module:zrender/animation/Animator
  4084. * @constructor
  4085. * @param {Object} target
  4086. * @param {boolean} loop
  4087. * @param {Function} getter
  4088. * @param {Function} setter
  4089. */
  4090. var Animator = function (target, loop, getter, setter) {
  4091. this._tracks = {};
  4092. this._target = target;
  4093. this._loop = loop || false;
  4094. this._getter = getter || defaultGetter;
  4095. this._setter = setter || defaultSetter;
  4096. this._clipCount = 0;
  4097. this._delay = 0;
  4098. this._doneList = [];
  4099. this._onframeList = [];
  4100. this._clipList = [];
  4101. };
  4102. Animator.prototype = {
  4103. /**
  4104. * Set Animation keyframe
  4105. * @param {number} time 关键帧时间,单位是ms
  4106. * @param {Object} props 关键帧的属性值,key-value表示
  4107. * @return {module:zrender/animation/Animator}
  4108. */
  4109. when: function (time
  4110. /* ms */
  4111. , props) {
  4112. var tracks = this._tracks;
  4113. for (var propName in props) {
  4114. if (!props.hasOwnProperty(propName)) {
  4115. continue;
  4116. }
  4117. if (!tracks[propName]) {
  4118. tracks[propName] = []; // Invalid value
  4119. var value = this._getter(this._target, propName);
  4120. if (value == null) {
  4121. // zrLog('Invalid property ' + propName);
  4122. continue;
  4123. } // If time is 0
  4124. // Then props is given initialize value
  4125. // Else
  4126. // Initialize value from current prop value
  4127. if (time !== 0) {
  4128. tracks[propName].push({
  4129. time: 0,
  4130. value: cloneValue(value)
  4131. });
  4132. }
  4133. }
  4134. tracks[propName].push({
  4135. time: time,
  4136. value: props[propName]
  4137. });
  4138. }
  4139. return this;
  4140. },
  4141. /**
  4142. * 添加动画每一帧的回调函数
  4143. * @param {Function} callback
  4144. * @return {module:zrender/animation/Animator}
  4145. */
  4146. during: function (callback) {
  4147. this._onframeList.push(callback);
  4148. return this;
  4149. },
  4150. pause: function () {
  4151. for (var i = 0; i < this._clipList.length; i++) {
  4152. this._clipList[i].pause();
  4153. }
  4154. this._paused = true;
  4155. },
  4156. resume: function () {
  4157. for (var i = 0; i < this._clipList.length; i++) {
  4158. this._clipList[i].resume();
  4159. }
  4160. this._paused = false;
  4161. },
  4162. isPaused: function () {
  4163. return !!this._paused;
  4164. },
  4165. _doneCallback: function () {
  4166. // Clear all tracks
  4167. this._tracks = {}; // Clear all clips
  4168. this._clipList.length = 0;
  4169. var doneList = this._doneList;
  4170. var len = doneList.length;
  4171. for (var i = 0; i < len; i++) {
  4172. doneList[i].call(this);
  4173. }
  4174. },
  4175. /**
  4176. * Start the animation
  4177. * @param {string|Function} [easing]
  4178. * 动画缓动函数,详见{@link module:zrender/animation/easing}
  4179. * @param {boolean} forceAnimate
  4180. * @return {module:zrender/animation/Animator}
  4181. */
  4182. start: function (easing, forceAnimate) {
  4183. var self = this;
  4184. var clipCount = 0;
  4185. var oneTrackDone = function () {
  4186. clipCount--;
  4187. if (!clipCount) {
  4188. self._doneCallback();
  4189. }
  4190. };
  4191. var lastClip;
  4192. for (var propName in this._tracks) {
  4193. if (!this._tracks.hasOwnProperty(propName)) {
  4194. continue;
  4195. }
  4196. var clip = createTrackClip(this, easing, oneTrackDone, this._tracks[propName], propName, forceAnimate);
  4197. if (clip) {
  4198. this._clipList.push(clip);
  4199. clipCount++; // If start after added to animation
  4200. if (this.animation) {
  4201. this.animation.addClip(clip);
  4202. }
  4203. lastClip = clip;
  4204. }
  4205. } // Add during callback on the last clip
  4206. if (lastClip) {
  4207. var oldOnFrame = lastClip.onframe;
  4208. lastClip.onframe = function (target, percent) {
  4209. oldOnFrame(target, percent);
  4210. for (var i = 0; i < self._onframeList.length; i++) {
  4211. self._onframeList[i](target, percent);
  4212. }
  4213. };
  4214. } // This optimization will help the case that in the upper application
  4215. // the view may be refreshed frequently, where animation will be
  4216. // called repeatly but nothing changed.
  4217. if (!clipCount) {
  4218. this._doneCallback();
  4219. }
  4220. return this;
  4221. },
  4222. /**
  4223. * Stop animation
  4224. * @param {boolean} forwardToLast If move to last frame before stop
  4225. */
  4226. stop: function (forwardToLast) {
  4227. var clipList = this._clipList;
  4228. var animation = this.animation;
  4229. for (var i = 0; i < clipList.length; i++) {
  4230. var clip = clipList[i];
  4231. if (forwardToLast) {
  4232. // Move to last frame before stop
  4233. clip.onframe(this._target, 1);
  4234. }
  4235. animation && animation.removeClip(clip);
  4236. }
  4237. clipList.length = 0;
  4238. },
  4239. /**
  4240. * Set when animation delay starts
  4241. * @param {number} time 单位ms
  4242. * @return {module:zrender/animation/Animator}
  4243. */
  4244. delay: function (time) {
  4245. this._delay = time;
  4246. return this;
  4247. },
  4248. /**
  4249. * Add callback for animation end
  4250. * @param {Function} cb
  4251. * @return {module:zrender/animation/Animator}
  4252. */
  4253. done: function (cb) {
  4254. if (cb) {
  4255. this._doneList.push(cb);
  4256. }
  4257. return this;
  4258. },
  4259. /**
  4260. * @return {Array.<module:zrender/animation/Clip>}
  4261. */
  4262. getClips: function () {
  4263. return this._clipList;
  4264. }
  4265. };
  4266. var dpr = 1; // If in browser environment
  4267. if (typeof window !== 'undefined') {
  4268. dpr = Math.max(window.devicePixelRatio || 1, 1);
  4269. }
  4270. /**
  4271. * config默认配置项
  4272. * @exports zrender/config
  4273. * @author Kener (@Kener-林峰, kener.linfeng@gmail.com)
  4274. */
  4275. /**
  4276. * Debug log mode:
  4277. * 0: Do nothing, for release.
  4278. * 1: console.error, for debug.
  4279. */
  4280. var debugMode = 0; // retina 屏幕优化
  4281. var devicePixelRatio = dpr;
  4282. var logError = function () {};
  4283. if (debugMode === 1) {
  4284. logError = console.error;
  4285. }
  4286. var logError$1 = logError;
  4287. /**
  4288. * @alias module:zrender/mixin/Animatable
  4289. * @constructor
  4290. */
  4291. var Animatable = function () {
  4292. /**
  4293. * @type {Array.<module:zrender/animation/Animator>}
  4294. * @readOnly
  4295. */
  4296. this.animators = [];
  4297. };
  4298. Animatable.prototype = {
  4299. constructor: Animatable,
  4300. /**
  4301. * 动画
  4302. *
  4303. * @param {string} path The path to fetch value from object, like 'a.b.c'.
  4304. * @param {boolean} [loop] Whether to loop animation.
  4305. * @return {module:zrender/animation/Animator}
  4306. * @example:
  4307. * el.animate('style', false)
  4308. * .when(1000, {x: 10} )
  4309. * .done(function(){ // Animation done })
  4310. * .start()
  4311. */
  4312. animate: function (path, loop) {
  4313. var target;
  4314. var animatingShape = false;
  4315. var el = this;
  4316. var zr = this.__zr;
  4317. if (path) {
  4318. var pathSplitted = path.split('.');
  4319. var prop = el; // If animating shape
  4320. animatingShape = pathSplitted[0] === 'shape';
  4321. for (var i = 0, l = pathSplitted.length; i < l; i++) {
  4322. if (!prop) {
  4323. continue;
  4324. }
  4325. prop = prop[pathSplitted[i]];
  4326. }
  4327. if (prop) {
  4328. target = prop;
  4329. }
  4330. } else {
  4331. target = el;
  4332. }
  4333. if (!target) {
  4334. logError$1('Property "' + path + '" is not existed in element ' + el.id);
  4335. return;
  4336. }
  4337. var animators = el.animators;
  4338. var animator = new Animator(target, loop);
  4339. animator.during(function (target) {
  4340. el.dirty(animatingShape);
  4341. }).done(function () {
  4342. // FIXME Animator will not be removed if use `Animator#stop` to stop animation
  4343. animators.splice(indexOf(animators, animator), 1);
  4344. });
  4345. animators.push(animator); // If animate after added to the zrender
  4346. if (zr) {
  4347. zr.animation.addAnimator(animator);
  4348. }
  4349. return animator;
  4350. },
  4351. /**
  4352. * 停止动画
  4353. * @param {boolean} forwardToLast If move to last frame before stop
  4354. */
  4355. stopAnimation: function (forwardToLast) {
  4356. var animators = this.animators;
  4357. var len = animators.length;
  4358. for (var i = 0; i < len; i++) {
  4359. animators[i].stop(forwardToLast);
  4360. }
  4361. animators.length = 0;
  4362. return this;
  4363. },
  4364. /**
  4365. * Caution: this method will stop previous animation.
  4366. * So do not use this method to one element twice before
  4367. * animation starts, unless you know what you are doing.
  4368. * @param {Object} target
  4369. * @param {number} [time=500] Time in ms
  4370. * @param {string} [easing='linear']
  4371. * @param {number} [delay=0]
  4372. * @param {Function} [callback]
  4373. * @param {Function} [forceAnimate] Prevent stop animation and callback
  4374. * immediently when target values are the same as current values.
  4375. *
  4376. * @example
  4377. * // Animate position
  4378. * el.animateTo({
  4379. * position: [10, 10]
  4380. * }, function () { // done })
  4381. *
  4382. * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing
  4383. * el.animateTo({
  4384. * shape: {
  4385. * width: 500
  4386. * },
  4387. * style: {
  4388. * fill: 'red'
  4389. * }
  4390. * position: [10, 10]
  4391. * }, 100, 100, 'cubicOut', function () { // done })
  4392. */
  4393. // TODO Return animation key
  4394. animateTo: function (target, time, delay, easing, callback, forceAnimate) {
  4395. animateTo(this, target, time, delay, easing, callback, forceAnimate);
  4396. },
  4397. /**
  4398. * Animate from the target state to current state.
  4399. * The params and the return value are the same as `this.animateTo`.
  4400. */
  4401. animateFrom: function (target, time, delay, easing, callback, forceAnimate) {
  4402. animateTo(this, target, time, delay, easing, callback, forceAnimate, true);
  4403. }
  4404. };
  4405. function animateTo(animatable, target, time, delay, easing, callback, forceAnimate, reverse) {
  4406. // animateTo(target, time, easing, callback);
  4407. if (isString(delay)) {
  4408. callback = easing;
  4409. easing = delay;
  4410. delay = 0;
  4411. } // animateTo(target, time, delay, callback);
  4412. else if (isFunction$1(easing)) {
  4413. callback = easing;
  4414. easing = 'linear';
  4415. delay = 0;
  4416. } // animateTo(target, time, callback);
  4417. else if (isFunction$1(delay)) {
  4418. callback = delay;
  4419. delay = 0;
  4420. } // animateTo(target, callback)
  4421. else if (isFunction$1(time)) {
  4422. callback = time;
  4423. time = 500;
  4424. } // animateTo(target)
  4425. else if (!time) {
  4426. time = 500;
  4427. } // Stop all previous animations
  4428. animatable.stopAnimation();
  4429. animateToShallow(animatable, '', animatable, target, time, delay, reverse); // Animators may be removed immediately after start
  4430. // if there is nothing to animate
  4431. var animators = animatable.animators.slice();
  4432. var count = animators.length;
  4433. function done() {
  4434. count--;
  4435. if (!count) {
  4436. callback && callback();
  4437. }
  4438. } // No animators. This should be checked before animators[i].start(),
  4439. // because 'done' may be executed immediately if no need to animate.
  4440. if (!count) {
  4441. callback && callback();
  4442. } // Start after all animators created
  4443. // Incase any animator is done immediately when all animation properties are not changed
  4444. for (var i = 0; i < animators.length; i++) {
  4445. animators[i].done(done).start(easing, forceAnimate);
  4446. }
  4447. }
  4448. /**
  4449. * @param {string} path=''
  4450. * @param {Object} source=animatable
  4451. * @param {Object} target
  4452. * @param {number} [time=500]
  4453. * @param {number} [delay=0]
  4454. * @param {boolean} [reverse] If `true`, animate
  4455. * from the `target` to current state.
  4456. *
  4457. * @example
  4458. * // Animate position
  4459. * el._animateToShallow({
  4460. * position: [10, 10]
  4461. * })
  4462. *
  4463. * // Animate shape, style and position in 100ms, delayed 100ms
  4464. * el._animateToShallow({
  4465. * shape: {
  4466. * width: 500
  4467. * },
  4468. * style: {
  4469. * fill: 'red'
  4470. * }
  4471. * position: [10, 10]
  4472. * }, 100, 100)
  4473. */
  4474. function animateToShallow(animatable, path, source, target, time, delay, reverse) {
  4475. var objShallow = {};
  4476. var propertyCount = 0;
  4477. for (var name in target) {
  4478. if (!target.hasOwnProperty(name)) {
  4479. continue;
  4480. }
  4481. if (source[name] != null) {
  4482. if (isObject$1(target[name]) && !isArrayLike(target[name])) {
  4483. animateToShallow(animatable, path ? path + '.' + name : name, source[name], target[name], time, delay, reverse);
  4484. } else {
  4485. if (reverse) {
  4486. objShallow[name] = source[name];
  4487. setAttrByPath(animatable, path, name, target[name]);
  4488. } else {
  4489. objShallow[name] = target[name];
  4490. }
  4491. propertyCount++;
  4492. }
  4493. } else if (target[name] != null && !reverse) {
  4494. setAttrByPath(animatable, path, name, target[name]);
  4495. }
  4496. }
  4497. if (propertyCount > 0) {
  4498. animatable.animate(path, false).when(time == null ? 500 : time, objShallow).delay(delay || 0);
  4499. }
  4500. }
  4501. function setAttrByPath(el, path, name, value) {
  4502. // Attr directly if not has property
  4503. // FIXME, if some property not needed for element ?
  4504. if (!path) {
  4505. el.attr(name, value);
  4506. } else {
  4507. // Only support set shape or style
  4508. var props = {};
  4509. props[path] = {};
  4510. props[path][name] = value;
  4511. el.attr(props);
  4512. }
  4513. }
  4514. /**
  4515. * @alias module:zrender/Element
  4516. * @constructor
  4517. * @extends {module:zrender/mixin/Animatable}
  4518. * @extends {module:zrender/mixin/Transformable}
  4519. * @extends {module:zrender/mixin/Eventful}
  4520. */
  4521. var Element = function (opts) {
  4522. // jshint ignore:line
  4523. Transformable.call(this, opts);
  4524. Eventful.call(this, opts);
  4525. Animatable.call(this, opts);
  4526. /**
  4527. * 画布元素ID
  4528. * @type {string}
  4529. */
  4530. this.id = opts.id || guid();
  4531. };
  4532. Element.prototype = {
  4533. /**
  4534. * 元素类型
  4535. * Element type
  4536. * @type {string}
  4537. */
  4538. type: 'element',
  4539. /**
  4540. * 元素名字
  4541. * Element name
  4542. * @type {string}
  4543. */
  4544. name: '',
  4545. /**
  4546. * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值
  4547. * ZRender instance will be assigned when element is associated with zrender
  4548. * @name module:/zrender/Element#__zr
  4549. * @type {module:zrender/ZRender}
  4550. */
  4551. __zr: null,
  4552. /**
  4553. * 图形是否忽略,为true时忽略图形的绘制以及事件触发
  4554. * If ignore drawing and events of the element object
  4555. * @name module:/zrender/Element#ignore
  4556. * @type {boolean}
  4557. * @default false
  4558. */
  4559. ignore: false,
  4560. /**
  4561. * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪
  4562. * 该路径会继承被裁减对象的变换
  4563. * @type {module:zrender/graphic/Path}
  4564. * @see http://www.w3.org/TR/2dcontext/#clipping-region
  4565. * @readOnly
  4566. */
  4567. clipPath: null,
  4568. /**
  4569. * 是否是 Group
  4570. * @type {boolean}
  4571. */
  4572. isGroup: false,
  4573. /**
  4574. * Drift element
  4575. * @param {number} dx dx on the global space
  4576. * @param {number} dy dy on the global space
  4577. */
  4578. drift: function (dx, dy) {
  4579. switch (this.draggable) {
  4580. case 'horizontal':
  4581. dy = 0;
  4582. break;
  4583. case 'vertical':
  4584. dx = 0;
  4585. break;
  4586. }
  4587. var m = this.transform;
  4588. if (!m) {
  4589. m = this.transform = [1, 0, 0, 1, 0, 0];
  4590. }
  4591. m[4] += dx;
  4592. m[5] += dy;
  4593. this.decomposeTransform();
  4594. this.dirty(false);
  4595. },
  4596. /**
  4597. * Hook before update
  4598. */
  4599. beforeUpdate: function () {},
  4600. /**
  4601. * Hook after update
  4602. */
  4603. afterUpdate: function () {},
  4604. /**
  4605. * Update each frame
  4606. */
  4607. update: function () {
  4608. this.updateTransform();
  4609. },
  4610. /**
  4611. * @param {Function} cb
  4612. * @param {} context
  4613. */
  4614. traverse: function (cb, context) {},
  4615. /**
  4616. * @protected
  4617. */
  4618. attrKV: function (key, value) {
  4619. if (key === 'position' || key === 'scale' || key === 'origin') {
  4620. // Copy the array
  4621. if (value) {
  4622. var target = this[key];
  4623. if (!target) {
  4624. target = this[key] = [];
  4625. }
  4626. target[0] = value[0];
  4627. target[1] = value[1];
  4628. }
  4629. } else {
  4630. this[key] = value;
  4631. }
  4632. },
  4633. /**
  4634. * Hide the element
  4635. */
  4636. hide: function () {
  4637. this.ignore = true;
  4638. this.__zr && this.__zr.refresh();
  4639. },
  4640. /**
  4641. * Show the element
  4642. */
  4643. show: function () {
  4644. this.ignore = false;
  4645. this.__zr && this.__zr.refresh();
  4646. },
  4647. /**
  4648. * @param {string|Object} key
  4649. * @param {*} value
  4650. */
  4651. attr: function (key, value) {
  4652. if (typeof key === 'string') {
  4653. this.attrKV(key, value);
  4654. } else if (isObject$1(key)) {
  4655. for (var name in key) {
  4656. if (key.hasOwnProperty(name)) {
  4657. this.attrKV(name, key[name]);
  4658. }
  4659. }
  4660. }
  4661. this.dirty(false);
  4662. return this;
  4663. },
  4664. /**
  4665. * @param {module:zrender/graphic/Path} clipPath
  4666. */
  4667. setClipPath: function (clipPath) {
  4668. var zr = this.__zr;
  4669. if (zr) {
  4670. clipPath.addSelfToZr(zr);
  4671. } // Remove previous clip path
  4672. if (this.clipPath && this.clipPath !== clipPath) {
  4673. this.removeClipPath();
  4674. }
  4675. this.clipPath = clipPath;
  4676. clipPath.__zr = zr;
  4677. clipPath.__clipTarget = this;
  4678. this.dirty(false);
  4679. },
  4680. /**
  4681. */
  4682. removeClipPath: function () {
  4683. var clipPath = this.clipPath;
  4684. if (clipPath) {
  4685. if (clipPath.__zr) {
  4686. clipPath.removeSelfFromZr(clipPath.__zr);
  4687. }
  4688. clipPath.__zr = null;
  4689. clipPath.__clipTarget = null;
  4690. this.clipPath = null;
  4691. this.dirty(false);
  4692. }
  4693. },
  4694. /**
  4695. * Add self from zrender instance.
  4696. * Not recursively because it will be invoked when element added to storage.
  4697. * @param {module:zrender/ZRender} zr
  4698. */
  4699. addSelfToZr: function (zr) {
  4700. this.__zr = zr; // 添加动画
  4701. var animators = this.animators;
  4702. if (animators) {
  4703. for (var i = 0; i < animators.length; i++) {
  4704. zr.animation.addAnimator(animators[i]);
  4705. }
  4706. }
  4707. if (this.clipPath) {
  4708. this.clipPath.addSelfToZr(zr);
  4709. }
  4710. },
  4711. /**
  4712. * Remove self from zrender instance.
  4713. * Not recursively because it will be invoked when element added to storage.
  4714. * @param {module:zrender/ZRender} zr
  4715. */
  4716. removeSelfFromZr: function (zr) {
  4717. this.__zr = null; // 移除动画
  4718. var animators = this.animators;
  4719. if (animators) {
  4720. for (var i = 0; i < animators.length; i++) {
  4721. zr.animation.removeAnimator(animators[i]);
  4722. }
  4723. }
  4724. if (this.clipPath) {
  4725. this.clipPath.removeSelfFromZr(zr);
  4726. }
  4727. }
  4728. };
  4729. mixin(Element, Animatable);
  4730. mixin(Element, Transformable);
  4731. mixin(Element, Eventful);
  4732. /**
  4733. * @module echarts/core/BoundingRect
  4734. */
  4735. var v2ApplyTransform = applyTransform;
  4736. var mathMin = Math.min;
  4737. var mathMax = Math.max;
  4738. /**
  4739. * @alias module:echarts/core/BoundingRect
  4740. */
  4741. function BoundingRect(x, y, width, height) {
  4742. if (width < 0) {
  4743. x = x + width;
  4744. width = -width;
  4745. }
  4746. if (height < 0) {
  4747. y = y + height;
  4748. height = -height;
  4749. }
  4750. /**
  4751. * @type {number}
  4752. */
  4753. this.x = x;
  4754. /**
  4755. * @type {number}
  4756. */
  4757. this.y = y;
  4758. /**
  4759. * @type {number}
  4760. */
  4761. this.width = width;
  4762. /**
  4763. * @type {number}
  4764. */
  4765. this.height = height;
  4766. }
  4767. BoundingRect.prototype = {
  4768. constructor: BoundingRect,
  4769. /**
  4770. * @param {module:echarts/core/BoundingRect} other
  4771. */
  4772. union: function (other) {
  4773. var x = mathMin(other.x, this.x);
  4774. var y = mathMin(other.y, this.y);
  4775. this.width = mathMax(other.x + other.width, this.x + this.width) - x;
  4776. this.height = mathMax(other.y + other.height, this.y + this.height) - y;
  4777. this.x = x;
  4778. this.y = y;
  4779. },
  4780. /**
  4781. * @param {Array.<number>} m
  4782. * @methods
  4783. */
  4784. applyTransform: function () {
  4785. var lt = [];
  4786. var rb = [];
  4787. var lb = [];
  4788. var rt = [];
  4789. return function (m) {
  4790. // In case usage like this
  4791. // el.getBoundingRect().applyTransform(el.transform)
  4792. // And element has no transform
  4793. if (!m) {
  4794. return;
  4795. }
  4796. lt[0] = lb[0] = this.x;
  4797. lt[1] = rt[1] = this.y;
  4798. rb[0] = rt[0] = this.x + this.width;
  4799. rb[1] = lb[1] = this.y + this.height;
  4800. v2ApplyTransform(lt, lt, m);
  4801. v2ApplyTransform(rb, rb, m);
  4802. v2ApplyTransform(lb, lb, m);
  4803. v2ApplyTransform(rt, rt, m);
  4804. this.x = mathMin(lt[0], rb[0], lb[0], rt[0]);
  4805. this.y = mathMin(lt[1], rb[1], lb[1], rt[1]);
  4806. var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]);
  4807. var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]);
  4808. this.width = maxX - this.x;
  4809. this.height = maxY - this.y;
  4810. };
  4811. }(),
  4812. /**
  4813. * Calculate matrix of transforming from self to target rect
  4814. * @param {module:zrender/core/BoundingRect} b
  4815. * @return {Array.<number>}
  4816. */
  4817. calculateTransform: function (b) {
  4818. var a = this;
  4819. var sx = b.width / a.width;
  4820. var sy = b.height / a.height;
  4821. var m = create$1(); // 矩阵右乘
  4822. translate(m, m, [-a.x, -a.y]);
  4823. scale$1(m, m, [sx, sy]);
  4824. translate(m, m, [b.x, b.y]);
  4825. return m;
  4826. },
  4827. /**
  4828. * @param {(module:echarts/core/BoundingRect|Object)} b
  4829. * @return {boolean}
  4830. */
  4831. intersect: function (b) {
  4832. if (!b) {
  4833. return false;
  4834. }
  4835. if (!(b instanceof BoundingRect)) {
  4836. // Normalize negative width/height.
  4837. b = BoundingRect.create(b);
  4838. }
  4839. var a = this;
  4840. var ax0 = a.x;
  4841. var ax1 = a.x + a.width;
  4842. var ay0 = a.y;
  4843. var ay1 = a.y + a.height;
  4844. var bx0 = b.x;
  4845. var bx1 = b.x + b.width;
  4846. var by0 = b.y;
  4847. var by1 = b.y + b.height;
  4848. return !(ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0);
  4849. },
  4850. contain: function (x, y) {
  4851. var rect = this;
  4852. return x >= rect.x && x <= rect.x + rect.width && y >= rect.y && y <= rect.y + rect.height;
  4853. },
  4854. /**
  4855. * @return {module:echarts/core/BoundingRect}
  4856. */
  4857. clone: function () {
  4858. return new BoundingRect(this.x, this.y, this.width, this.height);
  4859. },
  4860. /**
  4861. * Copy from another rect
  4862. */
  4863. copy: function (other) {
  4864. this.x = other.x;
  4865. this.y = other.y;
  4866. this.width = other.width;
  4867. this.height = other.height;
  4868. },
  4869. plain: function () {
  4870. return {
  4871. x: this.x,
  4872. y: this.y,
  4873. width: this.width,
  4874. height: this.height
  4875. };
  4876. }
  4877. };
  4878. /**
  4879. * @param {Object|module:zrender/core/BoundingRect} rect
  4880. * @param {number} rect.x
  4881. * @param {number} rect.y
  4882. * @param {number} rect.width
  4883. * @param {number} rect.height
  4884. * @return {module:zrender/core/BoundingRect}
  4885. */
  4886. BoundingRect.create = function (rect) {
  4887. return new BoundingRect(rect.x, rect.y, rect.width, rect.height);
  4888. };
  4889. /**
  4890. * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上
  4891. * @module zrender/graphic/Group
  4892. * @example
  4893. * var Group = require('zrender/container/Group');
  4894. * var Circle = require('zrender/graphic/shape/Circle');
  4895. * var g = new Group();
  4896. * g.position[0] = 100;
  4897. * g.position[1] = 100;
  4898. * g.add(new Circle({
  4899. * style: {
  4900. * x: 100,
  4901. * y: 100,
  4902. * r: 20,
  4903. * }
  4904. * }));
  4905. * zr.add(g);
  4906. */
  4907. /**
  4908. * @alias module:zrender/graphic/Group
  4909. * @constructor
  4910. * @extends module:zrender/mixin/Transformable
  4911. * @extends module:zrender/mixin/Eventful
  4912. */
  4913. var Group = function (opts) {
  4914. opts = opts || {};
  4915. Element.call(this, opts);
  4916. for (var key in opts) {
  4917. if (opts.hasOwnProperty(key)) {
  4918. this[key] = opts[key];
  4919. }
  4920. }
  4921. this._children = [];
  4922. this.__storage = null;
  4923. this.__dirty = true;
  4924. };
  4925. Group.prototype = {
  4926. constructor: Group,
  4927. isGroup: true,
  4928. /**
  4929. * @type {string}
  4930. */
  4931. type: 'group',
  4932. /**
  4933. * 所有子孙元素是否响应鼠标事件
  4934. * @name module:/zrender/container/Group#silent
  4935. * @type {boolean}
  4936. * @default false
  4937. */
  4938. silent: false,
  4939. /**
  4940. * @return {Array.<module:zrender/Element>}
  4941. */
  4942. children: function () {
  4943. return this._children.slice();
  4944. },
  4945. /**
  4946. * 获取指定 index 的儿子节点
  4947. * @param {number} idx
  4948. * @return {module:zrender/Element}
  4949. */
  4950. childAt: function (idx) {
  4951. return this._children[idx];
  4952. },
  4953. /**
  4954. * 获取指定名字的儿子节点
  4955. * @param {string} name
  4956. * @return {module:zrender/Element}
  4957. */
  4958. childOfName: function (name) {
  4959. var children = this._children;
  4960. for (var i = 0; i < children.length; i++) {
  4961. if (children[i].name === name) {
  4962. return children[i];
  4963. }
  4964. }
  4965. },
  4966. /**
  4967. * @return {number}
  4968. */
  4969. childCount: function () {
  4970. return this._children.length;
  4971. },
  4972. /**
  4973. * 添加子节点到最后
  4974. * @param {module:zrender/Element} child
  4975. */
  4976. add: function (child) {
  4977. if (child && child !== this && child.parent !== this) {
  4978. this._children.push(child);
  4979. this._doAdd(child);
  4980. }
  4981. return this;
  4982. },
  4983. /**
  4984. * 添加子节点在 nextSibling 之前
  4985. * @param {module:zrender/Element} child
  4986. * @param {module:zrender/Element} nextSibling
  4987. */
  4988. addBefore: function (child, nextSibling) {
  4989. if (child && child !== this && child.parent !== this && nextSibling && nextSibling.parent === this) {
  4990. var children = this._children;
  4991. var idx = children.indexOf(nextSibling);
  4992. if (idx >= 0) {
  4993. children.splice(idx, 0, child);
  4994. this._doAdd(child);
  4995. }
  4996. }
  4997. return this;
  4998. },
  4999. _doAdd: function (child) {
  5000. if (child.parent) {
  5001. child.parent.remove(child);
  5002. }
  5003. child.parent = this;
  5004. var storage = this.__storage;
  5005. var zr = this.__zr;
  5006. if (storage && storage !== child.__storage) {
  5007. storage.addToStorage(child);
  5008. if (child instanceof Group) {
  5009. child.addChildrenToStorage(storage);
  5010. }
  5011. }
  5012. zr && zr.refresh();
  5013. },
  5014. /**
  5015. * 移除子节点
  5016. * @param {module:zrender/Element} child
  5017. */
  5018. remove: function (child) {
  5019. var zr = this.__zr;
  5020. var storage = this.__storage;
  5021. var children = this._children;
  5022. var idx = indexOf(children, child);
  5023. if (idx < 0) {
  5024. return this;
  5025. }
  5026. children.splice(idx, 1);
  5027. child.parent = null;
  5028. if (storage) {
  5029. storage.delFromStorage(child);
  5030. if (child instanceof Group) {
  5031. child.delChildrenFromStorage(storage);
  5032. }
  5033. }
  5034. zr && zr.refresh();
  5035. return this;
  5036. },
  5037. /**
  5038. * 移除所有子节点
  5039. */
  5040. removeAll: function () {
  5041. var children = this._children;
  5042. var storage = this.__storage;
  5043. var child;
  5044. var i;
  5045. for (i = 0; i < children.length; i++) {
  5046. child = children[i];
  5047. if (storage) {
  5048. storage.delFromStorage(child);
  5049. if (child instanceof Group) {
  5050. child.delChildrenFromStorage(storage);
  5051. }
  5052. }
  5053. child.parent = null;
  5054. }
  5055. children.length = 0;
  5056. return this;
  5057. },
  5058. /**
  5059. * 遍历所有子节点
  5060. * @param {Function} cb
  5061. * @param {} context
  5062. */
  5063. eachChild: function (cb, context) {
  5064. var children = this._children;
  5065. for (var i = 0; i < children.length; i++) {
  5066. var child = children[i];
  5067. cb.call(context, child, i);
  5068. }
  5069. return this;
  5070. },
  5071. /**
  5072. * 深度优先遍历所有子孙节点
  5073. * @param {Function} cb
  5074. * @param {} context
  5075. */
  5076. traverse: function (cb, context) {
  5077. for (var i = 0; i < this._children.length; i++) {
  5078. var child = this._children[i];
  5079. cb.call(context, child);
  5080. if (child.type === 'group') {
  5081. child.traverse(cb, context);
  5082. }
  5083. }
  5084. return this;
  5085. },
  5086. addChildrenToStorage: function (storage) {
  5087. for (var i = 0; i < this._children.length; i++) {
  5088. var child = this._children[i];
  5089. storage.addToStorage(child);
  5090. if (child instanceof Group) {
  5091. child.addChildrenToStorage(storage);
  5092. }
  5093. }
  5094. },
  5095. delChildrenFromStorage: function (storage) {
  5096. for (var i = 0; i < this._children.length; i++) {
  5097. var child = this._children[i];
  5098. storage.delFromStorage(child);
  5099. if (child instanceof Group) {
  5100. child.delChildrenFromStorage(storage);
  5101. }
  5102. }
  5103. },
  5104. dirty: function () {
  5105. this.__dirty = true;
  5106. this.__zr && this.__zr.refresh();
  5107. return this;
  5108. },
  5109. /**
  5110. * @return {module:zrender/core/BoundingRect}
  5111. */
  5112. getBoundingRect: function (includeChildren) {
  5113. // TODO Caching
  5114. var rect = null;
  5115. var tmpRect = new BoundingRect(0, 0, 0, 0);
  5116. var children = includeChildren || this._children;
  5117. var tmpMat = [];
  5118. for (var i = 0; i < children.length; i++) {
  5119. var child = children[i];
  5120. if (child.ignore || child.invisible) {
  5121. continue;
  5122. }
  5123. var childRect = child.getBoundingRect();
  5124. var transform = child.getLocalTransform(tmpMat); // TODO
  5125. // The boundingRect cacluated by transforming original
  5126. // rect may be bigger than the actual bundingRect when rotation
  5127. // is used. (Consider a circle rotated aginst its center, where
  5128. // the actual boundingRect should be the same as that not be
  5129. // rotated.) But we can not find better approach to calculate
  5130. // actual boundingRect yet, considering performance.
  5131. if (transform) {
  5132. tmpRect.copy(childRect);
  5133. tmpRect.applyTransform(transform);
  5134. rect = rect || tmpRect.clone();
  5135. rect.union(tmpRect);
  5136. } else {
  5137. rect = rect || childRect.clone();
  5138. rect.union(childRect);
  5139. }
  5140. }
  5141. return rect || tmpRect;
  5142. }
  5143. };
  5144. inherits(Group, Element);
  5145. // https://github.com/mziccard/node-timsort
  5146. var DEFAULT_MIN_MERGE = 32;
  5147. var DEFAULT_MIN_GALLOPING = 7;
  5148. function minRunLength(n) {
  5149. var r = 0;
  5150. while (n >= DEFAULT_MIN_MERGE) {
  5151. r |= n & 1;
  5152. n >>= 1;
  5153. }
  5154. return n + r;
  5155. }
  5156. function makeAscendingRun(array, lo, hi, compare) {
  5157. var runHi = lo + 1;
  5158. if (runHi === hi) {
  5159. return 1;
  5160. }
  5161. if (compare(array[runHi++], array[lo]) < 0) {
  5162. while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) {
  5163. runHi++;
  5164. }
  5165. reverseRun(array, lo, runHi);
  5166. } else {
  5167. while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) {
  5168. runHi++;
  5169. }
  5170. }
  5171. return runHi - lo;
  5172. }
  5173. function reverseRun(array, lo, hi) {
  5174. hi--;
  5175. while (lo < hi) {
  5176. var t = array[lo];
  5177. array[lo++] = array[hi];
  5178. array[hi--] = t;
  5179. }
  5180. }
  5181. function binaryInsertionSort(array, lo, hi, start, compare) {
  5182. if (start === lo) {
  5183. start++;
  5184. }
  5185. for (; start < hi; start++) {
  5186. var pivot = array[start];
  5187. var left = lo;
  5188. var right = start;
  5189. var mid;
  5190. while (left < right) {
  5191. mid = left + right >>> 1;
  5192. if (compare(pivot, array[mid]) < 0) {
  5193. right = mid;
  5194. } else {
  5195. left = mid + 1;
  5196. }
  5197. }
  5198. var n = start - left;
  5199. switch (n) {
  5200. case 3:
  5201. array[left + 3] = array[left + 2];
  5202. case 2:
  5203. array[left + 2] = array[left + 1];
  5204. case 1:
  5205. array[left + 1] = array[left];
  5206. break;
  5207. default:
  5208. while (n > 0) {
  5209. array[left + n] = array[left + n - 1];
  5210. n--;
  5211. }
  5212. }
  5213. array[left] = pivot;
  5214. }
  5215. }
  5216. function gallopLeft(value, array, start, length, hint, compare) {
  5217. var lastOffset = 0;
  5218. var maxOffset = 0;
  5219. var offset = 1;
  5220. if (compare(value, array[start + hint]) > 0) {
  5221. maxOffset = length - hint;
  5222. while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) {
  5223. lastOffset = offset;
  5224. offset = (offset << 1) + 1;
  5225. if (offset <= 0) {
  5226. offset = maxOffset;
  5227. }
  5228. }
  5229. if (offset > maxOffset) {
  5230. offset = maxOffset;
  5231. }
  5232. lastOffset += hint;
  5233. offset += hint;
  5234. } else {
  5235. maxOffset = hint + 1;
  5236. while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) {
  5237. lastOffset = offset;
  5238. offset = (offset << 1) + 1;
  5239. if (offset <= 0) {
  5240. offset = maxOffset;
  5241. }
  5242. }
  5243. if (offset > maxOffset) {
  5244. offset = maxOffset;
  5245. }
  5246. var tmp = lastOffset;
  5247. lastOffset = hint - offset;
  5248. offset = hint - tmp;
  5249. }
  5250. lastOffset++;
  5251. while (lastOffset < offset) {
  5252. var m = lastOffset + (offset - lastOffset >>> 1);
  5253. if (compare(value, array[start + m]) > 0) {
  5254. lastOffset = m + 1;
  5255. } else {
  5256. offset = m;
  5257. }
  5258. }
  5259. return offset;
  5260. }
  5261. function gallopRight(value, array, start, length, hint, compare) {
  5262. var lastOffset = 0;
  5263. var maxOffset = 0;
  5264. var offset = 1;
  5265. if (compare(value, array[start + hint]) < 0) {
  5266. maxOffset = hint + 1;
  5267. while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) {
  5268. lastOffset = offset;
  5269. offset = (offset << 1) + 1;
  5270. if (offset <= 0) {
  5271. offset = maxOffset;
  5272. }
  5273. }
  5274. if (offset > maxOffset) {
  5275. offset = maxOffset;
  5276. }
  5277. var tmp = lastOffset;
  5278. lastOffset = hint - offset;
  5279. offset = hint - tmp;
  5280. } else {
  5281. maxOffset = length - hint;
  5282. while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) {
  5283. lastOffset = offset;
  5284. offset = (offset << 1) + 1;
  5285. if (offset <= 0) {
  5286. offset = maxOffset;
  5287. }
  5288. }
  5289. if (offset > maxOffset) {
  5290. offset = maxOffset;
  5291. }
  5292. lastOffset += hint;
  5293. offset += hint;
  5294. }
  5295. lastOffset++;
  5296. while (lastOffset < offset) {
  5297. var m = lastOffset + (offset - lastOffset >>> 1);
  5298. if (compare(value, array[start + m]) < 0) {
  5299. offset = m;
  5300. } else {
  5301. lastOffset = m + 1;
  5302. }
  5303. }
  5304. return offset;
  5305. }
  5306. function TimSort(array, compare) {
  5307. var minGallop = DEFAULT_MIN_GALLOPING;
  5308. var runStart;
  5309. var runLength;
  5310. var stackSize = 0;
  5311. var tmp = [];
  5312. runStart = [];
  5313. runLength = [];
  5314. function pushRun(_runStart, _runLength) {
  5315. runStart[stackSize] = _runStart;
  5316. runLength[stackSize] = _runLength;
  5317. stackSize += 1;
  5318. }
  5319. function mergeRuns() {
  5320. while (stackSize > 1) {
  5321. var n = stackSize - 2;
  5322. if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) {
  5323. if (runLength[n - 1] < runLength[n + 1]) {
  5324. n--;
  5325. }
  5326. } else if (runLength[n] > runLength[n + 1]) {
  5327. break;
  5328. }
  5329. mergeAt(n);
  5330. }
  5331. }
  5332. function forceMergeRuns() {
  5333. while (stackSize > 1) {
  5334. var n = stackSize - 2;
  5335. if (n > 0 && runLength[n - 1] < runLength[n + 1]) {
  5336. n--;
  5337. }
  5338. mergeAt(n);
  5339. }
  5340. }
  5341. function mergeAt(i) {
  5342. var start1 = runStart[i];
  5343. var length1 = runLength[i];
  5344. var start2 = runStart[i + 1];
  5345. var length2 = runLength[i + 1];
  5346. runLength[i] = length1 + length2;
  5347. if (i === stackSize - 3) {
  5348. runStart[i + 1] = runStart[i + 2];
  5349. runLength[i + 1] = runLength[i + 2];
  5350. }
  5351. stackSize--;
  5352. var k = gallopRight(array[start2], array, start1, length1, 0, compare);
  5353. start1 += k;
  5354. length1 -= k;
  5355. if (length1 === 0) {
  5356. return;
  5357. }
  5358. length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare);
  5359. if (length2 === 0) {
  5360. return;
  5361. }
  5362. if (length1 <= length2) {
  5363. mergeLow(start1, length1, start2, length2);
  5364. } else {
  5365. mergeHigh(start1, length1, start2, length2);
  5366. }
  5367. }
  5368. function mergeLow(start1, length1, start2, length2) {
  5369. var i = 0;
  5370. for (i = 0; i < length1; i++) {
  5371. tmp[i] = array[start1 + i];
  5372. }
  5373. var cursor1 = 0;
  5374. var cursor2 = start2;
  5375. var dest = start1;
  5376. array[dest++] = array[cursor2++];
  5377. if (--length2 === 0) {
  5378. for (i = 0; i < length1; i++) {
  5379. array[dest + i] = tmp[cursor1 + i];
  5380. }
  5381. return;
  5382. }
  5383. if (length1 === 1) {
  5384. for (i = 0; i < length2; i++) {
  5385. array[dest + i] = array[cursor2 + i];
  5386. }
  5387. array[dest + length2] = tmp[cursor1];
  5388. return;
  5389. }
  5390. var _minGallop = minGallop;
  5391. var count1;
  5392. var count2;
  5393. var exit;
  5394. while (1) {
  5395. count1 = 0;
  5396. count2 = 0;
  5397. exit = false;
  5398. do {
  5399. if (compare(array[cursor2], tmp[cursor1]) < 0) {
  5400. array[dest++] = array[cursor2++];
  5401. count2++;
  5402. count1 = 0;
  5403. if (--length2 === 0) {
  5404. exit = true;
  5405. break;
  5406. }
  5407. } else {
  5408. array[dest++] = tmp[cursor1++];
  5409. count1++;
  5410. count2 = 0;
  5411. if (--length1 === 1) {
  5412. exit = true;
  5413. break;
  5414. }
  5415. }
  5416. } while ((count1 | count2) < _minGallop);
  5417. if (exit) {
  5418. break;
  5419. }
  5420. do {
  5421. count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare);
  5422. if (count1 !== 0) {
  5423. for (i = 0; i < count1; i++) {
  5424. array[dest + i] = tmp[cursor1 + i];
  5425. }
  5426. dest += count1;
  5427. cursor1 += count1;
  5428. length1 -= count1;
  5429. if (length1 <= 1) {
  5430. exit = true;
  5431. break;
  5432. }
  5433. }
  5434. array[dest++] = array[cursor2++];
  5435. if (--length2 === 0) {
  5436. exit = true;
  5437. break;
  5438. }
  5439. count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare);
  5440. if (count2 !== 0) {
  5441. for (i = 0; i < count2; i++) {
  5442. array[dest + i] = array[cursor2 + i];
  5443. }
  5444. dest += count2;
  5445. cursor2 += count2;
  5446. length2 -= count2;
  5447. if (length2 === 0) {
  5448. exit = true;
  5449. break;
  5450. }
  5451. }
  5452. array[dest++] = tmp[cursor1++];
  5453. if (--length1 === 1) {
  5454. exit = true;
  5455. break;
  5456. }
  5457. _minGallop--;
  5458. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5459. if (exit) {
  5460. break;
  5461. }
  5462. if (_minGallop < 0) {
  5463. _minGallop = 0;
  5464. }
  5465. _minGallop += 2;
  5466. }
  5467. minGallop = _minGallop;
  5468. minGallop < 1 && (minGallop = 1);
  5469. if (length1 === 1) {
  5470. for (i = 0; i < length2; i++) {
  5471. array[dest + i] = array[cursor2 + i];
  5472. }
  5473. array[dest + length2] = tmp[cursor1];
  5474. } else if (length1 === 0) {
  5475. throw new Error(); // throw new Error('mergeLow preconditions were not respected');
  5476. } else {
  5477. for (i = 0; i < length1; i++) {
  5478. array[dest + i] = tmp[cursor1 + i];
  5479. }
  5480. }
  5481. }
  5482. function mergeHigh(start1, length1, start2, length2) {
  5483. var i = 0;
  5484. for (i = 0; i < length2; i++) {
  5485. tmp[i] = array[start2 + i];
  5486. }
  5487. var cursor1 = start1 + length1 - 1;
  5488. var cursor2 = length2 - 1;
  5489. var dest = start2 + length2 - 1;
  5490. var customCursor = 0;
  5491. var customDest = 0;
  5492. array[dest--] = array[cursor1--];
  5493. if (--length1 === 0) {
  5494. customCursor = dest - (length2 - 1);
  5495. for (i = 0; i < length2; i++) {
  5496. array[customCursor + i] = tmp[i];
  5497. }
  5498. return;
  5499. }
  5500. if (length2 === 1) {
  5501. dest -= length1;
  5502. cursor1 -= length1;
  5503. customDest = dest + 1;
  5504. customCursor = cursor1 + 1;
  5505. for (i = length1 - 1; i >= 0; i--) {
  5506. array[customDest + i] = array[customCursor + i];
  5507. }
  5508. array[dest] = tmp[cursor2];
  5509. return;
  5510. }
  5511. var _minGallop = minGallop;
  5512. while (true) {
  5513. var count1 = 0;
  5514. var count2 = 0;
  5515. var exit = false;
  5516. do {
  5517. if (compare(tmp[cursor2], array[cursor1]) < 0) {
  5518. array[dest--] = array[cursor1--];
  5519. count1++;
  5520. count2 = 0;
  5521. if (--length1 === 0) {
  5522. exit = true;
  5523. break;
  5524. }
  5525. } else {
  5526. array[dest--] = tmp[cursor2--];
  5527. count2++;
  5528. count1 = 0;
  5529. if (--length2 === 1) {
  5530. exit = true;
  5531. break;
  5532. }
  5533. }
  5534. } while ((count1 | count2) < _minGallop);
  5535. if (exit) {
  5536. break;
  5537. }
  5538. do {
  5539. count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare);
  5540. if (count1 !== 0) {
  5541. dest -= count1;
  5542. cursor1 -= count1;
  5543. length1 -= count1;
  5544. customDest = dest + 1;
  5545. customCursor = cursor1 + 1;
  5546. for (i = count1 - 1; i >= 0; i--) {
  5547. array[customDest + i] = array[customCursor + i];
  5548. }
  5549. if (length1 === 0) {
  5550. exit = true;
  5551. break;
  5552. }
  5553. }
  5554. array[dest--] = tmp[cursor2--];
  5555. if (--length2 === 1) {
  5556. exit = true;
  5557. break;
  5558. }
  5559. count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare);
  5560. if (count2 !== 0) {
  5561. dest -= count2;
  5562. cursor2 -= count2;
  5563. length2 -= count2;
  5564. customDest = dest + 1;
  5565. customCursor = cursor2 + 1;
  5566. for (i = 0; i < count2; i++) {
  5567. array[customDest + i] = tmp[customCursor + i];
  5568. }
  5569. if (length2 <= 1) {
  5570. exit = true;
  5571. break;
  5572. }
  5573. }
  5574. array[dest--] = array[cursor1--];
  5575. if (--length1 === 0) {
  5576. exit = true;
  5577. break;
  5578. }
  5579. _minGallop--;
  5580. } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING);
  5581. if (exit) {
  5582. break;
  5583. }
  5584. if (_minGallop < 0) {
  5585. _minGallop = 0;
  5586. }
  5587. _minGallop += 2;
  5588. }
  5589. minGallop = _minGallop;
  5590. if (minGallop < 1) {
  5591. minGallop = 1;
  5592. }
  5593. if (length2 === 1) {
  5594. dest -= length1;
  5595. cursor1 -= length1;
  5596. customDest = dest + 1;
  5597. customCursor = cursor1 + 1;
  5598. for (i = length1 - 1; i >= 0; i--) {
  5599. array[customDest + i] = array[customCursor + i];
  5600. }
  5601. array[dest] = tmp[cursor2];
  5602. } else if (length2 === 0) {
  5603. throw new Error(); // throw new Error('mergeHigh preconditions were not respected');
  5604. } else {
  5605. customCursor = dest - (length2 - 1);
  5606. for (i = 0; i < length2; i++) {
  5607. array[customCursor + i] = tmp[i];
  5608. }
  5609. }
  5610. }
  5611. this.mergeRuns = mergeRuns;
  5612. this.forceMergeRuns = forceMergeRuns;
  5613. this.pushRun = pushRun;
  5614. }
  5615. function sort(array, compare, lo, hi) {
  5616. if (!lo) {
  5617. lo = 0;
  5618. }
  5619. if (!hi) {
  5620. hi = array.length;
  5621. }
  5622. var remaining = hi - lo;
  5623. if (remaining < 2) {
  5624. return;
  5625. }
  5626. var runLength = 0;
  5627. if (remaining < DEFAULT_MIN_MERGE) {
  5628. runLength = makeAscendingRun(array, lo, hi, compare);
  5629. binaryInsertionSort(array, lo, hi, lo + runLength, compare);
  5630. return;
  5631. }
  5632. var ts = new TimSort(array, compare);
  5633. var minRun = minRunLength(remaining);
  5634. do {
  5635. runLength = makeAscendingRun(array, lo, hi, compare);
  5636. if (runLength < minRun) {
  5637. var force = remaining;
  5638. if (force > minRun) {
  5639. force = minRun;
  5640. }
  5641. binaryInsertionSort(array, lo, lo + force, lo + runLength, compare);
  5642. runLength = force;
  5643. }
  5644. ts.pushRun(lo, runLength);
  5645. ts.mergeRuns();
  5646. remaining -= runLength;
  5647. lo += runLength;
  5648. } while (remaining !== 0);
  5649. ts.forceMergeRuns();
  5650. }
  5651. // https://jsfiddle.net/pissang/jr4x7mdm/8/
  5652. function shapeCompareFunc(a, b) {
  5653. if (a.zlevel === b.zlevel) {
  5654. if (a.z === b.z) {
  5655. // if (a.z2 === b.z2) {
  5656. // // FIXME Slow has renderidx compare
  5657. // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement
  5658. // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012
  5659. // return a.__renderidx - b.__renderidx;
  5660. // }
  5661. return a.z2 - b.z2;
  5662. }
  5663. return a.z - b.z;
  5664. }
  5665. return a.zlevel - b.zlevel;
  5666. }
  5667. /**
  5668. * 内容仓库 (M)
  5669. * @alias module:zrender/Storage
  5670. * @constructor
  5671. */
  5672. var Storage = function () {
  5673. // jshint ignore:line
  5674. this._roots = [];
  5675. this._displayList = [];
  5676. this._displayListLen = 0;
  5677. };
  5678. Storage.prototype = {
  5679. constructor: Storage,
  5680. /**
  5681. * @param {Function} cb
  5682. *
  5683. */
  5684. traverse: function (cb, context) {
  5685. for (var i = 0; i < this._roots.length; i++) {
  5686. this._roots[i].traverse(cb, context);
  5687. }
  5688. },
  5689. /**
  5690. * 返回所有图形的绘制队列
  5691. * @param {boolean} [update=false] 是否在返回前更新该数组
  5692. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效
  5693. *
  5694. * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList}
  5695. * @return {Array.<module:zrender/graphic/Displayable>}
  5696. */
  5697. getDisplayList: function (update, includeIgnore) {
  5698. includeIgnore = includeIgnore || false;
  5699. if (update) {
  5700. this.updateDisplayList(includeIgnore);
  5701. }
  5702. return this._displayList;
  5703. },
  5704. /**
  5705. * 更新图形的绘制队列。
  5706. * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中,
  5707. * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列
  5708. * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组
  5709. */
  5710. updateDisplayList: function (includeIgnore) {
  5711. this._displayListLen = 0;
  5712. var roots = this._roots;
  5713. var displayList = this._displayList;
  5714. for (var i = 0, len = roots.length; i < len; i++) {
  5715. this._updateAndAddDisplayable(roots[i], null, includeIgnore);
  5716. }
  5717. displayList.length = this._displayListLen;
  5718. env$1.canvasSupported && sort(displayList, shapeCompareFunc);
  5719. },
  5720. _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) {
  5721. if (el.ignore && !includeIgnore) {
  5722. return;
  5723. }
  5724. el.beforeUpdate();
  5725. if (el.__dirty) {
  5726. el.update();
  5727. }
  5728. el.afterUpdate();
  5729. var userSetClipPath = el.clipPath;
  5730. if (userSetClipPath) {
  5731. // FIXME 效率影响
  5732. if (clipPaths) {
  5733. clipPaths = clipPaths.slice();
  5734. } else {
  5735. clipPaths = [];
  5736. }
  5737. var currentClipPath = userSetClipPath;
  5738. var parentClipPath = el; // Recursively add clip path
  5739. while (currentClipPath) {
  5740. // clipPath 的变换是基于使用这个 clipPath 的元素
  5741. currentClipPath.parent = parentClipPath;
  5742. currentClipPath.updateTransform();
  5743. clipPaths.push(currentClipPath);
  5744. parentClipPath = currentClipPath;
  5745. currentClipPath = currentClipPath.clipPath;
  5746. }
  5747. }
  5748. if (el.isGroup) {
  5749. var children = el._children;
  5750. for (var i = 0; i < children.length; i++) {
  5751. var child = children[i]; // Force to mark as dirty if group is dirty
  5752. // FIXME __dirtyPath ?
  5753. if (el.__dirty) {
  5754. child.__dirty = true;
  5755. }
  5756. this._updateAndAddDisplayable(child, clipPaths, includeIgnore);
  5757. } // Mark group clean here
  5758. el.__dirty = false;
  5759. } else {
  5760. el.__clipPaths = clipPaths;
  5761. this._displayList[this._displayListLen++] = el;
  5762. }
  5763. },
  5764. /**
  5765. * 添加图形(Shape)或者组(Group)到根节点
  5766. * @param {module:zrender/Element} el
  5767. */
  5768. addRoot: function (el) {
  5769. if (el.__storage === this) {
  5770. return;
  5771. }
  5772. if (el instanceof Group) {
  5773. el.addChildrenToStorage(this);
  5774. }
  5775. this.addToStorage(el);
  5776. this._roots.push(el);
  5777. },
  5778. /**
  5779. * 删除指定的图形(Shape)或者组(Group)
  5780. * @param {string|Array.<string>} [el] 如果为空清空整个Storage
  5781. */
  5782. delRoot: function (el) {
  5783. if (el == null) {
  5784. // 不指定el清空
  5785. for (var i = 0; i < this._roots.length; i++) {
  5786. var root = this._roots[i];
  5787. if (root instanceof Group) {
  5788. root.delChildrenFromStorage(this);
  5789. }
  5790. }
  5791. this._roots = [];
  5792. this._displayList = [];
  5793. this._displayListLen = 0;
  5794. return;
  5795. }
  5796. if (el instanceof Array) {
  5797. for (var i = 0, l = el.length; i < l; i++) {
  5798. this.delRoot(el[i]);
  5799. }
  5800. return;
  5801. }
  5802. var idx = indexOf(this._roots, el);
  5803. if (idx >= 0) {
  5804. this.delFromStorage(el);
  5805. this._roots.splice(idx, 1);
  5806. if (el instanceof Group) {
  5807. el.delChildrenFromStorage(this);
  5808. }
  5809. }
  5810. },
  5811. addToStorage: function (el) {
  5812. if (el) {
  5813. el.__storage = this;
  5814. el.dirty(false);
  5815. }
  5816. return this;
  5817. },
  5818. delFromStorage: function (el) {
  5819. if (el) {
  5820. el.__storage = null;
  5821. }
  5822. return this;
  5823. },
  5824. /**
  5825. * 清空并且释放Storage
  5826. */
  5827. dispose: function () {
  5828. this._renderList = this._roots = null;
  5829. },
  5830. displayableSortFunc: shapeCompareFunc
  5831. };
  5832. var SHADOW_PROPS = {
  5833. 'shadowBlur': 1,
  5834. 'shadowOffsetX': 1,
  5835. 'shadowOffsetY': 1,
  5836. 'textShadowBlur': 1,
  5837. 'textShadowOffsetX': 1,
  5838. 'textShadowOffsetY': 1,
  5839. 'textBoxShadowBlur': 1,
  5840. 'textBoxShadowOffsetX': 1,
  5841. 'textBoxShadowOffsetY': 1
  5842. };
  5843. var fixShadow = function (ctx, propName, value) {
  5844. if (SHADOW_PROPS.hasOwnProperty(propName)) {
  5845. return value *= ctx.dpr;
  5846. }
  5847. return value;
  5848. };
  5849. var ContextCachedBy = {
  5850. NONE: 0,
  5851. STYLE_BIND: 1,
  5852. PLAIN_TEXT: 2
  5853. }; // Avoid confused with 0/false.
  5854. var WILL_BE_RESTORED = 9;
  5855. var STYLE_COMMON_PROPS = [['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'], ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10]]; // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4);
  5856. // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4);
  5857. var Style = function (opts) {
  5858. this.extendFrom(opts, false);
  5859. };
  5860. function createLinearGradient(ctx, obj, rect) {
  5861. var x = obj.x == null ? 0 : obj.x;
  5862. var x2 = obj.x2 == null ? 1 : obj.x2;
  5863. var y = obj.y == null ? 0 : obj.y;
  5864. var y2 = obj.y2 == null ? 0 : obj.y2;
  5865. if (!obj.global) {
  5866. x = x * rect.width + rect.x;
  5867. x2 = x2 * rect.width + rect.x;
  5868. y = y * rect.height + rect.y;
  5869. y2 = y2 * rect.height + rect.y;
  5870. } // Fix NaN when rect is Infinity
  5871. x = isNaN(x) ? 0 : x;
  5872. x2 = isNaN(x2) ? 1 : x2;
  5873. y = isNaN(y) ? 0 : y;
  5874. y2 = isNaN(y2) ? 0 : y2;
  5875. var canvasGradient = ctx.createLinearGradient(x, y, x2, y2);
  5876. return canvasGradient;
  5877. }
  5878. function createRadialGradient(ctx, obj, rect) {
  5879. var width = rect.width;
  5880. var height = rect.height;
  5881. var min = Math.min(width, height);
  5882. var x = obj.x == null ? 0.5 : obj.x;
  5883. var y = obj.y == null ? 0.5 : obj.y;
  5884. var r = obj.r == null ? 0.5 : obj.r;
  5885. if (!obj.global) {
  5886. x = x * width + rect.x;
  5887. y = y * height + rect.y;
  5888. r = r * min;
  5889. }
  5890. var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r);
  5891. return canvasGradient;
  5892. }
  5893. Style.prototype = {
  5894. constructor: Style,
  5895. /**
  5896. * @type {string}
  5897. */
  5898. fill: '#000',
  5899. /**
  5900. * @type {string}
  5901. */
  5902. stroke: null,
  5903. /**
  5904. * @type {number}
  5905. */
  5906. opacity: 1,
  5907. /**
  5908. * @type {number}
  5909. */
  5910. fillOpacity: null,
  5911. /**
  5912. * @type {number}
  5913. */
  5914. strokeOpacity: null,
  5915. /**
  5916. * `true` is not supported.
  5917. * `false`/`null`/`undefined` are the same.
  5918. * `false` is used to remove lineDash in some
  5919. * case that `null`/`undefined` can not be set.
  5920. * (e.g., emphasis.lineStyle in echarts)
  5921. * @type {Array.<number>|boolean}
  5922. */
  5923. lineDash: null,
  5924. /**
  5925. * @type {number}
  5926. */
  5927. lineDashOffset: 0,
  5928. /**
  5929. * @type {number}
  5930. */
  5931. shadowBlur: 0,
  5932. /**
  5933. * @type {number}
  5934. */
  5935. shadowOffsetX: 0,
  5936. /**
  5937. * @type {number}
  5938. */
  5939. shadowOffsetY: 0,
  5940. /**
  5941. * @type {number}
  5942. */
  5943. lineWidth: 1,
  5944. /**
  5945. * If stroke ignore scale
  5946. * @type {Boolean}
  5947. */
  5948. strokeNoScale: false,
  5949. // Bounding rect text configuration
  5950. // Not affected by element transform
  5951. /**
  5952. * @type {string}
  5953. */
  5954. text: null,
  5955. /**
  5956. * If `fontSize` or `fontFamily` exists, `font` will be reset by
  5957. * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`.
  5958. * So do not visit it directly in upper application (like echarts),
  5959. * but use `contain/text#makeFont` instead.
  5960. * @type {string}
  5961. */
  5962. font: null,
  5963. /**
  5964. * The same as font. Use font please.
  5965. * @deprecated
  5966. * @type {string}
  5967. */
  5968. textFont: null,
  5969. /**
  5970. * It helps merging respectively, rather than parsing an entire font string.
  5971. * @type {string}
  5972. */
  5973. fontStyle: null,
  5974. /**
  5975. * It helps merging respectively, rather than parsing an entire font string.
  5976. * @type {string}
  5977. */
  5978. fontWeight: null,
  5979. /**
  5980. * It helps merging respectively, rather than parsing an entire font string.
  5981. * Should be 12 but not '12px'.
  5982. * @type {number}
  5983. */
  5984. fontSize: null,
  5985. /**
  5986. * It helps merging respectively, rather than parsing an entire font string.
  5987. * @type {string}
  5988. */
  5989. fontFamily: null,
  5990. /**
  5991. * Reserved for special functinality, like 'hr'.
  5992. * @type {string}
  5993. */
  5994. textTag: null,
  5995. /**
  5996. * @type {string}
  5997. */
  5998. textFill: '#000',
  5999. /**
  6000. * @type {string}
  6001. */
  6002. textStroke: null,
  6003. /**
  6004. * @type {number}
  6005. */
  6006. textWidth: null,
  6007. /**
  6008. * Only for textBackground.
  6009. * @type {number}
  6010. */
  6011. textHeight: null,
  6012. /**
  6013. * textStroke may be set as some color as a default
  6014. * value in upper applicaion, where the default value
  6015. * of textStrokeWidth should be 0 to make sure that
  6016. * user can choose to do not use text stroke.
  6017. * @type {number}
  6018. */
  6019. textStrokeWidth: 0,
  6020. /**
  6021. * @type {number}
  6022. */
  6023. textLineHeight: null,
  6024. /**
  6025. * 'inside', 'left', 'right', 'top', 'bottom'
  6026. * [x, y]
  6027. * Based on x, y of rect.
  6028. * @type {string|Array.<number>}
  6029. * @default 'inside'
  6030. */
  6031. textPosition: 'inside',
  6032. /**
  6033. * If not specified, use the boundingRect of a `displayable`.
  6034. * @type {Object}
  6035. */
  6036. textRect: null,
  6037. /**
  6038. * [x, y]
  6039. * @type {Array.<number>}
  6040. */
  6041. textOffset: null,
  6042. /**
  6043. * @type {string}
  6044. */
  6045. textAlign: null,
  6046. /**
  6047. * @type {string}
  6048. */
  6049. textVerticalAlign: null,
  6050. /**
  6051. * @type {number}
  6052. */
  6053. textDistance: 5,
  6054. /**
  6055. * @type {string}
  6056. */
  6057. textShadowColor: 'transparent',
  6058. /**
  6059. * @type {number}
  6060. */
  6061. textShadowBlur: 0,
  6062. /**
  6063. * @type {number}
  6064. */
  6065. textShadowOffsetX: 0,
  6066. /**
  6067. * @type {number}
  6068. */
  6069. textShadowOffsetY: 0,
  6070. /**
  6071. * @type {string}
  6072. */
  6073. textBoxShadowColor: 'transparent',
  6074. /**
  6075. * @type {number}
  6076. */
  6077. textBoxShadowBlur: 0,
  6078. /**
  6079. * @type {number}
  6080. */
  6081. textBoxShadowOffsetX: 0,
  6082. /**
  6083. * @type {number}
  6084. */
  6085. textBoxShadowOffsetY: 0,
  6086. /**
  6087. * Whether transform text.
  6088. * Only available in Path and Image element,
  6089. * where the text is called as `RectText`.
  6090. * @type {boolean}
  6091. */
  6092. transformText: false,
  6093. /**
  6094. * Text rotate around position of Path or Image.
  6095. * The origin of the rotation can be specified by `textOrigin`.
  6096. * Only available in Path and Image element,
  6097. * where the text is called as `RectText`.
  6098. */
  6099. textRotation: 0,
  6100. /**
  6101. * Text origin of text rotation.
  6102. * Useful in the case like label rotation of circular symbol.
  6103. * Only available in Path and Image element, where the text is called
  6104. * as `RectText` and the element is called as "host element".
  6105. * The value can be:
  6106. * + If specified as a coordinate like `[10, 40]`, it is the `[x, y]`
  6107. * base on the left-top corner of the rect of its host element.
  6108. * + If specified as a string `center`, it is the center of the rect of
  6109. * its host element.
  6110. * + By default, this origin is the `textPosition`.
  6111. * @type {string|Array.<number>}
  6112. */
  6113. textOrigin: null,
  6114. /**
  6115. * @type {string}
  6116. */
  6117. textBackgroundColor: null,
  6118. /**
  6119. * @type {string}
  6120. */
  6121. textBorderColor: null,
  6122. /**
  6123. * @type {number}
  6124. */
  6125. textBorderWidth: 0,
  6126. /**
  6127. * @type {number}
  6128. */
  6129. textBorderRadius: 0,
  6130. /**
  6131. * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]`
  6132. * @type {number|Array.<number>}
  6133. */
  6134. textPadding: null,
  6135. /**
  6136. * Text styles for rich text.
  6137. * @type {Object}
  6138. */
  6139. rich: null,
  6140. /**
  6141. * {outerWidth, outerHeight, ellipsis, placeholder}
  6142. * @type {Object}
  6143. */
  6144. truncate: null,
  6145. /**
  6146. * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  6147. * @type {string}
  6148. */
  6149. blend: null,
  6150. /**
  6151. * @param {CanvasRenderingContext2D} ctx
  6152. */
  6153. bind: function (ctx, el, prevEl) {
  6154. var style = this;
  6155. var prevStyle = prevEl && prevEl.style; // If no prevStyle, it means first draw.
  6156. // Only apply cache if the last time cachced by this function.
  6157. var notCheckCache = !prevStyle || ctx.__attrCachedBy !== ContextCachedBy.STYLE_BIND;
  6158. ctx.__attrCachedBy = ContextCachedBy.STYLE_BIND;
  6159. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6160. var prop = STYLE_COMMON_PROPS[i];
  6161. var styleName = prop[0];
  6162. if (notCheckCache || style[styleName] !== prevStyle[styleName]) {
  6163. // FIXME Invalid property value will cause style leak from previous element.
  6164. ctx[styleName] = fixShadow(ctx, styleName, style[styleName] || prop[1]);
  6165. }
  6166. }
  6167. if (notCheckCache || style.fill !== prevStyle.fill) {
  6168. ctx.fillStyle = style.fill;
  6169. }
  6170. if (notCheckCache || style.stroke !== prevStyle.stroke) {
  6171. ctx.strokeStyle = style.stroke;
  6172. }
  6173. if (notCheckCache || style.opacity !== prevStyle.opacity) {
  6174. ctx.globalAlpha = style.opacity == null ? 1 : style.opacity;
  6175. }
  6176. if (notCheckCache || style.blend !== prevStyle.blend) {
  6177. ctx.globalCompositeOperation = style.blend || 'source-over';
  6178. }
  6179. if (this.hasStroke()) {
  6180. var lineWidth = style.lineWidth;
  6181. ctx.lineWidth = lineWidth / (this.strokeNoScale && el && el.getLineScale ? el.getLineScale() : 1);
  6182. }
  6183. },
  6184. hasFill: function () {
  6185. var fill = this.fill;
  6186. return fill != null && fill !== 'none';
  6187. },
  6188. hasStroke: function () {
  6189. var stroke = this.stroke;
  6190. return stroke != null && stroke !== 'none' && this.lineWidth > 0;
  6191. },
  6192. /**
  6193. * Extend from other style
  6194. * @param {zrender/graphic/Style} otherStyle
  6195. * @param {boolean} overwrite true: overwrirte any way.
  6196. * false: overwrite only when !target.hasOwnProperty
  6197. * others: overwrite when property is not null/undefined.
  6198. */
  6199. extendFrom: function (otherStyle, overwrite) {
  6200. if (otherStyle) {
  6201. for (var name in otherStyle) {
  6202. if (otherStyle.hasOwnProperty(name) && (overwrite === true || (overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null))) {
  6203. this[name] = otherStyle[name];
  6204. }
  6205. }
  6206. }
  6207. },
  6208. /**
  6209. * Batch setting style with a given object
  6210. * @param {Object|string} obj
  6211. * @param {*} [obj]
  6212. */
  6213. set: function (obj, value) {
  6214. if (typeof obj === 'string') {
  6215. this[obj] = value;
  6216. } else {
  6217. this.extendFrom(obj, true);
  6218. }
  6219. },
  6220. /**
  6221. * Clone
  6222. * @return {zrender/graphic/Style} [description]
  6223. */
  6224. clone: function () {
  6225. var newStyle = new this.constructor();
  6226. newStyle.extendFrom(this, true);
  6227. return newStyle;
  6228. },
  6229. getGradient: function (ctx, obj, rect) {
  6230. var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient;
  6231. var canvasGradient = method(ctx, obj, rect);
  6232. var colorStops = obj.colorStops;
  6233. for (var i = 0; i < colorStops.length; i++) {
  6234. canvasGradient.addColorStop(colorStops[i].offset, colorStops[i].color);
  6235. }
  6236. return canvasGradient;
  6237. }
  6238. };
  6239. var styleProto = Style.prototype;
  6240. for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) {
  6241. var prop = STYLE_COMMON_PROPS[i];
  6242. if (!(prop[0] in styleProto)) {
  6243. styleProto[prop[0]] = prop[1];
  6244. }
  6245. } // Provide for others
  6246. Style.getGradient = styleProto.getGradient;
  6247. var Pattern = function (image, repeat) {
  6248. // Should do nothing more in this constructor. Because gradient can be
  6249. // declard by `color: {image: ...}`, where this constructor will not be called.
  6250. this.image = image;
  6251. this.repeat = repeat; // Can be cloned
  6252. this.type = 'pattern';
  6253. };
  6254. Pattern.prototype.getCanvasPattern = function (ctx) {
  6255. return ctx.createPattern(this.image, this.repeat || 'repeat');
  6256. };
  6257. /**
  6258. * @module zrender/Layer
  6259. * @author pissang(https://www.github.com/pissang)
  6260. */
  6261. function returnFalse() {
  6262. return false;
  6263. }
  6264. /**
  6265. * 创建dom
  6266. *
  6267. * @inner
  6268. * @param {string} id dom id 待用
  6269. * @param {Painter} painter painter instance
  6270. * @param {number} number
  6271. */
  6272. function createDom(id, painter, dpr) {
  6273. var newDom = createCanvas();
  6274. var width = painter.getWidth();
  6275. var height = painter.getHeight();
  6276. var newDomStyle = newDom.style;
  6277. if (newDomStyle) {
  6278. // In node or some other non-browser environment
  6279. newDomStyle.position = 'absolute';
  6280. newDomStyle.left = 0;
  6281. newDomStyle.top = 0;
  6282. newDomStyle.width = width + 'px';
  6283. newDomStyle.height = height + 'px';
  6284. newDom.setAttribute('data-zr-dom-id', id);
  6285. }
  6286. newDom.width = width * dpr;
  6287. newDom.height = height * dpr;
  6288. return newDom;
  6289. }
  6290. /**
  6291. * @alias module:zrender/Layer
  6292. * @constructor
  6293. * @extends module:zrender/mixin/Transformable
  6294. * @param {string} id
  6295. * @param {module:zrender/Painter} painter
  6296. * @param {number} [dpr]
  6297. */
  6298. var Layer = function (id, painter, dpr) {
  6299. var dom;
  6300. dpr = dpr || devicePixelRatio;
  6301. if (typeof id === 'string') {
  6302. dom = createDom(id, painter, dpr);
  6303. } // Not using isDom because in node it will return false
  6304. else if (isObject$1(id)) {
  6305. dom = id;
  6306. id = dom.id;
  6307. }
  6308. this.id = id;
  6309. this.dom = dom;
  6310. var domStyle = dom.style;
  6311. if (domStyle) {
  6312. // Not in node
  6313. dom.onselectstart = returnFalse; // 避免页面选中的尴尬
  6314. domStyle['-webkit-user-select'] = 'none';
  6315. domStyle['user-select'] = 'none';
  6316. domStyle['-webkit-touch-callout'] = 'none';
  6317. domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)';
  6318. domStyle['padding'] = 0; // eslint-disable-line dot-notation
  6319. domStyle['margin'] = 0; // eslint-disable-line dot-notation
  6320. domStyle['border-width'] = 0;
  6321. }
  6322. this.domBack = null;
  6323. this.ctxBack = null;
  6324. this.painter = painter;
  6325. this.config = null; // Configs
  6326. /**
  6327. * 每次清空画布的颜色
  6328. * @type {string}
  6329. * @default 0
  6330. */
  6331. this.clearColor = 0;
  6332. /**
  6333. * 是否开启动态模糊
  6334. * @type {boolean}
  6335. * @default false
  6336. */
  6337. this.motionBlur = false;
  6338. /**
  6339. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  6340. * @type {number}
  6341. * @default 0.7
  6342. */
  6343. this.lastFrameAlpha = 0.7;
  6344. /**
  6345. * Layer dpr
  6346. * @type {number}
  6347. */
  6348. this.dpr = dpr;
  6349. };
  6350. Layer.prototype = {
  6351. constructor: Layer,
  6352. __dirty: true,
  6353. __used: false,
  6354. __drawIndex: 0,
  6355. __startIndex: 0,
  6356. __endIndex: 0,
  6357. incremental: false,
  6358. getElementCount: function () {
  6359. return this.__endIndex - this.__startIndex;
  6360. },
  6361. initContext: function () {
  6362. this.ctx = this.dom.getContext('2d');
  6363. this.ctx.dpr = this.dpr;
  6364. },
  6365. createBackBuffer: function () {
  6366. var dpr = this.dpr;
  6367. this.domBack = createDom('back-' + this.id, this.painter, dpr);
  6368. this.ctxBack = this.domBack.getContext('2d');
  6369. if (dpr !== 1) {
  6370. this.ctxBack.scale(dpr, dpr);
  6371. }
  6372. },
  6373. /**
  6374. * @param {number} width
  6375. * @param {number} height
  6376. */
  6377. resize: function (width, height) {
  6378. var dpr = this.dpr;
  6379. var dom = this.dom;
  6380. var domStyle = dom.style;
  6381. var domBack = this.domBack;
  6382. if (domStyle) {
  6383. domStyle.width = width + 'px';
  6384. domStyle.height = height + 'px';
  6385. }
  6386. dom.width = width * dpr;
  6387. dom.height = height * dpr;
  6388. if (domBack) {
  6389. domBack.width = width * dpr;
  6390. domBack.height = height * dpr;
  6391. if (dpr !== 1) {
  6392. this.ctxBack.scale(dpr, dpr);
  6393. }
  6394. }
  6395. },
  6396. /**
  6397. * 清空该层画布
  6398. * @param {boolean} [clearAll]=false Clear all with out motion blur
  6399. * @param {Color} [clearColor]
  6400. */
  6401. clear: function (clearAll, clearColor) {
  6402. var dom = this.dom;
  6403. var ctx = this.ctx;
  6404. var width = dom.width;
  6405. var height = dom.height;
  6406. var clearColor = clearColor || this.clearColor;
  6407. var haveMotionBLur = this.motionBlur && !clearAll;
  6408. var lastFrameAlpha = this.lastFrameAlpha;
  6409. var dpr = this.dpr;
  6410. if (haveMotionBLur) {
  6411. if (!this.domBack) {
  6412. this.createBackBuffer();
  6413. }
  6414. this.ctxBack.globalCompositeOperation = 'copy';
  6415. this.ctxBack.drawImage(dom, 0, 0, width / dpr, height / dpr);
  6416. }
  6417. ctx.clearRect(0, 0, width, height);
  6418. if (clearColor && clearColor !== 'transparent') {
  6419. var clearColorGradientOrPattern; // Gradient
  6420. if (clearColor.colorStops) {
  6421. // Cache canvas gradient
  6422. clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, {
  6423. x: 0,
  6424. y: 0,
  6425. width: width,
  6426. height: height
  6427. });
  6428. clearColor.__canvasGradient = clearColorGradientOrPattern;
  6429. } // Pattern
  6430. else if (clearColor.image) {
  6431. clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx);
  6432. }
  6433. ctx.save();
  6434. ctx.fillStyle = clearColorGradientOrPattern || clearColor;
  6435. ctx.fillRect(0, 0, width, height);
  6436. ctx.restore();
  6437. }
  6438. if (haveMotionBLur) {
  6439. var domBack = this.domBack;
  6440. ctx.save();
  6441. ctx.globalAlpha = lastFrameAlpha;
  6442. ctx.drawImage(domBack, 0, 0, width, height);
  6443. ctx.restore();
  6444. }
  6445. }
  6446. };
  6447. var requestAnimationFrame = typeof window !== 'undefined' && (window.requestAnimationFrame && window.requestAnimationFrame.bind(window) || // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809
  6448. window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window) || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame) || function (func) {
  6449. setTimeout(func, 16);
  6450. };
  6451. var globalImageCache = new LRU(50);
  6452. /**
  6453. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6454. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6455. */
  6456. function findExistImage(newImageOrSrc) {
  6457. if (typeof newImageOrSrc === 'string') {
  6458. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6459. return cachedImgObj && cachedImgObj.image;
  6460. } else {
  6461. return newImageOrSrc;
  6462. }
  6463. }
  6464. /**
  6465. * Caution: User should cache loaded images, but not just count on LRU.
  6466. * Consider if required images more than LRU size, will dead loop occur?
  6467. *
  6468. * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc
  6469. * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image.
  6470. * @param {module:zrender/Element} [hostEl] For calling `dirty`.
  6471. * @param {Function} [cb] params: (image, cbPayload)
  6472. * @param {Object} [cbPayload] Payload on cb calling.
  6473. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image
  6474. */
  6475. function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) {
  6476. if (!newImageOrSrc) {
  6477. return image;
  6478. } else if (typeof newImageOrSrc === 'string') {
  6479. // Image should not be loaded repeatly.
  6480. if (image && image.__zrImageSrc === newImageOrSrc || !hostEl) {
  6481. return image;
  6482. } // Only when there is no existent image or existent image src
  6483. // is different, this method is responsible for load.
  6484. var cachedImgObj = globalImageCache.get(newImageOrSrc);
  6485. var pendingWrap = {
  6486. hostEl: hostEl,
  6487. cb: cb,
  6488. cbPayload: cbPayload
  6489. };
  6490. if (cachedImgObj) {
  6491. image = cachedImgObj.image;
  6492. !isImageReady(image) && cachedImgObj.pending.push(pendingWrap);
  6493. } else {
  6494. image = new Image();
  6495. image.onload = image.onerror = imageOnLoad;
  6496. globalImageCache.put(newImageOrSrc, image.__cachedImgObj = {
  6497. image: image,
  6498. pending: [pendingWrap]
  6499. });
  6500. image.src = image.__zrImageSrc = newImageOrSrc;
  6501. }
  6502. return image;
  6503. } // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas
  6504. else {
  6505. return newImageOrSrc;
  6506. }
  6507. }
  6508. function imageOnLoad() {
  6509. var cachedImgObj = this.__cachedImgObj;
  6510. this.onload = this.onerror = this.__cachedImgObj = null;
  6511. for (var i = 0; i < cachedImgObj.pending.length; i++) {
  6512. var pendingWrap = cachedImgObj.pending[i];
  6513. var cb = pendingWrap.cb;
  6514. cb && cb(this, pendingWrap.cbPayload);
  6515. pendingWrap.hostEl.dirty();
  6516. }
  6517. cachedImgObj.pending.length = 0;
  6518. }
  6519. function isImageReady(image) {
  6520. return image && image.width && image.height;
  6521. }
  6522. var textWidthCache = {};
  6523. var textWidthCacheCounter = 0;
  6524. var TEXT_CACHE_MAX = 5000;
  6525. var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g;
  6526. var DEFAULT_FONT$1 = '12px sans-serif'; // Avoid assign to an exported variable, for transforming to cjs.
  6527. var methods$1 = {};
  6528. /**
  6529. * @public
  6530. * @param {string} text
  6531. * @param {string} font
  6532. * @return {number} width
  6533. */
  6534. function getWidth(text, font) {
  6535. font = font || DEFAULT_FONT$1;
  6536. var key = text + ':' + font;
  6537. if (textWidthCache[key]) {
  6538. return textWidthCache[key];
  6539. }
  6540. var textLines = (text + '').split('\n');
  6541. var width = 0;
  6542. for (var i = 0, l = textLines.length; i < l; i++) {
  6543. // textContain.measureText may be overrided in SVG or VML
  6544. width = Math.max(measureText(textLines[i], font).width, width);
  6545. }
  6546. if (textWidthCacheCounter > TEXT_CACHE_MAX) {
  6547. textWidthCacheCounter = 0;
  6548. textWidthCache = {};
  6549. }
  6550. textWidthCacheCounter++;
  6551. textWidthCache[key] = width;
  6552. return width;
  6553. }
  6554. /**
  6555. * @public
  6556. * @param {string} text
  6557. * @param {string} font
  6558. * @param {string} [textAlign='left']
  6559. * @param {string} [textVerticalAlign='top']
  6560. * @param {Array.<number>} [textPadding]
  6561. * @param {Object} [rich]
  6562. * @param {Object} [truncate]
  6563. * @return {Object} {x, y, width, height, lineHeight}
  6564. */
  6565. function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6566. return rich ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate);
  6567. }
  6568. function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, truncate) {
  6569. var contentBlock = parsePlainText(text, font, textPadding, textLineHeight, truncate);
  6570. var outerWidth = getWidth(text, font);
  6571. if (textPadding) {
  6572. outerWidth += textPadding[1] + textPadding[3];
  6573. }
  6574. var outerHeight = contentBlock.outerHeight;
  6575. var x = adjustTextX(0, outerWidth, textAlign);
  6576. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6577. var rect = new BoundingRect(x, y, outerWidth, outerHeight);
  6578. rect.lineHeight = contentBlock.lineHeight;
  6579. return rect;
  6580. }
  6581. function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate) {
  6582. var contentBlock = parseRichText(text, {
  6583. rich: rich,
  6584. truncate: truncate,
  6585. font: font,
  6586. textAlign: textAlign,
  6587. textPadding: textPadding,
  6588. textLineHeight: textLineHeight
  6589. });
  6590. var outerWidth = contentBlock.outerWidth;
  6591. var outerHeight = contentBlock.outerHeight;
  6592. var x = adjustTextX(0, outerWidth, textAlign);
  6593. var y = adjustTextY(0, outerHeight, textVerticalAlign);
  6594. return new BoundingRect(x, y, outerWidth, outerHeight);
  6595. }
  6596. /**
  6597. * @public
  6598. * @param {number} x
  6599. * @param {number} width
  6600. * @param {string} [textAlign='left']
  6601. * @return {number} Adjusted x.
  6602. */
  6603. function adjustTextX(x, width, textAlign) {
  6604. // FIXME Right to left language
  6605. if (textAlign === 'right') {
  6606. x -= width;
  6607. } else if (textAlign === 'center') {
  6608. x -= width / 2;
  6609. }
  6610. return x;
  6611. }
  6612. /**
  6613. * @public
  6614. * @param {number} y
  6615. * @param {number} height
  6616. * @param {string} [textVerticalAlign='top']
  6617. * @return {number} Adjusted y.
  6618. */
  6619. function adjustTextY(y, height, textVerticalAlign) {
  6620. if (textVerticalAlign === 'middle') {
  6621. y -= height / 2;
  6622. } else if (textVerticalAlign === 'bottom') {
  6623. y -= height;
  6624. }
  6625. return y;
  6626. }
  6627. /**
  6628. * Follow same interface to `Displayable.prototype.calculateTextPosition`.
  6629. * @public
  6630. * @param {Obejct} [out] Prepared out object. If not input, auto created in the method.
  6631. * @param {module:zrender/graphic/Style} style where `textPosition` and `textDistance` are visited.
  6632. * @param {Object} rect {x, y, width, height} Rect of the host elment, according to which the text positioned.
  6633. * @return {Object} The input `out`. Set: {x, y, textAlign, textVerticalAlign}
  6634. */
  6635. function calculateTextPosition(out, style, rect) {
  6636. var textPosition = style.textPosition;
  6637. var distance = style.textDistance;
  6638. var x = rect.x;
  6639. var y = rect.y;
  6640. distance = distance || 0;
  6641. var height = rect.height;
  6642. var width = rect.width;
  6643. var halfHeight = height / 2;
  6644. var textAlign = 'left';
  6645. var textVerticalAlign = 'top';
  6646. switch (textPosition) {
  6647. case 'left':
  6648. x -= distance;
  6649. y += halfHeight;
  6650. textAlign = 'right';
  6651. textVerticalAlign = 'middle';
  6652. break;
  6653. case 'right':
  6654. x += distance + width;
  6655. y += halfHeight;
  6656. textVerticalAlign = 'middle';
  6657. break;
  6658. case 'top':
  6659. x += width / 2;
  6660. y -= distance;
  6661. textAlign = 'center';
  6662. textVerticalAlign = 'bottom';
  6663. break;
  6664. case 'bottom':
  6665. x += width / 2;
  6666. y += height + distance;
  6667. textAlign = 'center';
  6668. break;
  6669. case 'inside':
  6670. x += width / 2;
  6671. y += halfHeight;
  6672. textAlign = 'center';
  6673. textVerticalAlign = 'middle';
  6674. break;
  6675. case 'insideLeft':
  6676. x += distance;
  6677. y += halfHeight;
  6678. textVerticalAlign = 'middle';
  6679. break;
  6680. case 'insideRight':
  6681. x += width - distance;
  6682. y += halfHeight;
  6683. textAlign = 'right';
  6684. textVerticalAlign = 'middle';
  6685. break;
  6686. case 'insideTop':
  6687. x += width / 2;
  6688. y += distance;
  6689. textAlign = 'center';
  6690. break;
  6691. case 'insideBottom':
  6692. x += width / 2;
  6693. y += height - distance;
  6694. textAlign = 'center';
  6695. textVerticalAlign = 'bottom';
  6696. break;
  6697. case 'insideTopLeft':
  6698. x += distance;
  6699. y += distance;
  6700. break;
  6701. case 'insideTopRight':
  6702. x += width - distance;
  6703. y += distance;
  6704. textAlign = 'right';
  6705. break;
  6706. case 'insideBottomLeft':
  6707. x += distance;
  6708. y += height - distance;
  6709. textVerticalAlign = 'bottom';
  6710. break;
  6711. case 'insideBottomRight':
  6712. x += width - distance;
  6713. y += height - distance;
  6714. textAlign = 'right';
  6715. textVerticalAlign = 'bottom';
  6716. break;
  6717. }
  6718. out = out || {};
  6719. out.x = x;
  6720. out.y = y;
  6721. out.textAlign = textAlign;
  6722. out.textVerticalAlign = textVerticalAlign;
  6723. return out;
  6724. }
  6725. /**
  6726. * To be removed. But still do not remove in case that some one has imported it.
  6727. * @deprecated
  6728. * @public
  6729. * @param {stirng} textPosition
  6730. * @param {Object} rect {x, y, width, height}
  6731. * @param {number} distance
  6732. * @return {Object} {x, y, textAlign, textVerticalAlign}
  6733. */
  6734. /**
  6735. * Show ellipsis if overflow.
  6736. *
  6737. * @public
  6738. * @param {string} text
  6739. * @param {string} containerWidth
  6740. * @param {string} font
  6741. * @param {number} [ellipsis='...']
  6742. * @param {Object} [options]
  6743. * @param {number} [options.maxIterations=3]
  6744. * @param {number} [options.minChar=0] If truncate result are less
  6745. * then minChar, ellipsis will not show, which is
  6746. * better for user hint in some cases.
  6747. * @param {number} [options.placeholder=''] When all truncated, use the placeholder.
  6748. * @return {string}
  6749. */
  6750. function truncateText(text, containerWidth, font, ellipsis, options) {
  6751. if (!containerWidth) {
  6752. return '';
  6753. }
  6754. var textLines = (text + '').split('\n');
  6755. options = prepareTruncateOptions(containerWidth, font, ellipsis, options); // FIXME
  6756. // It is not appropriate that every line has '...' when truncate multiple lines.
  6757. for (var i = 0, len = textLines.length; i < len; i++) {
  6758. textLines[i] = truncateSingleLine(textLines[i], options);
  6759. }
  6760. return textLines.join('\n');
  6761. }
  6762. function prepareTruncateOptions(containerWidth, font, ellipsis, options) {
  6763. options = extend({}, options);
  6764. options.font = font;
  6765. var ellipsis = retrieve2(ellipsis, '...');
  6766. options.maxIterations = retrieve2(options.maxIterations, 2);
  6767. var minChar = options.minChar = retrieve2(options.minChar, 0); // FIXME
  6768. // Other languages?
  6769. options.cnCharWidth = getWidth('国', font); // FIXME
  6770. // Consider proportional font?
  6771. var ascCharWidth = options.ascCharWidth = getWidth('a', font);
  6772. options.placeholder = retrieve2(options.placeholder, ''); // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'.
  6773. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'.
  6774. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap.
  6775. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) {
  6776. contentWidth -= ascCharWidth;
  6777. }
  6778. var ellipsisWidth = getWidth(ellipsis, font);
  6779. if (ellipsisWidth > contentWidth) {
  6780. ellipsis = '';
  6781. ellipsisWidth = 0;
  6782. }
  6783. contentWidth = containerWidth - ellipsisWidth;
  6784. options.ellipsis = ellipsis;
  6785. options.ellipsisWidth = ellipsisWidth;
  6786. options.contentWidth = contentWidth;
  6787. options.containerWidth = containerWidth;
  6788. return options;
  6789. }
  6790. function truncateSingleLine(textLine, options) {
  6791. var containerWidth = options.containerWidth;
  6792. var font = options.font;
  6793. var contentWidth = options.contentWidth;
  6794. if (!containerWidth) {
  6795. return '';
  6796. }
  6797. var lineWidth = getWidth(textLine, font);
  6798. if (lineWidth <= containerWidth) {
  6799. return textLine;
  6800. }
  6801. for (var j = 0;; j++) {
  6802. if (lineWidth <= contentWidth || j >= options.maxIterations) {
  6803. textLine += options.ellipsis;
  6804. break;
  6805. }
  6806. var subLength = j === 0 ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth) : lineWidth > 0 ? Math.floor(textLine.length * contentWidth / lineWidth) : 0;
  6807. textLine = textLine.substr(0, subLength);
  6808. lineWidth = getWidth(textLine, font);
  6809. }
  6810. if (textLine === '') {
  6811. textLine = options.placeholder;
  6812. }
  6813. return textLine;
  6814. }
  6815. function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) {
  6816. var width = 0;
  6817. var i = 0;
  6818. for (var len = text.length; i < len && width < contentWidth; i++) {
  6819. var charCode = text.charCodeAt(i);
  6820. width += 0 <= charCode && charCode <= 127 ? ascCharWidth : cnCharWidth;
  6821. }
  6822. return i;
  6823. }
  6824. /**
  6825. * @public
  6826. * @param {string} font
  6827. * @return {number} line height
  6828. */
  6829. function getLineHeight(font) {
  6830. // FIXME A rough approach.
  6831. return getWidth('国', font);
  6832. }
  6833. /**
  6834. * @public
  6835. * @param {string} text
  6836. * @param {string} font
  6837. * @return {Object} width
  6838. */
  6839. function measureText(text, font) {
  6840. return methods$1.measureText(text, font);
  6841. } // Avoid assign to an exported variable, for transforming to cjs.
  6842. methods$1.measureText = function (text, font) {
  6843. var ctx = getContext();
  6844. ctx.font = font || DEFAULT_FONT$1;
  6845. return ctx.measureText(text);
  6846. };
  6847. /**
  6848. * @public
  6849. * @param {string} text
  6850. * @param {string} font
  6851. * @param {Object} [truncate]
  6852. * @return {Object} block: {lineHeight, lines, height, outerHeight, canCacheByTextString}
  6853. * Notice: for performance, do not calculate outerWidth util needed.
  6854. * `canCacheByTextString` means the result `lines` is only determined by the input `text`.
  6855. * Thus we can simply comparing the `input` text to determin whether the result changed,
  6856. * without travel the result `lines`.
  6857. */
  6858. function parsePlainText(text, font, padding, textLineHeight, truncate) {
  6859. text != null && (text += '');
  6860. var lineHeight = retrieve2(textLineHeight, getLineHeight(font));
  6861. var lines = text ? text.split('\n') : [];
  6862. var height = lines.length * lineHeight;
  6863. var outerHeight = height;
  6864. var canCacheByTextString = true;
  6865. if (padding) {
  6866. outerHeight += padding[0] + padding[2];
  6867. }
  6868. if (text && truncate) {
  6869. canCacheByTextString = false;
  6870. var truncOuterHeight = truncate.outerHeight;
  6871. var truncOuterWidth = truncate.outerWidth;
  6872. if (truncOuterHeight != null && outerHeight > truncOuterHeight) {
  6873. text = '';
  6874. lines = [];
  6875. } else if (truncOuterWidth != null) {
  6876. var options = prepareTruncateOptions(truncOuterWidth - (padding ? padding[1] + padding[3] : 0), font, truncate.ellipsis, {
  6877. minChar: truncate.minChar,
  6878. placeholder: truncate.placeholder
  6879. }); // FIXME
  6880. // It is not appropriate that every line has '...' when truncate multiple lines.
  6881. for (var i = 0, len = lines.length; i < len; i++) {
  6882. lines[i] = truncateSingleLine(lines[i], options);
  6883. }
  6884. }
  6885. }
  6886. return {
  6887. lines: lines,
  6888. height: height,
  6889. outerHeight: outerHeight,
  6890. lineHeight: lineHeight,
  6891. canCacheByTextString: canCacheByTextString
  6892. };
  6893. }
  6894. /**
  6895. * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx'
  6896. * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'.
  6897. *
  6898. * @public
  6899. * @param {string} text
  6900. * @param {Object} style
  6901. * @return {Object} block
  6902. * {
  6903. * width,
  6904. * height,
  6905. * lines: [{
  6906. * lineHeight,
  6907. * width,
  6908. * tokens: [[{
  6909. * styleName,
  6910. * text,
  6911. * width, // include textPadding
  6912. * height, // include textPadding
  6913. * textWidth, // pure text width
  6914. * textHeight, // pure text height
  6915. * lineHeihgt,
  6916. * font,
  6917. * textAlign,
  6918. * textVerticalAlign
  6919. * }], [...], ...]
  6920. * }, ...]
  6921. * }
  6922. * If styleName is undefined, it is plain text.
  6923. */
  6924. function parseRichText(text, style) {
  6925. var contentBlock = {
  6926. lines: [],
  6927. width: 0,
  6928. height: 0
  6929. };
  6930. text != null && (text += '');
  6931. if (!text) {
  6932. return contentBlock;
  6933. }
  6934. var lastIndex = STYLE_REG.lastIndex = 0;
  6935. var result;
  6936. while ((result = STYLE_REG.exec(text)) != null) {
  6937. var matchedIndex = result.index;
  6938. if (matchedIndex > lastIndex) {
  6939. pushTokens(contentBlock, text.substring(lastIndex, matchedIndex));
  6940. }
  6941. pushTokens(contentBlock, result[2], result[1]);
  6942. lastIndex = STYLE_REG.lastIndex;
  6943. }
  6944. if (lastIndex < text.length) {
  6945. pushTokens(contentBlock, text.substring(lastIndex, text.length));
  6946. }
  6947. var lines = contentBlock.lines;
  6948. var contentHeight = 0;
  6949. var contentWidth = 0; // For `textWidth: 100%`
  6950. var pendingList = [];
  6951. var stlPadding = style.textPadding;
  6952. var truncate = style.truncate;
  6953. var truncateWidth = truncate && truncate.outerWidth;
  6954. var truncateHeight = truncate && truncate.outerHeight;
  6955. if (stlPadding) {
  6956. truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]);
  6957. truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]);
  6958. } // Calculate layout info of tokens.
  6959. for (var i = 0; i < lines.length; i++) {
  6960. var line = lines[i];
  6961. var lineHeight = 0;
  6962. var lineWidth = 0;
  6963. for (var j = 0; j < line.tokens.length; j++) {
  6964. var token = line.tokens[j];
  6965. var tokenStyle = token.styleName && style.rich[token.styleName] || {}; // textPadding should not inherit from style.
  6966. var textPadding = token.textPadding = tokenStyle.textPadding; // textFont has been asigned to font by `normalizeStyle`.
  6967. var font = token.font = tokenStyle.font || style.font; // textHeight can be used when textVerticalAlign is specified in token.
  6968. var tokenHeight = token.textHeight = retrieve2( // textHeight should not be inherited, consider it can be specified
  6969. // as box height of the block.
  6970. tokenStyle.textHeight, getLineHeight(font));
  6971. textPadding && (tokenHeight += textPadding[0] + textPadding[2]);
  6972. token.height = tokenHeight;
  6973. token.lineHeight = retrieve3(tokenStyle.textLineHeight, style.textLineHeight, tokenHeight);
  6974. token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign;
  6975. token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle';
  6976. if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) {
  6977. return {
  6978. lines: [],
  6979. width: 0,
  6980. height: 0
  6981. };
  6982. }
  6983. token.textWidth = getWidth(token.text, font);
  6984. var tokenWidth = tokenStyle.textWidth;
  6985. var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto'; // Percent width, can be `100%`, can be used in drawing separate
  6986. // line when box width is needed to be auto.
  6987. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') {
  6988. token.percentWidth = tokenWidth;
  6989. pendingList.push(token);
  6990. tokenWidth = 0; // Do not truncate in this case, because there is no user case
  6991. // and it is too complicated.
  6992. } else {
  6993. if (tokenWidthNotSpecified) {
  6994. tokenWidth = token.textWidth; // FIXME: If image is not loaded and textWidth is not specified, calling
  6995. // `getBoundingRect()` will not get correct result.
  6996. var textBackgroundColor = tokenStyle.textBackgroundColor;
  6997. var bgImg = textBackgroundColor && textBackgroundColor.image; // Use cases:
  6998. // (1) If image is not loaded, it will be loaded at render phase and call
  6999. // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded
  7000. // image, and then the right size will be calculated here at the next tick.
  7001. // See `graphic/helper/text.js`.
  7002. // (2) If image loaded, and `textBackgroundColor.image` is image src string,
  7003. // use `imageHelper.findExistImage` to find cached image.
  7004. // `imageHelper.findExistImage` will always be called here before
  7005. // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText`
  7006. // which ensures that image will not be rendered before correct size calcualted.
  7007. if (bgImg) {
  7008. bgImg = findExistImage(bgImg);
  7009. if (isImageReady(bgImg)) {
  7010. tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height);
  7011. }
  7012. }
  7013. }
  7014. var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0;
  7015. tokenWidth += paddingW;
  7016. var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null;
  7017. if (remianTruncWidth != null && remianTruncWidth < tokenWidth) {
  7018. if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) {
  7019. token.text = '';
  7020. token.textWidth = tokenWidth = 0;
  7021. } else {
  7022. token.text = truncateText(token.text, remianTruncWidth - paddingW, font, truncate.ellipsis, {
  7023. minChar: truncate.minChar
  7024. });
  7025. token.textWidth = getWidth(token.text, font);
  7026. tokenWidth = token.textWidth + paddingW;
  7027. }
  7028. }
  7029. }
  7030. lineWidth += token.width = tokenWidth;
  7031. tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight));
  7032. }
  7033. line.width = lineWidth;
  7034. line.lineHeight = lineHeight;
  7035. contentHeight += lineHeight;
  7036. contentWidth = Math.max(contentWidth, lineWidth);
  7037. }
  7038. contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth);
  7039. contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight);
  7040. if (stlPadding) {
  7041. contentBlock.outerWidth += stlPadding[1] + stlPadding[3];
  7042. contentBlock.outerHeight += stlPadding[0] + stlPadding[2];
  7043. }
  7044. for (var i = 0; i < pendingList.length; i++) {
  7045. var token = pendingList[i];
  7046. var percentWidth = token.percentWidth; // Should not base on outerWidth, because token can not be placed out of padding.
  7047. token.width = parseInt(percentWidth, 10) / 100 * contentWidth;
  7048. }
  7049. return contentBlock;
  7050. }
  7051. function pushTokens(block, str, styleName) {
  7052. var isEmptyStr = str === '';
  7053. var strs = str.split('\n');
  7054. var lines = block.lines;
  7055. for (var i = 0; i < strs.length; i++) {
  7056. var text = strs[i];
  7057. var token = {
  7058. styleName: styleName,
  7059. text: text,
  7060. isLineHolder: !text && !isEmptyStr
  7061. }; // The first token should be appended to the last line.
  7062. if (!i) {
  7063. var tokens = (lines[lines.length - 1] || (lines[0] = {
  7064. tokens: []
  7065. })).tokens; // Consider cases:
  7066. // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item
  7067. // (which is a placeholder) should be replaced by new token.
  7068. // (2) A image backage, where token likes {a|}.
  7069. // (3) A redundant '' will affect textAlign in line.
  7070. // (4) tokens with the same tplName should not be merged, because
  7071. // they should be displayed in different box (with border and padding).
  7072. var tokensLen = tokens.length;
  7073. tokensLen === 1 && tokens[0].isLineHolder ? tokens[0] = token : // Consider text is '', only insert when it is the "lineHolder" or
  7074. // "emptyStr". Otherwise a redundant '' will affect textAlign in line.
  7075. (text || !tokensLen || isEmptyStr) && tokens.push(token);
  7076. } // Other tokens always start a new line.
  7077. else {
  7078. // If there is '', insert it as a placeholder.
  7079. lines.push({
  7080. tokens: [token]
  7081. });
  7082. }
  7083. }
  7084. }
  7085. function makeFont(style) {
  7086. // FIXME in node-canvas fontWeight is before fontStyle
  7087. // Use `fontSize` `fontFamily` to check whether font properties are defined.
  7088. var font = (style.fontSize || style.fontFamily) && [style.fontStyle, style.fontWeight, (style.fontSize || 12) + 'px', // If font properties are defined, `fontFamily` should not be ignored.
  7089. style.fontFamily || 'sans-serif'].join(' ');
  7090. return font && trim(font) || style.textFont || style.font;
  7091. }
  7092. /**
  7093. * @param {Object} ctx
  7094. * @param {Object} shape
  7095. * @param {number} shape.x
  7096. * @param {number} shape.y
  7097. * @param {number} shape.width
  7098. * @param {number} shape.height
  7099. * @param {number} shape.r
  7100. */
  7101. function buildPath(ctx, shape) {
  7102. var x = shape.x;
  7103. var y = shape.y;
  7104. var width = shape.width;
  7105. var height = shape.height;
  7106. var r = shape.r;
  7107. var r1;
  7108. var r2;
  7109. var r3;
  7110. var r4; // Convert width and height to positive for better borderRadius
  7111. if (width < 0) {
  7112. x = x + width;
  7113. width = -width;
  7114. }
  7115. if (height < 0) {
  7116. y = y + height;
  7117. height = -height;
  7118. }
  7119. if (typeof r === 'number') {
  7120. r1 = r2 = r3 = r4 = r;
  7121. } else if (r instanceof Array) {
  7122. if (r.length === 1) {
  7123. r1 = r2 = r3 = r4 = r[0];
  7124. } else if (r.length === 2) {
  7125. r1 = r3 = r[0];
  7126. r2 = r4 = r[1];
  7127. } else if (r.length === 3) {
  7128. r1 = r[0];
  7129. r2 = r4 = r[1];
  7130. r3 = r[2];
  7131. } else {
  7132. r1 = r[0];
  7133. r2 = r[1];
  7134. r3 = r[2];
  7135. r4 = r[3];
  7136. }
  7137. } else {
  7138. r1 = r2 = r3 = r4 = 0;
  7139. }
  7140. var total;
  7141. if (r1 + r2 > width) {
  7142. total = r1 + r2;
  7143. r1 *= width / total;
  7144. r2 *= width / total;
  7145. }
  7146. if (r3 + r4 > width) {
  7147. total = r3 + r4;
  7148. r3 *= width / total;
  7149. r4 *= width / total;
  7150. }
  7151. if (r2 + r3 > height) {
  7152. total = r2 + r3;
  7153. r2 *= height / total;
  7154. r3 *= height / total;
  7155. }
  7156. if (r1 + r4 > height) {
  7157. total = r1 + r4;
  7158. r1 *= height / total;
  7159. r4 *= height / total;
  7160. }
  7161. ctx.moveTo(x + r1, y);
  7162. ctx.lineTo(x + width - r2, y);
  7163. r2 !== 0 && ctx.arc(x + width - r2, y + r2, r2, -Math.PI / 2, 0);
  7164. ctx.lineTo(x + width, y + height - r3);
  7165. r3 !== 0 && ctx.arc(x + width - r3, y + height - r3, r3, 0, Math.PI / 2);
  7166. ctx.lineTo(x + r4, y + height);
  7167. r4 !== 0 && ctx.arc(x + r4, y + height - r4, r4, Math.PI / 2, Math.PI);
  7168. ctx.lineTo(x, y + r1);
  7169. r1 !== 0 && ctx.arc(x + r1, y + r1, r1, Math.PI, Math.PI * 1.5);
  7170. }
  7171. var DEFAULT_FONT = DEFAULT_FONT$1; // TODO: Have not support 'start', 'end' yet.
  7172. var VALID_TEXT_ALIGN = {
  7173. left: 1,
  7174. right: 1,
  7175. center: 1
  7176. };
  7177. var VALID_TEXT_VERTICAL_ALIGN = {
  7178. top: 1,
  7179. bottom: 1,
  7180. middle: 1
  7181. }; // Different from `STYLE_COMMON_PROPS` of `graphic/Style`,
  7182. // the default value of shadowColor is `'transparent'`.
  7183. var SHADOW_STYLE_COMMON_PROPS = [['textShadowBlur', 'shadowBlur', 0], ['textShadowOffsetX', 'shadowOffsetX', 0], ['textShadowOffsetY', 'shadowOffsetY', 0], ['textShadowColor', 'shadowColor', 'transparent']];
  7184. var _tmpTextPositionResult = {};
  7185. var _tmpBoxPositionResult = {};
  7186. /**
  7187. * @param {module:zrender/graphic/Style} style
  7188. * @return {module:zrender/graphic/Style} The input style.
  7189. */
  7190. function normalizeTextStyle(style) {
  7191. normalizeStyle(style);
  7192. each$1(style.rich, normalizeStyle);
  7193. return style;
  7194. }
  7195. function normalizeStyle(style) {
  7196. if (style) {
  7197. style.font = makeFont(style);
  7198. var textAlign = style.textAlign;
  7199. textAlign === 'middle' && (textAlign = 'center');
  7200. style.textAlign = textAlign == null || VALID_TEXT_ALIGN[textAlign] ? textAlign : 'left'; // Compatible with textBaseline.
  7201. var textVerticalAlign = style.textVerticalAlign || style.textBaseline;
  7202. textVerticalAlign === 'center' && (textVerticalAlign = 'middle');
  7203. style.textVerticalAlign = textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign] ? textVerticalAlign : 'top';
  7204. var textPadding = style.textPadding;
  7205. if (textPadding) {
  7206. style.textPadding = normalizeCssArray(style.textPadding);
  7207. }
  7208. }
  7209. }
  7210. /**
  7211. * @param {CanvasRenderingContext2D} ctx
  7212. * @param {string} text
  7213. * @param {module:zrender/graphic/Style} style
  7214. * @param {Object|boolean} [rect] {x, y, width, height}
  7215. * If set false, rect text is not used.
  7216. * @param {Element|module:zrender/graphic/helper/constant.WILL_BE_RESTORED} [prevEl] For ctx prop cache.
  7217. */
  7218. function renderText(hostEl, ctx, text, style, rect, prevEl) {
  7219. style.rich ? renderRichText(hostEl, ctx, text, style, rect, prevEl) : renderPlainText(hostEl, ctx, text, style, rect, prevEl);
  7220. } // Avoid setting to ctx according to prevEl if possible for
  7221. // performance in scenarios of large amount text.
  7222. function renderPlainText(hostEl, ctx, text, style, rect, prevEl) {
  7223. 'use strict';
  7224. var needDrawBg = needDrawBackground(style);
  7225. var prevStyle;
  7226. var checkCache = false;
  7227. var cachedByMe = ctx.__attrCachedBy === ContextCachedBy.PLAIN_TEXT; // Only take and check cache for `Text` el, but not RectText.
  7228. if (prevEl !== WILL_BE_RESTORED) {
  7229. if (prevEl) {
  7230. prevStyle = prevEl.style;
  7231. checkCache = !needDrawBg && cachedByMe && prevStyle;
  7232. } // Prevent from using cache in `Style::bind`, because of the case:
  7233. // ctx property is modified by other properties than `Style::bind`
  7234. // used, and Style::bind is called next.
  7235. ctx.__attrCachedBy = needDrawBg ? ContextCachedBy.NONE : ContextCachedBy.PLAIN_TEXT;
  7236. } // Since this will be restored, prevent from using these props to check cache in the next
  7237. // entering of this method. But do not need to clear other cache like `Style::bind`.
  7238. else if (cachedByMe) {
  7239. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7240. }
  7241. var styleFont = style.font || DEFAULT_FONT; // PENDING
  7242. // Only `Text` el set `font` and keep it (`RectText` will restore). So theoretically
  7243. // we can make font cache on ctx, which can cache for text el that are discontinuous.
  7244. // But layer save/restore needed to be considered.
  7245. // if (styleFont !== ctx.__fontCache) {
  7246. // ctx.font = styleFont;
  7247. // if (prevEl !== WILL_BE_RESTORED) {
  7248. // ctx.__fontCache = styleFont;
  7249. // }
  7250. // }
  7251. if (!checkCache || styleFont !== (prevStyle.font || DEFAULT_FONT)) {
  7252. ctx.font = styleFont;
  7253. } // Use the final font from context-2d, because the final
  7254. // font might not be the style.font when it is illegal.
  7255. // But get `ctx.font` might be time consuming.
  7256. var computedFont = hostEl.__computedFont;
  7257. if (hostEl.__styleFont !== styleFont) {
  7258. hostEl.__styleFont = styleFont;
  7259. computedFont = hostEl.__computedFont = ctx.font;
  7260. }
  7261. var textPadding = style.textPadding;
  7262. var textLineHeight = style.textLineHeight;
  7263. var contentBlock = hostEl.__textCotentBlock;
  7264. if (!contentBlock || hostEl.__dirtyText) {
  7265. contentBlock = hostEl.__textCotentBlock = parsePlainText(text, computedFont, textPadding, textLineHeight, style.truncate);
  7266. }
  7267. var outerHeight = contentBlock.outerHeight;
  7268. var textLines = contentBlock.lines;
  7269. var lineHeight = contentBlock.lineHeight;
  7270. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7271. var baseX = boxPos.baseX;
  7272. var baseY = boxPos.baseY;
  7273. var textAlign = boxPos.textAlign || 'left';
  7274. var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing.
  7275. applyTextRotation(ctx, style, rect, baseX, baseY);
  7276. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7277. var textX = baseX;
  7278. var textY = boxY;
  7279. if (needDrawBg || textPadding) {
  7280. // Consider performance, do not call getTextWidth util necessary.
  7281. var textWidth = getWidth(text, computedFont);
  7282. var outerWidth = textWidth;
  7283. textPadding && (outerWidth += textPadding[1] + textPadding[3]);
  7284. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7285. needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7286. if (textPadding) {
  7287. textX = getTextXForPadding(baseX, textAlign, textPadding);
  7288. textY += textPadding[0];
  7289. }
  7290. } // Always set textAlign and textBase line, because it is difficute to calculate
  7291. // textAlign from prevEl, and we dont sure whether textAlign will be reset if
  7292. // font set happened.
  7293. ctx.textAlign = textAlign; // Force baseline to be "middle". Otherwise, if using "top", the
  7294. // text will offset downward a little bit in font "Microsoft YaHei".
  7295. ctx.textBaseline = 'middle'; // Set text opacity
  7296. ctx.globalAlpha = style.opacity || 1; // Always set shadowBlur and shadowOffset to avoid leak from displayable.
  7297. for (var i = 0; i < SHADOW_STYLE_COMMON_PROPS.length; i++) {
  7298. var propItem = SHADOW_STYLE_COMMON_PROPS[i];
  7299. var styleProp = propItem[0];
  7300. var ctxProp = propItem[1];
  7301. var val = style[styleProp];
  7302. if (!checkCache || val !== prevStyle[styleProp]) {
  7303. ctx[ctxProp] = fixShadow(ctx, ctxProp, val || propItem[2]);
  7304. }
  7305. } // `textBaseline` is set as 'middle'.
  7306. textY += lineHeight / 2;
  7307. var textStrokeWidth = style.textStrokeWidth;
  7308. var textStrokeWidthPrev = checkCache ? prevStyle.textStrokeWidth : null;
  7309. var strokeWidthChanged = !checkCache || textStrokeWidth !== textStrokeWidthPrev;
  7310. var strokeChanged = !checkCache || strokeWidthChanged || style.textStroke !== prevStyle.textStroke;
  7311. var textStroke = getStroke(style.textStroke, textStrokeWidth);
  7312. var textFill = getFill(style.textFill);
  7313. if (textStroke) {
  7314. if (strokeWidthChanged) {
  7315. ctx.lineWidth = textStrokeWidth;
  7316. }
  7317. if (strokeChanged) {
  7318. ctx.strokeStyle = textStroke;
  7319. }
  7320. }
  7321. if (textFill) {
  7322. if (!checkCache || style.textFill !== prevStyle.textFill) {
  7323. ctx.fillStyle = textFill;
  7324. }
  7325. } // Optimize simply, in most cases only one line exists.
  7326. if (textLines.length === 1) {
  7327. // Fill after stroke so the outline will not cover the main part.
  7328. textStroke && ctx.strokeText(textLines[0], textX, textY);
  7329. textFill && ctx.fillText(textLines[0], textX, textY);
  7330. } else {
  7331. for (var i = 0; i < textLines.length; i++) {
  7332. // Fill after stroke so the outline will not cover the main part.
  7333. textStroke && ctx.strokeText(textLines[i], textX, textY);
  7334. textFill && ctx.fillText(textLines[i], textX, textY);
  7335. textY += lineHeight;
  7336. }
  7337. }
  7338. }
  7339. function renderRichText(hostEl, ctx, text, style, rect, prevEl) {
  7340. // Do not do cache for rich text because of the complexity.
  7341. // But `RectText` this will be restored, do not need to clear other cache like `Style::bind`.
  7342. if (prevEl !== WILL_BE_RESTORED) {
  7343. ctx.__attrCachedBy = ContextCachedBy.NONE;
  7344. }
  7345. var contentBlock = hostEl.__textCotentBlock;
  7346. if (!contentBlock || hostEl.__dirtyText) {
  7347. contentBlock = hostEl.__textCotentBlock = parseRichText(text, style);
  7348. }
  7349. drawRichText(hostEl, ctx, contentBlock, style, rect);
  7350. }
  7351. function drawRichText(hostEl, ctx, contentBlock, style, rect) {
  7352. var contentWidth = contentBlock.width;
  7353. var outerWidth = contentBlock.outerWidth;
  7354. var outerHeight = contentBlock.outerHeight;
  7355. var textPadding = style.textPadding;
  7356. var boxPos = getBoxPosition(_tmpBoxPositionResult, hostEl, style, rect);
  7357. var baseX = boxPos.baseX;
  7358. var baseY = boxPos.baseY;
  7359. var textAlign = boxPos.textAlign;
  7360. var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing.
  7361. applyTextRotation(ctx, style, rect, baseX, baseY);
  7362. var boxX = adjustTextX(baseX, outerWidth, textAlign);
  7363. var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign);
  7364. var xLeft = boxX;
  7365. var lineTop = boxY;
  7366. if (textPadding) {
  7367. xLeft += textPadding[3];
  7368. lineTop += textPadding[0];
  7369. }
  7370. var xRight = xLeft + contentWidth;
  7371. needDrawBackground(style) && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight);
  7372. for (var i = 0; i < contentBlock.lines.length; i++) {
  7373. var line = contentBlock.lines[i];
  7374. var tokens = line.tokens;
  7375. var tokenCount = tokens.length;
  7376. var lineHeight = line.lineHeight;
  7377. var usedWidth = line.width;
  7378. var leftIndex = 0;
  7379. var lineXLeft = xLeft;
  7380. var lineXRight = xRight;
  7381. var rightIndex = tokenCount - 1;
  7382. var token;
  7383. while (leftIndex < tokenCount && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left')) {
  7384. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left');
  7385. usedWidth -= token.width;
  7386. lineXLeft += token.width;
  7387. leftIndex++;
  7388. }
  7389. while (rightIndex >= 0 && (token = tokens[rightIndex], token.textAlign === 'right')) {
  7390. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right');
  7391. usedWidth -= token.width;
  7392. lineXRight -= token.width;
  7393. rightIndex--;
  7394. } // The other tokens are placed as textAlign 'center' if there is enough space.
  7395. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2;
  7396. while (leftIndex <= rightIndex) {
  7397. token = tokens[leftIndex]; // Consider width specified by user, use 'center' rather than 'left'.
  7398. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center');
  7399. lineXLeft += token.width;
  7400. leftIndex++;
  7401. }
  7402. lineTop += lineHeight;
  7403. }
  7404. }
  7405. function applyTextRotation(ctx, style, rect, x, y) {
  7406. // textRotation only apply in RectText.
  7407. if (rect && style.textRotation) {
  7408. var origin = style.textOrigin;
  7409. if (origin === 'center') {
  7410. x = rect.width / 2 + rect.x;
  7411. y = rect.height / 2 + rect.y;
  7412. } else if (origin) {
  7413. x = origin[0] + rect.x;
  7414. y = origin[1] + rect.y;
  7415. }
  7416. ctx.translate(x, y); // Positive: anticlockwise
  7417. ctx.rotate(-style.textRotation);
  7418. ctx.translate(-x, -y);
  7419. }
  7420. }
  7421. function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) {
  7422. var tokenStyle = style.rich[token.styleName] || {};
  7423. tokenStyle.text = token.text; // 'ctx.textBaseline' is always set as 'middle', for sake of
  7424. // the bias of "Microsoft YaHei".
  7425. var textVerticalAlign = token.textVerticalAlign;
  7426. var y = lineTop + lineHeight / 2;
  7427. if (textVerticalAlign === 'top') {
  7428. y = lineTop + token.height / 2;
  7429. } else if (textVerticalAlign === 'bottom') {
  7430. y = lineTop + lineHeight - token.height / 2;
  7431. }
  7432. !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground(hostEl, ctx, tokenStyle, textAlign === 'right' ? x - token.width : textAlign === 'center' ? x - token.width / 2 : x, y - token.height / 2, token.width, token.height);
  7433. var textPadding = token.textPadding;
  7434. if (textPadding) {
  7435. x = getTextXForPadding(x, textAlign, textPadding);
  7436. y -= token.height / 2 - textPadding[2] - token.textHeight / 2;
  7437. }
  7438. setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0));
  7439. setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent');
  7440. setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0));
  7441. setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0));
  7442. setCtx(ctx, 'textAlign', textAlign); // Force baseline to be "middle". Otherwise, if using "top", the
  7443. // text will offset downward a little bit in font "Microsoft YaHei".
  7444. setCtx(ctx, 'textBaseline', 'middle');
  7445. setCtx(ctx, 'font', token.font || DEFAULT_FONT);
  7446. var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth);
  7447. var textFill = getFill(tokenStyle.textFill || style.textFill);
  7448. var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth); // Fill after stroke so the outline will not cover the main part.
  7449. if (textStroke) {
  7450. setCtx(ctx, 'lineWidth', textStrokeWidth);
  7451. setCtx(ctx, 'strokeStyle', textStroke);
  7452. ctx.strokeText(token.text, x, y);
  7453. }
  7454. if (textFill) {
  7455. setCtx(ctx, 'fillStyle', textFill);
  7456. ctx.fillText(token.text, x, y);
  7457. }
  7458. }
  7459. function needDrawBackground(style) {
  7460. return !!(style.textBackgroundColor || style.textBorderWidth && style.textBorderColor);
  7461. } // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius, text}
  7462. // shape: {x, y, width, height}
  7463. function drawBackground(hostEl, ctx, style, x, y, width, height) {
  7464. var textBackgroundColor = style.textBackgroundColor;
  7465. var textBorderWidth = style.textBorderWidth;
  7466. var textBorderColor = style.textBorderColor;
  7467. var isPlainBg = isString(textBackgroundColor);
  7468. setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0);
  7469. setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent');
  7470. setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0);
  7471. setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0);
  7472. if (isPlainBg || textBorderWidth && textBorderColor) {
  7473. ctx.beginPath();
  7474. var textBorderRadius = style.textBorderRadius;
  7475. if (!textBorderRadius) {
  7476. ctx.rect(x, y, width, height);
  7477. } else {
  7478. buildPath(ctx, {
  7479. x: x,
  7480. y: y,
  7481. width: width,
  7482. height: height,
  7483. r: textBorderRadius
  7484. });
  7485. }
  7486. ctx.closePath();
  7487. }
  7488. if (isPlainBg) {
  7489. setCtx(ctx, 'fillStyle', textBackgroundColor);
  7490. if (style.fillOpacity != null) {
  7491. var originalGlobalAlpha = ctx.globalAlpha;
  7492. ctx.globalAlpha = style.fillOpacity * style.opacity;
  7493. ctx.fill();
  7494. ctx.globalAlpha = originalGlobalAlpha;
  7495. } else {
  7496. ctx.fill();
  7497. }
  7498. } else if (isObject$1(textBackgroundColor)) {
  7499. var image = textBackgroundColor.image;
  7500. image = createOrUpdateImage(image, null, hostEl, onBgImageLoaded, textBackgroundColor);
  7501. if (image && isImageReady(image)) {
  7502. ctx.drawImage(image, x, y, width, height);
  7503. }
  7504. }
  7505. if (textBorderWidth && textBorderColor) {
  7506. setCtx(ctx, 'lineWidth', textBorderWidth);
  7507. setCtx(ctx, 'strokeStyle', textBorderColor);
  7508. if (style.strokeOpacity != null) {
  7509. var originalGlobalAlpha = ctx.globalAlpha;
  7510. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  7511. ctx.stroke();
  7512. ctx.globalAlpha = originalGlobalAlpha;
  7513. } else {
  7514. ctx.stroke();
  7515. }
  7516. }
  7517. }
  7518. function onBgImageLoaded(image, textBackgroundColor) {
  7519. // Replace image, so that `contain/text.js#parseRichText`
  7520. // will get correct result in next tick.
  7521. textBackgroundColor.image = image;
  7522. }
  7523. function getBoxPosition(out, hostEl, style, rect) {
  7524. var baseX = style.x || 0;
  7525. var baseY = style.y || 0;
  7526. var textAlign = style.textAlign;
  7527. var textVerticalAlign = style.textVerticalAlign; // Text position represented by coord
  7528. if (rect) {
  7529. var textPosition = style.textPosition;
  7530. if (textPosition instanceof Array) {
  7531. // Percent
  7532. baseX = rect.x + parsePercent(textPosition[0], rect.width);
  7533. baseY = rect.y + parsePercent(textPosition[1], rect.height);
  7534. } else {
  7535. var res = hostEl && hostEl.calculateTextPosition ? hostEl.calculateTextPosition(_tmpTextPositionResult, style, rect) : calculateTextPosition(_tmpTextPositionResult, style, rect);
  7536. baseX = res.x;
  7537. baseY = res.y; // Default align and baseline when has textPosition
  7538. textAlign = textAlign || res.textAlign;
  7539. textVerticalAlign = textVerticalAlign || res.textVerticalAlign;
  7540. } // textOffset is only support in RectText, otherwise
  7541. // we have to adjust boundingRect for textOffset.
  7542. var textOffset = style.textOffset;
  7543. if (textOffset) {
  7544. baseX += textOffset[0];
  7545. baseY += textOffset[1];
  7546. }
  7547. }
  7548. out = out || {};
  7549. out.baseX = baseX;
  7550. out.baseY = baseY;
  7551. out.textAlign = textAlign;
  7552. out.textVerticalAlign = textVerticalAlign;
  7553. return out;
  7554. }
  7555. function setCtx(ctx, prop, value) {
  7556. ctx[prop] = fixShadow(ctx, prop, value);
  7557. return ctx[prop];
  7558. }
  7559. /**
  7560. * @param {string} [stroke] If specified, do not check style.textStroke.
  7561. * @param {string} [lineWidth] If specified, do not check style.textStroke.
  7562. * @param {number} style
  7563. */
  7564. function getStroke(stroke, lineWidth) {
  7565. return stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none' ? null // TODO pattern and gradient?
  7566. : stroke.image || stroke.colorStops ? '#000' : stroke;
  7567. }
  7568. function getFill(fill) {
  7569. return fill == null || fill === 'none' ? null // TODO pattern and gradient?
  7570. : fill.image || fill.colorStops ? '#000' : fill;
  7571. }
  7572. function parsePercent(value, maxValue) {
  7573. if (typeof value === 'string') {
  7574. if (value.lastIndexOf('%') >= 0) {
  7575. return parseFloat(value) / 100 * maxValue;
  7576. }
  7577. return parseFloat(value);
  7578. }
  7579. return value;
  7580. }
  7581. function getTextXForPadding(x, textAlign, textPadding) {
  7582. return textAlign === 'right' ? x - textPadding[1] : textAlign === 'center' ? x + textPadding[3] / 2 - textPadding[1] / 2 : x + textPadding[3];
  7583. }
  7584. /**
  7585. * @param {string} text
  7586. * @param {module:zrender/Style} style
  7587. * @return {boolean}
  7588. */
  7589. function needDrawText(text, style) {
  7590. return text != null && (text || style.textBackgroundColor || style.textBorderWidth && style.textBorderColor || style.textPadding);
  7591. }
  7592. /**
  7593. * Mixin for drawing text in a element bounding rect
  7594. * @module zrender/mixin/RectText
  7595. */
  7596. var tmpRect$1 = new BoundingRect();
  7597. var RectText = function () {};
  7598. RectText.prototype = {
  7599. constructor: RectText,
  7600. /**
  7601. * Draw text in a rect with specified position.
  7602. * @param {CanvasRenderingContext2D} ctx
  7603. * @param {Object} rect Displayable rect
  7604. */
  7605. drawRectText: function (ctx, rect) {
  7606. var style = this.style;
  7607. rect = style.textRect || rect; // Optimize, avoid normalize every time.
  7608. this.__dirty && normalizeTextStyle(style, true);
  7609. var text = style.text; // Convert to string
  7610. text != null && (text += '');
  7611. if (!needDrawText(text, style)) {
  7612. return;
  7613. } // FIXME
  7614. // Do not provide prevEl to `textHelper.renderText` for ctx prop cache,
  7615. // but use `ctx.save()` and `ctx.restore()`. Because the cache for rect
  7616. // text propably break the cache for its host elements.
  7617. ctx.save(); // Transform rect to view space
  7618. var transform = this.transform;
  7619. if (!style.transformText) {
  7620. if (transform) {
  7621. tmpRect$1.copy(rect);
  7622. tmpRect$1.applyTransform(transform);
  7623. rect = tmpRect$1;
  7624. }
  7625. } else {
  7626. this.setTransform(ctx);
  7627. } // transformText and textRotation can not be used at the same time.
  7628. renderText(this, ctx, text, style, rect, WILL_BE_RESTORED);
  7629. ctx.restore();
  7630. }
  7631. };
  7632. /**
  7633. * Base class of all displayable graphic objects
  7634. * @module zrender/graphic/Displayable
  7635. */
  7636. /**
  7637. * @alias module:zrender/graphic/Displayable
  7638. * @extends module:zrender/Element
  7639. * @extends module:zrender/graphic/mixin/RectText
  7640. */
  7641. function Displayable(opts) {
  7642. opts = opts || {};
  7643. Element.call(this, opts); // Extend properties
  7644. for (var name in opts) {
  7645. if (opts.hasOwnProperty(name) && name !== 'style') {
  7646. this[name] = opts[name];
  7647. }
  7648. }
  7649. /**
  7650. * @type {module:zrender/graphic/Style}
  7651. */
  7652. this.style = new Style(opts.style, this);
  7653. this._rect = null; // Shapes for cascade clipping.
  7654. // Can only be `null`/`undefined` or an non-empty array, MUST NOT be an empty array.
  7655. // because it is easy to only using null to check whether clipPaths changed.
  7656. this.__clipPaths = null; // FIXME Stateful must be mixined after style is setted
  7657. // Stateful.call(this, opts);
  7658. }
  7659. Displayable.prototype = {
  7660. constructor: Displayable,
  7661. type: 'displayable',
  7662. /**
  7663. * Dirty flag. From which painter will determine if this displayable object needs brush.
  7664. * @name module:zrender/graphic/Displayable#__dirty
  7665. * @type {boolean}
  7666. */
  7667. __dirty: true,
  7668. /**
  7669. * Whether the displayable object is visible. when it is true, the displayable object
  7670. * is not drawn, but the mouse event can still trigger the object.
  7671. * @name module:/zrender/graphic/Displayable#invisible
  7672. * @type {boolean}
  7673. * @default false
  7674. */
  7675. invisible: false,
  7676. /**
  7677. * @name module:/zrender/graphic/Displayable#z
  7678. * @type {number}
  7679. * @default 0
  7680. */
  7681. z: 0,
  7682. /**
  7683. * @name module:/zrender/graphic/Displayable#z
  7684. * @type {number}
  7685. * @default 0
  7686. */
  7687. z2: 0,
  7688. /**
  7689. * The z level determines the displayable object can be drawn in which layer canvas.
  7690. * @name module:/zrender/graphic/Displayable#zlevel
  7691. * @type {number}
  7692. * @default 0
  7693. */
  7694. zlevel: 0,
  7695. /**
  7696. * Whether it can be dragged.
  7697. * @name module:/zrender/graphic/Displayable#draggable
  7698. * @type {boolean}
  7699. * @default false
  7700. */
  7701. draggable: false,
  7702. /**
  7703. * Whether is it dragging.
  7704. * @name module:/zrender/graphic/Displayable#draggable
  7705. * @type {boolean}
  7706. * @default false
  7707. */
  7708. dragging: false,
  7709. /**
  7710. * Whether to respond to mouse events.
  7711. * @name module:/zrender/graphic/Displayable#silent
  7712. * @type {boolean}
  7713. * @default false
  7714. */
  7715. silent: false,
  7716. /**
  7717. * If enable culling
  7718. * @type {boolean}
  7719. * @default false
  7720. */
  7721. culling: false,
  7722. /**
  7723. * Mouse cursor when hovered
  7724. * @name module:/zrender/graphic/Displayable#cursor
  7725. * @type {string}
  7726. */
  7727. cursor: 'pointer',
  7728. /**
  7729. * If hover area is bounding rect
  7730. * @name module:/zrender/graphic/Displayable#rectHover
  7731. * @type {string}
  7732. */
  7733. rectHover: false,
  7734. /**
  7735. * Render the element progressively when the value >= 0,
  7736. * usefull for large data.
  7737. * @type {boolean}
  7738. */
  7739. progressive: false,
  7740. /**
  7741. * @type {boolean}
  7742. */
  7743. incremental: false,
  7744. /**
  7745. * Scale ratio for global scale.
  7746. * @type {boolean}
  7747. */
  7748. globalScaleRatio: 1,
  7749. beforeBrush: function (ctx) {},
  7750. afterBrush: function (ctx) {},
  7751. /**
  7752. * Graphic drawing method.
  7753. * @param {CanvasRenderingContext2D} ctx
  7754. */
  7755. // Interface
  7756. brush: function (ctx, prevEl) {},
  7757. /**
  7758. * Get the minimum bounding box.
  7759. * @return {module:zrender/core/BoundingRect}
  7760. */
  7761. // Interface
  7762. getBoundingRect: function () {},
  7763. /**
  7764. * If displayable element contain coord x, y
  7765. * @param {number} x
  7766. * @param {number} y
  7767. * @return {boolean}
  7768. */
  7769. contain: function (x, y) {
  7770. return this.rectContain(x, y);
  7771. },
  7772. /**
  7773. * @param {Function} cb
  7774. * @param {} context
  7775. */
  7776. traverse: function (cb, context) {
  7777. cb.call(context, this);
  7778. },
  7779. /**
  7780. * If bounding rect of element contain coord x, y
  7781. * @param {number} x
  7782. * @param {number} y
  7783. * @return {boolean}
  7784. */
  7785. rectContain: function (x, y) {
  7786. var coord = this.transformCoordToLocal(x, y);
  7787. var rect = this.getBoundingRect();
  7788. return rect.contain(coord[0], coord[1]);
  7789. },
  7790. /**
  7791. * Mark displayable element dirty and refresh next frame
  7792. */
  7793. dirty: function () {
  7794. this.__dirty = this.__dirtyText = true;
  7795. this._rect = null;
  7796. this.__zr && this.__zr.refresh();
  7797. },
  7798. /**
  7799. * If displayable object binded any event
  7800. * @return {boolean}
  7801. */
  7802. // TODO, events bound by bind
  7803. // isSilent: function () {
  7804. // return !(
  7805. // this.hoverable || this.draggable
  7806. // || this.onmousemove || this.onmouseover || this.onmouseout
  7807. // || this.onmousedown || this.onmouseup || this.onclick
  7808. // || this.ondragenter || this.ondragover || this.ondragleave
  7809. // || this.ondrop
  7810. // );
  7811. // },
  7812. /**
  7813. * Alias for animate('style')
  7814. * @param {boolean} loop
  7815. */
  7816. animateStyle: function (loop) {
  7817. return this.animate('style', loop);
  7818. },
  7819. attrKV: function (key, value) {
  7820. if (key !== 'style') {
  7821. Element.prototype.attrKV.call(this, key, value);
  7822. } else {
  7823. this.style.set(value);
  7824. }
  7825. },
  7826. /**
  7827. * @param {Object|string} key
  7828. * @param {*} value
  7829. */
  7830. setStyle: function (key, value) {
  7831. this.style.set(key, value);
  7832. this.dirty(false);
  7833. return this;
  7834. },
  7835. /**
  7836. * Use given style object
  7837. * @param {Object} obj
  7838. */
  7839. useStyle: function (obj) {
  7840. this.style = new Style(obj, this);
  7841. this.dirty(false);
  7842. return this;
  7843. },
  7844. /**
  7845. * The string value of `textPosition` needs to be calculated to a real postion.
  7846. * For example, `'inside'` is calculated to `[rect.width/2, rect.height/2]`
  7847. * by default. See `contain/text.js#calculateTextPosition` for more details.
  7848. * But some coutom shapes like "pin", "flag" have center that is not exactly
  7849. * `[width/2, height/2]`. So we provide this hook to customize the calculation
  7850. * for those shapes. It will be called if the `style.textPosition` is a string.
  7851. * @param {Obejct} [out] Prepared out object. If not provided, this method should
  7852. * be responsible for creating one.
  7853. * @param {module:zrender/graphic/Style} style
  7854. * @param {Object} rect {x, y, width, height}
  7855. * @return {Obejct} out The same as the input out.
  7856. * {
  7857. * x: number. mandatory.
  7858. * y: number. mandatory.
  7859. * textAlign: string. optional. use style.textAlign by default.
  7860. * textVerticalAlign: string. optional. use style.textVerticalAlign by default.
  7861. * }
  7862. */
  7863. calculateTextPosition: null
  7864. };
  7865. inherits(Displayable, Element);
  7866. mixin(Displayable, RectText); // zrUtil.mixin(Displayable, Stateful);
  7867. /**
  7868. * @alias zrender/graphic/Image
  7869. * @extends module:zrender/graphic/Displayable
  7870. * @constructor
  7871. * @param {Object} opts
  7872. */
  7873. function ZImage(opts) {
  7874. Displayable.call(this, opts);
  7875. }
  7876. ZImage.prototype = {
  7877. constructor: ZImage,
  7878. type: 'image',
  7879. brush: function (ctx, prevEl) {
  7880. var style = this.style;
  7881. var src = style.image; // Must bind each time
  7882. style.bind(ctx, this, prevEl);
  7883. var image = this._image = createOrUpdateImage(src, this._image, this, this.onload);
  7884. if (!image || !isImageReady(image)) {
  7885. return;
  7886. } // 图片已经加载完成
  7887. // if (image.nodeName.toUpperCase() == 'IMG') {
  7888. // if (!image.complete) {
  7889. // return;
  7890. // }
  7891. // }
  7892. // Else is canvas
  7893. var x = style.x || 0;
  7894. var y = style.y || 0;
  7895. var width = style.width;
  7896. var height = style.height;
  7897. var aspect = image.width / image.height;
  7898. if (width == null && height != null) {
  7899. // Keep image/height ratio
  7900. width = height * aspect;
  7901. } else if (height == null && width != null) {
  7902. height = width / aspect;
  7903. } else if (width == null && height == null) {
  7904. width = image.width;
  7905. height = image.height;
  7906. } // 设置transform
  7907. this.setTransform(ctx);
  7908. if (style.sWidth && style.sHeight) {
  7909. var sx = style.sx || 0;
  7910. var sy = style.sy || 0;
  7911. ctx.drawImage(image, sx, sy, style.sWidth, style.sHeight, x, y, width, height);
  7912. } else if (style.sx && style.sy) {
  7913. var sx = style.sx;
  7914. var sy = style.sy;
  7915. var sWidth = width - sx;
  7916. var sHeight = height - sy;
  7917. ctx.drawImage(image, sx, sy, sWidth, sHeight, x, y, width, height);
  7918. } else {
  7919. ctx.drawImage(image, x, y, width, height);
  7920. } // Draw rect text
  7921. if (style.text != null) {
  7922. // Only restore transform when needs draw text.
  7923. this.restoreTransform(ctx);
  7924. this.drawRectText(ctx, this.getBoundingRect());
  7925. }
  7926. },
  7927. getBoundingRect: function () {
  7928. var style = this.style;
  7929. if (!this._rect) {
  7930. this._rect = new BoundingRect(style.x || 0, style.y || 0, style.width || 0, style.height || 0);
  7931. }
  7932. return this._rect;
  7933. }
  7934. };
  7935. inherits(ZImage, Displayable);
  7936. var HOVER_LAYER_ZLEVEL = 1e5;
  7937. var CANVAS_ZLEVEL = 314159;
  7938. var EL_AFTER_INCREMENTAL_INC = 0.01;
  7939. var INCREMENTAL_INC = 0.001;
  7940. function parseInt10(val) {
  7941. return parseInt(val, 10);
  7942. }
  7943. function isLayerValid(layer) {
  7944. if (!layer) {
  7945. return false;
  7946. }
  7947. if (layer.__builtin__) {
  7948. return true;
  7949. }
  7950. if (typeof layer.resize !== 'function' || typeof layer.refresh !== 'function') {
  7951. return false;
  7952. }
  7953. return true;
  7954. }
  7955. var tmpRect = new BoundingRect(0, 0, 0, 0);
  7956. var viewRect = new BoundingRect(0, 0, 0, 0);
  7957. function isDisplayableCulled(el, width, height) {
  7958. tmpRect.copy(el.getBoundingRect());
  7959. if (el.transform) {
  7960. tmpRect.applyTransform(el.transform);
  7961. }
  7962. viewRect.width = width;
  7963. viewRect.height = height;
  7964. return !tmpRect.intersect(viewRect);
  7965. }
  7966. function isClipPathChanged(clipPaths, prevClipPaths) {
  7967. // displayable.__clipPaths can only be `null`/`undefined` or an non-empty array.
  7968. if (clipPaths === prevClipPaths) {
  7969. return false;
  7970. }
  7971. if (!clipPaths || !prevClipPaths || clipPaths.length !== prevClipPaths.length) {
  7972. return true;
  7973. }
  7974. for (var i = 0; i < clipPaths.length; i++) {
  7975. if (clipPaths[i] !== prevClipPaths[i]) {
  7976. return true;
  7977. }
  7978. }
  7979. return false;
  7980. }
  7981. function doClip(clipPaths, ctx) {
  7982. for (var i = 0; i < clipPaths.length; i++) {
  7983. var clipPath = clipPaths[i];
  7984. clipPath.setTransform(ctx);
  7985. ctx.beginPath();
  7986. clipPath.buildPath(ctx, clipPath.shape);
  7987. ctx.clip(); // Transform back
  7988. clipPath.restoreTransform(ctx);
  7989. }
  7990. }
  7991. function createRoot(width, height) {
  7992. var domRoot = document.createElement('div'); // domRoot.onselectstart = returnFalse; // Avoid page selected
  7993. domRoot.style.cssText = ['position:relative', // IOS13 safari probably has a compositing bug (z order of the canvas and the consequent
  7994. // dom does not act as expected) when some of the parent dom has
  7995. // `-webkit-overflow-scrolling: touch;` and the webpage is longer than one screen and
  7996. // the canvas is not at the top part of the page.
  7997. // Check `https://bugs.webkit.org/show_bug.cgi?id=203681` for more details. We remove
  7998. // this `overflow:hidden` to avoid the bug.
  7999. // 'overflow:hidden',
  8000. 'width:' + width + 'px', 'height:' + height + 'px', 'padding:0', 'margin:0', 'border-width:0'].join(';') + ';';
  8001. return domRoot;
  8002. }
  8003. /**
  8004. * @alias module:zrender/Painter
  8005. * @constructor
  8006. * @param {HTMLElement} root 绘图容器
  8007. * @param {module:zrender/Storage} storage
  8008. * @param {Object} opts
  8009. */
  8010. var Painter = function (root, storage, opts) {
  8011. this.type = 'canvas'; // In node environment using node-canvas
  8012. var singleCanvas = !root.nodeName // In node ?
  8013. || root.nodeName.toUpperCase() === 'CANVAS';
  8014. this._opts = opts = extend({}, opts || {});
  8015. /**
  8016. * @type {number}
  8017. */
  8018. this.dpr = opts.devicePixelRatio || devicePixelRatio;
  8019. /**
  8020. * @type {boolean}
  8021. * @private
  8022. */
  8023. this._singleCanvas = singleCanvas;
  8024. /**
  8025. * 绘图容器
  8026. * @type {HTMLElement}
  8027. */
  8028. this.root = root;
  8029. var rootStyle = root.style;
  8030. if (rootStyle) {
  8031. rootStyle['-webkit-tap-highlight-color'] = 'transparent';
  8032. rootStyle['-webkit-user-select'] = rootStyle['user-select'] = rootStyle['-webkit-touch-callout'] = 'none';
  8033. root.innerHTML = '';
  8034. }
  8035. /**
  8036. * @type {module:zrender/Storage}
  8037. */
  8038. this.storage = storage;
  8039. /**
  8040. * @type {Array.<number>}
  8041. * @private
  8042. */
  8043. var zlevelList = this._zlevelList = [];
  8044. /**
  8045. * @type {Object.<string, module:zrender/Layer>}
  8046. * @private
  8047. */
  8048. var layers = this._layers = {};
  8049. /**
  8050. * @type {Object.<string, Object>}
  8051. * @private
  8052. */
  8053. this._layerConfig = {};
  8054. /**
  8055. * zrender will do compositing when root is a canvas and have multiple zlevels.
  8056. */
  8057. this._needsManuallyCompositing = false;
  8058. if (!singleCanvas) {
  8059. this._width = this._getSize(0);
  8060. this._height = this._getSize(1);
  8061. var domRoot = this._domRoot = createRoot(this._width, this._height);
  8062. root.appendChild(domRoot);
  8063. } else {
  8064. var width = root.width;
  8065. var height = root.height;
  8066. if (opts.width != null) {
  8067. width = opts.width;
  8068. }
  8069. if (opts.height != null) {
  8070. height = opts.height;
  8071. }
  8072. this.dpr = opts.devicePixelRatio || 1; // Use canvas width and height directly
  8073. root.width = width * this.dpr;
  8074. root.height = height * this.dpr;
  8075. this._width = width;
  8076. this._height = height; // Create layer if only one given canvas
  8077. // Device can be specified to create a high dpi image.
  8078. var mainLayer = new Layer(root, this, this.dpr);
  8079. mainLayer.__builtin__ = true;
  8080. mainLayer.initContext(); // FIXME Use canvas width and height
  8081. // mainLayer.resize(width, height);
  8082. layers[CANVAS_ZLEVEL] = mainLayer;
  8083. mainLayer.zlevel = CANVAS_ZLEVEL; // Not use common zlevel.
  8084. zlevelList.push(CANVAS_ZLEVEL);
  8085. this._domRoot = root;
  8086. }
  8087. /**
  8088. * @type {module:zrender/Layer}
  8089. * @private
  8090. */
  8091. this._hoverlayer = null;
  8092. this._hoverElements = [];
  8093. };
  8094. Painter.prototype = {
  8095. constructor: Painter,
  8096. getType: function () {
  8097. return 'canvas';
  8098. },
  8099. /**
  8100. * If painter use a single canvas
  8101. * @return {boolean}
  8102. */
  8103. isSingleCanvas: function () {
  8104. return this._singleCanvas;
  8105. },
  8106. /**
  8107. * @return {HTMLDivElement}
  8108. */
  8109. getViewportRoot: function () {
  8110. return this._domRoot;
  8111. },
  8112. getViewportRootOffset: function () {
  8113. var viewportRoot = this.getViewportRoot();
  8114. if (viewportRoot) {
  8115. return {
  8116. offsetLeft: viewportRoot.offsetLeft || 0,
  8117. offsetTop: viewportRoot.offsetTop || 0
  8118. };
  8119. }
  8120. },
  8121. /**
  8122. * 刷新
  8123. * @param {boolean} [paintAll=false] 强制绘制所有displayable
  8124. */
  8125. refresh: function (paintAll) {
  8126. var list = this.storage.getDisplayList(true);
  8127. var zlevelList = this._zlevelList;
  8128. this._redrawId = Math.random();
  8129. this._paintList(list, paintAll, this._redrawId); // Paint custum layers
  8130. for (var i = 0; i < zlevelList.length; i++) {
  8131. var z = zlevelList[i];
  8132. var layer = this._layers[z];
  8133. if (!layer.__builtin__ && layer.refresh) {
  8134. var clearColor = i === 0 ? this._backgroundColor : null;
  8135. layer.refresh(clearColor);
  8136. }
  8137. }
  8138. this.refreshHover();
  8139. return this;
  8140. },
  8141. addHover: function (el, hoverStyle) {
  8142. if (el.__hoverMir) {
  8143. return;
  8144. }
  8145. var elMirror = new el.constructor({
  8146. style: el.style,
  8147. shape: el.shape,
  8148. z: el.z,
  8149. z2: el.z2,
  8150. silent: el.silent
  8151. });
  8152. elMirror.__from = el;
  8153. el.__hoverMir = elMirror;
  8154. hoverStyle && elMirror.setStyle(hoverStyle);
  8155. this._hoverElements.push(elMirror);
  8156. return elMirror;
  8157. },
  8158. removeHover: function (el) {
  8159. var elMirror = el.__hoverMir;
  8160. var hoverElements = this._hoverElements;
  8161. var idx = indexOf(hoverElements, elMirror);
  8162. if (idx >= 0) {
  8163. hoverElements.splice(idx, 1);
  8164. }
  8165. el.__hoverMir = null;
  8166. },
  8167. clearHover: function (el) {
  8168. var hoverElements = this._hoverElements;
  8169. for (var i = 0; i < hoverElements.length; i++) {
  8170. var from = hoverElements[i].__from;
  8171. if (from) {
  8172. from.__hoverMir = null;
  8173. }
  8174. }
  8175. hoverElements.length = 0;
  8176. },
  8177. refreshHover: function () {
  8178. var hoverElements = this._hoverElements;
  8179. var len = hoverElements.length;
  8180. var hoverLayer = this._hoverlayer;
  8181. hoverLayer && hoverLayer.clear();
  8182. if (!len) {
  8183. return;
  8184. }
  8185. sort(hoverElements, this.storage.displayableSortFunc); // Use a extream large zlevel
  8186. // FIXME?
  8187. if (!hoverLayer) {
  8188. hoverLayer = this._hoverlayer = this.getLayer(HOVER_LAYER_ZLEVEL);
  8189. }
  8190. var scope = {};
  8191. hoverLayer.ctx.save();
  8192. for (var i = 0; i < len;) {
  8193. var el = hoverElements[i];
  8194. var originalEl = el.__from; // Original el is removed
  8195. // PENDING
  8196. if (!(originalEl && originalEl.__zr)) {
  8197. hoverElements.splice(i, 1);
  8198. originalEl.__hoverMir = null;
  8199. len--;
  8200. continue;
  8201. }
  8202. i++; // Use transform
  8203. // FIXME style and shape ?
  8204. if (!originalEl.invisible) {
  8205. el.transform = originalEl.transform;
  8206. el.invTransform = originalEl.invTransform;
  8207. el.__clipPaths = originalEl.__clipPaths; // el.
  8208. this._doPaintEl(el, hoverLayer, true, scope);
  8209. }
  8210. }
  8211. hoverLayer.ctx.restore();
  8212. },
  8213. getHoverLayer: function () {
  8214. return this.getLayer(HOVER_LAYER_ZLEVEL);
  8215. },
  8216. _paintList: function (list, paintAll, redrawId) {
  8217. if (this._redrawId !== redrawId) {
  8218. return;
  8219. }
  8220. paintAll = paintAll || false;
  8221. this._updateLayerStatus(list);
  8222. var finished = this._doPaintList(list, paintAll);
  8223. if (this._needsManuallyCompositing) {
  8224. this._compositeManually();
  8225. }
  8226. if (!finished) {
  8227. var self = this;
  8228. requestAnimationFrame(function () {
  8229. self._paintList(list, paintAll, redrawId);
  8230. });
  8231. }
  8232. },
  8233. _compositeManually: function () {
  8234. var ctx = this.getLayer(CANVAS_ZLEVEL).ctx;
  8235. var width = this._domRoot.width;
  8236. var height = this._domRoot.height;
  8237. ctx.clearRect(0, 0, width, height); // PENDING, If only builtin layer?
  8238. this.eachBuiltinLayer(function (layer) {
  8239. if (layer.virtual) {
  8240. ctx.drawImage(layer.dom, 0, 0, width, height);
  8241. }
  8242. });
  8243. },
  8244. _doPaintList: function (list, paintAll) {
  8245. var layerList = [];
  8246. for (var zi = 0; zi < this._zlevelList.length; zi++) {
  8247. var zlevel = this._zlevelList[zi];
  8248. var layer = this._layers[zlevel];
  8249. if (layer.__builtin__ && layer !== this._hoverlayer && (layer.__dirty || paintAll)) {
  8250. layerList.push(layer);
  8251. }
  8252. }
  8253. var finished = true;
  8254. for (var k = 0; k < layerList.length; k++) {
  8255. var layer = layerList[k];
  8256. var ctx = layer.ctx;
  8257. var scope = {};
  8258. ctx.save();
  8259. var start = paintAll ? layer.__startIndex : layer.__drawIndex;
  8260. var useTimer = !paintAll && layer.incremental && Date.now;
  8261. var startTime = useTimer && Date.now();
  8262. var clearColor = layer.zlevel === this._zlevelList[0] ? this._backgroundColor : null; // All elements in this layer are cleared.
  8263. if (layer.__startIndex === layer.__endIndex) {
  8264. layer.clear(false, clearColor);
  8265. } else if (start === layer.__startIndex) {
  8266. var firstEl = list[start];
  8267. if (!firstEl.incremental || !firstEl.notClear || paintAll) {
  8268. layer.clear(false, clearColor);
  8269. }
  8270. }
  8271. if (start === -1) {
  8272. console.error('For some unknown reason. drawIndex is -1');
  8273. start = layer.__startIndex;
  8274. }
  8275. for (var i = start; i < layer.__endIndex; i++) {
  8276. var el = list[i];
  8277. this._doPaintEl(el, layer, paintAll, scope);
  8278. el.__dirty = el.__dirtyText = false;
  8279. if (useTimer) {
  8280. // Date.now can be executed in 13,025,305 ops/second.
  8281. var dTime = Date.now() - startTime; // Give 15 millisecond to draw.
  8282. // The rest elements will be drawn in the next frame.
  8283. if (dTime > 15) {
  8284. break;
  8285. }
  8286. }
  8287. }
  8288. layer.__drawIndex = i;
  8289. if (layer.__drawIndex < layer.__endIndex) {
  8290. finished = false;
  8291. }
  8292. if (scope.prevElClipPaths) {
  8293. // Needs restore the state. If last drawn element is in the clipping area.
  8294. ctx.restore();
  8295. }
  8296. ctx.restore();
  8297. }
  8298. if (env$1.wxa) {
  8299. // Flush for weixin application
  8300. each$1(this._layers, function (layer) {
  8301. if (layer && layer.ctx && layer.ctx.draw) {
  8302. layer.ctx.draw();
  8303. }
  8304. });
  8305. }
  8306. return finished;
  8307. },
  8308. _doPaintEl: function (el, currentLayer, forcePaint, scope) {
  8309. var ctx = currentLayer.ctx;
  8310. var m = el.transform;
  8311. if ((currentLayer.__dirty || forcePaint) && // Ignore invisible element
  8312. !el.invisible // Ignore transparent element
  8313. && el.style.opacity !== 0 // Ignore scale 0 element, in some environment like node-canvas
  8314. // Draw a scale 0 element can cause all following draw wrong
  8315. // And setTransform with scale 0 will cause set back transform failed.
  8316. && !(m && !m[0] && !m[3]) // Ignore culled element
  8317. && !(el.culling && isDisplayableCulled(el, this._width, this._height))) {
  8318. var clipPaths = el.__clipPaths;
  8319. var prevElClipPaths = scope.prevElClipPaths; // Optimize when clipping on group with several elements
  8320. if (!prevElClipPaths || isClipPathChanged(clipPaths, prevElClipPaths)) {
  8321. // If has previous clipping state, restore from it
  8322. if (prevElClipPaths) {
  8323. ctx.restore();
  8324. scope.prevElClipPaths = null; // Reset prevEl since context has been restored
  8325. scope.prevEl = null;
  8326. } // New clipping state
  8327. if (clipPaths) {
  8328. ctx.save();
  8329. doClip(clipPaths, ctx);
  8330. scope.prevElClipPaths = clipPaths;
  8331. }
  8332. }
  8333. el.beforeBrush && el.beforeBrush(ctx);
  8334. el.brush(ctx, scope.prevEl || null);
  8335. scope.prevEl = el;
  8336. el.afterBrush && el.afterBrush(ctx);
  8337. }
  8338. },
  8339. /**
  8340. * 获取 zlevel 所在层,如果不存在则会创建一个新的层
  8341. * @param {number} zlevel
  8342. * @param {boolean} virtual Virtual layer will not be inserted into dom.
  8343. * @return {module:zrender/Layer}
  8344. */
  8345. getLayer: function (zlevel, virtual) {
  8346. if (this._singleCanvas && !this._needsManuallyCompositing) {
  8347. zlevel = CANVAS_ZLEVEL;
  8348. }
  8349. var layer = this._layers[zlevel];
  8350. if (!layer) {
  8351. // Create a new layer
  8352. layer = new Layer('zr_' + zlevel, this, this.dpr);
  8353. layer.zlevel = zlevel;
  8354. layer.__builtin__ = true;
  8355. if (this._layerConfig[zlevel]) {
  8356. merge(layer, this._layerConfig[zlevel], true);
  8357. } // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8358. else if (this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC]) {
  8359. merge(layer, this._layerConfig[zlevel - EL_AFTER_INCREMENTAL_INC], true);
  8360. }
  8361. if (virtual) {
  8362. layer.virtual = virtual;
  8363. }
  8364. this.insertLayer(zlevel, layer); // Context is created after dom inserted to document
  8365. // Or excanvas will get 0px clientWidth and clientHeight
  8366. layer.initContext();
  8367. }
  8368. return layer;
  8369. },
  8370. insertLayer: function (zlevel, layer) {
  8371. var layersMap = this._layers;
  8372. var zlevelList = this._zlevelList;
  8373. var len = zlevelList.length;
  8374. var prevLayer = null;
  8375. var i = -1;
  8376. var domRoot = this._domRoot;
  8377. if (layersMap[zlevel]) {
  8378. logError$1('ZLevel ' + zlevel + ' has been used already');
  8379. return;
  8380. } // Check if is a valid layer
  8381. if (!isLayerValid(layer)) {
  8382. logError$1('Layer of zlevel ' + zlevel + ' is not valid');
  8383. return;
  8384. }
  8385. if (len > 0 && zlevel > zlevelList[0]) {
  8386. for (i = 0; i < len - 1; i++) {
  8387. if (zlevelList[i] < zlevel && zlevelList[i + 1] > zlevel) {
  8388. break;
  8389. }
  8390. }
  8391. prevLayer = layersMap[zlevelList[i]];
  8392. }
  8393. zlevelList.splice(i + 1, 0, zlevel);
  8394. layersMap[zlevel] = layer; // Vitual layer will not directly show on the screen.
  8395. // (It can be a WebGL layer and assigned to a ZImage element)
  8396. // But it still under management of zrender.
  8397. if (!layer.virtual) {
  8398. if (prevLayer) {
  8399. var prevDom = prevLayer.dom;
  8400. if (prevDom.nextSibling) {
  8401. domRoot.insertBefore(layer.dom, prevDom.nextSibling);
  8402. } else {
  8403. domRoot.appendChild(layer.dom);
  8404. }
  8405. } else {
  8406. if (domRoot.firstChild) {
  8407. domRoot.insertBefore(layer.dom, domRoot.firstChild);
  8408. } else {
  8409. domRoot.appendChild(layer.dom);
  8410. }
  8411. }
  8412. }
  8413. },
  8414. // Iterate each layer
  8415. eachLayer: function (cb, context) {
  8416. var zlevelList = this._zlevelList;
  8417. var z;
  8418. var i;
  8419. for (i = 0; i < zlevelList.length; i++) {
  8420. z = zlevelList[i];
  8421. cb.call(context, this._layers[z], z);
  8422. }
  8423. },
  8424. // Iterate each buildin layer
  8425. eachBuiltinLayer: function (cb, context) {
  8426. var zlevelList = this._zlevelList;
  8427. var layer;
  8428. var z;
  8429. var i;
  8430. for (i = 0; i < zlevelList.length; i++) {
  8431. z = zlevelList[i];
  8432. layer = this._layers[z];
  8433. if (layer.__builtin__) {
  8434. cb.call(context, layer, z);
  8435. }
  8436. }
  8437. },
  8438. // Iterate each other layer except buildin layer
  8439. eachOtherLayer: function (cb, context) {
  8440. var zlevelList = this._zlevelList;
  8441. var layer;
  8442. var z;
  8443. var i;
  8444. for (i = 0; i < zlevelList.length; i++) {
  8445. z = zlevelList[i];
  8446. layer = this._layers[z];
  8447. if (!layer.__builtin__) {
  8448. cb.call(context, layer, z);
  8449. }
  8450. }
  8451. },
  8452. /**
  8453. * 获取所有已创建的层
  8454. * @param {Array.<module:zrender/Layer>} [prevLayer]
  8455. */
  8456. getLayers: function () {
  8457. return this._layers;
  8458. },
  8459. _updateLayerStatus: function (list) {
  8460. this.eachBuiltinLayer(function (layer, z) {
  8461. layer.__dirty = layer.__used = false;
  8462. });
  8463. function updatePrevLayer(idx) {
  8464. if (prevLayer) {
  8465. if (prevLayer.__endIndex !== idx) {
  8466. prevLayer.__dirty = true;
  8467. }
  8468. prevLayer.__endIndex = idx;
  8469. }
  8470. }
  8471. if (this._singleCanvas) {
  8472. for (var i = 1; i < list.length; i++) {
  8473. var el = list[i];
  8474. if (el.zlevel !== list[i - 1].zlevel || el.incremental) {
  8475. this._needsManuallyCompositing = true;
  8476. break;
  8477. }
  8478. }
  8479. }
  8480. var prevLayer = null;
  8481. var incrementalLayerCount = 0;
  8482. var prevZlevel;
  8483. for (var i = 0; i < list.length; i++) {
  8484. var el = list[i];
  8485. var zlevel = el.zlevel;
  8486. var layer;
  8487. if (prevZlevel !== zlevel) {
  8488. prevZlevel = zlevel;
  8489. incrementalLayerCount = 0;
  8490. } // TODO Not use magic number on zlevel.
  8491. // Each layer with increment element can be separated to 3 layers.
  8492. // (Other Element drawn after incremental element)
  8493. // -----------------zlevel + EL_AFTER_INCREMENTAL_INC--------------------
  8494. // (Incremental element)
  8495. // ----------------------zlevel + INCREMENTAL_INC------------------------
  8496. // (Element drawn before incremental element)
  8497. // --------------------------------zlevel--------------------------------
  8498. if (el.incremental) {
  8499. layer = this.getLayer(zlevel + INCREMENTAL_INC, this._needsManuallyCompositing);
  8500. layer.incremental = true;
  8501. incrementalLayerCount = 1;
  8502. } else {
  8503. layer = this.getLayer(zlevel + (incrementalLayerCount > 0 ? EL_AFTER_INCREMENTAL_INC : 0), this._needsManuallyCompositing);
  8504. }
  8505. if (!layer.__builtin__) {
  8506. logError$1('ZLevel ' + zlevel + ' has been used by unkown layer ' + layer.id);
  8507. }
  8508. if (layer !== prevLayer) {
  8509. layer.__used = true;
  8510. if (layer.__startIndex !== i) {
  8511. layer.__dirty = true;
  8512. }
  8513. layer.__startIndex = i;
  8514. if (!layer.incremental) {
  8515. layer.__drawIndex = i;
  8516. } else {
  8517. // Mark layer draw index needs to update.
  8518. layer.__drawIndex = -1;
  8519. }
  8520. updatePrevLayer(i);
  8521. prevLayer = layer;
  8522. }
  8523. if (el.__dirty) {
  8524. layer.__dirty = true;
  8525. if (layer.incremental && layer.__drawIndex < 0) {
  8526. // Start draw from the first dirty element.
  8527. layer.__drawIndex = i;
  8528. }
  8529. }
  8530. }
  8531. updatePrevLayer(i);
  8532. this.eachBuiltinLayer(function (layer, z) {
  8533. // Used in last frame but not in this frame. Needs clear
  8534. if (!layer.__used && layer.getElementCount() > 0) {
  8535. layer.__dirty = true;
  8536. layer.__startIndex = layer.__endIndex = layer.__drawIndex = 0;
  8537. } // For incremental layer. In case start index changed and no elements are dirty.
  8538. if (layer.__dirty && layer.__drawIndex < 0) {
  8539. layer.__drawIndex = layer.__startIndex;
  8540. }
  8541. });
  8542. },
  8543. /**
  8544. * 清除hover层外所有内容
  8545. */
  8546. clear: function () {
  8547. this.eachBuiltinLayer(this._clearLayer);
  8548. return this;
  8549. },
  8550. _clearLayer: function (layer) {
  8551. layer.clear();
  8552. },
  8553. setBackgroundColor: function (backgroundColor) {
  8554. this._backgroundColor = backgroundColor;
  8555. },
  8556. /**
  8557. * 修改指定zlevel的绘制参数
  8558. *
  8559. * @param {string} zlevel
  8560. * @param {Object} config 配置对象
  8561. * @param {string} [config.clearColor=0] 每次清空画布的颜色
  8562. * @param {string} [config.motionBlur=false] 是否开启动态模糊
  8563. * @param {number} [config.lastFrameAlpha=0.7]
  8564. * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显
  8565. */
  8566. configLayer: function (zlevel, config) {
  8567. if (config) {
  8568. var layerConfig = this._layerConfig;
  8569. if (!layerConfig[zlevel]) {
  8570. layerConfig[zlevel] = config;
  8571. } else {
  8572. merge(layerConfig[zlevel], config, true);
  8573. }
  8574. for (var i = 0; i < this._zlevelList.length; i++) {
  8575. var _zlevel = this._zlevelList[i]; // TODO Remove EL_AFTER_INCREMENTAL_INC magic number
  8576. if (_zlevel === zlevel || _zlevel === zlevel + EL_AFTER_INCREMENTAL_INC) {
  8577. var layer = this._layers[_zlevel];
  8578. merge(layer, layerConfig[zlevel], true);
  8579. }
  8580. }
  8581. }
  8582. },
  8583. /**
  8584. * 删除指定层
  8585. * @param {number} zlevel 层所在的zlevel
  8586. */
  8587. delLayer: function (zlevel) {
  8588. var layers = this._layers;
  8589. var zlevelList = this._zlevelList;
  8590. var layer = layers[zlevel];
  8591. if (!layer) {
  8592. return;
  8593. }
  8594. layer.dom.parentNode.removeChild(layer.dom);
  8595. delete layers[zlevel];
  8596. zlevelList.splice(indexOf(zlevelList, zlevel), 1);
  8597. },
  8598. /**
  8599. * 区域大小变化后重绘
  8600. */
  8601. resize: function (width, height) {
  8602. if (!this._domRoot.style) {
  8603. // Maybe in node or worker
  8604. if (width == null || height == null) {
  8605. return;
  8606. }
  8607. this._width = width;
  8608. this._height = height;
  8609. this.getLayer(CANVAS_ZLEVEL).resize(width, height);
  8610. } else {
  8611. var domRoot = this._domRoot; // FIXME Why ?
  8612. domRoot.style.display = 'none'; // Save input w/h
  8613. var opts = this._opts;
  8614. width != null && (opts.width = width);
  8615. height != null && (opts.height = height);
  8616. width = this._getSize(0);
  8617. height = this._getSize(1);
  8618. domRoot.style.display = ''; // 优化没有实际改变的resize
  8619. if (this._width !== width || height !== this._height) {
  8620. domRoot.style.width = width + 'px';
  8621. domRoot.style.height = height + 'px';
  8622. for (var id in this._layers) {
  8623. if (this._layers.hasOwnProperty(id)) {
  8624. this._layers[id].resize(width, height);
  8625. }
  8626. }
  8627. each$1(this._progressiveLayers, function (layer) {
  8628. layer.resize(width, height);
  8629. });
  8630. this.refresh(true);
  8631. }
  8632. this._width = width;
  8633. this._height = height;
  8634. }
  8635. return this;
  8636. },
  8637. /**
  8638. * 清除单独的一个层
  8639. * @param {number} zlevel
  8640. */
  8641. clearLayer: function (zlevel) {
  8642. var layer = this._layers[zlevel];
  8643. if (layer) {
  8644. layer.clear();
  8645. }
  8646. },
  8647. /**
  8648. * 释放
  8649. */
  8650. dispose: function () {
  8651. this.root.innerHTML = '';
  8652. this.root = this.storage = this._domRoot = this._layers = null;
  8653. },
  8654. /**
  8655. * Get canvas which has all thing rendered
  8656. * @param {Object} opts
  8657. * @param {string} [opts.backgroundColor]
  8658. * @param {number} [opts.pixelRatio]
  8659. */
  8660. getRenderedCanvas: function (opts) {
  8661. opts = opts || {};
  8662. if (this._singleCanvas && !this._compositeManually) {
  8663. return this._layers[CANVAS_ZLEVEL].dom;
  8664. }
  8665. var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr);
  8666. imageLayer.initContext();
  8667. imageLayer.clear(false, opts.backgroundColor || this._backgroundColor);
  8668. if (opts.pixelRatio <= this.dpr) {
  8669. this.refresh();
  8670. var width = imageLayer.dom.width;
  8671. var height = imageLayer.dom.height;
  8672. var ctx = imageLayer.ctx;
  8673. this.eachLayer(function (layer) {
  8674. if (layer.__builtin__) {
  8675. ctx.drawImage(layer.dom, 0, 0, width, height);
  8676. } else if (layer.renderToCanvas) {
  8677. imageLayer.ctx.save();
  8678. layer.renderToCanvas(imageLayer.ctx);
  8679. imageLayer.ctx.restore();
  8680. }
  8681. });
  8682. } else {
  8683. // PENDING, echarts-gl and incremental rendering.
  8684. var scope = {};
  8685. var displayList = this.storage.getDisplayList(true);
  8686. for (var i = 0; i < displayList.length; i++) {
  8687. var el = displayList[i];
  8688. this._doPaintEl(el, imageLayer, true, scope);
  8689. }
  8690. }
  8691. return imageLayer.dom;
  8692. },
  8693. /**
  8694. * 获取绘图区域宽度
  8695. */
  8696. getWidth: function () {
  8697. return this._width;
  8698. },
  8699. /**
  8700. * 获取绘图区域高度
  8701. */
  8702. getHeight: function () {
  8703. return this._height;
  8704. },
  8705. _getSize: function (whIdx) {
  8706. var opts = this._opts;
  8707. var wh = ['width', 'height'][whIdx];
  8708. var cwh = ['clientWidth', 'clientHeight'][whIdx];
  8709. var plt = ['paddingLeft', 'paddingTop'][whIdx];
  8710. var prb = ['paddingRight', 'paddingBottom'][whIdx];
  8711. if (opts[wh] != null && opts[wh] !== 'auto') {
  8712. return parseFloat(opts[wh]);
  8713. }
  8714. var root = this.root; // IE8 does not support getComputedStyle, but it use VML.
  8715. var stl = document.defaultView.getComputedStyle(root);
  8716. return (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh])) - (parseInt10(stl[plt]) || 0) - (parseInt10(stl[prb]) || 0) | 0;
  8717. },
  8718. pathToImage: function (path, dpr) {
  8719. dpr = dpr || this.dpr;
  8720. var canvas = document.createElement('canvas');
  8721. var ctx = canvas.getContext('2d');
  8722. var rect = path.getBoundingRect();
  8723. var style = path.style;
  8724. var shadowBlurSize = style.shadowBlur * dpr;
  8725. var shadowOffsetX = style.shadowOffsetX * dpr;
  8726. var shadowOffsetY = style.shadowOffsetY * dpr;
  8727. var lineWidth = style.hasStroke() ? style.lineWidth : 0;
  8728. var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize);
  8729. var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize);
  8730. var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize);
  8731. var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize);
  8732. var width = rect.width + leftMargin + rightMargin;
  8733. var height = rect.height + topMargin + bottomMargin;
  8734. canvas.width = width * dpr;
  8735. canvas.height = height * dpr;
  8736. ctx.scale(dpr, dpr);
  8737. ctx.clearRect(0, 0, width, height);
  8738. ctx.dpr = dpr;
  8739. var pathTransform = {
  8740. position: path.position,
  8741. rotation: path.rotation,
  8742. scale: path.scale
  8743. };
  8744. path.position = [leftMargin - rect.x, topMargin - rect.y];
  8745. path.rotation = 0;
  8746. path.scale = [1, 1];
  8747. path.updateTransform();
  8748. if (path) {
  8749. path.brush(ctx);
  8750. }
  8751. var ImageShape = ZImage;
  8752. var imgShape = new ImageShape({
  8753. style: {
  8754. x: 0,
  8755. y: 0,
  8756. image: canvas
  8757. }
  8758. });
  8759. if (pathTransform.position != null) {
  8760. imgShape.position = path.position = pathTransform.position;
  8761. }
  8762. if (pathTransform.rotation != null) {
  8763. imgShape.rotation = path.rotation = pathTransform.rotation;
  8764. }
  8765. if (pathTransform.scale != null) {
  8766. imgShape.scale = path.scale = pathTransform.scale;
  8767. }
  8768. return imgShape;
  8769. }
  8770. };
  8771. /**
  8772. * Animation main class, dispatch and manage all animation controllers
  8773. *
  8774. * @module zrender/animation/Animation
  8775. * @author pissang(https://github.com/pissang)
  8776. */
  8777. // TODO Additive animation
  8778. // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/
  8779. // https://developer.apple.com/videos/wwdc2014/#236
  8780. /**
  8781. * @typedef {Object} IZRenderStage
  8782. * @property {Function} update
  8783. */
  8784. /**
  8785. * @alias module:zrender/animation/Animation
  8786. * @constructor
  8787. * @param {Object} [options]
  8788. * @param {Function} [options.onframe]
  8789. * @param {IZRenderStage} [options.stage]
  8790. * @example
  8791. * var animation = new Animation();
  8792. * var obj = {
  8793. * x: 100,
  8794. * y: 100
  8795. * };
  8796. * animation.animate(node.position)
  8797. * .when(1000, {
  8798. * x: 500,
  8799. * y: 500
  8800. * })
  8801. * .when(2000, {
  8802. * x: 100,
  8803. * y: 100
  8804. * })
  8805. * .start('spline');
  8806. */
  8807. var Animation = function (options) {
  8808. options = options || {};
  8809. this.stage = options.stage || {};
  8810. this.onframe = options.onframe || function () {}; // private properties
  8811. this._clips = [];
  8812. this._running = false;
  8813. this._time;
  8814. this._pausedTime;
  8815. this._pauseStart;
  8816. this._paused = false;
  8817. Eventful.call(this);
  8818. };
  8819. Animation.prototype = {
  8820. constructor: Animation,
  8821. /**
  8822. * Add clip
  8823. * @param {module:zrender/animation/Clip} clip
  8824. */
  8825. addClip: function (clip) {
  8826. this._clips.push(clip);
  8827. },
  8828. /**
  8829. * Add animator
  8830. * @param {module:zrender/animation/Animator} animator
  8831. */
  8832. addAnimator: function (animator) {
  8833. animator.animation = this;
  8834. var clips = animator.getClips();
  8835. for (var i = 0; i < clips.length; i++) {
  8836. this.addClip(clips[i]);
  8837. }
  8838. },
  8839. /**
  8840. * Delete animation clip
  8841. * @param {module:zrender/animation/Clip} clip
  8842. */
  8843. removeClip: function (clip) {
  8844. var idx = indexOf(this._clips, clip);
  8845. if (idx >= 0) {
  8846. this._clips.splice(idx, 1);
  8847. }
  8848. },
  8849. /**
  8850. * Delete animation clip
  8851. * @param {module:zrender/animation/Animator} animator
  8852. */
  8853. removeAnimator: function (animator) {
  8854. var clips = animator.getClips();
  8855. for (var i = 0; i < clips.length; i++) {
  8856. this.removeClip(clips[i]);
  8857. }
  8858. animator.animation = null;
  8859. },
  8860. _update: function () {
  8861. var time = new Date().getTime() - this._pausedTime;
  8862. var delta = time - this._time;
  8863. var clips = this._clips;
  8864. var len = clips.length;
  8865. var deferredEvents = [];
  8866. var deferredClips = [];
  8867. for (var i = 0; i < len; i++) {
  8868. var clip = clips[i];
  8869. var e = clip.step(time, delta); // Throw out the events need to be called after
  8870. // stage.update, like destroy
  8871. if (e) {
  8872. deferredEvents.push(e);
  8873. deferredClips.push(clip);
  8874. }
  8875. } // Remove the finished clip
  8876. for (var i = 0; i < len;) {
  8877. if (clips[i]._needsRemove) {
  8878. clips[i] = clips[len - 1];
  8879. clips.pop();
  8880. len--;
  8881. } else {
  8882. i++;
  8883. }
  8884. }
  8885. len = deferredEvents.length;
  8886. for (var i = 0; i < len; i++) {
  8887. deferredClips[i].fire(deferredEvents[i]);
  8888. }
  8889. this._time = time;
  8890. this.onframe(delta); // 'frame' should be triggered before stage, because upper application
  8891. // depends on the sequence (e.g., echarts-stream and finish
  8892. // event judge)
  8893. this.trigger('frame', delta);
  8894. if (this.stage.update) {
  8895. this.stage.update();
  8896. }
  8897. },
  8898. _startLoop: function () {
  8899. var self = this;
  8900. this._running = true;
  8901. function step() {
  8902. if (self._running) {
  8903. requestAnimationFrame(step);
  8904. !self._paused && self._update();
  8905. }
  8906. }
  8907. requestAnimationFrame(step);
  8908. },
  8909. /**
  8910. * Start animation.
  8911. */
  8912. start: function () {
  8913. this._time = new Date().getTime();
  8914. this._pausedTime = 0;
  8915. this._startLoop();
  8916. },
  8917. /**
  8918. * Stop animation.
  8919. */
  8920. stop: function () {
  8921. this._running = false;
  8922. },
  8923. /**
  8924. * Pause animation.
  8925. */
  8926. pause: function () {
  8927. if (!this._paused) {
  8928. this._pauseStart = new Date().getTime();
  8929. this._paused = true;
  8930. }
  8931. },
  8932. /**
  8933. * Resume animation.
  8934. */
  8935. resume: function () {
  8936. if (this._paused) {
  8937. this._pausedTime += new Date().getTime() - this._pauseStart;
  8938. this._paused = false;
  8939. }
  8940. },
  8941. /**
  8942. * Clear animation.
  8943. */
  8944. clear: function () {
  8945. this._clips = [];
  8946. },
  8947. /**
  8948. * Whether animation finished.
  8949. */
  8950. isFinished: function () {
  8951. return !this._clips.length;
  8952. },
  8953. /**
  8954. * Creat animator for a target, whose props can be animated.
  8955. *
  8956. * @param {Object} target
  8957. * @param {Object} options
  8958. * @param {boolean} [options.loop=false] Whether loop animation.
  8959. * @param {Function} [options.getter=null] Get value from target.
  8960. * @param {Function} [options.setter=null] Set value to target.
  8961. * @return {module:zrender/animation/Animation~Animator}
  8962. */
  8963. // TODO Gap
  8964. animate: function (target, options) {
  8965. options = options || {};
  8966. var animator = new Animator(target, options.loop, options.getter, options.setter);
  8967. this.addAnimator(animator);
  8968. return animator;
  8969. }
  8970. };
  8971. mixin(Animation, Eventful);
  8972. /* global document */
  8973. var TOUCH_CLICK_DELAY = 300;
  8974. var globalEventSupported = env$1.domSupported;
  8975. var localNativeListenerNames = function () {
  8976. var mouseHandlerNames = ['click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu'];
  8977. var touchHandlerNames = ['touchstart', 'touchend', 'touchmove'];
  8978. var pointerEventNameMap = {
  8979. pointerdown: 1,
  8980. pointerup: 1,
  8981. pointermove: 1,
  8982. pointerout: 1
  8983. };
  8984. var pointerHandlerNames = map(mouseHandlerNames, function (name) {
  8985. var nm = name.replace('mouse', 'pointer');
  8986. return pointerEventNameMap.hasOwnProperty(nm) ? nm : name;
  8987. });
  8988. return {
  8989. mouse: mouseHandlerNames,
  8990. touch: touchHandlerNames,
  8991. pointer: pointerHandlerNames
  8992. };
  8993. }();
  8994. var globalNativeListenerNames = {
  8995. mouse: ['mousemove', 'mouseup'],
  8996. pointer: ['pointermove', 'pointerup']
  8997. };
  8998. function eventNameFix(name) {
  8999. return name === 'mousewheel' && env$1.browser.firefox ? 'DOMMouseScroll' : name;
  9000. }
  9001. function isPointerFromTouch(event) {
  9002. var pointerType = event.pointerType;
  9003. return pointerType === 'pen' || pointerType === 'touch';
  9004. } // function useMSGuesture(handlerProxy, event) {
  9005. // return isPointerFromTouch(event) && !!handlerProxy._msGesture;
  9006. // }
  9007. // function onMSGestureChange(proxy, event) {
  9008. // if (event.translationX || event.translationY) {
  9009. // // mousemove is carried by MSGesture to reduce the sensitivity.
  9010. // proxy.handler.dispatchToElement(event.target, 'mousemove', event);
  9011. // }
  9012. // if (event.scale !== 1) {
  9013. // event.pinchX = event.offsetX;
  9014. // event.pinchY = event.offsetY;
  9015. // event.pinchScale = event.scale;
  9016. // proxy.handler.dispatchToElement(event.target, 'pinch', event);
  9017. // }
  9018. // }
  9019. /**
  9020. * Prevent mouse event from being dispatched after Touch Events action
  9021. * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js>
  9022. * 1. Mobile browsers dispatch mouse events 300ms after touchend.
  9023. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms
  9024. * Result: Blocking Mouse Events for 700ms.
  9025. *
  9026. * @param {DOMHandlerScope} scope
  9027. */
  9028. function setTouchTimer(scope) {
  9029. scope.touching = true;
  9030. if (scope.touchTimer != null) {
  9031. clearTimeout(scope.touchTimer);
  9032. scope.touchTimer = null;
  9033. }
  9034. scope.touchTimer = setTimeout(function () {
  9035. scope.touching = false;
  9036. scope.touchTimer = null;
  9037. }, 700);
  9038. } // Mark touch, which is useful in distinguish touch and
  9039. // mouse event in upper applicatoin.
  9040. function markTouch(event) {
  9041. event && (event.zrByTouch = true);
  9042. } // function markTriggeredFromLocal(event) {
  9043. // event && (event.__zrIsFromLocal = true);
  9044. // }
  9045. // function isTriggeredFromLocal(instance, event) {
  9046. // return !!(event && event.__zrIsFromLocal);
  9047. // }
  9048. function normalizeGlobalEvent(instance, event) {
  9049. // offsetX, offsetY still need to be calculated. They are necessary in the event
  9050. // handlers of the upper applications. Set `true` to force calculate them.
  9051. return normalizeEvent(instance.dom, new FakeGlobalEvent(instance, event), true);
  9052. }
  9053. /**
  9054. * Detect whether the given el is in `painterRoot`.
  9055. */
  9056. function isLocalEl(instance, el) {
  9057. var elTmp = el;
  9058. var isLocal = false;
  9059. while (elTmp && elTmp.nodeType !== 9 && !(isLocal = elTmp.domBelongToZr || elTmp !== el && elTmp === instance.painterRoot)) {
  9060. elTmp = elTmp.parentNode;
  9061. }
  9062. return isLocal;
  9063. }
  9064. /**
  9065. * Make a fake event but not change the original event,
  9066. * becuase the global event probably be used by other
  9067. * listeners not belonging to zrender.
  9068. * @class
  9069. */
  9070. function FakeGlobalEvent(instance, event) {
  9071. this.type = event.type;
  9072. this.target = this.currentTarget = instance.dom;
  9073. this.pointerType = event.pointerType; // Necessray for the force calculation of zrX, zrY
  9074. this.clientX = event.clientX;
  9075. this.clientY = event.clientY; // Because we do not mount global listeners to touch events,
  9076. // we do not copy `targetTouches` and `changedTouches` here.
  9077. }
  9078. var fakeGlobalEventProto = FakeGlobalEvent.prototype; // we make the default methods on the event do nothing,
  9079. // otherwise it is dangerous. See more details in
  9080. // [Drag outside] in `Handler.js`.
  9081. fakeGlobalEventProto.stopPropagation = fakeGlobalEventProto.stopImmediatePropagation = fakeGlobalEventProto.preventDefault = noop;
  9082. /**
  9083. * Local DOM Handlers
  9084. * @this {HandlerProxy}
  9085. */
  9086. var localDOMHandlers = {
  9087. mousedown: function (event) {
  9088. event = normalizeEvent(this.dom, event);
  9089. this._mayPointerCapture = [event.zrX, event.zrY];
  9090. this.trigger('mousedown', event);
  9091. },
  9092. mousemove: function (event) {
  9093. event = normalizeEvent(this.dom, event);
  9094. var downPoint = this._mayPointerCapture;
  9095. if (downPoint && (event.zrX !== downPoint[0] || event.zrY !== downPoint[1])) {
  9096. togglePointerCapture(this, true);
  9097. }
  9098. this.trigger('mousemove', event);
  9099. },
  9100. mouseup: function (event) {
  9101. event = normalizeEvent(this.dom, event);
  9102. togglePointerCapture(this, false);
  9103. this.trigger('mouseup', event);
  9104. },
  9105. mouseout: function (event) {
  9106. event = normalizeEvent(this.dom, event); // Similarly to the browser did on `document` and touch event,
  9107. // `globalout` will be delayed to final pointer cature release.
  9108. if (this._pointerCapturing) {
  9109. event.zrEventControl = 'no_globalout';
  9110. } // There might be some doms created by upper layer application
  9111. // at the same level of painter.getViewportRoot() (e.g., tooltip
  9112. // dom created by echarts), where 'globalout' event should not
  9113. // be triggered when mouse enters these doms. (But 'mouseout'
  9114. // should be triggered at the original hovered element as usual).
  9115. var element = event.toElement || event.relatedTarget;
  9116. event.zrIsToLocalDOM = isLocalEl(this, element);
  9117. this.trigger('mouseout', event);
  9118. },
  9119. touchstart: function (event) {
  9120. // Default mouse behaviour should not be disabled here.
  9121. // For example, page may needs to be slided.
  9122. event = normalizeEvent(this.dom, event);
  9123. markTouch(event);
  9124. this._lastTouchMoment = new Date();
  9125. this.handler.processGesture(event, 'start'); // For consistent event listener for both touch device and mouse device,
  9126. // we simulate "mouseover-->mousedown" in touch device. So we trigger
  9127. // `mousemove` here (to trigger `mouseover` inside), and then trigger
  9128. // `mousedown`.
  9129. localDOMHandlers.mousemove.call(this, event);
  9130. localDOMHandlers.mousedown.call(this, event);
  9131. },
  9132. touchmove: function (event) {
  9133. event = normalizeEvent(this.dom, event);
  9134. markTouch(event);
  9135. this.handler.processGesture(event, 'change'); // Mouse move should always be triggered no matter whether
  9136. // there is gestrue event, because mouse move and pinch may
  9137. // be used at the same time.
  9138. localDOMHandlers.mousemove.call(this, event);
  9139. },
  9140. touchend: function (event) {
  9141. event = normalizeEvent(this.dom, event);
  9142. markTouch(event);
  9143. this.handler.processGesture(event, 'end');
  9144. localDOMHandlers.mouseup.call(this, event); // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is
  9145. // triggered in `touchstart`. This seems to be illogical, but by this mechanism,
  9146. // we can conveniently implement "hover style" in both PC and touch device just
  9147. // by listening to `mouseover` to add "hover style" and listening to `mouseout`
  9148. // to remove "hover style" on an element, without any additional code for
  9149. // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover
  9150. // style" will remain for user view)
  9151. // click event should always be triggered no matter whether
  9152. // there is gestrue event. System click can not be prevented.
  9153. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) {
  9154. localDOMHandlers.click.call(this, event);
  9155. }
  9156. },
  9157. pointerdown: function (event) {
  9158. localDOMHandlers.mousedown.call(this, event); // if (useMSGuesture(this, event)) {
  9159. // this._msGesture.addPointer(event.pointerId);
  9160. // }
  9161. },
  9162. pointermove: function (event) {
  9163. // FIXME
  9164. // pointermove is so sensitive that it always triggered when
  9165. // tap(click) on touch screen, which affect some judgement in
  9166. // upper application. So, we dont support mousemove on MS touch
  9167. // device yet.
  9168. if (!isPointerFromTouch(event)) {
  9169. localDOMHandlers.mousemove.call(this, event);
  9170. }
  9171. },
  9172. pointerup: function (event) {
  9173. localDOMHandlers.mouseup.call(this, event);
  9174. },
  9175. pointerout: function (event) {
  9176. // pointerout will be triggered when tap on touch screen
  9177. // (IE11+/Edge on MS Surface) after click event triggered,
  9178. // which is inconsistent with the mousout behavior we defined
  9179. // in touchend. So we unify them.
  9180. // (check localDOMHandlers.touchend for detailed explanation)
  9181. if (!isPointerFromTouch(event)) {
  9182. localDOMHandlers.mouseout.call(this, event);
  9183. }
  9184. }
  9185. };
  9186. /**
  9187. * Othere DOM UI Event handlers for zr dom.
  9188. * @this {HandlerProxy}
  9189. */
  9190. each$1(['click', 'mousewheel', 'dblclick', 'contextmenu'], function (name) {
  9191. localDOMHandlers[name] = function (event) {
  9192. event = normalizeEvent(this.dom, event);
  9193. this.trigger(name, event);
  9194. };
  9195. });
  9196. /**
  9197. * DOM UI Event handlers for global page.
  9198. *
  9199. * [Caution]:
  9200. * those handlers should both support in capture phase and bubble phase!
  9201. *
  9202. * @this {HandlerProxy}
  9203. */
  9204. var globalDOMHandlers = {
  9205. pointermove: function (event) {
  9206. // FIXME
  9207. // pointermove is so sensitive that it always triggered when
  9208. // tap(click) on touch screen, which affect some judgement in
  9209. // upper application. So, we dont support mousemove on MS touch
  9210. // device yet.
  9211. if (!isPointerFromTouch(event)) {
  9212. globalDOMHandlers.mousemove.call(this, event);
  9213. }
  9214. },
  9215. pointerup: function (event) {
  9216. globalDOMHandlers.mouseup.call(this, event);
  9217. },
  9218. mousemove: function (event) {
  9219. this.trigger('mousemove', event);
  9220. },
  9221. mouseup: function (event) {
  9222. var pointerCaptureReleasing = this._pointerCapturing;
  9223. togglePointerCapture(this, false);
  9224. this.trigger('mouseup', event);
  9225. if (pointerCaptureReleasing) {
  9226. event.zrEventControl = 'only_globalout';
  9227. this.trigger('mouseout', event);
  9228. }
  9229. }
  9230. };
  9231. /**
  9232. * @param {HandlerProxy} instance
  9233. * @param {DOMHandlerScope} scope
  9234. */
  9235. function mountLocalDOMEventListeners(instance, scope) {
  9236. var domHandlers = scope.domHandlers;
  9237. if (env$1.pointerEventsSupported) {
  9238. // Only IE11+/Edge
  9239. // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240),
  9240. // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event
  9241. // at the same time.
  9242. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on
  9243. // screen, which do not occurs in pointer event.
  9244. // So we use pointer event to both detect touch gesture and mouse behavior.
  9245. each$1(localNativeListenerNames.pointer, function (nativeEventName) {
  9246. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9247. // markTriggeredFromLocal(event);
  9248. domHandlers[nativeEventName].call(instance, event);
  9249. });
  9250. }); // FIXME
  9251. // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable,
  9252. // which does not prevent defuault behavior occasionally (which may cause view port
  9253. // zoomed in but use can not zoom it back). And event.preventDefault() does not work.
  9254. // So we have to not to use MSGesture and not to support touchmove and pinch on MS
  9255. // touch screen. And we only support click behavior on MS touch screen now.
  9256. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+.
  9257. // We dont support touch on IE on win7.
  9258. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx>
  9259. // if (typeof MSGesture === 'function') {
  9260. // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line
  9261. // dom.addEventListener('MSGestureChange', onMSGestureChange);
  9262. // }
  9263. } else {
  9264. if (env$1.touchEventsSupported) {
  9265. each$1(localNativeListenerNames.touch, function (nativeEventName) {
  9266. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9267. // markTriggeredFromLocal(event);
  9268. domHandlers[nativeEventName].call(instance, event);
  9269. setTouchTimer(scope);
  9270. });
  9271. }); // Handler of 'mouseout' event is needed in touch mode, which will be mounted below.
  9272. // addEventListener(root, 'mouseout', this._mouseoutHandler);
  9273. } // 1. Considering some devices that both enable touch and mouse event (like on MS Surface
  9274. // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise
  9275. // mouse event can not be handle in those devices.
  9276. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent
  9277. // mouseevent after touch event triggered, see `setTouchTimer`.
  9278. each$1(localNativeListenerNames.mouse, function (nativeEventName) {
  9279. mountSingleDOMEventListener(scope, nativeEventName, function (event) {
  9280. event = getNativeEvent(event);
  9281. if (!scope.touching) {
  9282. // markTriggeredFromLocal(event);
  9283. domHandlers[nativeEventName].call(instance, event);
  9284. }
  9285. });
  9286. });
  9287. }
  9288. }
  9289. /**
  9290. * @param {HandlerProxy} instance
  9291. * @param {DOMHandlerScope} scope
  9292. */
  9293. function mountGlobalDOMEventListeners(instance, scope) {
  9294. // Only IE11+/Edge. See the comment in `mountLocalDOMEventListeners`.
  9295. if (env$1.pointerEventsSupported) {
  9296. each$1(globalNativeListenerNames.pointer, mount);
  9297. } // Touch event has implemented "drag outside" so we do not mount global listener for touch event.
  9298. // (see https://www.w3.org/TR/touch-events/#the-touchmove-event)
  9299. // We do not consider "both-support-touch-and-mouse device" for this feature (see the comment of
  9300. // `mountLocalDOMEventListeners`) to avoid bugs util some requirements come.
  9301. else if (!env$1.touchEventsSupported) {
  9302. each$1(globalNativeListenerNames.mouse, mount);
  9303. }
  9304. function mount(nativeEventName) {
  9305. function nativeEventListener(event) {
  9306. event = getNativeEvent(event); // See the reason in [Drag outside] in `Handler.js`
  9307. // This checking supports both `useCapture` or not.
  9308. // PENDING: if there is performance issue in some devices,
  9309. // we probably can not use `useCapture` and change a easier
  9310. // to judes whether local (mark).
  9311. if (!isLocalEl(instance, event.target)) {
  9312. event = normalizeGlobalEvent(instance, event);
  9313. scope.domHandlers[nativeEventName].call(instance, event);
  9314. }
  9315. }
  9316. mountSingleDOMEventListener(scope, nativeEventName, nativeEventListener, {
  9317. capture: true // See [Drag Outside] in `Handler.js`
  9318. });
  9319. }
  9320. }
  9321. function mountSingleDOMEventListener(scope, nativeEventName, listener, opt) {
  9322. scope.mounted[nativeEventName] = listener;
  9323. scope.listenerOpts[nativeEventName] = opt;
  9324. addEventListener(scope.domTarget, eventNameFix(nativeEventName), listener, opt);
  9325. }
  9326. function unmountDOMEventListeners(scope) {
  9327. var mounted = scope.mounted;
  9328. for (var nativeEventName in mounted) {
  9329. if (mounted.hasOwnProperty(nativeEventName)) {
  9330. removeEventListener(scope.domTarget, eventNameFix(nativeEventName), mounted[nativeEventName], scope.listenerOpts[nativeEventName]);
  9331. }
  9332. }
  9333. scope.mounted = {};
  9334. }
  9335. /**
  9336. * See [Drag Outside] in `Handler.js`.
  9337. * @implement
  9338. * @param {boolean} isPointerCapturing Should never be `null`/`undefined`.
  9339. * `true`: start to capture pointer if it is not capturing.
  9340. * `false`: end the capture if it is capturing.
  9341. */
  9342. function togglePointerCapture(instance, isPointerCapturing) {
  9343. instance._mayPointerCapture = null;
  9344. if (globalEventSupported && instance._pointerCapturing ^ isPointerCapturing) {
  9345. instance._pointerCapturing = isPointerCapturing;
  9346. var globalHandlerScope = instance._globalHandlerScope;
  9347. isPointerCapturing ? mountGlobalDOMEventListeners(instance, globalHandlerScope) : unmountDOMEventListeners(globalHandlerScope);
  9348. }
  9349. }
  9350. /**
  9351. * @inner
  9352. * @class
  9353. */
  9354. function DOMHandlerScope(domTarget, domHandlers) {
  9355. this.domTarget = domTarget;
  9356. this.domHandlers = domHandlers; // Key: eventName, value: mounted handler funcitons.
  9357. // Used for unmount.
  9358. this.mounted = {};
  9359. this.listenerOpts = {};
  9360. this.touchTimer = null;
  9361. this.touching = false;
  9362. }
  9363. /**
  9364. * @public
  9365. * @class
  9366. */
  9367. function HandlerDomProxy(dom, painterRoot) {
  9368. Eventful.call(this);
  9369. this.dom = dom;
  9370. this.painterRoot = painterRoot;
  9371. this._localHandlerScope = new DOMHandlerScope(dom, localDOMHandlers);
  9372. if (globalEventSupported) {
  9373. this._globalHandlerScope = new DOMHandlerScope(document, globalDOMHandlers);
  9374. }
  9375. /**
  9376. * @type {boolean}
  9377. */
  9378. this._pointerCapturing = false;
  9379. /**
  9380. * @type {Array.<number>} [x, y] or null.
  9381. */
  9382. this._mayPointerCapture = null;
  9383. mountLocalDOMEventListeners(this, this._localHandlerScope);
  9384. }
  9385. var handlerDomProxyProto = HandlerDomProxy.prototype;
  9386. handlerDomProxyProto.dispose = function () {
  9387. unmountDOMEventListeners(this._localHandlerScope);
  9388. if (globalEventSupported) {
  9389. unmountDOMEventListeners(this._globalHandlerScope);
  9390. }
  9391. };
  9392. handlerDomProxyProto.setCursor = function (cursorStyle) {
  9393. this.dom.style && (this.dom.style.cursor = cursorStyle || 'default');
  9394. };
  9395. mixin(HandlerDomProxy, Eventful);
  9396. /*!
  9397. * ZRender, a high performance 2d drawing library.
  9398. *
  9399. * Copyright (c) 2013, Baidu Inc.
  9400. * All rights reserved.
  9401. *
  9402. * LICENSE
  9403. * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt
  9404. */
  9405. var useVML = !env$1.canvasSupported;
  9406. var painterCtors = {
  9407. canvas: Painter
  9408. };
  9409. var instances$1 = {}; // ZRender实例map索引
  9410. /**
  9411. * @type {string}
  9412. */
  9413. var version$1 = '4.3.1';
  9414. /**
  9415. * Initializing a zrender instance
  9416. * @param {HTMLElement} dom
  9417. * @param {Object} [opts]
  9418. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9419. * @param {number} [opts.devicePixelRatio]
  9420. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9421. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9422. * @return {module:zrender/ZRender}
  9423. */
  9424. function init$1(dom, opts) {
  9425. var zr = new ZRender(guid(), dom, opts);
  9426. instances$1[zr.id] = zr;
  9427. return zr;
  9428. }
  9429. /**
  9430. * Dispose zrender instance
  9431. * @param {module:zrender/ZRender} zr
  9432. */
  9433. function dispose$1(zr) {
  9434. if (zr) {
  9435. zr.dispose();
  9436. } else {
  9437. for (var key in instances$1) {
  9438. if (instances$1.hasOwnProperty(key)) {
  9439. instances$1[key].dispose();
  9440. }
  9441. }
  9442. instances$1 = {};
  9443. }
  9444. return this;
  9445. }
  9446. /**
  9447. * Get zrender instance by id
  9448. * @param {string} id zrender instance id
  9449. * @return {module:zrender/ZRender}
  9450. */
  9451. function getInstance(id) {
  9452. return instances$1[id];
  9453. }
  9454. function registerPainter(name, Ctor) {
  9455. painterCtors[name] = Ctor;
  9456. }
  9457. function delInstance(id) {
  9458. delete instances$1[id];
  9459. }
  9460. /**
  9461. * @module zrender/ZRender
  9462. */
  9463. /**
  9464. * @constructor
  9465. * @alias module:zrender/ZRender
  9466. * @param {string} id
  9467. * @param {HTMLElement} dom
  9468. * @param {Object} opts
  9469. * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg'
  9470. * @param {number} [opts.devicePixelRatio]
  9471. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  9472. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  9473. */
  9474. var ZRender = function (id, dom, opts) {
  9475. opts = opts || {};
  9476. /**
  9477. * @type {HTMLDomElement}
  9478. */
  9479. this.dom = dom;
  9480. /**
  9481. * @type {string}
  9482. */
  9483. this.id = id;
  9484. var self = this;
  9485. var storage = new Storage();
  9486. var rendererType = opts.renderer; // TODO WebGL
  9487. if (useVML) {
  9488. if (!painterCtors.vml) {
  9489. throw new Error('You need to require \'zrender/vml/vml\' to support IE8');
  9490. }
  9491. rendererType = 'vml';
  9492. } else if (!rendererType || !painterCtors[rendererType]) {
  9493. rendererType = 'canvas';
  9494. }
  9495. var painter = new painterCtors[rendererType](dom, storage, opts, id);
  9496. this.storage = storage;
  9497. this.painter = painter;
  9498. var handerProxy = !env$1.node && !env$1.worker ? new HandlerDomProxy(painter.getViewportRoot(), painter.root) : null;
  9499. this.handler = new Handler(storage, painter, handerProxy, painter.root);
  9500. /**
  9501. * @type {module:zrender/animation/Animation}
  9502. */
  9503. this.animation = new Animation({
  9504. stage: {
  9505. update: bind(this.flush, this)
  9506. }
  9507. });
  9508. this.animation.start();
  9509. /**
  9510. * @type {boolean}
  9511. * @private
  9512. */
  9513. this._needsRefresh; // 修改 storage.delFromStorage, 每次删除元素之前删除动画
  9514. // FIXME 有点ugly
  9515. var oldDelFromStorage = storage.delFromStorage;
  9516. var oldAddToStorage = storage.addToStorage;
  9517. storage.delFromStorage = function (el) {
  9518. oldDelFromStorage.call(storage, el);
  9519. el && el.removeSelfFromZr(self);
  9520. };
  9521. storage.addToStorage = function (el) {
  9522. oldAddToStorage.call(storage, el);
  9523. el.addSelfToZr(self);
  9524. };
  9525. };
  9526. ZRender.prototype = {
  9527. constructor: ZRender,
  9528. /**
  9529. * 获取实例唯一标识
  9530. * @return {string}
  9531. */
  9532. getId: function () {
  9533. return this.id;
  9534. },
  9535. /**
  9536. * 添加元素
  9537. * @param {module:zrender/Element} el
  9538. */
  9539. add: function (el) {
  9540. this.storage.addRoot(el);
  9541. this._needsRefresh = true;
  9542. },
  9543. /**
  9544. * 删除元素
  9545. * @param {module:zrender/Element} el
  9546. */
  9547. remove: function (el) {
  9548. this.storage.delRoot(el);
  9549. this._needsRefresh = true;
  9550. },
  9551. /**
  9552. * Change configuration of layer
  9553. * @param {string} zLevel
  9554. * @param {Object} config
  9555. * @param {string} [config.clearColor=0] Clear color
  9556. * @param {string} [config.motionBlur=false] If enable motion blur
  9557. * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer
  9558. */
  9559. configLayer: function (zLevel, config) {
  9560. if (this.painter.configLayer) {
  9561. this.painter.configLayer(zLevel, config);
  9562. }
  9563. this._needsRefresh = true;
  9564. },
  9565. /**
  9566. * Set background color
  9567. * @param {string} backgroundColor
  9568. */
  9569. setBackgroundColor: function (backgroundColor) {
  9570. if (this.painter.setBackgroundColor) {
  9571. this.painter.setBackgroundColor(backgroundColor);
  9572. }
  9573. this._needsRefresh = true;
  9574. },
  9575. /**
  9576. * Repaint the canvas immediately
  9577. */
  9578. refreshImmediately: function () {
  9579. // var start = new Date();
  9580. // Clear needsRefresh ahead to avoid something wrong happens in refresh
  9581. // Or it will cause zrender refreshes again and again.
  9582. this._needsRefresh = this._needsRefreshHover = false;
  9583. this.painter.refresh(); // Avoid trigger zr.refresh in Element#beforeUpdate hook
  9584. this._needsRefresh = this._needsRefreshHover = false; // var end = new Date();
  9585. // var log = document.getElementById('log');
  9586. // if (log) {
  9587. // log.innerHTML = log.innerHTML + '<br>' + (end - start);
  9588. // }
  9589. },
  9590. /**
  9591. * Mark and repaint the canvas in the next frame of browser
  9592. */
  9593. refresh: function () {
  9594. this._needsRefresh = true;
  9595. },
  9596. /**
  9597. * Perform all refresh
  9598. */
  9599. flush: function () {
  9600. var triggerRendered;
  9601. if (this._needsRefresh) {
  9602. triggerRendered = true;
  9603. this.refreshImmediately();
  9604. }
  9605. if (this._needsRefreshHover) {
  9606. triggerRendered = true;
  9607. this.refreshHoverImmediately();
  9608. }
  9609. triggerRendered && this.trigger('rendered');
  9610. },
  9611. /**
  9612. * Add element to hover layer
  9613. * @param {module:zrender/Element} el
  9614. * @param {Object} style
  9615. */
  9616. addHover: function (el, style) {
  9617. if (this.painter.addHover) {
  9618. var elMirror = this.painter.addHover(el, style);
  9619. this.refreshHover();
  9620. return elMirror;
  9621. }
  9622. },
  9623. /**
  9624. * Add element from hover layer
  9625. * @param {module:zrender/Element} el
  9626. */
  9627. removeHover: function (el) {
  9628. if (this.painter.removeHover) {
  9629. this.painter.removeHover(el);
  9630. this.refreshHover();
  9631. }
  9632. },
  9633. /**
  9634. * Clear all hover elements in hover layer
  9635. * @param {module:zrender/Element} el
  9636. */
  9637. clearHover: function () {
  9638. if (this.painter.clearHover) {
  9639. this.painter.clearHover();
  9640. this.refreshHover();
  9641. }
  9642. },
  9643. /**
  9644. * Refresh hover in next frame
  9645. */
  9646. refreshHover: function () {
  9647. this._needsRefreshHover = true;
  9648. },
  9649. /**
  9650. * Refresh hover immediately
  9651. */
  9652. refreshHoverImmediately: function () {
  9653. this._needsRefreshHover = false;
  9654. this.painter.refreshHover && this.painter.refreshHover();
  9655. },
  9656. /**
  9657. * Resize the canvas.
  9658. * Should be invoked when container size is changed
  9659. * @param {Object} [opts]
  9660. * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined)
  9661. * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined)
  9662. */
  9663. resize: function (opts) {
  9664. opts = opts || {};
  9665. this.painter.resize(opts.width, opts.height);
  9666. this.handler.resize();
  9667. },
  9668. /**
  9669. * Stop and clear all animation immediately
  9670. */
  9671. clearAnimation: function () {
  9672. this.animation.clear();
  9673. },
  9674. /**
  9675. * Get container width
  9676. */
  9677. getWidth: function () {
  9678. return this.painter.getWidth();
  9679. },
  9680. /**
  9681. * Get container height
  9682. */
  9683. getHeight: function () {
  9684. return this.painter.getHeight();
  9685. },
  9686. /**
  9687. * Export the canvas as Base64 URL
  9688. * @param {string} type
  9689. * @param {string} [backgroundColor='#fff']
  9690. * @return {string} Base64 URL
  9691. */
  9692. // toDataURL: function(type, backgroundColor) {
  9693. // return this.painter.getRenderedCanvas({
  9694. // backgroundColor: backgroundColor
  9695. // }).toDataURL(type);
  9696. // },
  9697. /**
  9698. * Converting a path to image.
  9699. * It has much better performance of drawing image rather than drawing a vector path.
  9700. * @param {module:zrender/graphic/Path} e
  9701. * @param {number} width
  9702. * @param {number} height
  9703. */
  9704. pathToImage: function (e, dpr) {
  9705. return this.painter.pathToImage(e, dpr);
  9706. },
  9707. /**
  9708. * Set default cursor
  9709. * @param {string} [cursorStyle='default'] 例如 crosshair
  9710. */
  9711. setCursorStyle: function (cursorStyle) {
  9712. this.handler.setCursorStyle(cursorStyle);
  9713. },
  9714. /**
  9715. * Find hovered element
  9716. * @param {number} x
  9717. * @param {number} y
  9718. * @return {Object} {target, topTarget}
  9719. */
  9720. findHover: function (x, y) {
  9721. return this.handler.findHover(x, y);
  9722. },
  9723. /**
  9724. * Bind event
  9725. *
  9726. * @param {string} eventName Event name
  9727. * @param {Function} eventHandler Handler function
  9728. * @param {Object} [context] Context object
  9729. */
  9730. on: function (eventName, eventHandler, context) {
  9731. this.handler.on(eventName, eventHandler, context);
  9732. },
  9733. /**
  9734. * Unbind event
  9735. * @param {string} eventName Event name
  9736. * @param {Function} [eventHandler] Handler function
  9737. */
  9738. off: function (eventName, eventHandler) {
  9739. this.handler.off(eventName, eventHandler);
  9740. },
  9741. /**
  9742. * Trigger event manually
  9743. *
  9744. * @param {string} eventName Event name
  9745. * @param {event=} event Event object
  9746. */
  9747. trigger: function (eventName, event) {
  9748. this.handler.trigger(eventName, event);
  9749. },
  9750. /**
  9751. * Clear all objects and the canvas.
  9752. */
  9753. clear: function () {
  9754. this.storage.delRoot();
  9755. this.painter.clear();
  9756. },
  9757. /**
  9758. * Dispose self.
  9759. */
  9760. dispose: function () {
  9761. this.animation.stop();
  9762. this.clear();
  9763. this.storage.dispose();
  9764. this.painter.dispose();
  9765. this.handler.dispose();
  9766. this.animation = this.storage = this.painter = this.handler = null;
  9767. delInstance(this.id);
  9768. }
  9769. };
  9770. var zrender = (Object.freeze || Object)({
  9771. version: version$1,
  9772. init: init$1,
  9773. dispose: dispose$1,
  9774. getInstance: getInstance,
  9775. registerPainter: registerPainter
  9776. });
  9777. /*
  9778. * Licensed to the Apache Software Foundation (ASF) under one
  9779. * or more contributor license agreements. See the NOTICE file
  9780. * distributed with this work for additional information
  9781. * regarding copyright ownership. The ASF licenses this file
  9782. * to you under the Apache License, Version 2.0 (the
  9783. * "License"); you may not use this file except in compliance
  9784. * with the License. You may obtain a copy of the License at
  9785. *
  9786. * http://www.apache.org/licenses/LICENSE-2.0
  9787. *
  9788. * Unless required by applicable law or agreed to in writing,
  9789. * software distributed under the License is distributed on an
  9790. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  9791. * KIND, either express or implied. See the License for the
  9792. * specific language governing permissions and limitations
  9793. * under the License.
  9794. */
  9795. var each$2 = each$1;
  9796. var isObject$2 = isObject$1;
  9797. var isArray$1 = isArray;
  9798. /**
  9799. * Make the name displayable. But we should
  9800. * make sure it is not duplicated with user
  9801. * specified name, so use '\0';
  9802. */
  9803. var DUMMY_COMPONENT_NAME_PREFIX = 'series\0';
  9804. /**
  9805. * If value is not array, then translate it to array.
  9806. * @param {*} value
  9807. * @return {Array} [value] or value
  9808. */
  9809. function normalizeToArray(value) {
  9810. return value instanceof Array ? value : value == null ? [] : [value];
  9811. }
  9812. /**
  9813. * Sync default option between normal and emphasis like `position` and `show`
  9814. * In case some one will write code like
  9815. * label: {
  9816. * show: false,
  9817. * position: 'outside',
  9818. * fontSize: 18
  9819. * },
  9820. * emphasis: {
  9821. * label: { show: true }
  9822. * }
  9823. * @param {Object} opt
  9824. * @param {string} key
  9825. * @param {Array.<string>} subOpts
  9826. */
  9827. function defaultEmphasis(opt, key, subOpts) {
  9828. // Caution: performance sensitive.
  9829. if (opt) {
  9830. opt[key] = opt[key] || {};
  9831. opt.emphasis = opt.emphasis || {};
  9832. opt.emphasis[key] = opt.emphasis[key] || {}; // Default emphasis option from normal
  9833. for (var i = 0, len = subOpts.length; i < len; i++) {
  9834. var subOptName = subOpts[i];
  9835. if (!opt.emphasis[key].hasOwnProperty(subOptName) && opt[key].hasOwnProperty(subOptName)) {
  9836. opt.emphasis[key][subOptName] = opt[key][subOptName];
  9837. }
  9838. }
  9839. }
  9840. }
  9841. var TEXT_STYLE_OPTIONS = ['fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding']; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([
  9842. // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter',
  9843. // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily',
  9844. // // FIXME: deprecated, check and remove it.
  9845. // 'textStyle'
  9846. // ]);
  9847. /**
  9848. * The method do not ensure performance.
  9849. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9850. * This helper method retieves value from data.
  9851. * @param {string|number|Date|Array|Object} dataItem
  9852. * @return {number|string|Date|Array.<number|string|Date>}
  9853. */
  9854. function getDataItemValue(dataItem) {
  9855. return isObject$2(dataItem) && !isArray$1(dataItem) && !(dataItem instanceof Date) ? dataItem.value : dataItem;
  9856. }
  9857. /**
  9858. * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}]
  9859. * This helper method determine if dataItem has extra option besides value
  9860. * @param {string|number|Date|Array|Object} dataItem
  9861. */
  9862. function isDataItemOption(dataItem) {
  9863. return isObject$2(dataItem) && !(dataItem instanceof Array); // // markLine data can be array
  9864. // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array));
  9865. }
  9866. /**
  9867. * Mapping to exists for merge.
  9868. *
  9869. * @public
  9870. * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists
  9871. * @param {Object|Array.<Object>} newCptOptions
  9872. * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9873. * index of which is the same as exists.
  9874. */
  9875. function mappingToExists(exists, newCptOptions) {
  9876. // Mapping by the order by original option (but not order of
  9877. // new option) in merge mode. Because we should ensure
  9878. // some specified index (like xAxisIndex) is consistent with
  9879. // original option, which is easy to understand, espatially in
  9880. // media query. And in most case, merge option is used to
  9881. // update partial option but not be expected to change order.
  9882. newCptOptions = (newCptOptions || []).slice();
  9883. var result = map(exists || [], function (obj, index) {
  9884. return {
  9885. exist: obj
  9886. };
  9887. }); // Mapping by id or name if specified.
  9888. each$2(newCptOptions, function (cptOption, index) {
  9889. if (!isObject$2(cptOption)) {
  9890. return;
  9891. } // id has highest priority.
  9892. for (var i = 0; i < result.length; i++) {
  9893. if (!result[i].option // Consider name: two map to one.
  9894. && cptOption.id != null && result[i].exist.id === cptOption.id + '') {
  9895. result[i].option = cptOption;
  9896. newCptOptions[index] = null;
  9897. return;
  9898. }
  9899. }
  9900. for (var i = 0; i < result.length; i++) {
  9901. var exist = result[i].exist;
  9902. if (!result[i].option // Consider name: two map to one.
  9903. // Can not match when both ids exist but different.
  9904. && (exist.id == null || cptOption.id == null) && cptOption.name != null && !isIdInner(cptOption) && !isIdInner(exist) && exist.name === cptOption.name + '') {
  9905. result[i].option = cptOption;
  9906. newCptOptions[index] = null;
  9907. return;
  9908. }
  9909. }
  9910. }); // Otherwise mapping by index.
  9911. each$2(newCptOptions, function (cptOption, index) {
  9912. if (!isObject$2(cptOption)) {
  9913. return;
  9914. }
  9915. var i = 0;
  9916. for (; i < result.length; i++) {
  9917. var exist = result[i].exist;
  9918. if (!result[i].option // Existing model that already has id should be able to
  9919. // mapped to (because after mapping performed model may
  9920. // be assigned with a id, whish should not affect next
  9921. // mapping), except those has inner id.
  9922. && !isIdInner(exist) // Caution:
  9923. // Do not overwrite id. But name can be overwritten,
  9924. // because axis use name as 'show label text'.
  9925. // 'exist' always has id and name and we dont
  9926. // need to check it.
  9927. && cptOption.id == null) {
  9928. result[i].option = cptOption;
  9929. break;
  9930. }
  9931. }
  9932. if (i >= result.length) {
  9933. result.push({
  9934. option: cptOption
  9935. });
  9936. }
  9937. });
  9938. return result;
  9939. }
  9940. /**
  9941. * Make id and name for mapping result (result of mappingToExists)
  9942. * into `keyInfo` field.
  9943. *
  9944. * @public
  9945. * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}],
  9946. * which order is the same as exists.
  9947. * @return {Array.<Object>} The input.
  9948. */
  9949. function makeIdAndName(mapResult) {
  9950. // We use this id to hash component models and view instances
  9951. // in echarts. id can be specified by user, or auto generated.
  9952. // The id generation rule ensures new view instance are able
  9953. // to mapped to old instance when setOption are called in
  9954. // no-merge mode. So we generate model id by name and plus
  9955. // type in view id.
  9956. // name can be duplicated among components, which is convenient
  9957. // to specify multi components (like series) by one name.
  9958. // Ensure that each id is distinct.
  9959. var idMap = createHashMap();
  9960. each$2(mapResult, function (item, index) {
  9961. var existCpt = item.exist;
  9962. existCpt && idMap.set(existCpt.id, item);
  9963. });
  9964. each$2(mapResult, function (item, index) {
  9965. var opt = item.option;
  9966. assert$1(!opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id));
  9967. opt && opt.id != null && idMap.set(opt.id, item);
  9968. !item.keyInfo && (item.keyInfo = {});
  9969. }); // Make name and id.
  9970. each$2(mapResult, function (item, index) {
  9971. var existCpt = item.exist;
  9972. var opt = item.option;
  9973. var keyInfo = item.keyInfo;
  9974. if (!isObject$2(opt)) {
  9975. return;
  9976. } // name can be overwitten. Consider case: axis.name = '20km'.
  9977. // But id generated by name will not be changed, which affect
  9978. // only in that case: setOption with 'not merge mode' and view
  9979. // instance will be recreated, which can be accepted.
  9980. keyInfo.name = opt.name != null ? opt.name + '' : existCpt ? existCpt.name // Avoid diffferent series has the same name,
  9981. // because name may be used like in color pallet.
  9982. : DUMMY_COMPONENT_NAME_PREFIX + index;
  9983. if (existCpt) {
  9984. keyInfo.id = existCpt.id;
  9985. } else if (opt.id != null) {
  9986. keyInfo.id = opt.id + '';
  9987. } else {
  9988. // Consider this situatoin:
  9989. // optionA: [{name: 'a'}, {name: 'a'}, {..}]
  9990. // optionB [{..}, {name: 'a'}, {name: 'a'}]
  9991. // Series with the same name between optionA and optionB
  9992. // should be mapped.
  9993. var idNum = 0;
  9994. do {
  9995. keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++;
  9996. } while (idMap.get(keyInfo.id));
  9997. }
  9998. idMap.set(keyInfo.id, item);
  9999. });
  10000. }
  10001. function isNameSpecified(componentModel) {
  10002. var name = componentModel.name; // Is specified when `indexOf` get -1 or > 0.
  10003. return !!(name && name.indexOf(DUMMY_COMPONENT_NAME_PREFIX));
  10004. }
  10005. /**
  10006. * @public
  10007. * @param {Object} cptOption
  10008. * @return {boolean}
  10009. */
  10010. function isIdInner(cptOption) {
  10011. return isObject$2(cptOption) && cptOption.id && (cptOption.id + '').indexOf('\0_ec_\0') === 0;
  10012. }
  10013. /**
  10014. * A helper for removing duplicate items between batchA and batchB,
  10015. * and in themselves, and categorize by series.
  10016. *
  10017. * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10018. * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...]
  10019. * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB]
  10020. */
  10021. function compressBatches(batchA, batchB) {
  10022. var mapA = {};
  10023. var mapB = {};
  10024. makeMap(batchA || [], mapA);
  10025. makeMap(batchB || [], mapB, mapA);
  10026. return [mapToArray(mapA), mapToArray(mapB)];
  10027. function makeMap(sourceBatch, map$$1, otherMap) {
  10028. for (var i = 0, len = sourceBatch.length; i < len; i++) {
  10029. var seriesId = sourceBatch[i].seriesId;
  10030. var dataIndices = normalizeToArray(sourceBatch[i].dataIndex);
  10031. var otherDataIndices = otherMap && otherMap[seriesId];
  10032. for (var j = 0, lenj = dataIndices.length; j < lenj; j++) {
  10033. var dataIndex = dataIndices[j];
  10034. if (otherDataIndices && otherDataIndices[dataIndex]) {
  10035. otherDataIndices[dataIndex] = null;
  10036. } else {
  10037. (map$$1[seriesId] || (map$$1[seriesId] = {}))[dataIndex] = 1;
  10038. }
  10039. }
  10040. }
  10041. }
  10042. function mapToArray(map$$1, isData) {
  10043. var result = [];
  10044. for (var i in map$$1) {
  10045. if (map$$1.hasOwnProperty(i) && map$$1[i] != null) {
  10046. if (isData) {
  10047. result.push(+i);
  10048. } else {
  10049. var dataIndices = mapToArray(map$$1[i], true);
  10050. dataIndices.length && result.push({
  10051. seriesId: i,
  10052. dataIndex: dataIndices
  10053. });
  10054. }
  10055. }
  10056. }
  10057. return result;
  10058. }
  10059. }
  10060. /**
  10061. * @param {module:echarts/data/List} data
  10062. * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name
  10063. * each of which can be Array or primary type.
  10064. * @return {number|Array.<number>} dataIndex If not found, return undefined/null.
  10065. */
  10066. function queryDataIndex(data, payload) {
  10067. if (payload.dataIndexInside != null) {
  10068. return payload.dataIndexInside;
  10069. } else if (payload.dataIndex != null) {
  10070. return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) {
  10071. return data.indexOfRawIndex(value);
  10072. }) : data.indexOfRawIndex(payload.dataIndex);
  10073. } else if (payload.name != null) {
  10074. return isArray(payload.name) ? map(payload.name, function (value) {
  10075. return data.indexOfName(value);
  10076. }) : data.indexOfName(payload.name);
  10077. }
  10078. }
  10079. /**
  10080. * Enable property storage to any host object.
  10081. * Notice: Serialization is not supported.
  10082. *
  10083. * For example:
  10084. * var inner = zrUitl.makeInner();
  10085. *
  10086. * function some1(hostObj) {
  10087. * inner(hostObj).someProperty = 1212;
  10088. * ...
  10089. * }
  10090. * function some2() {
  10091. * var fields = inner(this);
  10092. * fields.someProperty1 = 1212;
  10093. * fields.someProperty2 = 'xx';
  10094. * ...
  10095. * }
  10096. *
  10097. * @return {Function}
  10098. */
  10099. function makeInner() {
  10100. // Consider different scope by es module import.
  10101. var key = '__\0ec_inner_' + innerUniqueIndex++ + '_' + Math.random().toFixed(5);
  10102. return function (hostObj) {
  10103. return hostObj[key] || (hostObj[key] = {});
  10104. };
  10105. }
  10106. var innerUniqueIndex = 0;
  10107. /**
  10108. * @param {module:echarts/model/Global} ecModel
  10109. * @param {string|Object} finder
  10110. * If string, e.g., 'geo', means {geoIndex: 0}.
  10111. * If Object, could contain some of these properties below:
  10112. * {
  10113. * seriesIndex, seriesId, seriesName,
  10114. * geoIndex, geoId, geoName,
  10115. * bmapIndex, bmapId, bmapName,
  10116. * xAxisIndex, xAxisId, xAxisName,
  10117. * yAxisIndex, yAxisId, yAxisName,
  10118. * gridIndex, gridId, gridName,
  10119. * ... (can be extended)
  10120. * }
  10121. * Each properties can be number|string|Array.<number>|Array.<string>
  10122. * For example, a finder could be
  10123. * {
  10124. * seriesIndex: 3,
  10125. * geoId: ['aa', 'cc'],
  10126. * gridName: ['xx', 'rr']
  10127. * }
  10128. * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify)
  10129. * If nothing or null/undefined specified, return nothing.
  10130. * @param {Object} [opt]
  10131. * @param {string} [opt.defaultMainType]
  10132. * @param {Array.<string>} [opt.includeMainTypes]
  10133. * @return {Object} result like:
  10134. * {
  10135. * seriesModels: [seriesModel1, seriesModel2],
  10136. * seriesModel: seriesModel1, // The first model
  10137. * geoModels: [geoModel1, geoModel2],
  10138. * geoModel: geoModel1, // The first model
  10139. * ...
  10140. * }
  10141. */
  10142. function parseFinder(ecModel, finder, opt) {
  10143. if (isString(finder)) {
  10144. var obj = {};
  10145. obj[finder + 'Index'] = 0;
  10146. finder = obj;
  10147. }
  10148. var defaultMainType = opt && opt.defaultMainType;
  10149. if (defaultMainType && !has(finder, defaultMainType + 'Index') && !has(finder, defaultMainType + 'Id') && !has(finder, defaultMainType + 'Name')) {
  10150. finder[defaultMainType + 'Index'] = 0;
  10151. }
  10152. var result = {};
  10153. each$2(finder, function (value, key) {
  10154. var value = finder[key]; // Exclude 'dataIndex' and other illgal keys.
  10155. if (key === 'dataIndex' || key === 'dataIndexInside') {
  10156. result[key] = value;
  10157. return;
  10158. }
  10159. var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || [];
  10160. var mainType = parsedKey[1];
  10161. var queryType = (parsedKey[2] || '').toLowerCase();
  10162. if (!mainType || !queryType || value == null || queryType === 'index' && value === 'none' || opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) {
  10163. return;
  10164. }
  10165. var queryParam = {
  10166. mainType: mainType
  10167. };
  10168. if (queryType !== 'index' || value !== 'all') {
  10169. queryParam[queryType] = value;
  10170. }
  10171. var models = ecModel.queryComponents(queryParam);
  10172. result[mainType + 'Models'] = models;
  10173. result[mainType + 'Model'] = models[0];
  10174. });
  10175. return result;
  10176. }
  10177. function has(obj, prop) {
  10178. return obj && obj.hasOwnProperty(prop);
  10179. }
  10180. function setAttribute(dom, key, value) {
  10181. dom.setAttribute ? dom.setAttribute(key, value) : dom[key] = value;
  10182. }
  10183. function getAttribute(dom, key) {
  10184. return dom.getAttribute ? dom.getAttribute(key) : dom[key];
  10185. }
  10186. function getTooltipRenderMode(renderModeOption) {
  10187. if (renderModeOption === 'auto') {
  10188. // Using html when `document` exists, use richText otherwise
  10189. return env$1.domSupported ? 'html' : 'richText';
  10190. } else {
  10191. return renderModeOption || 'html';
  10192. }
  10193. }
  10194. /**
  10195. * Group a list by key.
  10196. *
  10197. * @param {Array} array
  10198. * @param {Function} getKey
  10199. * param {*} Array item
  10200. * return {string} key
  10201. * @return {Object} Result
  10202. * {Array}: keys,
  10203. * {module:zrender/core/util/HashMap} buckets: {key -> Array}
  10204. */
  10205. function groupData(array, getKey) {
  10206. var buckets = createHashMap();
  10207. var keys = [];
  10208. each$1(array, function (item) {
  10209. var key = getKey(item);
  10210. (buckets.get(key) || (keys.push(key), buckets.set(key, []))).push(item);
  10211. });
  10212. return {
  10213. keys: keys,
  10214. buckets: buckets
  10215. };
  10216. }
  10217. /*
  10218. * Licensed to the Apache Software Foundation (ASF) under one
  10219. * or more contributor license agreements. See the NOTICE file
  10220. * distributed with this work for additional information
  10221. * regarding copyright ownership. The ASF licenses this file
  10222. * to you under the Apache License, Version 2.0 (the
  10223. * "License"); you may not use this file except in compliance
  10224. * with the License. You may obtain a copy of the License at
  10225. *
  10226. * http://www.apache.org/licenses/LICENSE-2.0
  10227. *
  10228. * Unless required by applicable law or agreed to in writing,
  10229. * software distributed under the License is distributed on an
  10230. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10231. * KIND, either express or implied. See the License for the
  10232. * specific language governing permissions and limitations
  10233. * under the License.
  10234. */
  10235. var TYPE_DELIMITER = '.';
  10236. var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___';
  10237. /**
  10238. * Notice, parseClassType('') should returns {main: '', sub: ''}
  10239. * @public
  10240. */
  10241. function parseClassType$1(componentType) {
  10242. var ret = {
  10243. main: '',
  10244. sub: ''
  10245. };
  10246. if (componentType) {
  10247. componentType = componentType.split(TYPE_DELIMITER);
  10248. ret.main = componentType[0] || '';
  10249. ret.sub = componentType[1] || '';
  10250. }
  10251. return ret;
  10252. }
  10253. /**
  10254. * @public
  10255. */
  10256. function checkClassType(componentType) {
  10257. assert$1(/^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal');
  10258. }
  10259. /**
  10260. * @public
  10261. */
  10262. function enableClassExtend(RootClass, mandatoryMethods) {
  10263. RootClass.$constructor = RootClass;
  10264. RootClass.extend = function (proto) {
  10265. var superClass = this;
  10266. var ExtendedClass = function () {
  10267. if (!proto.$constructor) {
  10268. superClass.apply(this, arguments);
  10269. } else {
  10270. proto.$constructor.apply(this, arguments);
  10271. }
  10272. };
  10273. extend(ExtendedClass.prototype, proto);
  10274. ExtendedClass.extend = this.extend;
  10275. ExtendedClass.superCall = superCall;
  10276. ExtendedClass.superApply = superApply;
  10277. inherits(ExtendedClass, this);
  10278. ExtendedClass.superClass = superClass;
  10279. return ExtendedClass;
  10280. };
  10281. }
  10282. var classBase = 0;
  10283. /**
  10284. * Can not use instanceof, consider different scope by
  10285. * cross domain or es module import in ec extensions.
  10286. * Mount a method "isInstance()" to Clz.
  10287. */
  10288. function enableClassCheck(Clz) {
  10289. var classAttr = ['__\0is_clz', classBase++, Math.random().toFixed(3)].join('_');
  10290. Clz.prototype[classAttr] = true;
  10291. Clz.isInstance = function (obj) {
  10292. return !!(obj && obj[classAttr]);
  10293. };
  10294. } // superCall should have class info, which can not be fetch from 'this'.
  10295. // Consider this case:
  10296. // class A has method f,
  10297. // class B inherits class A, overrides method f, f call superApply('f'),
  10298. // class C inherits class B, do not overrides method f,
  10299. // then when method of class C is called, dead loop occured.
  10300. function superCall(context, methodName) {
  10301. var args = slice(arguments, 2);
  10302. return this.superClass.prototype[methodName].apply(context, args);
  10303. }
  10304. function superApply(context, methodName, args) {
  10305. return this.superClass.prototype[methodName].apply(context, args);
  10306. }
  10307. /**
  10308. * @param {Object} entity
  10309. * @param {Object} options
  10310. * @param {boolean} [options.registerWhenExtend]
  10311. * @public
  10312. */
  10313. function enableClassManagement(entity, options) {
  10314. options = options || {};
  10315. /**
  10316. * Component model classes
  10317. * key: componentType,
  10318. * value:
  10319. * componentClass, when componentType is 'xxx'
  10320. * or Object.<subKey, componentClass>, when componentType is 'xxx.yy'
  10321. * @type {Object}
  10322. */
  10323. var storage = {};
  10324. entity.registerClass = function (Clazz, componentType) {
  10325. if (componentType) {
  10326. checkClassType(componentType);
  10327. componentType = parseClassType$1(componentType);
  10328. if (!componentType.sub) {
  10329. storage[componentType.main] = Clazz;
  10330. } else if (componentType.sub !== IS_CONTAINER) {
  10331. var container = makeContainer(componentType);
  10332. container[componentType.sub] = Clazz;
  10333. }
  10334. }
  10335. return Clazz;
  10336. };
  10337. entity.getClass = function (componentMainType, subType, throwWhenNotFound) {
  10338. var Clazz = storage[componentMainType];
  10339. if (Clazz && Clazz[IS_CONTAINER]) {
  10340. Clazz = subType ? Clazz[subType] : null;
  10341. }
  10342. if (throwWhenNotFound && !Clazz) {
  10343. throw new Error(!subType ? componentMainType + '.' + 'type should be specified.' : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.');
  10344. }
  10345. return Clazz;
  10346. };
  10347. entity.getClassesByMainType = function (componentType) {
  10348. componentType = parseClassType$1(componentType);
  10349. var result = [];
  10350. var obj = storage[componentType.main];
  10351. if (obj && obj[IS_CONTAINER]) {
  10352. each$1(obj, function (o, type) {
  10353. type !== IS_CONTAINER && result.push(o);
  10354. });
  10355. } else {
  10356. result.push(obj);
  10357. }
  10358. return result;
  10359. };
  10360. entity.hasClass = function (componentType) {
  10361. // Just consider componentType.main.
  10362. componentType = parseClassType$1(componentType);
  10363. return !!storage[componentType.main];
  10364. };
  10365. /**
  10366. * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx']
  10367. */
  10368. entity.getAllClassMainTypes = function () {
  10369. var types = [];
  10370. each$1(storage, function (obj, type) {
  10371. types.push(type);
  10372. });
  10373. return types;
  10374. };
  10375. /**
  10376. * If a main type is container and has sub types
  10377. * @param {string} mainType
  10378. * @return {boolean}
  10379. */
  10380. entity.hasSubTypes = function (componentType) {
  10381. componentType = parseClassType$1(componentType);
  10382. var obj = storage[componentType.main];
  10383. return obj && obj[IS_CONTAINER];
  10384. };
  10385. entity.parseClassType = parseClassType$1;
  10386. function makeContainer(componentType) {
  10387. var container = storage[componentType.main];
  10388. if (!container || !container[IS_CONTAINER]) {
  10389. container = storage[componentType.main] = {};
  10390. container[IS_CONTAINER] = true;
  10391. }
  10392. return container;
  10393. }
  10394. if (options.registerWhenExtend) {
  10395. var originalExtend = entity.extend;
  10396. if (originalExtend) {
  10397. entity.extend = function (proto) {
  10398. var ExtendedClass = originalExtend.call(this, proto);
  10399. return entity.registerClass(ExtendedClass, proto.type);
  10400. };
  10401. }
  10402. }
  10403. return entity;
  10404. }
  10405. /**
  10406. * @param {string|Array.<string>} properties
  10407. */
  10408. /*
  10409. * Licensed to the Apache Software Foundation (ASF) under one
  10410. * or more contributor license agreements. See the NOTICE file
  10411. * distributed with this work for additional information
  10412. * regarding copyright ownership. The ASF licenses this file
  10413. * to you under the Apache License, Version 2.0 (the
  10414. * "License"); you may not use this file except in compliance
  10415. * with the License. You may obtain a copy of the License at
  10416. *
  10417. * http://www.apache.org/licenses/LICENSE-2.0
  10418. *
  10419. * Unless required by applicable law or agreed to in writing,
  10420. * software distributed under the License is distributed on an
  10421. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10422. * KIND, either express or implied. See the License for the
  10423. * specific language governing permissions and limitations
  10424. * under the License.
  10425. */
  10426. // TODO Parse shadow style
  10427. // TODO Only shallow path support
  10428. var makeStyleMapper = function (properties) {
  10429. // Normalize
  10430. for (var i = 0; i < properties.length; i++) {
  10431. if (!properties[i][1]) {
  10432. properties[i][1] = properties[i][0];
  10433. }
  10434. }
  10435. return function (model, excludes, includes) {
  10436. var style = {};
  10437. for (var i = 0; i < properties.length; i++) {
  10438. var propName = properties[i][1];
  10439. if (excludes && indexOf(excludes, propName) >= 0 || includes && indexOf(includes, propName) < 0) {
  10440. continue;
  10441. }
  10442. var val = model.getShallow(propName);
  10443. if (val != null) {
  10444. style[properties[i][0]] = val;
  10445. }
  10446. }
  10447. return style;
  10448. };
  10449. };
  10450. /*
  10451. * Licensed to the Apache Software Foundation (ASF) under one
  10452. * or more contributor license agreements. See the NOTICE file
  10453. * distributed with this work for additional information
  10454. * regarding copyright ownership. The ASF licenses this file
  10455. * to you under the Apache License, Version 2.0 (the
  10456. * "License"); you may not use this file except in compliance
  10457. * with the License. You may obtain a copy of the License at
  10458. *
  10459. * http://www.apache.org/licenses/LICENSE-2.0
  10460. *
  10461. * Unless required by applicable law or agreed to in writing,
  10462. * software distributed under the License is distributed on an
  10463. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10464. * KIND, either express or implied. See the License for the
  10465. * specific language governing permissions and limitations
  10466. * under the License.
  10467. */
  10468. var getLineStyle = makeStyleMapper([['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor']]);
  10469. var lineStyleMixin = {
  10470. getLineStyle: function (excludes) {
  10471. var style = getLineStyle(this, excludes); // Always set lineDash whether dashed, otherwise we can not
  10472. // erase the previous style when assigning to el.style.
  10473. style.lineDash = this.getLineDash(style.lineWidth);
  10474. return style;
  10475. },
  10476. getLineDash: function (lineWidth) {
  10477. if (lineWidth == null) {
  10478. lineWidth = 1;
  10479. }
  10480. var lineType = this.get('type');
  10481. var dotSize = Math.max(lineWidth, 2);
  10482. var dashSize = lineWidth * 4;
  10483. return lineType === 'solid' || lineType == null ? // Use `false` but not `null` for the solid line here, because `null` might be
  10484. // ignored when assigning to `el.style`. e.g., when setting `lineStyle.type` as
  10485. // `'dashed'` and `emphasis.lineStyle.type` as `'solid'` in graph series, the
  10486. // `lineDash` gotten form the latter one is not able to erase that from the former
  10487. // one if using `null` here according to the emhpsis strategy in `util/graphic.js`.
  10488. false : lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize];
  10489. }
  10490. };
  10491. /*
  10492. * Licensed to the Apache Software Foundation (ASF) under one
  10493. * or more contributor license agreements. See the NOTICE file
  10494. * distributed with this work for additional information
  10495. * regarding copyright ownership. The ASF licenses this file
  10496. * to you under the Apache License, Version 2.0 (the
  10497. * "License"); you may not use this file except in compliance
  10498. * with the License. You may obtain a copy of the License at
  10499. *
  10500. * http://www.apache.org/licenses/LICENSE-2.0
  10501. *
  10502. * Unless required by applicable law or agreed to in writing,
  10503. * software distributed under the License is distributed on an
  10504. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  10505. * KIND, either express or implied. See the License for the
  10506. * specific language governing permissions and limitations
  10507. * under the License.
  10508. */
  10509. var getAreaStyle = makeStyleMapper([['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor']]);
  10510. var areaStyleMixin = {
  10511. getAreaStyle: function (excludes, includes) {
  10512. return getAreaStyle(this, excludes, includes);
  10513. }
  10514. };
  10515. /**
  10516. * 曲线辅助模块
  10517. * @module zrender/core/curve
  10518. * @author pissang(https://www.github.com/pissang)
  10519. */
  10520. var mathPow = Math.pow;
  10521. var mathSqrt$2 = Math.sqrt;
  10522. var EPSILON$1 = 1e-8;
  10523. var EPSILON_NUMERIC = 1e-4;
  10524. var THREE_SQRT = mathSqrt$2(3);
  10525. var ONE_THIRD = 1 / 3; // 临时变量
  10526. var _v0 = create();
  10527. var _v1 = create();
  10528. var _v2 = create();
  10529. function isAroundZero(val) {
  10530. return val > -EPSILON$1 && val < EPSILON$1;
  10531. }
  10532. function isNotAroundZero$1(val) {
  10533. return val > EPSILON$1 || val < -EPSILON$1;
  10534. }
  10535. /**
  10536. * 计算三次贝塞尔值
  10537. * @memberOf module:zrender/core/curve
  10538. * @param {number} p0
  10539. * @param {number} p1
  10540. * @param {number} p2
  10541. * @param {number} p3
  10542. * @param {number} t
  10543. * @return {number}
  10544. */
  10545. function cubicAt(p0, p1, p2, p3, t) {
  10546. var onet = 1 - t;
  10547. return onet * onet * (onet * p0 + 3 * t * p1) + t * t * (t * p3 + 3 * onet * p2);
  10548. }
  10549. /**
  10550. * 计算三次贝塞尔导数值
  10551. * @memberOf module:zrender/core/curve
  10552. * @param {number} p0
  10553. * @param {number} p1
  10554. * @param {number} p2
  10555. * @param {number} p3
  10556. * @param {number} t
  10557. * @return {number}
  10558. */
  10559. function cubicDerivativeAt(p0, p1, p2, p3, t) {
  10560. var onet = 1 - t;
  10561. return 3 * (((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t);
  10562. }
  10563. /**
  10564. * 计算三次贝塞尔方程根,使用盛金公式
  10565. * @memberOf module:zrender/core/curve
  10566. * @param {number} p0
  10567. * @param {number} p1
  10568. * @param {number} p2
  10569. * @param {number} p3
  10570. * @param {number} val
  10571. * @param {Array.<number>} roots
  10572. * @return {number} 有效根数目
  10573. */
  10574. function cubicRootAt(p0, p1, p2, p3, val, roots) {
  10575. // Evaluate roots of cubic functions
  10576. var a = p3 + 3 * (p1 - p2) - p0;
  10577. var b = 3 * (p2 - p1 * 2 + p0);
  10578. var c = 3 * (p1 - p0);
  10579. var d = p0 - val;
  10580. var A = b * b - 3 * a * c;
  10581. var B = b * c - 9 * a * d;
  10582. var C = c * c - 3 * b * d;
  10583. var n = 0;
  10584. if (isAroundZero(A) && isAroundZero(B)) {
  10585. if (isAroundZero(b)) {
  10586. roots[0] = 0;
  10587. } else {
  10588. var t1 = -c / b; //t1, t2, t3, b is not zero
  10589. if (t1 >= 0 && t1 <= 1) {
  10590. roots[n++] = t1;
  10591. }
  10592. }
  10593. } else {
  10594. var disc = B * B - 4 * A * C;
  10595. if (isAroundZero(disc)) {
  10596. var K = B / A;
  10597. var t1 = -b / a + K; // t1, a is not zero
  10598. var t2 = -K / 2; // t2, t3
  10599. if (t1 >= 0 && t1 <= 1) {
  10600. roots[n++] = t1;
  10601. }
  10602. if (t2 >= 0 && t2 <= 1) {
  10603. roots[n++] = t2;
  10604. }
  10605. } else if (disc > 0) {
  10606. var discSqrt = mathSqrt$2(disc);
  10607. var Y1 = A * b + 1.5 * a * (-B + discSqrt);
  10608. var Y2 = A * b + 1.5 * a * (-B - discSqrt);
  10609. if (Y1 < 0) {
  10610. Y1 = -mathPow(-Y1, ONE_THIRD);
  10611. } else {
  10612. Y1 = mathPow(Y1, ONE_THIRD);
  10613. }
  10614. if (Y2 < 0) {
  10615. Y2 = -mathPow(-Y2, ONE_THIRD);
  10616. } else {
  10617. Y2 = mathPow(Y2, ONE_THIRD);
  10618. }
  10619. var t1 = (-b - (Y1 + Y2)) / (3 * a);
  10620. if (t1 >= 0 && t1 <= 1) {
  10621. roots[n++] = t1;
  10622. }
  10623. } else {
  10624. var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A));
  10625. var theta = Math.acos(T) / 3;
  10626. var ASqrt = mathSqrt$2(A);
  10627. var tmp = Math.cos(theta);
  10628. var t1 = (-b - 2 * ASqrt * tmp) / (3 * a);
  10629. var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a);
  10630. var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a);
  10631. if (t1 >= 0 && t1 <= 1) {
  10632. roots[n++] = t1;
  10633. }
  10634. if (t2 >= 0 && t2 <= 1) {
  10635. roots[n++] = t2;
  10636. }
  10637. if (t3 >= 0 && t3 <= 1) {
  10638. roots[n++] = t3;
  10639. }
  10640. }
  10641. }
  10642. return n;
  10643. }
  10644. /**
  10645. * 计算三次贝塞尔方程极限值的位置
  10646. * @memberOf module:zrender/core/curve
  10647. * @param {number} p0
  10648. * @param {number} p1
  10649. * @param {number} p2
  10650. * @param {number} p3
  10651. * @param {Array.<number>} extrema
  10652. * @return {number} 有效数目
  10653. */
  10654. function cubicExtrema(p0, p1, p2, p3, extrema) {
  10655. var b = 6 * p2 - 12 * p1 + 6 * p0;
  10656. var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2;
  10657. var c = 3 * p1 - 3 * p0;
  10658. var n = 0;
  10659. if (isAroundZero(a)) {
  10660. if (isNotAroundZero$1(b)) {
  10661. var t1 = -c / b;
  10662. if (t1 >= 0 && t1 <= 1) {
  10663. extrema[n++] = t1;
  10664. }
  10665. }
  10666. } else {
  10667. var disc = b * b - 4 * a * c;
  10668. if (isAroundZero(disc)) {
  10669. extrema[0] = -b / (2 * a);
  10670. } else if (disc > 0) {
  10671. var discSqrt = mathSqrt$2(disc);
  10672. var t1 = (-b + discSqrt) / (2 * a);
  10673. var t2 = (-b - discSqrt) / (2 * a);
  10674. if (t1 >= 0 && t1 <= 1) {
  10675. extrema[n++] = t1;
  10676. }
  10677. if (t2 >= 0 && t2 <= 1) {
  10678. extrema[n++] = t2;
  10679. }
  10680. }
  10681. }
  10682. return n;
  10683. }
  10684. /**
  10685. * 细分三次贝塞尔曲线
  10686. * @memberOf module:zrender/core/curve
  10687. * @param {number} p0
  10688. * @param {number} p1
  10689. * @param {number} p2
  10690. * @param {number} p3
  10691. * @param {number} t
  10692. * @param {Array.<number>} out
  10693. */
  10694. function cubicSubdivide(p0, p1, p2, p3, t, out) {
  10695. var p01 = (p1 - p0) * t + p0;
  10696. var p12 = (p2 - p1) * t + p1;
  10697. var p23 = (p3 - p2) * t + p2;
  10698. var p012 = (p12 - p01) * t + p01;
  10699. var p123 = (p23 - p12) * t + p12;
  10700. var p0123 = (p123 - p012) * t + p012; // Seg0
  10701. out[0] = p0;
  10702. out[1] = p01;
  10703. out[2] = p012;
  10704. out[3] = p0123; // Seg1
  10705. out[4] = p0123;
  10706. out[5] = p123;
  10707. out[6] = p23;
  10708. out[7] = p3;
  10709. }
  10710. /**
  10711. * 投射点到三次贝塞尔曲线上,返回投射距离。
  10712. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10713. * @param {number} x0
  10714. * @param {number} y0
  10715. * @param {number} x1
  10716. * @param {number} y1
  10717. * @param {number} x2
  10718. * @param {number} y2
  10719. * @param {number} x3
  10720. * @param {number} y3
  10721. * @param {number} x
  10722. * @param {number} y
  10723. * @param {Array.<number>} [out] 投射点
  10724. * @return {number}
  10725. */
  10726. function cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, out) {
  10727. // http://pomax.github.io/bezierinfo/#projections
  10728. var t;
  10729. var interval = 0.005;
  10730. var d = Infinity;
  10731. var prev;
  10732. var next;
  10733. var d1;
  10734. var d2;
  10735. _v0[0] = x;
  10736. _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值
  10737. // PENDING
  10738. for (var _t = 0; _t < 1; _t += 0.05) {
  10739. _v1[0] = cubicAt(x0, x1, x2, x3, _t);
  10740. _v1[1] = cubicAt(y0, y1, y2, y3, _t);
  10741. d1 = distSquare(_v0, _v1);
  10742. if (d1 < d) {
  10743. t = _t;
  10744. d = d1;
  10745. }
  10746. }
  10747. d = Infinity; // At most 32 iteration
  10748. for (var i = 0; i < 32; i++) {
  10749. if (interval < EPSILON_NUMERIC) {
  10750. break;
  10751. }
  10752. prev = t - interval;
  10753. next = t + interval; // t - interval
  10754. _v1[0] = cubicAt(x0, x1, x2, x3, prev);
  10755. _v1[1] = cubicAt(y0, y1, y2, y3, prev);
  10756. d1 = distSquare(_v1, _v0);
  10757. if (prev >= 0 && d1 < d) {
  10758. t = prev;
  10759. d = d1;
  10760. } else {
  10761. // t + interval
  10762. _v2[0] = cubicAt(x0, x1, x2, x3, next);
  10763. _v2[1] = cubicAt(y0, y1, y2, y3, next);
  10764. d2 = distSquare(_v2, _v0);
  10765. if (next <= 1 && d2 < d) {
  10766. t = next;
  10767. d = d2;
  10768. } else {
  10769. interval *= 0.5;
  10770. }
  10771. }
  10772. } // t
  10773. if (out) {
  10774. out[0] = cubicAt(x0, x1, x2, x3, t);
  10775. out[1] = cubicAt(y0, y1, y2, y3, t);
  10776. } // console.log(interval, i);
  10777. return mathSqrt$2(d);
  10778. }
  10779. /**
  10780. * 计算二次方贝塞尔值
  10781. * @param {number} p0
  10782. * @param {number} p1
  10783. * @param {number} p2
  10784. * @param {number} t
  10785. * @return {number}
  10786. */
  10787. function quadraticAt(p0, p1, p2, t) {
  10788. var onet = 1 - t;
  10789. return onet * (onet * p0 + 2 * t * p1) + t * t * p2;
  10790. }
  10791. /**
  10792. * 计算二次方贝塞尔导数值
  10793. * @param {number} p0
  10794. * @param {number} p1
  10795. * @param {number} p2
  10796. * @param {number} t
  10797. * @return {number}
  10798. */
  10799. function quadraticDerivativeAt(p0, p1, p2, t) {
  10800. return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1));
  10801. }
  10802. /**
  10803. * 计算二次方贝塞尔方程根
  10804. * @param {number} p0
  10805. * @param {number} p1
  10806. * @param {number} p2
  10807. * @param {number} t
  10808. * @param {Array.<number>} roots
  10809. * @return {number} 有效根数目
  10810. */
  10811. function quadraticRootAt(p0, p1, p2, val, roots) {
  10812. var a = p0 - 2 * p1 + p2;
  10813. var b = 2 * (p1 - p0);
  10814. var c = p0 - val;
  10815. var n = 0;
  10816. if (isAroundZero(a)) {
  10817. if (isNotAroundZero$1(b)) {
  10818. var t1 = -c / b;
  10819. if (t1 >= 0 && t1 <= 1) {
  10820. roots[n++] = t1;
  10821. }
  10822. }
  10823. } else {
  10824. var disc = b * b - 4 * a * c;
  10825. if (isAroundZero(disc)) {
  10826. var t1 = -b / (2 * a);
  10827. if (t1 >= 0 && t1 <= 1) {
  10828. roots[n++] = t1;
  10829. }
  10830. } else if (disc > 0) {
  10831. var discSqrt = mathSqrt$2(disc);
  10832. var t1 = (-b + discSqrt) / (2 * a);
  10833. var t2 = (-b - discSqrt) / (2 * a);
  10834. if (t1 >= 0 && t1 <= 1) {
  10835. roots[n++] = t1;
  10836. }
  10837. if (t2 >= 0 && t2 <= 1) {
  10838. roots[n++] = t2;
  10839. }
  10840. }
  10841. }
  10842. return n;
  10843. }
  10844. /**
  10845. * 计算二次贝塞尔方程极限值
  10846. * @memberOf module:zrender/core/curve
  10847. * @param {number} p0
  10848. * @param {number} p1
  10849. * @param {number} p2
  10850. * @return {number}
  10851. */
  10852. function quadraticExtremum(p0, p1, p2) {
  10853. var divider = p0 + p2 - 2 * p1;
  10854. if (divider === 0) {
  10855. // p1 is center of p0 and p2
  10856. return 0.5;
  10857. } else {
  10858. return (p0 - p1) / divider;
  10859. }
  10860. }
  10861. /**
  10862. * 细分二次贝塞尔曲线
  10863. * @memberOf module:zrender/core/curve
  10864. * @param {number} p0
  10865. * @param {number} p1
  10866. * @param {number} p2
  10867. * @param {number} t
  10868. * @param {Array.<number>} out
  10869. */
  10870. function quadraticSubdivide(p0, p1, p2, t, out) {
  10871. var p01 = (p1 - p0) * t + p0;
  10872. var p12 = (p2 - p1) * t + p1;
  10873. var p012 = (p12 - p01) * t + p01; // Seg0
  10874. out[0] = p0;
  10875. out[1] = p01;
  10876. out[2] = p012; // Seg1
  10877. out[3] = p012;
  10878. out[4] = p12;
  10879. out[5] = p2;
  10880. }
  10881. /**
  10882. * 投射点到二次贝塞尔曲线上,返回投射距离。
  10883. * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。
  10884. * @param {number} x0
  10885. * @param {number} y0
  10886. * @param {number} x1
  10887. * @param {number} y1
  10888. * @param {number} x2
  10889. * @param {number} y2
  10890. * @param {number} x
  10891. * @param {number} y
  10892. * @param {Array.<number>} out 投射点
  10893. * @return {number}
  10894. */
  10895. function quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, out) {
  10896. // http://pomax.github.io/bezierinfo/#projections
  10897. var t;
  10898. var interval = 0.005;
  10899. var d = Infinity;
  10900. _v0[0] = x;
  10901. _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值
  10902. // PENDING
  10903. for (var _t = 0; _t < 1; _t += 0.05) {
  10904. _v1[0] = quadraticAt(x0, x1, x2, _t);
  10905. _v1[1] = quadraticAt(y0, y1, y2, _t);
  10906. var d1 = distSquare(_v0, _v1);
  10907. if (d1 < d) {
  10908. t = _t;
  10909. d = d1;
  10910. }
  10911. }
  10912. d = Infinity; // At most 32 iteration
  10913. for (var i = 0; i < 32; i++) {
  10914. if (interval < EPSILON_NUMERIC) {
  10915. break;
  10916. }
  10917. var prev = t - interval;
  10918. var next = t + interval; // t - interval
  10919. _v1[0] = quadraticAt(x0, x1, x2, prev);
  10920. _v1[1] = quadraticAt(y0, y1, y2, prev);
  10921. var d1 = distSquare(_v1, _v0);
  10922. if (prev >= 0 && d1 < d) {
  10923. t = prev;
  10924. d = d1;
  10925. } else {
  10926. // t + interval
  10927. _v2[0] = quadraticAt(x0, x1, x2, next);
  10928. _v2[1] = quadraticAt(y0, y1, y2, next);
  10929. var d2 = distSquare(_v2, _v0);
  10930. if (next <= 1 && d2 < d) {
  10931. t = next;
  10932. d = d2;
  10933. } else {
  10934. interval *= 0.5;
  10935. }
  10936. }
  10937. } // t
  10938. if (out) {
  10939. out[0] = quadraticAt(x0, x1, x2, t);
  10940. out[1] = quadraticAt(y0, y1, y2, t);
  10941. } // console.log(interval, i);
  10942. return mathSqrt$2(d);
  10943. }
  10944. /**
  10945. * @author Yi Shen(https://github.com/pissang)
  10946. */
  10947. var mathMin$3 = Math.min;
  10948. var mathMax$3 = Math.max;
  10949. var mathSin$2 = Math.sin;
  10950. var mathCos$2 = Math.cos;
  10951. var PI2 = Math.PI * 2;
  10952. var start = create();
  10953. var end = create();
  10954. var extremity = create();
  10955. /**
  10956. * 从顶点数组中计算出最小包围盒,写入`min`和`max`中
  10957. * @module zrender/core/bbox
  10958. * @param {Array<Object>} points 顶点数组
  10959. * @param {number} min
  10960. * @param {number} max
  10961. */
  10962. function fromPoints(points, min$$1, max$$1) {
  10963. if (points.length === 0) {
  10964. return;
  10965. }
  10966. var p = points[0];
  10967. var left = p[0];
  10968. var right = p[0];
  10969. var top = p[1];
  10970. var bottom = p[1];
  10971. var i;
  10972. for (i = 1; i < points.length; i++) {
  10973. p = points[i];
  10974. left = mathMin$3(left, p[0]);
  10975. right = mathMax$3(right, p[0]);
  10976. top = mathMin$3(top, p[1]);
  10977. bottom = mathMax$3(bottom, p[1]);
  10978. }
  10979. min$$1[0] = left;
  10980. min$$1[1] = top;
  10981. max$$1[0] = right;
  10982. max$$1[1] = bottom;
  10983. }
  10984. /**
  10985. * @memberOf module:zrender/core/bbox
  10986. * @param {number} x0
  10987. * @param {number} y0
  10988. * @param {number} x1
  10989. * @param {number} y1
  10990. * @param {Array.<number>} min
  10991. * @param {Array.<number>} max
  10992. */
  10993. function fromLine(x0, y0, x1, y1, min$$1, max$$1) {
  10994. min$$1[0] = mathMin$3(x0, x1);
  10995. min$$1[1] = mathMin$3(y0, y1);
  10996. max$$1[0] = mathMax$3(x0, x1);
  10997. max$$1[1] = mathMax$3(y0, y1);
  10998. }
  10999. var xDim = [];
  11000. var yDim = [];
  11001. /**
  11002. * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中
  11003. * @memberOf module:zrender/core/bbox
  11004. * @param {number} x0
  11005. * @param {number} y0
  11006. * @param {number} x1
  11007. * @param {number} y1
  11008. * @param {number} x2
  11009. * @param {number} y2
  11010. * @param {number} x3
  11011. * @param {number} y3
  11012. * @param {Array.<number>} min
  11013. * @param {Array.<number>} max
  11014. */
  11015. function fromCubic(x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1) {
  11016. var cubicExtrema$$1 = cubicExtrema;
  11017. var cubicAt$$1 = cubicAt;
  11018. var i;
  11019. var n = cubicExtrema$$1(x0, x1, x2, x3, xDim);
  11020. min$$1[0] = Infinity;
  11021. min$$1[1] = Infinity;
  11022. max$$1[0] = -Infinity;
  11023. max$$1[1] = -Infinity;
  11024. for (i = 0; i < n; i++) {
  11025. var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]);
  11026. min$$1[0] = mathMin$3(x, min$$1[0]);
  11027. max$$1[0] = mathMax$3(x, max$$1[0]);
  11028. }
  11029. n = cubicExtrema$$1(y0, y1, y2, y3, yDim);
  11030. for (i = 0; i < n; i++) {
  11031. var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]);
  11032. min$$1[1] = mathMin$3(y, min$$1[1]);
  11033. max$$1[1] = mathMax$3(y, max$$1[1]);
  11034. }
  11035. min$$1[0] = mathMin$3(x0, min$$1[0]);
  11036. max$$1[0] = mathMax$3(x0, max$$1[0]);
  11037. min$$1[0] = mathMin$3(x3, min$$1[0]);
  11038. max$$1[0] = mathMax$3(x3, max$$1[0]);
  11039. min$$1[1] = mathMin$3(y0, min$$1[1]);
  11040. max$$1[1] = mathMax$3(y0, max$$1[1]);
  11041. min$$1[1] = mathMin$3(y3, min$$1[1]);
  11042. max$$1[1] = mathMax$3(y3, max$$1[1]);
  11043. }
  11044. /**
  11045. * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中
  11046. * @memberOf module:zrender/core/bbox
  11047. * @param {number} x0
  11048. * @param {number} y0
  11049. * @param {number} x1
  11050. * @param {number} y1
  11051. * @param {number} x2
  11052. * @param {number} y2
  11053. * @param {Array.<number>} min
  11054. * @param {Array.<number>} max
  11055. */
  11056. function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) {
  11057. var quadraticExtremum$$1 = quadraticExtremum;
  11058. var quadraticAt$$1 = quadraticAt; // Find extremities, where derivative in x dim or y dim is zero
  11059. var tx = mathMax$3(mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0);
  11060. var ty = mathMax$3(mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0);
  11061. var x = quadraticAt$$1(x0, x1, x2, tx);
  11062. var y = quadraticAt$$1(y0, y1, y2, ty);
  11063. min$$1[0] = mathMin$3(x0, x2, x);
  11064. min$$1[1] = mathMin$3(y0, y2, y);
  11065. max$$1[0] = mathMax$3(x0, x2, x);
  11066. max$$1[1] = mathMax$3(y0, y2, y);
  11067. }
  11068. /**
  11069. * 从圆弧中计算出最小包围盒,写入`min`和`max`中
  11070. * @method
  11071. * @memberOf module:zrender/core/bbox
  11072. * @param {number} x
  11073. * @param {number} y
  11074. * @param {number} rx
  11075. * @param {number} ry
  11076. * @param {number} startAngle
  11077. * @param {number} endAngle
  11078. * @param {number} anticlockwise
  11079. * @param {Array.<number>} min
  11080. * @param {Array.<number>} max
  11081. */
  11082. function fromArc(x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1) {
  11083. var vec2Min = min;
  11084. var vec2Max = max;
  11085. var diff = Math.abs(startAngle - endAngle);
  11086. if (diff % PI2 < 1e-4 && diff > 1e-4) {
  11087. // Is a circle
  11088. min$$1[0] = x - rx;
  11089. min$$1[1] = y - ry;
  11090. max$$1[0] = x + rx;
  11091. max$$1[1] = y + ry;
  11092. return;
  11093. }
  11094. start[0] = mathCos$2(startAngle) * rx + x;
  11095. start[1] = mathSin$2(startAngle) * ry + y;
  11096. end[0] = mathCos$2(endAngle) * rx + x;
  11097. end[1] = mathSin$2(endAngle) * ry + y;
  11098. vec2Min(min$$1, start, end);
  11099. vec2Max(max$$1, start, end); // Thresh to [0, Math.PI * 2]
  11100. startAngle = startAngle % PI2;
  11101. if (startAngle < 0) {
  11102. startAngle = startAngle + PI2;
  11103. }
  11104. endAngle = endAngle % PI2;
  11105. if (endAngle < 0) {
  11106. endAngle = endAngle + PI2;
  11107. }
  11108. if (startAngle > endAngle && !anticlockwise) {
  11109. endAngle += PI2;
  11110. } else if (startAngle < endAngle && anticlockwise) {
  11111. startAngle += PI2;
  11112. }
  11113. if (anticlockwise) {
  11114. var tmp = endAngle;
  11115. endAngle = startAngle;
  11116. startAngle = tmp;
  11117. } // var number = 0;
  11118. // var step = (anticlockwise ? -Math.PI : Math.PI) / 2;
  11119. for (var angle = 0; angle < endAngle; angle += Math.PI / 2) {
  11120. if (angle > startAngle) {
  11121. extremity[0] = mathCos$2(angle) * rx + x;
  11122. extremity[1] = mathSin$2(angle) * ry + y;
  11123. vec2Min(min$$1, extremity, min$$1);
  11124. vec2Max(max$$1, extremity, max$$1);
  11125. }
  11126. }
  11127. }
  11128. /**
  11129. * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中
  11130. * 可以用于 isInsidePath 判断以及获取boundingRect
  11131. *
  11132. * @module zrender/core/PathProxy
  11133. * @author Yi Shen (http://www.github.com/pissang)
  11134. */
  11135. // TODO getTotalLength, getPointAtLength
  11136. /* global Float32Array */
  11137. var CMD = {
  11138. M: 1,
  11139. L: 2,
  11140. C: 3,
  11141. Q: 4,
  11142. A: 5,
  11143. Z: 6,
  11144. // Rect
  11145. R: 7
  11146. }; // var CMD_MEM_SIZE = {
  11147. // M: 3,
  11148. // L: 3,
  11149. // C: 7,
  11150. // Q: 5,
  11151. // A: 9,
  11152. // R: 5,
  11153. // Z: 1
  11154. // };
  11155. var min$1 = [];
  11156. var max$1 = [];
  11157. var min2 = [];
  11158. var max2 = [];
  11159. var mathMin$2 = Math.min;
  11160. var mathMax$2 = Math.max;
  11161. var mathCos$1 = Math.cos;
  11162. var mathSin$1 = Math.sin;
  11163. var mathSqrt$1 = Math.sqrt;
  11164. var mathAbs = Math.abs;
  11165. var hasTypedArray = typeof Float32Array !== 'undefined';
  11166. /**
  11167. * @alias module:zrender/core/PathProxy
  11168. * @constructor
  11169. */
  11170. var PathProxy = function (notSaveData) {
  11171. this._saveData = !(notSaveData || false);
  11172. if (this._saveData) {
  11173. /**
  11174. * Path data. Stored as flat array
  11175. * @type {Array.<Object>}
  11176. */
  11177. this.data = [];
  11178. }
  11179. this._ctx = null;
  11180. };
  11181. /**
  11182. * 快速计算Path包围盒(并不是最小包围盒)
  11183. * @return {Object}
  11184. */
  11185. PathProxy.prototype = {
  11186. constructor: PathProxy,
  11187. _xi: 0,
  11188. _yi: 0,
  11189. _x0: 0,
  11190. _y0: 0,
  11191. // Unit x, Unit y. Provide for avoiding drawing that too short line segment
  11192. _ux: 0,
  11193. _uy: 0,
  11194. _len: 0,
  11195. _lineDash: null,
  11196. _dashOffset: 0,
  11197. _dashIdx: 0,
  11198. _dashSum: 0,
  11199. /**
  11200. * @readOnly
  11201. */
  11202. setScale: function (sx, sy, segmentIgnoreThreshold) {
  11203. // Compat. Previously there is no segmentIgnoreThreshold.
  11204. segmentIgnoreThreshold = segmentIgnoreThreshold || 0;
  11205. this._ux = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sx) || 0;
  11206. this._uy = mathAbs(segmentIgnoreThreshold / devicePixelRatio / sy) || 0;
  11207. },
  11208. getContext: function () {
  11209. return this._ctx;
  11210. },
  11211. /**
  11212. * @param {CanvasRenderingContext2D} ctx
  11213. * @return {module:zrender/core/PathProxy}
  11214. */
  11215. beginPath: function (ctx) {
  11216. this._ctx = ctx;
  11217. ctx && ctx.beginPath();
  11218. ctx && (this.dpr = ctx.dpr); // Reset
  11219. if (this._saveData) {
  11220. this._len = 0;
  11221. }
  11222. if (this._lineDash) {
  11223. this._lineDash = null;
  11224. this._dashOffset = 0;
  11225. }
  11226. return this;
  11227. },
  11228. /**
  11229. * @param {number} x
  11230. * @param {number} y
  11231. * @return {module:zrender/core/PathProxy}
  11232. */
  11233. moveTo: function (x, y) {
  11234. this.addData(CMD.M, x, y);
  11235. this._ctx && this._ctx.moveTo(x, y); // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用
  11236. // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。
  11237. // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要
  11238. // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持
  11239. this._x0 = x;
  11240. this._y0 = y;
  11241. this._xi = x;
  11242. this._yi = y;
  11243. return this;
  11244. },
  11245. /**
  11246. * @param {number} x
  11247. * @param {number} y
  11248. * @return {module:zrender/core/PathProxy}
  11249. */
  11250. lineTo: function (x, y) {
  11251. var exceedUnit = mathAbs(x - this._xi) > this._ux || mathAbs(y - this._yi) > this._uy // Force draw the first segment
  11252. || this._len < 5;
  11253. this.addData(CMD.L, x, y);
  11254. if (this._ctx && exceedUnit) {
  11255. this._needsDash() ? this._dashedLineTo(x, y) : this._ctx.lineTo(x, y);
  11256. }
  11257. if (exceedUnit) {
  11258. this._xi = x;
  11259. this._yi = y;
  11260. }
  11261. return this;
  11262. },
  11263. /**
  11264. * @param {number} x1
  11265. * @param {number} y1
  11266. * @param {number} x2
  11267. * @param {number} y2
  11268. * @param {number} x3
  11269. * @param {number} y3
  11270. * @return {module:zrender/core/PathProxy}
  11271. */
  11272. bezierCurveTo: function (x1, y1, x2, y2, x3, y3) {
  11273. this.addData(CMD.C, x1, y1, x2, y2, x3, y3);
  11274. if (this._ctx) {
  11275. this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3) : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3);
  11276. }
  11277. this._xi = x3;
  11278. this._yi = y3;
  11279. return this;
  11280. },
  11281. /**
  11282. * @param {number} x1
  11283. * @param {number} y1
  11284. * @param {number} x2
  11285. * @param {number} y2
  11286. * @return {module:zrender/core/PathProxy}
  11287. */
  11288. quadraticCurveTo: function (x1, y1, x2, y2) {
  11289. this.addData(CMD.Q, x1, y1, x2, y2);
  11290. if (this._ctx) {
  11291. this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2) : this._ctx.quadraticCurveTo(x1, y1, x2, y2);
  11292. }
  11293. this._xi = x2;
  11294. this._yi = y2;
  11295. return this;
  11296. },
  11297. /**
  11298. * @param {number} cx
  11299. * @param {number} cy
  11300. * @param {number} r
  11301. * @param {number} startAngle
  11302. * @param {number} endAngle
  11303. * @param {boolean} anticlockwise
  11304. * @return {module:zrender/core/PathProxy}
  11305. */
  11306. arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) {
  11307. this.addData(CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1);
  11308. this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise);
  11309. this._xi = mathCos$1(endAngle) * r + cx;
  11310. this._yi = mathSin$1(endAngle) * r + cy;
  11311. return this;
  11312. },
  11313. // TODO
  11314. arcTo: function (x1, y1, x2, y2, radius) {
  11315. if (this._ctx) {
  11316. this._ctx.arcTo(x1, y1, x2, y2, radius);
  11317. }
  11318. return this;
  11319. },
  11320. // TODO
  11321. rect: function (x, y, w, h) {
  11322. this._ctx && this._ctx.rect(x, y, w, h);
  11323. this.addData(CMD.R, x, y, w, h);
  11324. return this;
  11325. },
  11326. /**
  11327. * @return {module:zrender/core/PathProxy}
  11328. */
  11329. closePath: function () {
  11330. this.addData(CMD.Z);
  11331. var ctx = this._ctx;
  11332. var x0 = this._x0;
  11333. var y0 = this._y0;
  11334. if (ctx) {
  11335. this._needsDash() && this._dashedLineTo(x0, y0);
  11336. ctx.closePath();
  11337. }
  11338. this._xi = x0;
  11339. this._yi = y0;
  11340. return this;
  11341. },
  11342. /**
  11343. * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。
  11344. * stroke 同样
  11345. * @param {CanvasRenderingContext2D} ctx
  11346. * @return {module:zrender/core/PathProxy}
  11347. */
  11348. fill: function (ctx) {
  11349. ctx && ctx.fill();
  11350. this.toStatic();
  11351. },
  11352. /**
  11353. * @param {CanvasRenderingContext2D} ctx
  11354. * @return {module:zrender/core/PathProxy}
  11355. */
  11356. stroke: function (ctx) {
  11357. ctx && ctx.stroke();
  11358. this.toStatic();
  11359. },
  11360. /**
  11361. * 必须在其它绘制命令前调用
  11362. * Must be invoked before all other path drawing methods
  11363. * @return {module:zrender/core/PathProxy}
  11364. */
  11365. setLineDash: function (lineDash) {
  11366. if (lineDash instanceof Array) {
  11367. this._lineDash = lineDash;
  11368. this._dashIdx = 0;
  11369. var lineDashSum = 0;
  11370. for (var i = 0; i < lineDash.length; i++) {
  11371. lineDashSum += lineDash[i];
  11372. }
  11373. this._dashSum = lineDashSum;
  11374. }
  11375. return this;
  11376. },
  11377. /**
  11378. * 必须在其它绘制命令前调用
  11379. * Must be invoked before all other path drawing methods
  11380. * @return {module:zrender/core/PathProxy}
  11381. */
  11382. setLineDashOffset: function (offset) {
  11383. this._dashOffset = offset;
  11384. return this;
  11385. },
  11386. /**
  11387. *
  11388. * @return {boolean}
  11389. */
  11390. len: function () {
  11391. return this._len;
  11392. },
  11393. /**
  11394. * 直接设置 Path 数据
  11395. */
  11396. setData: function (data) {
  11397. var len$$1 = data.length;
  11398. if (!(this.data && this.data.length === len$$1) && hasTypedArray) {
  11399. this.data = new Float32Array(len$$1);
  11400. }
  11401. for (var i = 0; i < len$$1; i++) {
  11402. this.data[i] = data[i];
  11403. }
  11404. this._len = len$$1;
  11405. },
  11406. /**
  11407. * 添加子路径
  11408. * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path
  11409. */
  11410. appendPath: function (path) {
  11411. if (!(path instanceof Array)) {
  11412. path = [path];
  11413. }
  11414. var len$$1 = path.length;
  11415. var appendSize = 0;
  11416. var offset = this._len;
  11417. for (var i = 0; i < len$$1; i++) {
  11418. appendSize += path[i].len();
  11419. }
  11420. if (hasTypedArray && this.data instanceof Float32Array) {
  11421. this.data = new Float32Array(offset + appendSize);
  11422. }
  11423. for (var i = 0; i < len$$1; i++) {
  11424. var appendPathData = path[i].data;
  11425. for (var k = 0; k < appendPathData.length; k++) {
  11426. this.data[offset++] = appendPathData[k];
  11427. }
  11428. }
  11429. this._len = offset;
  11430. },
  11431. /**
  11432. * 填充 Path 数据。
  11433. * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。
  11434. */
  11435. addData: function (cmd) {
  11436. if (!this._saveData) {
  11437. return;
  11438. }
  11439. var data = this.data;
  11440. if (this._len + arguments.length > data.length) {
  11441. // 因为之前的数组已经转换成静态的 Float32Array
  11442. // 所以不够用时需要扩展一个新的动态数组
  11443. this._expandData();
  11444. data = this.data;
  11445. }
  11446. for (var i = 0; i < arguments.length; i++) {
  11447. data[this._len++] = arguments[i];
  11448. }
  11449. this._prevCmd = cmd;
  11450. },
  11451. _expandData: function () {
  11452. // Only if data is Float32Array
  11453. if (!(this.data instanceof Array)) {
  11454. var newData = [];
  11455. for (var i = 0; i < this._len; i++) {
  11456. newData[i] = this.data[i];
  11457. }
  11458. this.data = newData;
  11459. }
  11460. },
  11461. /**
  11462. * If needs js implemented dashed line
  11463. * @return {boolean}
  11464. * @private
  11465. */
  11466. _needsDash: function () {
  11467. return this._lineDash;
  11468. },
  11469. _dashedLineTo: function (x1, y1) {
  11470. var dashSum = this._dashSum;
  11471. var offset = this._dashOffset;
  11472. var lineDash = this._lineDash;
  11473. var ctx = this._ctx;
  11474. var x0 = this._xi;
  11475. var y0 = this._yi;
  11476. var dx = x1 - x0;
  11477. var dy = y1 - y0;
  11478. var dist$$1 = mathSqrt$1(dx * dx + dy * dy);
  11479. var x = x0;
  11480. var y = y0;
  11481. var dash;
  11482. var nDash = lineDash.length;
  11483. var idx;
  11484. dx /= dist$$1;
  11485. dy /= dist$$1;
  11486. if (offset < 0) {
  11487. // Convert to positive offset
  11488. offset = dashSum + offset;
  11489. }
  11490. offset %= dashSum;
  11491. x -= offset * dx;
  11492. y -= offset * dy;
  11493. while (dx > 0 && x <= x1 || dx < 0 && x >= x1 || dx === 0 && (dy > 0 && y <= y1 || dy < 0 && y >= y1)) {
  11494. idx = this._dashIdx;
  11495. dash = lineDash[idx];
  11496. x += dx * dash;
  11497. y += dy * dash;
  11498. this._dashIdx = (idx + 1) % nDash; // Skip positive offset
  11499. if (dx > 0 && x < x0 || dx < 0 && x > x0 || dy > 0 && y < y0 || dy < 0 && y > y0) {
  11500. continue;
  11501. }
  11502. ctx[idx % 2 ? 'moveTo' : 'lineTo'](dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1), dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1));
  11503. } // Offset for next lineTo
  11504. dx = x - x1;
  11505. dy = y - y1;
  11506. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11507. },
  11508. // Not accurate dashed line to
  11509. _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) {
  11510. var dashSum = this._dashSum;
  11511. var offset = this._dashOffset;
  11512. var lineDash = this._lineDash;
  11513. var ctx = this._ctx;
  11514. var x0 = this._xi;
  11515. var y0 = this._yi;
  11516. var t;
  11517. var dx;
  11518. var dy;
  11519. var cubicAt$$1 = cubicAt;
  11520. var bezierLen = 0;
  11521. var idx = this._dashIdx;
  11522. var nDash = lineDash.length;
  11523. var x;
  11524. var y;
  11525. var tmpLen = 0;
  11526. if (offset < 0) {
  11527. // Convert to positive offset
  11528. offset = dashSum + offset;
  11529. }
  11530. offset %= dashSum; // Bezier approx length
  11531. for (t = 0; t < 1; t += 0.1) {
  11532. dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1) - cubicAt$$1(x0, x1, x2, x3, t);
  11533. dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1) - cubicAt$$1(y0, y1, y2, y3, t);
  11534. bezierLen += mathSqrt$1(dx * dx + dy * dy);
  11535. } // Find idx after add offset
  11536. for (; idx < nDash; idx++) {
  11537. tmpLen += lineDash[idx];
  11538. if (tmpLen > offset) {
  11539. break;
  11540. }
  11541. }
  11542. t = (tmpLen - offset) / bezierLen;
  11543. while (t <= 1) {
  11544. x = cubicAt$$1(x0, x1, x2, x3, t);
  11545. y = cubicAt$$1(y0, y1, y2, y3, t); // Use line to approximate dashed bezier
  11546. // Bad result if dash is long
  11547. idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y);
  11548. t += lineDash[idx] / bezierLen;
  11549. idx = (idx + 1) % nDash;
  11550. } // Finish the last segment and calculate the new offset
  11551. idx % 2 !== 0 && ctx.lineTo(x3, y3);
  11552. dx = x3 - x;
  11553. dy = y3 - y;
  11554. this._dashOffset = -mathSqrt$1(dx * dx + dy * dy);
  11555. },
  11556. _dashedQuadraticTo: function (x1, y1, x2, y2) {
  11557. // Convert quadratic to cubic using degree elevation
  11558. var x3 = x2;
  11559. var y3 = y2;
  11560. x2 = (x2 + 2 * x1) / 3;
  11561. y2 = (y2 + 2 * y1) / 3;
  11562. x1 = (this._xi + 2 * x1) / 3;
  11563. y1 = (this._yi + 2 * y1) / 3;
  11564. this._dashedBezierTo(x1, y1, x2, y2, x3, y3);
  11565. },
  11566. /**
  11567. * 转成静态的 Float32Array 减少堆内存占用
  11568. * Convert dynamic array to static Float32Array
  11569. */
  11570. toStatic: function () {
  11571. var data = this.data;
  11572. if (data instanceof Array) {
  11573. data.length = this._len;
  11574. if (hasTypedArray) {
  11575. this.data = new Float32Array(data);
  11576. }
  11577. }
  11578. },
  11579. /**
  11580. * @return {module:zrender/core/BoundingRect}
  11581. */
  11582. getBoundingRect: function () {
  11583. min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE;
  11584. max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE;
  11585. var data = this.data;
  11586. var xi = 0;
  11587. var yi = 0;
  11588. var x0 = 0;
  11589. var y0 = 0;
  11590. for (var i = 0; i < data.length;) {
  11591. var cmd = data[i++];
  11592. if (i === 1) {
  11593. // 如果第一个命令是 L, C, Q
  11594. // 则 previous point 同绘制命令的第一个 point
  11595. //
  11596. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11597. xi = data[i];
  11598. yi = data[i + 1];
  11599. x0 = xi;
  11600. y0 = yi;
  11601. }
  11602. switch (cmd) {
  11603. case CMD.M:
  11604. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  11605. // 在 closePath 的时候使用
  11606. x0 = data[i++];
  11607. y0 = data[i++];
  11608. xi = x0;
  11609. yi = y0;
  11610. min2[0] = x0;
  11611. min2[1] = y0;
  11612. max2[0] = x0;
  11613. max2[1] = y0;
  11614. break;
  11615. case CMD.L:
  11616. fromLine(xi, yi, data[i], data[i + 1], min2, max2);
  11617. xi = data[i++];
  11618. yi = data[i++];
  11619. break;
  11620. case CMD.C:
  11621. fromCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2);
  11622. xi = data[i++];
  11623. yi = data[i++];
  11624. break;
  11625. case CMD.Q:
  11626. fromQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2);
  11627. xi = data[i++];
  11628. yi = data[i++];
  11629. break;
  11630. case CMD.A:
  11631. // TODO Arc 判断的开销比较大
  11632. var cx = data[i++];
  11633. var cy = data[i++];
  11634. var rx = data[i++];
  11635. var ry = data[i++];
  11636. var startAngle = data[i++];
  11637. var endAngle = data[i++] + startAngle; // TODO Arc 旋转
  11638. i += 1;
  11639. var anticlockwise = 1 - data[i++];
  11640. if (i === 1) {
  11641. // 直接使用 arc 命令
  11642. // 第一个命令起点还未定义
  11643. x0 = mathCos$1(startAngle) * rx + cx;
  11644. y0 = mathSin$1(startAngle) * ry + cy;
  11645. }
  11646. fromArc(cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2);
  11647. xi = mathCos$1(endAngle) * rx + cx;
  11648. yi = mathSin$1(endAngle) * ry + cy;
  11649. break;
  11650. case CMD.R:
  11651. x0 = xi = data[i++];
  11652. y0 = yi = data[i++];
  11653. var width = data[i++];
  11654. var height = data[i++]; // Use fromLine
  11655. fromLine(x0, y0, x0 + width, y0 + height, min2, max2);
  11656. break;
  11657. case CMD.Z:
  11658. xi = x0;
  11659. yi = y0;
  11660. break;
  11661. } // Union
  11662. min(min$1, min$1, min2);
  11663. max(max$1, max$1, max2);
  11664. } // No data
  11665. if (i === 0) {
  11666. min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0;
  11667. }
  11668. return new BoundingRect(min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1]);
  11669. },
  11670. /**
  11671. * Rebuild path from current data
  11672. * Rebuild path will not consider javascript implemented line dash.
  11673. * @param {CanvasRenderingContext2D} ctx
  11674. */
  11675. rebuildPath: function (ctx) {
  11676. var d = this.data;
  11677. var x0;
  11678. var y0;
  11679. var xi;
  11680. var yi;
  11681. var x;
  11682. var y;
  11683. var ux = this._ux;
  11684. var uy = this._uy;
  11685. var len$$1 = this._len;
  11686. for (var i = 0; i < len$$1;) {
  11687. var cmd = d[i++];
  11688. if (i === 1) {
  11689. // 如果第一个命令是 L, C, Q
  11690. // 则 previous point 同绘制命令的第一个 point
  11691. //
  11692. // 第一个命令为 Arc 的情况下会在后面特殊处理
  11693. xi = d[i];
  11694. yi = d[i + 1];
  11695. x0 = xi;
  11696. y0 = yi;
  11697. }
  11698. switch (cmd) {
  11699. case CMD.M:
  11700. x0 = xi = d[i++];
  11701. y0 = yi = d[i++];
  11702. ctx.moveTo(xi, yi);
  11703. break;
  11704. case CMD.L:
  11705. x = d[i++];
  11706. y = d[i++]; // Not draw too small seg between
  11707. if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) {
  11708. ctx.lineTo(x, y);
  11709. xi = x;
  11710. yi = y;
  11711. }
  11712. break;
  11713. case CMD.C:
  11714. ctx.bezierCurveTo(d[i++], d[i++], d[i++], d[i++], d[i++], d[i++]);
  11715. xi = d[i - 2];
  11716. yi = d[i - 1];
  11717. break;
  11718. case CMD.Q:
  11719. ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]);
  11720. xi = d[i - 2];
  11721. yi = d[i - 1];
  11722. break;
  11723. case CMD.A:
  11724. var cx = d[i++];
  11725. var cy = d[i++];
  11726. var rx = d[i++];
  11727. var ry = d[i++];
  11728. var theta = d[i++];
  11729. var dTheta = d[i++];
  11730. var psi = d[i++];
  11731. var fs = d[i++];
  11732. var r = rx > ry ? rx : ry;
  11733. var scaleX = rx > ry ? 1 : rx / ry;
  11734. var scaleY = rx > ry ? ry / rx : 1;
  11735. var isEllipse = Math.abs(rx - ry) > 1e-3;
  11736. var endAngle = theta + dTheta;
  11737. if (isEllipse) {
  11738. ctx.translate(cx, cy);
  11739. ctx.rotate(psi);
  11740. ctx.scale(scaleX, scaleY);
  11741. ctx.arc(0, 0, r, theta, endAngle, 1 - fs);
  11742. ctx.scale(1 / scaleX, 1 / scaleY);
  11743. ctx.rotate(-psi);
  11744. ctx.translate(-cx, -cy);
  11745. } else {
  11746. ctx.arc(cx, cy, r, theta, endAngle, 1 - fs);
  11747. }
  11748. if (i === 1) {
  11749. // 直接使用 arc 命令
  11750. // 第一个命令起点还未定义
  11751. x0 = mathCos$1(theta) * rx + cx;
  11752. y0 = mathSin$1(theta) * ry + cy;
  11753. }
  11754. xi = mathCos$1(endAngle) * rx + cx;
  11755. yi = mathSin$1(endAngle) * ry + cy;
  11756. break;
  11757. case CMD.R:
  11758. x0 = xi = d[i];
  11759. y0 = yi = d[i + 1];
  11760. ctx.rect(d[i++], d[i++], d[i++], d[i++]);
  11761. break;
  11762. case CMD.Z:
  11763. ctx.closePath();
  11764. xi = x0;
  11765. yi = y0;
  11766. }
  11767. }
  11768. }
  11769. };
  11770. PathProxy.CMD = CMD;
  11771. /**
  11772. * 线段包含判断
  11773. * @param {number} x0
  11774. * @param {number} y0
  11775. * @param {number} x1
  11776. * @param {number} y1
  11777. * @param {number} lineWidth
  11778. * @param {number} x
  11779. * @param {number} y
  11780. * @return {boolean}
  11781. */
  11782. function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) {
  11783. if (lineWidth === 0) {
  11784. return false;
  11785. }
  11786. var _l = lineWidth;
  11787. var _a = 0;
  11788. var _b = x0; // Quick reject
  11789. if (y > y0 + _l && y > y1 + _l || y < y0 - _l && y < y1 - _l || x > x0 + _l && x > x1 + _l || x < x0 - _l && x < x1 - _l) {
  11790. return false;
  11791. }
  11792. if (x0 !== x1) {
  11793. _a = (y0 - y1) / (x0 - x1);
  11794. _b = (x0 * y1 - x1 * y0) / (x0 - x1);
  11795. } else {
  11796. return Math.abs(x - x0) <= _l / 2;
  11797. }
  11798. var tmp = _a * x - y + _b;
  11799. var _s = tmp * tmp / (_a * _a + 1);
  11800. return _s <= _l / 2 * _l / 2;
  11801. }
  11802. /**
  11803. * 三次贝塞尔曲线描边包含判断
  11804. * @param {number} x0
  11805. * @param {number} y0
  11806. * @param {number} x1
  11807. * @param {number} y1
  11808. * @param {number} x2
  11809. * @param {number} y2
  11810. * @param {number} x3
  11811. * @param {number} y3
  11812. * @param {number} lineWidth
  11813. * @param {number} x
  11814. * @param {number} y
  11815. * @return {boolean}
  11816. */
  11817. function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) {
  11818. if (lineWidth === 0) {
  11819. return false;
  11820. }
  11821. var _l = lineWidth; // Quick reject
  11822. if (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l || y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l || x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l || x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l) {
  11823. return false;
  11824. }
  11825. var d = cubicProjectPoint(x0, y0, x1, y1, x2, y2, x3, y3, x, y, null);
  11826. return d <= _l / 2;
  11827. }
  11828. /**
  11829. * 二次贝塞尔曲线描边包含判断
  11830. * @param {number} x0
  11831. * @param {number} y0
  11832. * @param {number} x1
  11833. * @param {number} y1
  11834. * @param {number} x2
  11835. * @param {number} y2
  11836. * @param {number} lineWidth
  11837. * @param {number} x
  11838. * @param {number} y
  11839. * @return {boolean}
  11840. */
  11841. function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) {
  11842. if (lineWidth === 0) {
  11843. return false;
  11844. }
  11845. var _l = lineWidth; // Quick reject
  11846. if (y > y0 + _l && y > y1 + _l && y > y2 + _l || y < y0 - _l && y < y1 - _l && y < y2 - _l || x > x0 + _l && x > x1 + _l && x > x2 + _l || x < x0 - _l && x < x1 - _l && x < x2 - _l) {
  11847. return false;
  11848. }
  11849. var d = quadraticProjectPoint(x0, y0, x1, y1, x2, y2, x, y, null);
  11850. return d <= _l / 2;
  11851. }
  11852. var PI2$3 = Math.PI * 2;
  11853. function normalizeRadian(angle) {
  11854. angle %= PI2$3;
  11855. if (angle < 0) {
  11856. angle += PI2$3;
  11857. }
  11858. return angle;
  11859. }
  11860. var PI2$2 = Math.PI * 2;
  11861. /**
  11862. * 圆弧描边包含判断
  11863. * @param {number} cx
  11864. * @param {number} cy
  11865. * @param {number} r
  11866. * @param {number} startAngle
  11867. * @param {number} endAngle
  11868. * @param {boolean} anticlockwise
  11869. * @param {number} lineWidth
  11870. * @param {number} x
  11871. * @param {number} y
  11872. * @return {Boolean}
  11873. */
  11874. function containStroke$4(cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y) {
  11875. if (lineWidth === 0) {
  11876. return false;
  11877. }
  11878. var _l = lineWidth;
  11879. x -= cx;
  11880. y -= cy;
  11881. var d = Math.sqrt(x * x + y * y);
  11882. if (d - _l > r || d + _l < r) {
  11883. return false;
  11884. }
  11885. if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) {
  11886. // Is a circle
  11887. return true;
  11888. }
  11889. if (anticlockwise) {
  11890. var tmp = startAngle;
  11891. startAngle = normalizeRadian(endAngle);
  11892. endAngle = normalizeRadian(tmp);
  11893. } else {
  11894. startAngle = normalizeRadian(startAngle);
  11895. endAngle = normalizeRadian(endAngle);
  11896. }
  11897. if (startAngle > endAngle) {
  11898. endAngle += PI2$2;
  11899. }
  11900. var angle = Math.atan2(y, x);
  11901. if (angle < 0) {
  11902. angle += PI2$2;
  11903. }
  11904. return angle >= startAngle && angle <= endAngle || angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle;
  11905. }
  11906. function windingLine(x0, y0, x1, y1, x, y) {
  11907. if (y > y0 && y > y1 || y < y0 && y < y1) {
  11908. return 0;
  11909. } // Ignore horizontal line
  11910. if (y1 === y0) {
  11911. return 0;
  11912. }
  11913. var dir = y1 < y0 ? 1 : -1;
  11914. var t = (y - y0) / (y1 - y0); // Avoid winding error when intersection point is the connect point of two line of polygon
  11915. if (t === 1 || t === 0) {
  11916. dir = y1 < y0 ? 0.5 : -0.5;
  11917. }
  11918. var x_ = t * (x1 - x0) + x0; // If (x, y) on the line, considered as "contain".
  11919. return x_ === x ? Infinity : x_ > x ? dir : 0;
  11920. }
  11921. var CMD$1 = PathProxy.CMD;
  11922. var PI2$1 = Math.PI * 2;
  11923. var EPSILON$2 = 1e-4;
  11924. function isAroundEqual(a, b) {
  11925. return Math.abs(a - b) < EPSILON$2;
  11926. } // 临时数组
  11927. var roots = [-1, -1, -1];
  11928. var extrema = [-1, -1];
  11929. function swapExtrema() {
  11930. var tmp = extrema[0];
  11931. extrema[0] = extrema[1];
  11932. extrema[1] = tmp;
  11933. }
  11934. function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) {
  11935. // Quick reject
  11936. if (y > y0 && y > y1 && y > y2 && y > y3 || y < y0 && y < y1 && y < y2 && y < y3) {
  11937. return 0;
  11938. }
  11939. var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots);
  11940. if (nRoots === 0) {
  11941. return 0;
  11942. } else {
  11943. var w = 0;
  11944. var nExtrema = -1;
  11945. var y0_;
  11946. var y1_;
  11947. for (var i = 0; i < nRoots; i++) {
  11948. var t = roots[i]; // Avoid winding error when intersection point is the connect point of two line of polygon
  11949. var unit = t === 0 || t === 1 ? 0.5 : 1;
  11950. var x_ = cubicAt(x0, x1, x2, x3, t);
  11951. if (x_ < x) {
  11952. // Quick reject
  11953. continue;
  11954. }
  11955. if (nExtrema < 0) {
  11956. nExtrema = cubicExtrema(y0, y1, y2, y3, extrema);
  11957. if (extrema[1] < extrema[0] && nExtrema > 1) {
  11958. swapExtrema();
  11959. }
  11960. y0_ = cubicAt(y0, y1, y2, y3, extrema[0]);
  11961. if (nExtrema > 1) {
  11962. y1_ = cubicAt(y0, y1, y2, y3, extrema[1]);
  11963. }
  11964. }
  11965. if (nExtrema === 2) {
  11966. // 分成三段单调函数
  11967. if (t < extrema[0]) {
  11968. w += y0_ < y0 ? unit : -unit;
  11969. } else if (t < extrema[1]) {
  11970. w += y1_ < y0_ ? unit : -unit;
  11971. } else {
  11972. w += y3 < y1_ ? unit : -unit;
  11973. }
  11974. } else {
  11975. // 分成两段单调函数
  11976. if (t < extrema[0]) {
  11977. w += y0_ < y0 ? unit : -unit;
  11978. } else {
  11979. w += y3 < y0_ ? unit : -unit;
  11980. }
  11981. }
  11982. }
  11983. return w;
  11984. }
  11985. }
  11986. function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) {
  11987. // Quick reject
  11988. if (y > y0 && y > y1 && y > y2 || y < y0 && y < y1 && y < y2) {
  11989. return 0;
  11990. }
  11991. var nRoots = quadraticRootAt(y0, y1, y2, y, roots);
  11992. if (nRoots === 0) {
  11993. return 0;
  11994. } else {
  11995. var t = quadraticExtremum(y0, y1, y2);
  11996. if (t >= 0 && t <= 1) {
  11997. var w = 0;
  11998. var y_ = quadraticAt(y0, y1, y2, t);
  11999. for (var i = 0; i < nRoots; i++) {
  12000. // Remove one endpoint.
  12001. var unit = roots[i] === 0 || roots[i] === 1 ? 0.5 : 1;
  12002. var x_ = quadraticAt(x0, x1, x2, roots[i]);
  12003. if (x_ < x) {
  12004. // Quick reject
  12005. continue;
  12006. }
  12007. if (roots[i] < t) {
  12008. w += y_ < y0 ? unit : -unit;
  12009. } else {
  12010. w += y2 < y_ ? unit : -unit;
  12011. }
  12012. }
  12013. return w;
  12014. } else {
  12015. // Remove one endpoint.
  12016. var unit = roots[0] === 0 || roots[0] === 1 ? 0.5 : 1;
  12017. var x_ = quadraticAt(x0, x1, x2, roots[0]);
  12018. if (x_ < x) {
  12019. // Quick reject
  12020. return 0;
  12021. }
  12022. return y2 < y0 ? unit : -unit;
  12023. }
  12024. }
  12025. } // TODO
  12026. // Arc 旋转
  12027. function windingArc(cx, cy, r, startAngle, endAngle, anticlockwise, x, y) {
  12028. y -= cy;
  12029. if (y > r || y < -r) {
  12030. return 0;
  12031. }
  12032. var tmp = Math.sqrt(r * r - y * y);
  12033. roots[0] = -tmp;
  12034. roots[1] = tmp;
  12035. var diff = Math.abs(startAngle - endAngle);
  12036. if (diff < 1e-4) {
  12037. return 0;
  12038. }
  12039. if (diff % PI2$1 < 1e-4) {
  12040. // Is a circle
  12041. startAngle = 0;
  12042. endAngle = PI2$1;
  12043. var dir = anticlockwise ? 1 : -1;
  12044. if (x >= roots[0] + cx && x <= roots[1] + cx) {
  12045. return dir;
  12046. } else {
  12047. return 0;
  12048. }
  12049. }
  12050. if (anticlockwise) {
  12051. var tmp = startAngle;
  12052. startAngle = normalizeRadian(endAngle);
  12053. endAngle = normalizeRadian(tmp);
  12054. } else {
  12055. startAngle = normalizeRadian(startAngle);
  12056. endAngle = normalizeRadian(endAngle);
  12057. }
  12058. if (startAngle > endAngle) {
  12059. endAngle += PI2$1;
  12060. }
  12061. var w = 0;
  12062. for (var i = 0; i < 2; i++) {
  12063. var x_ = roots[i];
  12064. if (x_ + cx > x) {
  12065. var angle = Math.atan2(y, x_);
  12066. var dir = anticlockwise ? 1 : -1;
  12067. if (angle < 0) {
  12068. angle = PI2$1 + angle;
  12069. }
  12070. if (angle >= startAngle && angle <= endAngle || angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle) {
  12071. if (angle > Math.PI / 2 && angle < Math.PI * 1.5) {
  12072. dir = -dir;
  12073. }
  12074. w += dir;
  12075. }
  12076. }
  12077. }
  12078. return w;
  12079. }
  12080. function containPath(data, lineWidth, isStroke, x, y) {
  12081. var w = 0;
  12082. var xi = 0;
  12083. var yi = 0;
  12084. var x0 = 0;
  12085. var y0 = 0;
  12086. for (var i = 0; i < data.length;) {
  12087. var cmd = data[i++]; // Begin a new subpath
  12088. if (cmd === CMD$1.M && i > 1) {
  12089. // Close previous subpath
  12090. if (!isStroke) {
  12091. w += windingLine(xi, yi, x0, y0, x, y);
  12092. } // 如果被任何一个 subpath 包含
  12093. // if (w !== 0) {
  12094. // return true;
  12095. // }
  12096. }
  12097. if (i === 1) {
  12098. // 如果第一个命令是 L, C, Q
  12099. // 则 previous point 同绘制命令的第一个 point
  12100. //
  12101. // 第一个命令为 Arc 的情况下会在后面特殊处理
  12102. xi = data[i];
  12103. yi = data[i + 1];
  12104. x0 = xi;
  12105. y0 = yi;
  12106. }
  12107. switch (cmd) {
  12108. case CMD$1.M:
  12109. // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点
  12110. // 在 closePath 的时候使用
  12111. x0 = data[i++];
  12112. y0 = data[i++];
  12113. xi = x0;
  12114. yi = y0;
  12115. break;
  12116. case CMD$1.L:
  12117. if (isStroke) {
  12118. if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) {
  12119. return true;
  12120. }
  12121. } else {
  12122. // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN
  12123. w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0;
  12124. }
  12125. xi = data[i++];
  12126. yi = data[i++];
  12127. break;
  12128. case CMD$1.C:
  12129. if (isStroke) {
  12130. if (containStroke$2(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  12131. return true;
  12132. }
  12133. } else {
  12134. w += windingCubic(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  12135. }
  12136. xi = data[i++];
  12137. yi = data[i++];
  12138. break;
  12139. case CMD$1.Q:
  12140. if (isStroke) {
  12141. if (containStroke$3(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y)) {
  12142. return true;
  12143. }
  12144. } else {
  12145. w += windingQuadratic(xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y) || 0;
  12146. }
  12147. xi = data[i++];
  12148. yi = data[i++];
  12149. break;
  12150. case CMD$1.A:
  12151. // TODO Arc 判断的开销比较大
  12152. var cx = data[i++];
  12153. var cy = data[i++];
  12154. var rx = data[i++];
  12155. var ry = data[i++];
  12156. var theta = data[i++];
  12157. var dTheta = data[i++]; // TODO Arc 旋转
  12158. i += 1;
  12159. var anticlockwise = 1 - data[i++];
  12160. var x1 = Math.cos(theta) * rx + cx;
  12161. var y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令
  12162. if (i > 1) {
  12163. w += windingLine(xi, yi, x1, y1, x, y);
  12164. } else {
  12165. // 第一个命令起点还未定义
  12166. x0 = x1;
  12167. y0 = y1;
  12168. } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放
  12169. var _x = (x - cx) * ry / rx + cx;
  12170. if (isStroke) {
  12171. if (containStroke$4(cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y)) {
  12172. return true;
  12173. }
  12174. } else {
  12175. w += windingArc(cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y);
  12176. }
  12177. xi = Math.cos(theta + dTheta) * rx + cx;
  12178. yi = Math.sin(theta + dTheta) * ry + cy;
  12179. break;
  12180. case CMD$1.R:
  12181. x0 = xi = data[i++];
  12182. y0 = yi = data[i++];
  12183. var width = data[i++];
  12184. var height = data[i++];
  12185. var x1 = x0 + width;
  12186. var y1 = y0 + height;
  12187. if (isStroke) {
  12188. if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y) || containStroke$1(x1, y0, x1, y1, lineWidth, x, y) || containStroke$1(x1, y1, x0, y1, lineWidth, x, y) || containStroke$1(x0, y1, x0, y0, lineWidth, x, y)) {
  12189. return true;
  12190. }
  12191. } else {
  12192. // FIXME Clockwise ?
  12193. w += windingLine(x1, y0, x1, y1, x, y);
  12194. w += windingLine(x0, y1, x0, y0, x, y);
  12195. }
  12196. break;
  12197. case CMD$1.Z:
  12198. if (isStroke) {
  12199. if (containStroke$1(xi, yi, x0, y0, lineWidth, x, y)) {
  12200. return true;
  12201. }
  12202. } else {
  12203. // Close a subpath
  12204. w += windingLine(xi, yi, x0, y0, x, y); // 如果被任何一个 subpath 包含
  12205. // FIXME subpaths may overlap
  12206. // if (w !== 0) {
  12207. // return true;
  12208. // }
  12209. }
  12210. xi = x0;
  12211. yi = y0;
  12212. break;
  12213. }
  12214. }
  12215. if (!isStroke && !isAroundEqual(yi, y0)) {
  12216. w += windingLine(xi, yi, x0, y0, x, y) || 0;
  12217. }
  12218. return w !== 0;
  12219. }
  12220. function contain(pathData, x, y) {
  12221. return containPath(pathData, 0, false, x, y);
  12222. }
  12223. function containStroke(pathData, lineWidth, x, y) {
  12224. return containPath(pathData, lineWidth, true, x, y);
  12225. }
  12226. var getCanvasPattern = Pattern.prototype.getCanvasPattern;
  12227. var abs = Math.abs;
  12228. var pathProxyForDraw = new PathProxy(true);
  12229. /**
  12230. * @alias module:zrender/graphic/Path
  12231. * @extends module:zrender/graphic/Displayable
  12232. * @constructor
  12233. * @param {Object} opts
  12234. */
  12235. function Path(opts) {
  12236. Displayable.call(this, opts);
  12237. /**
  12238. * @type {module:zrender/core/PathProxy}
  12239. * @readOnly
  12240. */
  12241. this.path = null;
  12242. }
  12243. Path.prototype = {
  12244. constructor: Path,
  12245. type: 'path',
  12246. __dirtyPath: true,
  12247. strokeContainThreshold: 5,
  12248. // This item default to be false. But in map series in echarts,
  12249. // in order to improve performance, it should be set to true,
  12250. // so the shorty segment won't draw.
  12251. segmentIgnoreThreshold: 0,
  12252. /**
  12253. * See `module:zrender/src/graphic/helper/subPixelOptimize`.
  12254. * @type {boolean}
  12255. */
  12256. subPixelOptimize: false,
  12257. brush: function (ctx, prevEl) {
  12258. var style = this.style;
  12259. var path = this.path || pathProxyForDraw;
  12260. var hasStroke = style.hasStroke();
  12261. var hasFill = style.hasFill();
  12262. var fill = style.fill;
  12263. var stroke = style.stroke;
  12264. var hasFillGradient = hasFill && !!fill.colorStops;
  12265. var hasStrokeGradient = hasStroke && !!stroke.colorStops;
  12266. var hasFillPattern = hasFill && !!fill.image;
  12267. var hasStrokePattern = hasStroke && !!stroke.image;
  12268. style.bind(ctx, this, prevEl);
  12269. this.setTransform(ctx);
  12270. if (this.__dirty) {
  12271. var rect; // Update gradient because bounding rect may changed
  12272. if (hasFillGradient) {
  12273. rect = rect || this.getBoundingRect();
  12274. this._fillGradient = style.getGradient(ctx, fill, rect);
  12275. }
  12276. if (hasStrokeGradient) {
  12277. rect = rect || this.getBoundingRect();
  12278. this._strokeGradient = style.getGradient(ctx, stroke, rect);
  12279. }
  12280. } // Use the gradient or pattern
  12281. if (hasFillGradient) {
  12282. // PENDING If may have affect the state
  12283. ctx.fillStyle = this._fillGradient;
  12284. } else if (hasFillPattern) {
  12285. ctx.fillStyle = getCanvasPattern.call(fill, ctx);
  12286. }
  12287. if (hasStrokeGradient) {
  12288. ctx.strokeStyle = this._strokeGradient;
  12289. } else if (hasStrokePattern) {
  12290. ctx.strokeStyle = getCanvasPattern.call(stroke, ctx);
  12291. }
  12292. var lineDash = style.lineDash;
  12293. var lineDashOffset = style.lineDashOffset;
  12294. var ctxLineDash = !!ctx.setLineDash; // Update path sx, sy
  12295. var scale = this.getGlobalScale();
  12296. path.setScale(scale[0], scale[1], this.segmentIgnoreThreshold); // Proxy context
  12297. // Rebuild path in following 2 cases
  12298. // 1. Path is dirty
  12299. // 2. Path needs javascript implemented lineDash stroking.
  12300. // In this case, lineDash information will not be saved in PathProxy
  12301. if (this.__dirtyPath || lineDash && !ctxLineDash && hasStroke) {
  12302. path.beginPath(ctx); // Setting line dash before build path
  12303. if (lineDash && !ctxLineDash) {
  12304. path.setLineDash(lineDash);
  12305. path.setLineDashOffset(lineDashOffset);
  12306. }
  12307. this.buildPath(path, this.shape, false); // Clear path dirty flag
  12308. if (this.path) {
  12309. this.__dirtyPath = false;
  12310. }
  12311. } else {
  12312. // Replay path building
  12313. ctx.beginPath();
  12314. this.path.rebuildPath(ctx);
  12315. }
  12316. if (hasFill) {
  12317. if (style.fillOpacity != null) {
  12318. var originalGlobalAlpha = ctx.globalAlpha;
  12319. ctx.globalAlpha = style.fillOpacity * style.opacity;
  12320. path.fill(ctx);
  12321. ctx.globalAlpha = originalGlobalAlpha;
  12322. } else {
  12323. path.fill(ctx);
  12324. }
  12325. }
  12326. if (lineDash && ctxLineDash) {
  12327. ctx.setLineDash(lineDash);
  12328. ctx.lineDashOffset = lineDashOffset;
  12329. }
  12330. if (hasStroke) {
  12331. if (style.strokeOpacity != null) {
  12332. var originalGlobalAlpha = ctx.globalAlpha;
  12333. ctx.globalAlpha = style.strokeOpacity * style.opacity;
  12334. path.stroke(ctx);
  12335. ctx.globalAlpha = originalGlobalAlpha;
  12336. } else {
  12337. path.stroke(ctx);
  12338. }
  12339. }
  12340. if (lineDash && ctxLineDash) {
  12341. // PENDING
  12342. // Remove lineDash
  12343. ctx.setLineDash([]);
  12344. } // Draw rect text
  12345. if (style.text != null) {
  12346. // Only restore transform when needs draw text.
  12347. this.restoreTransform(ctx);
  12348. this.drawRectText(ctx, this.getBoundingRect());
  12349. }
  12350. },
  12351. // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath
  12352. // Like in circle
  12353. buildPath: function (ctx, shapeCfg, inBundle) {},
  12354. createPathProxy: function () {
  12355. this.path = new PathProxy();
  12356. },
  12357. getBoundingRect: function () {
  12358. var rect = this._rect;
  12359. var style = this.style;
  12360. var needsUpdateRect = !rect;
  12361. if (needsUpdateRect) {
  12362. var path = this.path;
  12363. if (!path) {
  12364. // Create path on demand.
  12365. path = this.path = new PathProxy();
  12366. }
  12367. if (this.__dirtyPath) {
  12368. path.beginPath();
  12369. this.buildPath(path, this.shape, false);
  12370. }
  12371. rect = path.getBoundingRect();
  12372. }
  12373. this._rect = rect;
  12374. if (style.hasStroke()) {
  12375. // Needs update rect with stroke lineWidth when
  12376. // 1. Element changes scale or lineWidth
  12377. // 2. Shape is changed
  12378. var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone());
  12379. if (this.__dirty || needsUpdateRect) {
  12380. rectWithStroke.copy(rect); // FIXME Must after updateTransform
  12381. var w = style.lineWidth; // PENDING, Min line width is needed when line is horizontal or vertical
  12382. var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Only add extra hover lineWidth when there are no fill
  12383. if (!style.hasFill()) {
  12384. w = Math.max(w, this.strokeContainThreshold || 4);
  12385. } // Consider line width
  12386. // Line scale can't be 0;
  12387. if (lineScale > 1e-10) {
  12388. rectWithStroke.width += w / lineScale;
  12389. rectWithStroke.height += w / lineScale;
  12390. rectWithStroke.x -= w / lineScale / 2;
  12391. rectWithStroke.y -= w / lineScale / 2;
  12392. }
  12393. } // Return rect with stroke
  12394. return rectWithStroke;
  12395. }
  12396. return rect;
  12397. },
  12398. contain: function (x, y) {
  12399. var localPos = this.transformCoordToLocal(x, y);
  12400. var rect = this.getBoundingRect();
  12401. var style = this.style;
  12402. x = localPos[0];
  12403. y = localPos[1];
  12404. if (rect.contain(x, y)) {
  12405. var pathData = this.path.data;
  12406. if (style.hasStroke()) {
  12407. var lineWidth = style.lineWidth;
  12408. var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Line scale can't be 0;
  12409. if (lineScale > 1e-10) {
  12410. // Only add extra hover lineWidth when there are no fill
  12411. if (!style.hasFill()) {
  12412. lineWidth = Math.max(lineWidth, this.strokeContainThreshold);
  12413. }
  12414. if (containStroke(pathData, lineWidth / lineScale, x, y)) {
  12415. return true;
  12416. }
  12417. }
  12418. }
  12419. if (style.hasFill()) {
  12420. return contain(pathData, x, y);
  12421. }
  12422. }
  12423. return false;
  12424. },
  12425. /**
  12426. * @param {boolean} dirtyPath
  12427. */
  12428. dirty: function (dirtyPath) {
  12429. if (dirtyPath == null) {
  12430. dirtyPath = true;
  12431. } // Only mark dirty, not mark clean
  12432. if (dirtyPath) {
  12433. this.__dirtyPath = dirtyPath;
  12434. this._rect = null;
  12435. }
  12436. this.__dirty = this.__dirtyText = true;
  12437. this.__zr && this.__zr.refresh(); // Used as a clipping path
  12438. if (this.__clipTarget) {
  12439. this.__clipTarget.dirty();
  12440. }
  12441. },
  12442. /**
  12443. * Alias for animate('shape')
  12444. * @param {boolean} loop
  12445. */
  12446. animateShape: function (loop) {
  12447. return this.animate('shape', loop);
  12448. },
  12449. // Overwrite attrKV
  12450. attrKV: function (key, value) {
  12451. // FIXME
  12452. if (key === 'shape') {
  12453. this.setShape(value);
  12454. this.__dirtyPath = true;
  12455. this._rect = null;
  12456. } else {
  12457. Displayable.prototype.attrKV.call(this, key, value);
  12458. }
  12459. },
  12460. /**
  12461. * @param {Object|string} key
  12462. * @param {*} value
  12463. */
  12464. setShape: function (key, value) {
  12465. var shape = this.shape; // Path from string may not have shape
  12466. if (shape) {
  12467. if (isObject$1(key)) {
  12468. for (var name in key) {
  12469. if (key.hasOwnProperty(name)) {
  12470. shape[name] = key[name];
  12471. }
  12472. }
  12473. } else {
  12474. shape[key] = value;
  12475. }
  12476. this.dirty(true);
  12477. }
  12478. return this;
  12479. },
  12480. getLineScale: function () {
  12481. var m = this.transform; // Get the line scale.
  12482. // Determinant of `m` means how much the area is enlarged by the
  12483. // transformation. So its square root can be used as a scale factor
  12484. // for width.
  12485. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10 ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1])) : 1;
  12486. }
  12487. };
  12488. /**
  12489. * 扩展一个 Path element, 比如星形,圆等。
  12490. * Extend a path element
  12491. * @param {Object} props
  12492. * @param {string} props.type Path type
  12493. * @param {Function} props.init Initialize
  12494. * @param {Function} props.buildPath Overwrite buildPath method
  12495. * @param {Object} [props.style] Extended default style config
  12496. * @param {Object} [props.shape] Extended default shape config
  12497. */
  12498. Path.extend = function (defaults$$1) {
  12499. var Sub = function (opts) {
  12500. Path.call(this, opts);
  12501. if (defaults$$1.style) {
  12502. // Extend default style
  12503. this.style.extendFrom(defaults$$1.style, false);
  12504. } // Extend default shape
  12505. var defaultShape = defaults$$1.shape;
  12506. if (defaultShape) {
  12507. this.shape = this.shape || {};
  12508. var thisShape = this.shape;
  12509. for (var name in defaultShape) {
  12510. if (!thisShape.hasOwnProperty(name) && defaultShape.hasOwnProperty(name)) {
  12511. thisShape[name] = defaultShape[name];
  12512. }
  12513. }
  12514. }
  12515. defaults$$1.init && defaults$$1.init.call(this, opts);
  12516. };
  12517. inherits(Sub, Path); // FIXME 不能 extend position, rotation 等引用对象
  12518. for (var name in defaults$$1) {
  12519. // Extending prototype values and methods
  12520. if (name !== 'style' && name !== 'shape') {
  12521. Sub.prototype[name] = defaults$$1[name];
  12522. }
  12523. }
  12524. return Sub;
  12525. };
  12526. inherits(Path, Displayable);
  12527. var CMD$2 = PathProxy.CMD;
  12528. var points = [[], [], []];
  12529. var mathSqrt$3 = Math.sqrt;
  12530. var mathAtan2 = Math.atan2;
  12531. var transformPath = function (path, m) {
  12532. var data = path.data;
  12533. var cmd;
  12534. var nPoint;
  12535. var i;
  12536. var j;
  12537. var k;
  12538. var p;
  12539. var M = CMD$2.M;
  12540. var C = CMD$2.C;
  12541. var L = CMD$2.L;
  12542. var R = CMD$2.R;
  12543. var A = CMD$2.A;
  12544. var Q = CMD$2.Q;
  12545. for (i = 0, j = 0; i < data.length;) {
  12546. cmd = data[i++];
  12547. j = i;
  12548. nPoint = 0;
  12549. switch (cmd) {
  12550. case M:
  12551. nPoint = 1;
  12552. break;
  12553. case L:
  12554. nPoint = 1;
  12555. break;
  12556. case C:
  12557. nPoint = 3;
  12558. break;
  12559. case Q:
  12560. nPoint = 2;
  12561. break;
  12562. case A:
  12563. var x = m[4];
  12564. var y = m[5];
  12565. var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]);
  12566. var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]);
  12567. var angle = mathAtan2(-m[1] / sy, m[0] / sx); // cx
  12568. data[i] *= sx;
  12569. data[i++] += x; // cy
  12570. data[i] *= sy;
  12571. data[i++] += y; // Scale rx and ry
  12572. // FIXME Assume psi is 0 here
  12573. data[i++] *= sx;
  12574. data[i++] *= sy; // Start angle
  12575. data[i++] += angle; // end angle
  12576. data[i++] += angle; // FIXME psi
  12577. i += 2;
  12578. j = i;
  12579. break;
  12580. case R:
  12581. // x0, y0
  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]; // x1, y1
  12587. p[0] += data[i++];
  12588. p[1] += data[i++];
  12589. applyTransform(p, p, m);
  12590. data[j++] = p[0];
  12591. data[j++] = p[1];
  12592. }
  12593. for (k = 0; k < nPoint; k++) {
  12594. var p = points[k];
  12595. p[0] = data[i++];
  12596. p[1] = data[i++];
  12597. applyTransform(p, p, m); // Write back
  12598. data[j++] = p[0];
  12599. data[j++] = p[1];
  12600. }
  12601. }
  12602. };
  12603. // var cc = [
  12604. // 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z',
  12605. // 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A'
  12606. // ];
  12607. var mathSqrt = Math.sqrt;
  12608. var mathSin = Math.sin;
  12609. var mathCos = Math.cos;
  12610. var PI = Math.PI;
  12611. var vMag = function (v) {
  12612. return Math.sqrt(v[0] * v[0] + v[1] * v[1]);
  12613. };
  12614. var vRatio = function (u, v) {
  12615. return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v));
  12616. };
  12617. var vAngle = function (u, v) {
  12618. return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v));
  12619. };
  12620. function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) {
  12621. var psi = psiDeg * (PI / 180.0);
  12622. var xp = mathCos(psi) * (x1 - x2) / 2.0 + mathSin(psi) * (y1 - y2) / 2.0;
  12623. var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0 + 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) * mathSqrt((rx * rx * (ry * ry) - rx * rx * (yp * yp) - ry * ry * (xp * xp)) / (rx * rx * (yp * yp) + ry * ry * (xp * xp))) || 0;
  12630. var cxp = f * rx * yp / ry;
  12631. var cyp = f * -ry * xp / rx;
  12632. var cx = (x1 + x2) / 2.0 + mathCos(psi) * cxp - mathSin(psi) * cyp;
  12633. var cy = (y1 + y2) / 2.0 + mathSin(psi) * cxp + mathCos(psi) * cyp;
  12634. var theta = vAngle([1, 0], [(xp - cxp) / rx, (yp - cyp) / ry]);
  12635. var u = [(xp - cxp) / rx, (yp - cyp) / ry];
  12636. var v = [(-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry];
  12637. var dTheta = vAngle(u, v);
  12638. if (vRatio(u, v) <= -1) {
  12639. dTheta = PI;
  12640. }
  12641. if (vRatio(u, v) >= 1) {
  12642. dTheta = 0;
  12643. }
  12644. if (fs === 0 && dTheta > 0) {
  12645. dTheta = dTheta - 2 * PI;
  12646. }
  12647. if (fs === 1 && dTheta < 0) {
  12648. dTheta = dTheta + 2 * PI;
  12649. }
  12650. path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs);
  12651. }
  12652. var commandReg = /([mlvhzcqtsa])([^mlvhzcqtsa]*)/ig; // Consider case:
  12653. // (1) delimiter can be comma or space, where continuous commas
  12654. // or spaces should be seen as one comma.
  12655. // (2) value can be like:
  12656. // '2e-4', 'l.5.9' (ignore 0), 'M-10-10', 'l-2.43e-1,34.9983',
  12657. // 'l-.5E1,54', '121-23-44-11' (no delimiter)
  12658. var numberReg = /-?([0-9]*\.)?[0-9]+([eE]-?[0-9]+)?/g; // var valueSplitReg = /[\s,]+/;
  12659. function createPathProxyFromString(data) {
  12660. if (!data) {
  12661. return new PathProxy();
  12662. } // var data = data.replace(/-/g, ' -')
  12663. // .replace(/ /g, ' ')
  12664. // .replace(/ /g, ',')
  12665. // .replace(/,,/g, ',');
  12666. // var n;
  12667. // create pipes so that we can split the data
  12668. // for (n = 0; n < cc.length; n++) {
  12669. // cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]);
  12670. // }
  12671. // data = data.replace(/-/g, ',-');
  12672. // create array
  12673. // var arr = cs.split('|');
  12674. // init context point
  12675. var cpx = 0;
  12676. var cpy = 0;
  12677. var subpathX = cpx;
  12678. var subpathY = cpy;
  12679. var prevCmd;
  12680. var path = new PathProxy();
  12681. var CMD = PathProxy.CMD; // commandReg.lastIndex = 0;
  12682. // var cmdResult;
  12683. // while ((cmdResult = commandReg.exec(data)) != null) {
  12684. // var cmdStr = cmdResult[1];
  12685. // var cmdContent = cmdResult[2];
  12686. var cmdList = data.match(commandReg);
  12687. for (var l = 0; l < cmdList.length; l++) {
  12688. var cmdText = cmdList[l];
  12689. var cmdStr = cmdText.charAt(0);
  12690. var cmd; // String#split is faster a little bit than String#replace or RegExp#exec.
  12691. // var p = cmdContent.split(valueSplitReg);
  12692. // var pLen = 0;
  12693. // for (var i = 0; i < p.length; i++) {
  12694. // // '' and other invalid str => NaN
  12695. // var val = parseFloat(p[i]);
  12696. // !isNaN(val) && (p[pLen++] = val);
  12697. // }
  12698. var p = cmdText.match(numberReg) || [];
  12699. var pLen = p.length;
  12700. for (var i = 0; i < pLen; i++) {
  12701. p[i] = parseFloat(p[i]);
  12702. }
  12703. var off = 0;
  12704. while (off < pLen) {
  12705. var ctlPtx;
  12706. var ctlPty;
  12707. var rx;
  12708. var ry;
  12709. var psi;
  12710. var fa;
  12711. var fs;
  12712. var x1 = cpx;
  12713. var y1 = cpy; // convert l, H, h, V, and v to L
  12714. switch (cmdStr) {
  12715. case 'l':
  12716. cpx += p[off++];
  12717. cpy += p[off++];
  12718. cmd = CMD.L;
  12719. path.addData(cmd, cpx, cpy);
  12720. break;
  12721. case 'L':
  12722. cpx = p[off++];
  12723. cpy = p[off++];
  12724. cmd = CMD.L;
  12725. path.addData(cmd, cpx, cpy);
  12726. break;
  12727. case 'm':
  12728. cpx += p[off++];
  12729. cpy += p[off++];
  12730. cmd = CMD.M;
  12731. path.addData(cmd, cpx, cpy);
  12732. subpathX = cpx;
  12733. subpathY = cpy;
  12734. cmdStr = 'l';
  12735. break;
  12736. case 'M':
  12737. cpx = p[off++];
  12738. cpy = p[off++];
  12739. cmd = CMD.M;
  12740. path.addData(cmd, cpx, cpy);
  12741. subpathX = cpx;
  12742. subpathY = cpy;
  12743. cmdStr = 'L';
  12744. break;
  12745. case 'h':
  12746. cpx += p[off++];
  12747. cmd = CMD.L;
  12748. path.addData(cmd, cpx, cpy);
  12749. break;
  12750. case 'H':
  12751. cpx = p[off++];
  12752. cmd = CMD.L;
  12753. path.addData(cmd, cpx, cpy);
  12754. break;
  12755. case 'v':
  12756. cpy += p[off++];
  12757. cmd = CMD.L;
  12758. path.addData(cmd, cpx, cpy);
  12759. break;
  12760. case 'V':
  12761. cpy = p[off++];
  12762. cmd = CMD.L;
  12763. path.addData(cmd, cpx, cpy);
  12764. break;
  12765. case 'C':
  12766. cmd = CMD.C;
  12767. path.addData(cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++]);
  12768. cpx = p[off - 2];
  12769. cpy = p[off - 1];
  12770. break;
  12771. case 'c':
  12772. cmd = CMD.C;
  12773. path.addData(cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy);
  12774. cpx += p[off - 2];
  12775. cpy += p[off - 1];
  12776. break;
  12777. case 'S':
  12778. ctlPtx = cpx;
  12779. ctlPty = cpy;
  12780. var len = path.len();
  12781. var pathData = path.data;
  12782. if (prevCmd === CMD.C) {
  12783. ctlPtx += cpx - pathData[len - 4];
  12784. ctlPty += cpy - pathData[len - 3];
  12785. }
  12786. cmd = CMD.C;
  12787. x1 = p[off++];
  12788. y1 = p[off++];
  12789. cpx = p[off++];
  12790. cpy = p[off++];
  12791. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12792. break;
  12793. case 's':
  12794. ctlPtx = cpx;
  12795. ctlPty = cpy;
  12796. var len = path.len();
  12797. var pathData = path.data;
  12798. if (prevCmd === CMD.C) {
  12799. ctlPtx += cpx - pathData[len - 4];
  12800. ctlPty += cpy - pathData[len - 3];
  12801. }
  12802. cmd = CMD.C;
  12803. x1 = cpx + p[off++];
  12804. y1 = cpy + p[off++];
  12805. cpx += p[off++];
  12806. cpy += p[off++];
  12807. path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy);
  12808. break;
  12809. case 'Q':
  12810. x1 = p[off++];
  12811. y1 = p[off++];
  12812. cpx = p[off++];
  12813. cpy = p[off++];
  12814. cmd = CMD.Q;
  12815. path.addData(cmd, x1, y1, cpx, cpy);
  12816. break;
  12817. case 'q':
  12818. x1 = p[off++] + cpx;
  12819. y1 = p[off++] + cpy;
  12820. cpx += p[off++];
  12821. cpy += p[off++];
  12822. cmd = CMD.Q;
  12823. path.addData(cmd, x1, y1, cpx, cpy);
  12824. break;
  12825. case 'T':
  12826. ctlPtx = cpx;
  12827. ctlPty = cpy;
  12828. var len = path.len();
  12829. var pathData = path.data;
  12830. if (prevCmd === CMD.Q) {
  12831. ctlPtx += cpx - pathData[len - 4];
  12832. ctlPty += cpy - pathData[len - 3];
  12833. }
  12834. cpx = p[off++];
  12835. cpy = p[off++];
  12836. cmd = CMD.Q;
  12837. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12838. break;
  12839. case 't':
  12840. ctlPtx = cpx;
  12841. ctlPty = cpy;
  12842. var len = path.len();
  12843. var pathData = path.data;
  12844. if (prevCmd === CMD.Q) {
  12845. ctlPtx += cpx - pathData[len - 4];
  12846. ctlPty += cpy - pathData[len - 3];
  12847. }
  12848. cpx += p[off++];
  12849. cpy += p[off++];
  12850. cmd = CMD.Q;
  12851. path.addData(cmd, ctlPtx, ctlPty, cpx, cpy);
  12852. break;
  12853. case 'A':
  12854. rx = p[off++];
  12855. ry = p[off++];
  12856. psi = p[off++];
  12857. fa = p[off++];
  12858. fs = p[off++];
  12859. x1 = cpx, y1 = cpy;
  12860. cpx = p[off++];
  12861. cpy = p[off++];
  12862. cmd = CMD.A;
  12863. processArc(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  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(x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path);
  12876. break;
  12877. }
  12878. }
  12879. if (cmdStr === 'z' || cmdStr === 'Z') {
  12880. cmd = CMD.Z;
  12881. path.addData(cmd); // z may be in the middle of the path.
  12882. cpx = subpathX;
  12883. cpy = subpathY;
  12884. }
  12885. prevCmd = cmd;
  12886. }
  12887. path.toStatic();
  12888. return path;
  12889. } // TODO Optimize double memory cost problem
  12890. function createPathOptions(str, opts) {
  12891. var pathProxy = createPathProxyFromString(str);
  12892. opts = opts || {};
  12893. opts.buildPath = function (path) {
  12894. if (path.setData) {
  12895. path.setData(pathProxy.data); // Svg and vml renderer don't have context
  12896. var ctx = path.getContext();
  12897. if (ctx) {
  12898. path.rebuildPath(ctx);
  12899. }
  12900. } else {
  12901. var ctx = path;
  12902. pathProxy.rebuildPath(ctx);
  12903. }
  12904. };
  12905. opts.applyTransform = function (m) {
  12906. transformPath(pathProxy, m);
  12907. this.dirty(true);
  12908. };
  12909. return opts;
  12910. }
  12911. /**
  12912. * Create a Path object from path string data
  12913. * http://www.w3.org/TR/SVG/paths.html#PathData
  12914. * @param {Object} opts Other options
  12915. */
  12916. function createFromString(str, opts) {
  12917. return new Path(createPathOptions(str, opts));
  12918. }
  12919. /**
  12920. * Create a Path class from path string data
  12921. * @param {string} str
  12922. * @param {Object} opts Other options
  12923. */
  12924. function extendFromString(str, opts) {
  12925. return Path.extend(createPathOptions(str, opts));
  12926. }
  12927. /**
  12928. * Merge multiple paths
  12929. */
  12930. // TODO Apply transform
  12931. // TODO stroke dash
  12932. // TODO Optimize double memory cost problem
  12933. function mergePath$1(pathEls, opts) {
  12934. var pathList = [];
  12935. var len = pathEls.length;
  12936. for (var i = 0; i < len; i++) {
  12937. var pathEl = pathEls[i];
  12938. if (!pathEl.path) {
  12939. pathEl.createPathProxy();
  12940. }
  12941. if (pathEl.__dirtyPath) {
  12942. pathEl.buildPath(pathEl.path, pathEl.shape, true);
  12943. }
  12944. pathList.push(pathEl.path);
  12945. }
  12946. var pathBundle = new Path(opts); // Need path proxy.
  12947. pathBundle.createPathProxy();
  12948. pathBundle.buildPath = function (path) {
  12949. path.appendPath(pathList); // Svg and vml renderer don't have context
  12950. var ctx = path.getContext();
  12951. if (ctx) {
  12952. path.rebuildPath(ctx);
  12953. }
  12954. };
  12955. return pathBundle;
  12956. }
  12957. /**
  12958. * @alias zrender/graphic/Text
  12959. * @extends module:zrender/graphic/Displayable
  12960. * @constructor
  12961. * @param {Object} opts
  12962. */
  12963. var Text = function (opts) {
  12964. // jshint ignore:line
  12965. Displayable.call(this, opts);
  12966. };
  12967. Text.prototype = {
  12968. constructor: Text,
  12969. type: 'text',
  12970. brush: function (ctx, prevEl) {
  12971. var style = this.style; // Optimize, avoid normalize every time.
  12972. this.__dirty && normalizeTextStyle(style, true); // Use props with prefix 'text'.
  12973. style.fill = style.stroke = style.shadowBlur = style.shadowColor = style.shadowOffsetX = style.shadowOffsetY = null;
  12974. var text = style.text; // Convert to string
  12975. text != null && (text += ''); // Do not apply style.bind in Text node. Because the real bind job
  12976. // is in textHelper.renderText, and performance of text render should
  12977. // be considered.
  12978. // style.bind(ctx, this, prevEl);
  12979. if (!needDrawText(text, style)) {
  12980. // The current el.style is not applied
  12981. // and should not be used as cache.
  12982. ctx.__attrCachedBy = ContextCachedBy.NONE;
  12983. return;
  12984. }
  12985. this.setTransform(ctx);
  12986. renderText(this, ctx, text, style, null, prevEl);
  12987. this.restoreTransform(ctx);
  12988. },
  12989. getBoundingRect: function () {
  12990. var style = this.style; // Optimize, avoid normalize every time.
  12991. this.__dirty && normalizeTextStyle(style, true);
  12992. if (!this._rect) {
  12993. var text = style.text;
  12994. text != null ? text += '' : text = '';
  12995. var rect = getBoundingRect(style.text + '', style.font, style.textAlign, style.textVerticalAlign, style.textPadding, style.textLineHeight, style.rich);
  12996. rect.x += style.x || 0;
  12997. rect.y += style.y || 0;
  12998. if (getStroke(style.textStroke, style.textStrokeWidth)) {
  12999. var w = style.textStrokeWidth;
  13000. rect.x -= w / 2;
  13001. rect.y -= w / 2;
  13002. rect.width += w;
  13003. rect.height += w;
  13004. }
  13005. this._rect = rect;
  13006. }
  13007. return this._rect;
  13008. }
  13009. };
  13010. inherits(Text, Displayable);
  13011. /**
  13012. * 圆形
  13013. * @module zrender/shape/Circle
  13014. */
  13015. var Circle = Path.extend({
  13016. type: 'circle',
  13017. shape: {
  13018. cx: 0,
  13019. cy: 0,
  13020. r: 0
  13021. },
  13022. buildPath: function (ctx, shape, inBundle) {
  13023. // Better stroking in ShapeBundle
  13024. // Always do it may have performence issue ( fill may be 2x more cost)
  13025. if (inBundle) {
  13026. ctx.moveTo(shape.cx + shape.r, shape.cy);
  13027. } // else {
  13028. // if (ctx.allocate && !ctx.data.length) {
  13029. // ctx.allocate(ctx.CMD_MEM_SIZE.A);
  13030. // }
  13031. // }
  13032. // Better stroking in ShapeBundle
  13033. // ctx.moveTo(shape.cx + shape.r, shape.cy);
  13034. ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true);
  13035. }
  13036. });
  13037. // where exception "unexpected call to method or property access"
  13038. // might be thrown when calling ctx.fill or ctx.stroke after a path
  13039. // whose area size is zero is drawn and ctx.clip() is called and
  13040. // shadowBlur is set. See #4572, #3112, #5777.
  13041. // (e.g.,
  13042. // ctx.moveTo(10, 10);
  13043. // ctx.lineTo(20, 10);
  13044. // ctx.closePath();
  13045. // ctx.clip();
  13046. // ctx.shadowBlur = 10;
  13047. // ...
  13048. // ctx.fill();
  13049. // )
  13050. var shadowTemp = [['shadowBlur', 0], ['shadowColor', '#000'], ['shadowOffsetX', 0], ['shadowOffsetY', 0]];
  13051. var fixClipWithShadow = function (orignalBrush) {
  13052. // version string can be: '11.0'
  13053. return env$1.browser.ie && env$1.browser.version >= 11 ? function () {
  13054. var clipPaths = this.__clipPaths;
  13055. var style = this.style;
  13056. var modified;
  13057. if (clipPaths) {
  13058. for (var i = 0; i < clipPaths.length; i++) {
  13059. var clipPath = clipPaths[i];
  13060. var shape = clipPath && clipPath.shape;
  13061. var type = clipPath && clipPath.type;
  13062. if (shape && (type === 'sector' && shape.startAngle === shape.endAngle || type === 'rect' && (!shape.width || !shape.height))) {
  13063. for (var j = 0; j < shadowTemp.length; j++) {
  13064. // It is save to put shadowTemp static, because shadowTemp
  13065. // will be all modified each item brush called.
  13066. shadowTemp[j][2] = style[shadowTemp[j][0]];
  13067. style[shadowTemp[j][0]] = shadowTemp[j][1];
  13068. }
  13069. modified = true;
  13070. break;
  13071. }
  13072. }
  13073. }
  13074. orignalBrush.apply(this, arguments);
  13075. if (modified) {
  13076. for (var j = 0; j < shadowTemp.length; j++) {
  13077. style[shadowTemp[j][0]] = shadowTemp[j][2];
  13078. }
  13079. }
  13080. } : orignalBrush;
  13081. };
  13082. /**
  13083. * 扇形
  13084. * @module zrender/graphic/shape/Sector
  13085. */
  13086. var Sector = Path.extend({
  13087. type: 'sector',
  13088. shape: {
  13089. cx: 0,
  13090. cy: 0,
  13091. r0: 0,
  13092. r: 0,
  13093. startAngle: 0,
  13094. endAngle: Math.PI * 2,
  13095. clockwise: true
  13096. },
  13097. brush: fixClipWithShadow(Path.prototype.brush),
  13098. buildPath: function (ctx, shape) {
  13099. var x = shape.cx;
  13100. var y = shape.cy;
  13101. var r0 = Math.max(shape.r0 || 0, 0);
  13102. var r = Math.max(shape.r, 0);
  13103. var startAngle = shape.startAngle;
  13104. var endAngle = shape.endAngle;
  13105. var clockwise = shape.clockwise;
  13106. var unitX = Math.cos(startAngle);
  13107. var unitY = Math.sin(startAngle);
  13108. ctx.moveTo(unitX * r0 + x, unitY * r0 + y);
  13109. ctx.lineTo(unitX * r + x, unitY * r + y);
  13110. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13111. ctx.lineTo(Math.cos(endAngle) * r0 + x, Math.sin(endAngle) * r0 + y);
  13112. if (r0 !== 0) {
  13113. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  13114. }
  13115. ctx.closePath();
  13116. }
  13117. });
  13118. /**
  13119. * 圆环
  13120. * @module zrender/graphic/shape/Ring
  13121. */
  13122. var Ring = Path.extend({
  13123. type: 'ring',
  13124. shape: {
  13125. cx: 0,
  13126. cy: 0,
  13127. r: 0,
  13128. r0: 0
  13129. },
  13130. buildPath: function (ctx, shape) {
  13131. var x = shape.cx;
  13132. var y = shape.cy;
  13133. var PI2 = Math.PI * 2;
  13134. ctx.moveTo(x + shape.r, y);
  13135. ctx.arc(x, y, shape.r, 0, PI2, false);
  13136. ctx.moveTo(x + shape.r0, y);
  13137. ctx.arc(x, y, shape.r0, 0, PI2, true);
  13138. }
  13139. });
  13140. /**
  13141. * Catmull-Rom spline 插值折线
  13142. * @module zrender/shape/util/smoothSpline
  13143. * @author pissang (https://www.github.com/pissang)
  13144. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13145. * errorrik (errorrik@gmail.com)
  13146. */
  13147. /**
  13148. * @inner
  13149. */
  13150. function interpolate(p0, p1, p2, p3, t, t2, t3) {
  13151. var v0 = (p2 - p0) * 0.5;
  13152. var v1 = (p3 - p1) * 0.5;
  13153. return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1;
  13154. }
  13155. /**
  13156. * @alias module:zrender/shape/util/smoothSpline
  13157. * @param {Array} points 线段顶点数组
  13158. * @param {boolean} isLoop
  13159. * @return {Array}
  13160. */
  13161. var smoothSpline = function (points, isLoop) {
  13162. var len$$1 = points.length;
  13163. var ret = [];
  13164. var distance$$1 = 0;
  13165. for (var i = 1; i < len$$1; i++) {
  13166. distance$$1 += distance(points[i - 1], points[i]);
  13167. }
  13168. var segs = distance$$1 / 2;
  13169. segs = segs < len$$1 ? len$$1 : segs;
  13170. for (var i = 0; i < segs; i++) {
  13171. var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1);
  13172. var idx = Math.floor(pos);
  13173. var w = pos - idx;
  13174. var p0;
  13175. var p1 = points[idx % len$$1];
  13176. var p2;
  13177. var p3;
  13178. if (!isLoop) {
  13179. p0 = points[idx === 0 ? idx : idx - 1];
  13180. p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1];
  13181. p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2];
  13182. } else {
  13183. p0 = points[(idx - 1 + len$$1) % len$$1];
  13184. p2 = points[(idx + 1) % len$$1];
  13185. p3 = points[(idx + 2) % len$$1];
  13186. }
  13187. var w2 = w * w;
  13188. var w3 = w * w2;
  13189. ret.push([interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3)]);
  13190. }
  13191. return ret;
  13192. };
  13193. /**
  13194. * 贝塞尔平滑曲线
  13195. * @module zrender/shape/util/smoothBezier
  13196. * @author pissang (https://www.github.com/pissang)
  13197. * Kener (@Kener-林峰, kener.linfeng@gmail.com)
  13198. * errorrik (errorrik@gmail.com)
  13199. */
  13200. /**
  13201. * 贝塞尔平滑曲线
  13202. * @alias module:zrender/shape/util/smoothBezier
  13203. * @param {Array} points 线段顶点数组
  13204. * @param {number} smooth 平滑等级, 0-1
  13205. * @param {boolean} isLoop
  13206. * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内
  13207. * 比如 [[0, 0], [100, 100]], 这个包围盒会与
  13208. * 整个折线的包围盒做一个并集用来约束控制点。
  13209. * @param {Array} 计算出来的控制点数组
  13210. */
  13211. var smoothBezier = function (points, smooth, isLoop, constraint) {
  13212. var cps = [];
  13213. var v = [];
  13214. var v1 = [];
  13215. var v2 = [];
  13216. var prevPoint;
  13217. var nextPoint;
  13218. var min$$1;
  13219. var max$$1;
  13220. if (constraint) {
  13221. min$$1 = [Infinity, Infinity];
  13222. max$$1 = [-Infinity, -Infinity];
  13223. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13224. min(min$$1, min$$1, points[i]);
  13225. max(max$$1, max$$1, points[i]);
  13226. } // 与指定的包围盒做并集
  13227. min(min$$1, min$$1, constraint[0]);
  13228. max(max$$1, max$$1, constraint[1]);
  13229. }
  13230. for (var i = 0, len$$1 = points.length; i < len$$1; i++) {
  13231. var point = points[i];
  13232. if (isLoop) {
  13233. prevPoint = points[i ? i - 1 : len$$1 - 1];
  13234. nextPoint = points[(i + 1) % len$$1];
  13235. } else {
  13236. if (i === 0 || i === len$$1 - 1) {
  13237. cps.push(clone$1(points[i]));
  13238. continue;
  13239. } else {
  13240. prevPoint = points[i - 1];
  13241. nextPoint = points[i + 1];
  13242. }
  13243. }
  13244. sub(v, nextPoint, prevPoint); // use degree to scale the handle length
  13245. scale(v, v, smooth);
  13246. var d0 = distance(point, prevPoint);
  13247. var d1 = distance(point, nextPoint);
  13248. var sum = d0 + d1;
  13249. if (sum !== 0) {
  13250. d0 /= sum;
  13251. d1 /= sum;
  13252. }
  13253. scale(v1, v, -d0);
  13254. scale(v2, v, d1);
  13255. var cp0 = add([], point, v1);
  13256. var cp1 = add([], point, v2);
  13257. if (constraint) {
  13258. max(cp0, cp0, min$$1);
  13259. min(cp0, cp0, max$$1);
  13260. max(cp1, cp1, min$$1);
  13261. min(cp1, cp1, max$$1);
  13262. }
  13263. cps.push(cp0);
  13264. cps.push(cp1);
  13265. }
  13266. if (isLoop) {
  13267. cps.push(cps.shift());
  13268. }
  13269. return cps;
  13270. };
  13271. function buildPath$1(ctx, shape, closePath) {
  13272. var points = shape.points;
  13273. var smooth = shape.smooth;
  13274. if (points && points.length >= 2) {
  13275. if (smooth && smooth !== 'spline') {
  13276. var controlPoints = smoothBezier(points, smooth, closePath, shape.smoothConstraint);
  13277. ctx.moveTo(points[0][0], points[0][1]);
  13278. var len = points.length;
  13279. for (var i = 0; i < (closePath ? len : len - 1); i++) {
  13280. var cp1 = controlPoints[i * 2];
  13281. var cp2 = controlPoints[i * 2 + 1];
  13282. var p = points[(i + 1) % len];
  13283. ctx.bezierCurveTo(cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1]);
  13284. }
  13285. } else {
  13286. if (smooth === 'spline') {
  13287. points = smoothSpline(points, closePath);
  13288. }
  13289. ctx.moveTo(points[0][0], points[0][1]);
  13290. for (var i = 1, l = points.length; i < l; i++) {
  13291. ctx.lineTo(points[i][0], points[i][1]);
  13292. }
  13293. }
  13294. closePath && ctx.closePath();
  13295. }
  13296. }
  13297. /**
  13298. * 多边形
  13299. * @module zrender/shape/Polygon
  13300. */
  13301. var Polygon = Path.extend({
  13302. type: 'polygon',
  13303. shape: {
  13304. points: null,
  13305. smooth: false,
  13306. smoothConstraint: null
  13307. },
  13308. buildPath: function (ctx, shape) {
  13309. buildPath$1(ctx, shape, true);
  13310. }
  13311. });
  13312. /**
  13313. * @module zrender/graphic/shape/Polyline
  13314. */
  13315. var Polyline = Path.extend({
  13316. type: 'polyline',
  13317. shape: {
  13318. points: null,
  13319. smooth: false,
  13320. smoothConstraint: null
  13321. },
  13322. style: {
  13323. stroke: '#000',
  13324. fill: null
  13325. },
  13326. buildPath: function (ctx, shape) {
  13327. buildPath$1(ctx, shape, false);
  13328. }
  13329. });
  13330. /**
  13331. * Sub-pixel optimize for canvas rendering, prevent from blur
  13332. * when rendering a thin vertical/horizontal line.
  13333. */
  13334. var round = Math.round;
  13335. /**
  13336. * Sub pixel optimize line for canvas
  13337. *
  13338. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13339. * `outputShape` and `inputShape` can be the same object.
  13340. * `outputShape` object can be used repeatly, because all of
  13341. * the `x1`, `x2`, `y1`, `y2` will be assigned in this method.
  13342. * @param {Object} [inputShape]
  13343. * @param {number} [inputShape.x1]
  13344. * @param {number} [inputShape.y1]
  13345. * @param {number} [inputShape.x2]
  13346. * @param {number} [inputShape.y2]
  13347. * @param {Object} [style]
  13348. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  13349. */
  13350. function subPixelOptimizeLine$1(outputShape, inputShape, style) {
  13351. if (!inputShape) {
  13352. return;
  13353. }
  13354. var x1 = inputShape.x1;
  13355. var x2 = inputShape.x2;
  13356. var y1 = inputShape.y1;
  13357. var y2 = inputShape.y2;
  13358. outputShape.x1 = x1;
  13359. outputShape.x2 = x2;
  13360. outputShape.y1 = y1;
  13361. outputShape.y2 = y2;
  13362. var lineWidth = style && style.lineWidth;
  13363. if (!lineWidth) {
  13364. return;
  13365. }
  13366. if (round(x1 * 2) === round(x2 * 2)) {
  13367. outputShape.x1 = outputShape.x2 = subPixelOptimize$1(x1, lineWidth, true);
  13368. }
  13369. if (round(y1 * 2) === round(y2 * 2)) {
  13370. outputShape.y1 = outputShape.y2 = subPixelOptimize$1(y1, lineWidth, true);
  13371. }
  13372. }
  13373. /**
  13374. * Sub pixel optimize rect for canvas
  13375. *
  13376. * @param {Object} outputShape The modification will be performed on `outputShape`.
  13377. * `outputShape` and `inputShape` can be the same object.
  13378. * `outputShape` object can be used repeatly, because all of
  13379. * the `x`, `y`, `width`, `height` will be assigned in this method.
  13380. * @param {Object} [inputShape]
  13381. * @param {number} [inputShape.x]
  13382. * @param {number} [inputShape.y]
  13383. * @param {number} [inputShape.width]
  13384. * @param {number} [inputShape.height]
  13385. * @param {Object} [style]
  13386. * @param {number} [style.lineWidth] If `null`/`undefined`/`0`, do not optimize.
  13387. */
  13388. function subPixelOptimizeRect$1(outputShape, inputShape, style) {
  13389. if (!inputShape) {
  13390. return;
  13391. }
  13392. var originX = inputShape.x;
  13393. var originY = inputShape.y;
  13394. var originWidth = inputShape.width;
  13395. var originHeight = inputShape.height;
  13396. outputShape.x = originX;
  13397. outputShape.y = originY;
  13398. outputShape.width = originWidth;
  13399. outputShape.height = originHeight;
  13400. var lineWidth = style && style.lineWidth;
  13401. if (!lineWidth) {
  13402. return;
  13403. }
  13404. outputShape.x = subPixelOptimize$1(originX, lineWidth, true);
  13405. outputShape.y = subPixelOptimize$1(originY, lineWidth, true);
  13406. outputShape.width = Math.max(subPixelOptimize$1(originX + originWidth, lineWidth, false) - outputShape.x, originWidth === 0 ? 0 : 1);
  13407. outputShape.height = Math.max(subPixelOptimize$1(originY + originHeight, lineWidth, false) - outputShape.y, originHeight === 0 ? 0 : 1);
  13408. }
  13409. /**
  13410. * Sub pixel optimize for canvas
  13411. *
  13412. * @param {number} position Coordinate, such as x, y
  13413. * @param {number} lineWidth If `null`/`undefined`/`0`, do not optimize.
  13414. * @param {boolean=} positiveOrNegative Default false (negative).
  13415. * @return {number} Optimized position.
  13416. */
  13417. function subPixelOptimize$1(position, lineWidth, positiveOrNegative) {
  13418. if (!lineWidth) {
  13419. return position;
  13420. } // Assure that (position + lineWidth / 2) is near integer edge,
  13421. // otherwise line will be fuzzy in canvas.
  13422. var doubledPosition = round(position * 2);
  13423. return (doubledPosition + round(lineWidth)) % 2 === 0 ? doubledPosition / 2 : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2;
  13424. }
  13425. /**
  13426. * 矩形
  13427. * @module zrender/graphic/shape/Rect
  13428. */
  13429. var subPixelOptimizeOutputShape = {};
  13430. var Rect = Path.extend({
  13431. type: 'rect',
  13432. shape: {
  13433. // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4
  13434. // r缩写为1 相当于 [1, 1, 1, 1]
  13435. // r缩写为[1] 相当于 [1, 1, 1, 1]
  13436. // r缩写为[1, 2] 相当于 [1, 2, 1, 2]
  13437. // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2]
  13438. r: 0,
  13439. x: 0,
  13440. y: 0,
  13441. width: 0,
  13442. height: 0
  13443. },
  13444. buildPath: function (ctx, shape) {
  13445. var x;
  13446. var y;
  13447. var width;
  13448. var height;
  13449. if (this.subPixelOptimize) {
  13450. subPixelOptimizeRect$1(subPixelOptimizeOutputShape, shape, this.style);
  13451. x = subPixelOptimizeOutputShape.x;
  13452. y = subPixelOptimizeOutputShape.y;
  13453. width = subPixelOptimizeOutputShape.width;
  13454. height = subPixelOptimizeOutputShape.height;
  13455. subPixelOptimizeOutputShape.r = shape.r;
  13456. shape = subPixelOptimizeOutputShape;
  13457. } else {
  13458. x = shape.x;
  13459. y = shape.y;
  13460. width = shape.width;
  13461. height = shape.height;
  13462. }
  13463. if (!shape.r) {
  13464. ctx.rect(x, y, width, height);
  13465. } else {
  13466. buildPath(ctx, shape);
  13467. }
  13468. ctx.closePath();
  13469. return;
  13470. }
  13471. });
  13472. /**
  13473. * 直线
  13474. * @module zrender/graphic/shape/Line
  13475. */
  13476. var subPixelOptimizeOutputShape$1 = {};
  13477. var Line = Path.extend({
  13478. type: 'line',
  13479. shape: {
  13480. // Start point
  13481. x1: 0,
  13482. y1: 0,
  13483. // End point
  13484. x2: 0,
  13485. y2: 0,
  13486. percent: 1
  13487. },
  13488. style: {
  13489. stroke: '#000',
  13490. fill: null
  13491. },
  13492. buildPath: function (ctx, shape) {
  13493. var x1;
  13494. var y1;
  13495. var x2;
  13496. var y2;
  13497. if (this.subPixelOptimize) {
  13498. subPixelOptimizeLine$1(subPixelOptimizeOutputShape$1, shape, this.style);
  13499. x1 = subPixelOptimizeOutputShape$1.x1;
  13500. y1 = subPixelOptimizeOutputShape$1.y1;
  13501. x2 = subPixelOptimizeOutputShape$1.x2;
  13502. y2 = subPixelOptimizeOutputShape$1.y2;
  13503. } else {
  13504. x1 = shape.x1;
  13505. y1 = shape.y1;
  13506. x2 = shape.x2;
  13507. y2 = shape.y2;
  13508. }
  13509. var percent = shape.percent;
  13510. if (percent === 0) {
  13511. return;
  13512. }
  13513. ctx.moveTo(x1, y1);
  13514. if (percent < 1) {
  13515. x2 = x1 * (1 - percent) + x2 * percent;
  13516. y2 = y1 * (1 - percent) + y2 * percent;
  13517. }
  13518. ctx.lineTo(x2, y2);
  13519. },
  13520. /**
  13521. * Get point at percent
  13522. * @param {number} percent
  13523. * @return {Array.<number>}
  13524. */
  13525. pointAt: function (p) {
  13526. var shape = this.shape;
  13527. return [shape.x1 * (1 - p) + shape.x2 * p, shape.y1 * (1 - p) + shape.y2 * p];
  13528. }
  13529. });
  13530. /**
  13531. * 贝塞尔曲线
  13532. * @module zrender/shape/BezierCurve
  13533. */
  13534. var out = [];
  13535. function someVectorAt(shape, t, isTangent) {
  13536. var cpx2 = shape.cpx2;
  13537. var cpy2 = shape.cpy2;
  13538. if (cpx2 === null || cpy2 === null) {
  13539. return [(isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t), (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t)];
  13540. } else {
  13541. return [(isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t), (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t)];
  13542. }
  13543. }
  13544. var BezierCurve = Path.extend({
  13545. type: 'bezier-curve',
  13546. shape: {
  13547. x1: 0,
  13548. y1: 0,
  13549. x2: 0,
  13550. y2: 0,
  13551. cpx1: 0,
  13552. cpy1: 0,
  13553. // cpx2: 0,
  13554. // cpy2: 0
  13555. // Curve show percent, for animating
  13556. percent: 1
  13557. },
  13558. style: {
  13559. stroke: '#000',
  13560. fill: null
  13561. },
  13562. buildPath: function (ctx, shape) {
  13563. var x1 = shape.x1;
  13564. var y1 = shape.y1;
  13565. var x2 = shape.x2;
  13566. var y2 = shape.y2;
  13567. var cpx1 = shape.cpx1;
  13568. var cpy1 = shape.cpy1;
  13569. var cpx2 = shape.cpx2;
  13570. var cpy2 = shape.cpy2;
  13571. var percent = shape.percent;
  13572. if (percent === 0) {
  13573. return;
  13574. }
  13575. ctx.moveTo(x1, y1);
  13576. if (cpx2 == null || cpy2 == null) {
  13577. if (percent < 1) {
  13578. quadraticSubdivide(x1, cpx1, x2, percent, out);
  13579. cpx1 = out[1];
  13580. x2 = out[2];
  13581. quadraticSubdivide(y1, cpy1, y2, percent, out);
  13582. cpy1 = out[1];
  13583. y2 = out[2];
  13584. }
  13585. ctx.quadraticCurveTo(cpx1, cpy1, x2, y2);
  13586. } else {
  13587. if (percent < 1) {
  13588. cubicSubdivide(x1, cpx1, cpx2, x2, percent, out);
  13589. cpx1 = out[1];
  13590. cpx2 = out[2];
  13591. x2 = out[3];
  13592. cubicSubdivide(y1, cpy1, cpy2, y2, percent, out);
  13593. cpy1 = out[1];
  13594. cpy2 = out[2];
  13595. y2 = out[3];
  13596. }
  13597. ctx.bezierCurveTo(cpx1, cpy1, cpx2, cpy2, x2, y2);
  13598. }
  13599. },
  13600. /**
  13601. * Get point at percent
  13602. * @param {number} t
  13603. * @return {Array.<number>}
  13604. */
  13605. pointAt: function (t) {
  13606. return someVectorAt(this.shape, t, false);
  13607. },
  13608. /**
  13609. * Get tangent at percent
  13610. * @param {number} t
  13611. * @return {Array.<number>}
  13612. */
  13613. tangentAt: function (t) {
  13614. var p = someVectorAt(this.shape, t, true);
  13615. return normalize(p, p);
  13616. }
  13617. });
  13618. /**
  13619. * 圆弧
  13620. * @module zrender/graphic/shape/Arc
  13621. */
  13622. var Arc = Path.extend({
  13623. type: 'arc',
  13624. shape: {
  13625. cx: 0,
  13626. cy: 0,
  13627. r: 0,
  13628. startAngle: 0,
  13629. endAngle: Math.PI * 2,
  13630. clockwise: true
  13631. },
  13632. style: {
  13633. stroke: '#000',
  13634. fill: null
  13635. },
  13636. buildPath: function (ctx, shape) {
  13637. var x = shape.cx;
  13638. var y = shape.cy;
  13639. var r = Math.max(shape.r, 0);
  13640. var startAngle = shape.startAngle;
  13641. var endAngle = shape.endAngle;
  13642. var clockwise = shape.clockwise;
  13643. var unitX = Math.cos(startAngle);
  13644. var unitY = Math.sin(startAngle);
  13645. ctx.moveTo(unitX * r + x, unitY * r + y);
  13646. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  13647. }
  13648. });
  13649. // CompoundPath to improve performance
  13650. var CompoundPath = Path.extend({
  13651. type: 'compound',
  13652. shape: {
  13653. paths: null
  13654. },
  13655. _updatePathDirty: function () {
  13656. var dirtyPath = this.__dirtyPath;
  13657. var paths = this.shape.paths;
  13658. for (var i = 0; i < paths.length; i++) {
  13659. // Mark as dirty if any subpath is dirty
  13660. dirtyPath = dirtyPath || paths[i].__dirtyPath;
  13661. }
  13662. this.__dirtyPath = dirtyPath;
  13663. this.__dirty = this.__dirty || dirtyPath;
  13664. },
  13665. beforeBrush: function () {
  13666. this._updatePathDirty();
  13667. var paths = this.shape.paths || [];
  13668. var scale = this.getGlobalScale(); // Update path scale
  13669. for (var i = 0; i < paths.length; i++) {
  13670. if (!paths[i].path) {
  13671. paths[i].createPathProxy();
  13672. }
  13673. paths[i].path.setScale(scale[0], scale[1], paths[i].segmentIgnoreThreshold);
  13674. }
  13675. },
  13676. buildPath: function (ctx, shape) {
  13677. var paths = shape.paths || [];
  13678. for (var i = 0; i < paths.length; i++) {
  13679. paths[i].buildPath(ctx, paths[i].shape, true);
  13680. }
  13681. },
  13682. afterBrush: function () {
  13683. var paths = this.shape.paths || [];
  13684. for (var i = 0; i < paths.length; i++) {
  13685. paths[i].__dirtyPath = false;
  13686. }
  13687. },
  13688. getBoundingRect: function () {
  13689. this._updatePathDirty();
  13690. return Path.prototype.getBoundingRect.call(this);
  13691. }
  13692. });
  13693. /**
  13694. * @param {Array.<Object>} colorStops
  13695. */
  13696. var Gradient = function (colorStops) {
  13697. this.colorStops = colorStops || [];
  13698. };
  13699. Gradient.prototype = {
  13700. constructor: Gradient,
  13701. addColorStop: function (offset, color) {
  13702. this.colorStops.push({
  13703. offset: offset,
  13704. color: color
  13705. });
  13706. }
  13707. };
  13708. /**
  13709. * x, y, x2, y2 are all percent from 0 to 1
  13710. * @param {number} [x=0]
  13711. * @param {number} [y=0]
  13712. * @param {number} [x2=1]
  13713. * @param {number} [y2=0]
  13714. * @param {Array.<Object>} colorStops
  13715. * @param {boolean} [globalCoord=false]
  13716. */
  13717. var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) {
  13718. // Should do nothing more in this constructor. Because gradient can be
  13719. // declard by `color: {type: 'linear', colorStops: ...}`, where
  13720. // this constructor will not be called.
  13721. this.x = x == null ? 0 : x;
  13722. this.y = y == null ? 0 : y;
  13723. this.x2 = x2 == null ? 1 : x2;
  13724. this.y2 = y2 == null ? 0 : y2; // Can be cloned
  13725. this.type = 'linear'; // If use global coord
  13726. this.global = globalCoord || false;
  13727. Gradient.call(this, colorStops);
  13728. };
  13729. LinearGradient.prototype = {
  13730. constructor: LinearGradient
  13731. };
  13732. inherits(LinearGradient, Gradient);
  13733. /**
  13734. * x, y, r are all percent from 0 to 1
  13735. * @param {number} [x=0.5]
  13736. * @param {number} [y=0.5]
  13737. * @param {number} [r=0.5]
  13738. * @param {Array.<Object>} [colorStops]
  13739. * @param {boolean} [globalCoord=false]
  13740. */
  13741. var RadialGradient = function (x, y, r, colorStops, globalCoord) {
  13742. // Should do nothing more in this constructor. Because gradient can be
  13743. // declard by `color: {type: 'radial', colorStops: ...}`, where
  13744. // this constructor will not be called.
  13745. this.x = x == null ? 0.5 : x;
  13746. this.y = y == null ? 0.5 : y;
  13747. this.r = r == null ? 0.5 : r; // Can be cloned
  13748. this.type = 'radial'; // If use global coord
  13749. this.global = globalCoord || false;
  13750. Gradient.call(this, colorStops);
  13751. };
  13752. RadialGradient.prototype = {
  13753. constructor: RadialGradient
  13754. };
  13755. inherits(RadialGradient, Gradient);
  13756. /**
  13757. * Displayable for incremental rendering. It will be rendered in a separate layer
  13758. * IncrementalDisplay have two main methods. `clearDisplayables` and `addDisplayables`
  13759. * addDisplayables will render the added displayables incremetally.
  13760. *
  13761. * It use a not clearFlag to tell the painter don't clear the layer if it's the first element.
  13762. */
  13763. function IncrementalDisplayble(opts) {
  13764. Displayable.call(this, opts);
  13765. this._displayables = [];
  13766. this._temporaryDisplayables = [];
  13767. this._cursor = 0;
  13768. this.notClear = true;
  13769. }
  13770. IncrementalDisplayble.prototype.incremental = true;
  13771. IncrementalDisplayble.prototype.clearDisplaybles = function () {
  13772. this._displayables = [];
  13773. this._temporaryDisplayables = [];
  13774. this._cursor = 0;
  13775. this.dirty();
  13776. this.notClear = false;
  13777. };
  13778. IncrementalDisplayble.prototype.addDisplayable = function (displayable, notPersistent) {
  13779. if (notPersistent) {
  13780. this._temporaryDisplayables.push(displayable);
  13781. } else {
  13782. this._displayables.push(displayable);
  13783. }
  13784. this.dirty();
  13785. };
  13786. IncrementalDisplayble.prototype.addDisplayables = function (displayables, notPersistent) {
  13787. notPersistent = notPersistent || false;
  13788. for (var i = 0; i < displayables.length; i++) {
  13789. this.addDisplayable(displayables[i], notPersistent);
  13790. }
  13791. };
  13792. IncrementalDisplayble.prototype.eachPendingDisplayable = function (cb) {
  13793. for (var i = this._cursor; i < this._displayables.length; i++) {
  13794. cb && cb(this._displayables[i]);
  13795. }
  13796. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13797. cb && cb(this._temporaryDisplayables[i]);
  13798. }
  13799. };
  13800. IncrementalDisplayble.prototype.update = function () {
  13801. this.updateTransform();
  13802. for (var i = this._cursor; i < this._displayables.length; i++) {
  13803. var displayable = this._displayables[i]; // PENDING
  13804. displayable.parent = this;
  13805. displayable.update();
  13806. displayable.parent = null;
  13807. }
  13808. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13809. var displayable = this._temporaryDisplayables[i]; // PENDING
  13810. displayable.parent = this;
  13811. displayable.update();
  13812. displayable.parent = null;
  13813. }
  13814. };
  13815. IncrementalDisplayble.prototype.brush = function (ctx, prevEl) {
  13816. // Render persistant displayables.
  13817. for (var i = this._cursor; i < this._displayables.length; i++) {
  13818. var displayable = this._displayables[i];
  13819. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13820. displayable.brush(ctx, i === this._cursor ? null : this._displayables[i - 1]);
  13821. displayable.afterBrush && displayable.afterBrush(ctx);
  13822. }
  13823. this._cursor = i; // Render temporary displayables.
  13824. for (var i = 0; i < this._temporaryDisplayables.length; i++) {
  13825. var displayable = this._temporaryDisplayables[i];
  13826. displayable.beforeBrush && displayable.beforeBrush(ctx);
  13827. displayable.brush(ctx, i === 0 ? null : this._temporaryDisplayables[i - 1]);
  13828. displayable.afterBrush && displayable.afterBrush(ctx);
  13829. }
  13830. this._temporaryDisplayables = [];
  13831. this.notClear = true;
  13832. };
  13833. var m = [];
  13834. IncrementalDisplayble.prototype.getBoundingRect = function () {
  13835. if (!this._rect) {
  13836. var rect = new BoundingRect(Infinity, Infinity, -Infinity, -Infinity);
  13837. for (var i = 0; i < this._displayables.length; i++) {
  13838. var displayable = this._displayables[i];
  13839. var childRect = displayable.getBoundingRect().clone();
  13840. if (displayable.needLocalTransform()) {
  13841. childRect.applyTransform(displayable.getLocalTransform(m));
  13842. }
  13843. rect.union(childRect);
  13844. }
  13845. this._rect = rect;
  13846. }
  13847. return this._rect;
  13848. };
  13849. IncrementalDisplayble.prototype.contain = function (x, y) {
  13850. var localPos = this.transformCoordToLocal(x, y);
  13851. var rect = this.getBoundingRect();
  13852. if (rect.contain(localPos[0], localPos[1])) {
  13853. for (var i = 0; i < this._displayables.length; i++) {
  13854. var displayable = this._displayables[i];
  13855. if (displayable.contain(x, y)) {
  13856. return true;
  13857. }
  13858. }
  13859. }
  13860. return false;
  13861. };
  13862. inherits(IncrementalDisplayble, Displayable);
  13863. /*
  13864. * Licensed to the Apache Software Foundation (ASF) under one
  13865. * or more contributor license agreements. See the NOTICE file
  13866. * distributed with this work for additional information
  13867. * regarding copyright ownership. The ASF licenses this file
  13868. * to you under the Apache License, Version 2.0 (the
  13869. * "License"); you may not use this file except in compliance
  13870. * with the License. You may obtain a copy of the License at
  13871. *
  13872. * http://www.apache.org/licenses/LICENSE-2.0
  13873. *
  13874. * Unless required by applicable law or agreed to in writing,
  13875. * software distributed under the License is distributed on an
  13876. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  13877. * KIND, either express or implied. See the License for the
  13878. * specific language governing permissions and limitations
  13879. * under the License.
  13880. */
  13881. var mathMax$1 = Math.max;
  13882. var mathMin$1 = Math.min;
  13883. var EMPTY_OBJ = {};
  13884. var Z2_EMPHASIS_LIFT = 1; // key: label model property nane, value: style property name.
  13885. var CACHED_LABEL_STYLE_PROPERTIES = {
  13886. color: 'textFill',
  13887. textBorderColor: 'textStroke',
  13888. textBorderWidth: 'textStrokeWidth'
  13889. };
  13890. var EMPHASIS = 'emphasis';
  13891. var NORMAL = 'normal'; // Reserve 0 as default.
  13892. var _highlightNextDigit = 1;
  13893. var _highlightKeyMap = {};
  13894. var _customShapeMap = {};
  13895. /**
  13896. * Extend shape with parameters
  13897. */
  13898. function extendShape(opts) {
  13899. return Path.extend(opts);
  13900. }
  13901. /**
  13902. * Extend path
  13903. */
  13904. function extendPath(pathData, opts) {
  13905. return extendFromString(pathData, opts);
  13906. }
  13907. /**
  13908. * Register a user defined shape.
  13909. * The shape class can be fetched by `getShapeClass`
  13910. * This method will overwrite the registered shapes, including
  13911. * the registered built-in shapes, if using the same `name`.
  13912. * The shape can be used in `custom series` and
  13913. * `graphic component` by declaring `{type: name}`.
  13914. *
  13915. * @param {string} name
  13916. * @param {Object} ShapeClass Can be generated by `extendShape`.
  13917. */
  13918. function registerShape(name, ShapeClass) {
  13919. _customShapeMap[name] = ShapeClass;
  13920. }
  13921. /**
  13922. * Find shape class registered by `registerShape`. Usually used in
  13923. * fetching user defined shape.
  13924. *
  13925. * [Caution]:
  13926. * (1) This method **MUST NOT be used inside echarts !!!**, unless it is prepared
  13927. * to use user registered shapes.
  13928. * Because the built-in shape (see `getBuiltInShape`) will be registered by
  13929. * `registerShape` by default. That enables users to get both built-in
  13930. * shapes as well as the shapes belonging to themsleves. But users can overwrite
  13931. * the built-in shapes by using names like 'circle', 'rect' via calling
  13932. * `registerShape`. So the echarts inner featrues should not fetch shapes from here
  13933. * in case that it is overwritten by users, except that some features, like
  13934. * `custom series`, `graphic component`, do it deliberately.
  13935. *
  13936. * (2) In the features like `custom series`, `graphic component`, the user input
  13937. * `{tpye: 'xxx'}` does not only specify shapes but also specify other graphic
  13938. * elements like `'group'`, `'text'`, `'image'` or event `'path'`. Those names
  13939. * are reserved names, that is, if some user register a shape named `'image'`,
  13940. * the shape will not be used. If we intending to add some more reserved names
  13941. * in feature, that might bring break changes (disable some existing user shape
  13942. * names). But that case probably rearly happen. So we dont make more mechanism
  13943. * to resolve this issue here.
  13944. *
  13945. * @param {string} name
  13946. * @return {Object} The shape class. If not found, return nothing.
  13947. */
  13948. function getShapeClass(name) {
  13949. if (_customShapeMap.hasOwnProperty(name)) {
  13950. return _customShapeMap[name];
  13951. }
  13952. }
  13953. /**
  13954. * Create a path element from path data string
  13955. * @param {string} pathData
  13956. * @param {Object} opts
  13957. * @param {module:zrender/core/BoundingRect} rect
  13958. * @param {string} [layout=cover] 'center' or 'cover'
  13959. */
  13960. function makePath(pathData, opts, rect, layout) {
  13961. var path = createFromString(pathData, opts);
  13962. if (rect) {
  13963. if (layout === 'center') {
  13964. rect = centerGraphic(rect, path.getBoundingRect());
  13965. }
  13966. resizePath(path, rect);
  13967. }
  13968. return path;
  13969. }
  13970. /**
  13971. * Create a image element from image url
  13972. * @param {string} imageUrl image url
  13973. * @param {Object} opts options
  13974. * @param {module:zrender/core/BoundingRect} rect constrain rect
  13975. * @param {string} [layout=cover] 'center' or 'cover'
  13976. */
  13977. function makeImage(imageUrl, rect, layout) {
  13978. var path = new ZImage({
  13979. style: {
  13980. image: imageUrl,
  13981. x: rect.x,
  13982. y: rect.y,
  13983. width: rect.width,
  13984. height: rect.height
  13985. },
  13986. onload: function (img) {
  13987. if (layout === 'center') {
  13988. var boundingRect = {
  13989. width: img.width,
  13990. height: img.height
  13991. };
  13992. path.setStyle(centerGraphic(rect, boundingRect));
  13993. }
  13994. }
  13995. });
  13996. return path;
  13997. }
  13998. /**
  13999. * Get position of centered element in bounding box.
  14000. *
  14001. * @param {Object} rect element local bounding box
  14002. * @param {Object} boundingRect constraint bounding box
  14003. * @return {Object} element position containing x, y, width, and height
  14004. */
  14005. function centerGraphic(rect, boundingRect) {
  14006. // Set rect to center, keep width / height ratio.
  14007. var aspect = boundingRect.width / boundingRect.height;
  14008. var width = rect.height * aspect;
  14009. var height;
  14010. if (width <= rect.width) {
  14011. height = rect.height;
  14012. } else {
  14013. width = rect.width;
  14014. height = width / aspect;
  14015. }
  14016. var cx = rect.x + rect.width / 2;
  14017. var cy = rect.y + rect.height / 2;
  14018. return {
  14019. x: cx - width / 2,
  14020. y: cy - height / 2,
  14021. width: width,
  14022. height: height
  14023. };
  14024. }
  14025. var mergePath = mergePath$1;
  14026. /**
  14027. * Resize a path to fit the rect
  14028. * @param {module:zrender/graphic/Path} path
  14029. * @param {Object} rect
  14030. */
  14031. function resizePath(path, rect) {
  14032. if (!path.applyTransform) {
  14033. return;
  14034. }
  14035. var pathRect = path.getBoundingRect();
  14036. var m = pathRect.calculateTransform(rect);
  14037. path.applyTransform(m);
  14038. }
  14039. /**
  14040. * Sub pixel optimize line for canvas
  14041. *
  14042. * @param {Object} param
  14043. * @param {Object} [param.shape]
  14044. * @param {number} [param.shape.x1]
  14045. * @param {number} [param.shape.y1]
  14046. * @param {number} [param.shape.x2]
  14047. * @param {number} [param.shape.y2]
  14048. * @param {Object} [param.style]
  14049. * @param {number} [param.style.lineWidth]
  14050. * @return {Object} Modified param
  14051. */
  14052. function subPixelOptimizeLine(param) {
  14053. subPixelOptimizeLine$1(param.shape, param.shape, param.style);
  14054. return param;
  14055. }
  14056. /**
  14057. * Sub pixel optimize rect for canvas
  14058. *
  14059. * @param {Object} param
  14060. * @param {Object} [param.shape]
  14061. * @param {number} [param.shape.x]
  14062. * @param {number} [param.shape.y]
  14063. * @param {number} [param.shape.width]
  14064. * @param {number} [param.shape.height]
  14065. * @param {Object} [param.style]
  14066. * @param {number} [param.style.lineWidth]
  14067. * @return {Object} Modified param
  14068. */
  14069. function subPixelOptimizeRect(param) {
  14070. subPixelOptimizeRect$1(param.shape, param.shape, param.style);
  14071. return param;
  14072. }
  14073. /**
  14074. * Sub pixel optimize for canvas
  14075. *
  14076. * @param {number} position Coordinate, such as x, y
  14077. * @param {number} lineWidth Should be nonnegative integer.
  14078. * @param {boolean=} positiveOrNegative Default false (negative).
  14079. * @return {number} Optimized position.
  14080. */
  14081. var subPixelOptimize = subPixelOptimize$1;
  14082. function hasFillOrStroke(fillOrStroke) {
  14083. return fillOrStroke != null && fillOrStroke !== 'none';
  14084. } // Most lifted color are duplicated.
  14085. var liftedColorMap = createHashMap();
  14086. var liftedColorCount = 0;
  14087. function liftColor(color) {
  14088. if (typeof color !== 'string') {
  14089. return color;
  14090. }
  14091. var liftedColor = liftedColorMap.get(color);
  14092. if (!liftedColor) {
  14093. liftedColor = lift(color, -0.1);
  14094. if (liftedColorCount < 10000) {
  14095. liftedColorMap.set(color, liftedColor);
  14096. liftedColorCount++;
  14097. }
  14098. }
  14099. return liftedColor;
  14100. }
  14101. function cacheElementStl(el) {
  14102. if (!el.__hoverStlDirty) {
  14103. return;
  14104. }
  14105. el.__hoverStlDirty = false;
  14106. var hoverStyle = el.__hoverStl;
  14107. if (!hoverStyle) {
  14108. el.__cachedNormalStl = el.__cachedNormalZ2 = null;
  14109. return;
  14110. }
  14111. var normalStyle = el.__cachedNormalStl = {};
  14112. el.__cachedNormalZ2 = el.z2;
  14113. var elStyle = el.style;
  14114. for (var name in hoverStyle) {
  14115. // See comment in `singleEnterEmphasis`.
  14116. if (hoverStyle[name] != null) {
  14117. normalStyle[name] = elStyle[name];
  14118. }
  14119. } // Always cache fill and stroke to normalStyle for lifting color.
  14120. normalStyle.fill = elStyle.fill;
  14121. normalStyle.stroke = elStyle.stroke;
  14122. }
  14123. function singleEnterEmphasis(el) {
  14124. var hoverStl = el.__hoverStl;
  14125. if (!hoverStl || el.__highlighted) {
  14126. return;
  14127. }
  14128. var zr = el.__zr;
  14129. var useHoverLayer = el.useHoverLayer && zr && zr.painter.type === 'canvas';
  14130. el.__highlighted = useHoverLayer ? 'layer' : 'plain';
  14131. if (el.isGroup || !zr && el.useHoverLayer) {
  14132. return;
  14133. }
  14134. var elTarget = el;
  14135. var targetStyle = el.style;
  14136. if (useHoverLayer) {
  14137. elTarget = zr.addHover(el);
  14138. targetStyle = elTarget.style;
  14139. }
  14140. rollbackDefaultTextStyle(targetStyle);
  14141. if (!useHoverLayer) {
  14142. cacheElementStl(elTarget);
  14143. } // styles can be:
  14144. // {
  14145. // label: {
  14146. // show: false,
  14147. // position: 'outside',
  14148. // fontSize: 18
  14149. // },
  14150. // emphasis: {
  14151. // label: {
  14152. // show: true
  14153. // }
  14154. // }
  14155. // },
  14156. // where properties of `emphasis` may not appear in `normal`. We previously use
  14157. // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`.
  14158. // But consider rich text and setOption in merge mode, it is impossible to cover
  14159. // all properties in merge. So we use merge mode when setting style here.
  14160. // But we choose the merge strategy that only properties that is not `null/undefined`.
  14161. // Because when making a textStyle (espacially rich text), it is not easy to distinguish
  14162. // `hasOwnProperty` and `null/undefined` in code, so we trade them as the same for simplicity.
  14163. // But this strategy brings a trouble that `null/undefined` can not be used to remove
  14164. // style any more in `emphasis`. Users can both set properties directly on normal and
  14165. // emphasis to avoid this issue, or we might support `'none'` for this case if required.
  14166. targetStyle.extendFrom(hoverStl);
  14167. setDefaultHoverFillStroke(targetStyle, hoverStl, 'fill');
  14168. setDefaultHoverFillStroke(targetStyle, hoverStl, 'stroke');
  14169. applyDefaultTextStyle(targetStyle);
  14170. if (!useHoverLayer) {
  14171. el.dirty(false);
  14172. el.z2 += Z2_EMPHASIS_LIFT;
  14173. }
  14174. }
  14175. function setDefaultHoverFillStroke(targetStyle, hoverStyle, prop) {
  14176. if (!hasFillOrStroke(hoverStyle[prop]) && hasFillOrStroke(targetStyle[prop])) {
  14177. targetStyle[prop] = liftColor(targetStyle[prop]);
  14178. }
  14179. }
  14180. function singleEnterNormal(el) {
  14181. var highlighted = el.__highlighted;
  14182. if (!highlighted) {
  14183. return;
  14184. }
  14185. el.__highlighted = false;
  14186. if (el.isGroup) {
  14187. return;
  14188. }
  14189. if (highlighted === 'layer') {
  14190. el.__zr && el.__zr.removeHover(el);
  14191. } else {
  14192. var style = el.style;
  14193. var normalStl = el.__cachedNormalStl;
  14194. if (normalStl) {
  14195. rollbackDefaultTextStyle(style);
  14196. el.setStyle(normalStl);
  14197. applyDefaultTextStyle(style);
  14198. } // `__cachedNormalZ2` will not be reset if calling `setElementHoverStyle`
  14199. // when `el` is on emphasis state. So here by comparing with 1, we try
  14200. // hard to make the bug case rare.
  14201. var normalZ2 = el.__cachedNormalZ2;
  14202. if (normalZ2 != null && el.z2 - normalZ2 === Z2_EMPHASIS_LIFT) {
  14203. el.z2 = normalZ2;
  14204. }
  14205. }
  14206. }
  14207. function traverseUpdate(el, updater, commonParam) {
  14208. // If root is group, also enter updater for `highDownOnUpdate`.
  14209. var fromState = NORMAL;
  14210. var toState = NORMAL;
  14211. var trigger; // See the rule of `highDownOnUpdate` on `graphic.setAsHighDownDispatcher`.
  14212. el.__highlighted && (fromState = EMPHASIS, trigger = true);
  14213. updater(el, commonParam);
  14214. el.__highlighted && (toState = EMPHASIS, trigger = true);
  14215. el.isGroup && el.traverse(function (child) {
  14216. !child.isGroup && updater(child, commonParam);
  14217. });
  14218. trigger && el.__highDownOnUpdate && el.__highDownOnUpdate(fromState, toState);
  14219. }
  14220. /**
  14221. * Set hover style (namely "emphasis style") of element, based on the current
  14222. * style of the given `el`.
  14223. * This method should be called after all of the normal styles have been adopted
  14224. * to the `el`. See the reason on `setHoverStyle`.
  14225. *
  14226. * @param {module:zrender/Element} el Should not be `zrender/container/Group`.
  14227. * @param {Object} [el.hoverStyle] Can be set on el or its descendants,
  14228. * e.g., `el.hoverStyle = ...; graphic.setHoverStyle(el); `.
  14229. * Often used when item group has a label element and it's hoverStyle is different.
  14230. * @param {Object|boolean} [hoverStl] The specified hover style.
  14231. * If set as `false`, disable the hover style.
  14232. * Similarly, The `el.hoverStyle` can alse be set
  14233. * as `false` to disable the hover style.
  14234. * Otherwise, use the default hover style if not provided.
  14235. */
  14236. function setElementHoverStyle(el, hoverStl) {
  14237. // For performance consideration, it might be better to make the "hover style" only the
  14238. // difference properties from the "normal style", but not a entire copy of all styles.
  14239. hoverStl = el.__hoverStl = hoverStl !== false && (el.hoverStyle || hoverStl || {});
  14240. el.__hoverStlDirty = true; // FIXME
  14241. // It is not completely right to save "normal"/"emphasis" flag on elements.
  14242. // It probably should be saved on `data` of series. Consider the cases:
  14243. // (1) A highlighted elements are moved out of the view port and re-enter
  14244. // again by dataZoom.
  14245. // (2) call `setOption` and replace elements totally when they are highlighted.
  14246. if (el.__highlighted) {
  14247. // Consider the case:
  14248. // The styles of a highlighted `el` is being updated. The new "emphasis style"
  14249. // should be adapted to the `el`. Notice here new "normal styles" should have
  14250. // been set outside and the cached "normal style" is out of date.
  14251. el.__cachedNormalStl = null; // Do not clear `__cachedNormalZ2` here, because setting `z2` is not a constraint
  14252. // of this method. In most cases, `z2` is not set and hover style should be able
  14253. // to rollback. Of course, that would bring bug, but only in a rare case, see
  14254. // `doSingleLeaveHover` for details.
  14255. singleEnterNormal(el);
  14256. singleEnterEmphasis(el);
  14257. }
  14258. }
  14259. function onElementMouseOver(e) {
  14260. !shouldSilent(this, e) // "emphasis" event highlight has higher priority than mouse highlight.
  14261. && !this.__highByOuter && traverseUpdate(this, singleEnterEmphasis);
  14262. }
  14263. function onElementMouseOut(e) {
  14264. !shouldSilent(this, e) // "emphasis" event highlight has higher priority than mouse highlight.
  14265. && !this.__highByOuter && traverseUpdate(this, singleEnterNormal);
  14266. }
  14267. function onElementEmphasisEvent(highlightDigit) {
  14268. this.__highByOuter |= 1 << (highlightDigit || 0);
  14269. traverseUpdate(this, singleEnterEmphasis);
  14270. }
  14271. function onElementNormalEvent(highlightDigit) {
  14272. !(this.__highByOuter &= ~(1 << (highlightDigit || 0))) && traverseUpdate(this, singleEnterNormal);
  14273. }
  14274. function shouldSilent(el, e) {
  14275. return el.__highDownSilentOnTouch && e.zrByTouch;
  14276. }
  14277. /**
  14278. * Set hover style (namely "emphasis style") of element,
  14279. * based on the current style of the given `el`.
  14280. *
  14281. * (1)
  14282. * **CONSTRAINTS** for this method:
  14283. * <A> This method MUST be called after all of the normal styles having been adopted
  14284. * to the `el`.
  14285. * <B> The input `hoverStyle` (that is, "emphasis style") MUST be the subset of the
  14286. * "normal style" having been set to the el.
  14287. * <C> `color` MUST be one of the "normal styles" (because color might be lifted as
  14288. * a default hover style).
  14289. *
  14290. * The reason: this method treat the current style of the `el` as the "normal style"
  14291. * and cache them when enter/update the "emphasis style". Consider the case: the `el`
  14292. * is in "emphasis" state and `setOption`/`dispatchAction` trigger the style updating
  14293. * logic, where the el should shift from the original emphasis style to the new
  14294. * "emphasis style" and should be able to "downplay" back to the new "normal style".
  14295. *
  14296. * Indeed, it is error-prone to make a interface has so many constraints, but I have
  14297. * not found a better solution yet to fit the backward compatibility, performance and
  14298. * the current programming style.
  14299. *
  14300. * (2)
  14301. * Call the method for a "root" element once. Do not call it for each descendants.
  14302. * If the descendants elemenets of a group has itself hover style different from the
  14303. * root group, we can simply mount the style on `el.hoverStyle` for them, but should
  14304. * not call this method for them.
  14305. *
  14306. * (3) These input parameters can be set directly on `el`:
  14307. *
  14308. * @param {module:zrender/Element} el
  14309. * @param {Object} [el.hoverStyle] See `graphic.setElementHoverStyle`.
  14310. * @param {boolean} [el.highDownSilentOnTouch=false] See `graphic.setAsHighDownDispatcher`.
  14311. * @param {Function} [el.highDownOnUpdate] See `graphic.setAsHighDownDispatcher`.
  14312. * @param {Object|boolean} [hoverStyle] See `graphic.setElementHoverStyle`.
  14313. */
  14314. function setHoverStyle(el, hoverStyle) {
  14315. setAsHighDownDispatcher(el, true);
  14316. traverseUpdate(el, setElementHoverStyle, hoverStyle);
  14317. }
  14318. /**
  14319. * @param {module:zrender/Element} el
  14320. * @param {Function} [el.highDownOnUpdate] Called when state updated.
  14321. * Since `setHoverStyle` has the constraint that it must be called after
  14322. * all of the normal style updated, `highDownOnUpdate` is not needed to
  14323. * trigger if both `fromState` and `toState` is 'normal', and needed to
  14324. * trigger if both `fromState` and `toState` is 'emphasis', which enables
  14325. * to sync outside style settings to "emphasis" state.
  14326. * @this {string} This dispatcher `el`.
  14327. * @param {string} fromState Can be "normal" or "emphasis".
  14328. * `fromState` might equal to `toState`,
  14329. * for example, when this method is called when `el` is
  14330. * on "emphasis" state.
  14331. * @param {string} toState Can be "normal" or "emphasis".
  14332. *
  14333. * FIXME
  14334. * CAUTION: Do not expose `highDownOnUpdate` outside echarts.
  14335. * Because it is not a complete solution. The update
  14336. * listener should not have been mount in element,
  14337. * and the normal/emphasis state should not have
  14338. * mantained on elements.
  14339. *
  14340. * @param {boolean} [el.highDownSilentOnTouch=false]
  14341. * In touch device, mouseover event will be trigger on touchstart event
  14342. * (see module:zrender/dom/HandlerProxy). By this mechanism, we can
  14343. * conveniently use hoverStyle when tap on touch screen without additional
  14344. * code for compatibility.
  14345. * But if the chart/component has select feature, which usually also use
  14346. * hoverStyle, there might be conflict between 'select-highlight' and
  14347. * 'hover-highlight' especially when roam is enabled (see geo for example).
  14348. * In this case, `highDownSilentOnTouch` should be used to disable
  14349. * hover-highlight on touch device.
  14350. * @param {boolean} [asDispatcher=true] If `false`, do not set as "highDownDispatcher".
  14351. */
  14352. function setAsHighDownDispatcher(el, asDispatcher) {
  14353. var disable = asDispatcher === false; // Make `highDownSilentOnTouch` and `highDownOnUpdate` only work after
  14354. // `setAsHighDownDispatcher` called. Avoid it is modified by user unexpectedly.
  14355. el.__highDownSilentOnTouch = el.highDownSilentOnTouch;
  14356. el.__highDownOnUpdate = el.highDownOnUpdate; // Simple optimize, since this method might be
  14357. // called for each elements of a group in some cases.
  14358. if (!disable || el.__highDownDispatcher) {
  14359. var method = disable ? 'off' : 'on'; // Duplicated function will be auto-ignored, see Eventful.js.
  14360. el[method]('mouseover', onElementMouseOver)[method]('mouseout', onElementMouseOut); // Emphasis, normal can be triggered manually by API or other components like hover link.
  14361. el[method]('emphasis', onElementEmphasisEvent)[method]('normal', onElementNormalEvent); // Also keep previous record.
  14362. el.__highByOuter = el.__highByOuter || 0;
  14363. el.__highDownDispatcher = !disable;
  14364. }
  14365. }
  14366. /**
  14367. * @param {module:zrender/src/Element} el
  14368. * @return {boolean}
  14369. */
  14370. function isHighDownDispatcher(el) {
  14371. return !!(el && el.__highDownDispatcher);
  14372. }
  14373. /**
  14374. * Support hightlight/downplay record on each elements.
  14375. * For the case: hover highlight/downplay (legend, visualMap, ...) and
  14376. * user triggerred hightlight/downplay should not conflict.
  14377. * Only all of the highlightDigit cleared, return to normal.
  14378. * @param {string} highlightKey
  14379. * @return {number} highlightDigit
  14380. */
  14381. function getHighlightDigit(highlightKey) {
  14382. var highlightDigit = _highlightKeyMap[highlightKey];
  14383. if (highlightDigit == null && _highlightNextDigit <= 32) {
  14384. highlightDigit = _highlightKeyMap[highlightKey] = _highlightNextDigit++;
  14385. }
  14386. return highlightDigit;
  14387. }
  14388. /**
  14389. * See more info in `setTextStyleCommon`.
  14390. * @param {Object|module:zrender/graphic/Style} normalStyle
  14391. * @param {Object} emphasisStyle
  14392. * @param {module:echarts/model/Model} normalModel
  14393. * @param {module:echarts/model/Model} emphasisModel
  14394. * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props.
  14395. * @param {string|Function} [opt.defaultText]
  14396. * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by
  14397. * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14398. * @param {number} [opt.labelDataIndex] Fetch text by
  14399. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14400. * @param {number} [opt.labelDimIndex] Fetch text by
  14401. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14402. * @param {string} [opt.labelProp] Fetch text by
  14403. * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex, opt.labelProp)`
  14404. * @param {Object} [normalSpecified]
  14405. * @param {Object} [emphasisSpecified]
  14406. */
  14407. function setLabelStyle(normalStyle, emphasisStyle, normalModel, emphasisModel, opt, normalSpecified, emphasisSpecified) {
  14408. opt = opt || EMPTY_OBJ;
  14409. var labelFetcher = opt.labelFetcher;
  14410. var labelDataIndex = opt.labelDataIndex;
  14411. var labelDimIndex = opt.labelDimIndex;
  14412. var labelProp = opt.labelProp; // This scenario, `label.normal.show = true; label.emphasis.show = false`,
  14413. // is not supported util someone requests.
  14414. var showNormal = normalModel.getShallow('show');
  14415. var showEmphasis = emphasisModel.getShallow('show'); // Consider performance, only fetch label when necessary.
  14416. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set,
  14417. // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`.
  14418. var baseText;
  14419. if (showNormal || showEmphasis) {
  14420. if (labelFetcher) {
  14421. baseText = labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex, labelProp);
  14422. }
  14423. if (baseText == null) {
  14424. baseText = isFunction$1(opt.defaultText) ? opt.defaultText(labelDataIndex, opt) : opt.defaultText;
  14425. }
  14426. }
  14427. var normalStyleText = showNormal ? baseText : null;
  14428. var emphasisStyleText = showEmphasis ? retrieve2(labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex, labelProp) : null, baseText) : null; // Optimize: If style.text is null, text will not be drawn.
  14429. if (normalStyleText != null || emphasisStyleText != null) {
  14430. // Always set `textStyle` even if `normalStyle.text` is null, because default
  14431. // values have to be set on `normalStyle`.
  14432. // If we set default values on `emphasisStyle`, consider case:
  14433. // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);`
  14434. // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);`
  14435. // Then the 'red' will not work on emphasis.
  14436. setTextStyle(normalStyle, normalModel, normalSpecified, opt);
  14437. setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true);
  14438. }
  14439. normalStyle.text = normalStyleText;
  14440. emphasisStyle.text = emphasisStyleText;
  14441. }
  14442. /**
  14443. * Modify label style manually.
  14444. * Only works after `setLabelStyle` and `setElementHoverStyle` called.
  14445. *
  14446. * @param {module:zrender/src/Element} el
  14447. * @param {Object} [normalStyleProps] optional
  14448. * @param {Object} [emphasisStyleProps] optional
  14449. */
  14450. function modifyLabelStyle(el, normalStyleProps, emphasisStyleProps) {
  14451. var elStyle = el.style;
  14452. if (normalStyleProps) {
  14453. rollbackDefaultTextStyle(elStyle);
  14454. el.setStyle(normalStyleProps);
  14455. applyDefaultTextStyle(elStyle);
  14456. }
  14457. elStyle = el.__hoverStl;
  14458. if (emphasisStyleProps && elStyle) {
  14459. rollbackDefaultTextStyle(elStyle);
  14460. extend(elStyle, emphasisStyleProps);
  14461. applyDefaultTextStyle(elStyle);
  14462. }
  14463. }
  14464. /**
  14465. * Set basic textStyle properties.
  14466. * See more info in `setTextStyleCommon`.
  14467. * @param {Object|module:zrender/graphic/Style} textStyle
  14468. * @param {module:echarts/model/Model} model
  14469. * @param {Object} [specifiedTextStyle] Can be overrided by settings in model.
  14470. * @param {Object} [opt] See `opt` of `setTextStyleCommon`.
  14471. * @param {boolean} [isEmphasis]
  14472. */
  14473. function setTextStyle(textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis) {
  14474. setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis);
  14475. specifiedTextStyle && extend(textStyle, specifiedTextStyle); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14476. return textStyle;
  14477. }
  14478. /**
  14479. * Set text option in the style.
  14480. * See more info in `setTextStyleCommon`.
  14481. * @deprecated
  14482. * @param {Object} textStyle
  14483. * @param {module:echarts/model/Model} labelModel
  14484. * @param {string|boolean} defaultColor Default text color.
  14485. * If set as false, it will be processed as a emphasis style.
  14486. */
  14487. function setText(textStyle, labelModel, defaultColor) {
  14488. var opt = {
  14489. isRectText: true
  14490. };
  14491. var isEmphasis;
  14492. if (defaultColor === false) {
  14493. isEmphasis = true;
  14494. } else {
  14495. // Support setting color as 'auto' to get visual color.
  14496. opt.autoColor = defaultColor;
  14497. }
  14498. setTextStyleCommon(textStyle, labelModel, opt, isEmphasis); // textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false);
  14499. }
  14500. /**
  14501. * The uniform entry of set text style, that is, retrieve style definitions
  14502. * from `model` and set to `textStyle` object.
  14503. *
  14504. * Never in merge mode, but in overwrite mode, that is, all of the text style
  14505. * properties will be set. (Consider the states of normal and emphasis and
  14506. * default value can be adopted, merge would make the logic too complicated
  14507. * to manage.)
  14508. *
  14509. * The `textStyle` object can either be a plain object or an instance of
  14510. * `zrender/src/graphic/Style`, and either be the style of normal or emphasis.
  14511. * After this mothod called, the `textStyle` object can then be used in
  14512. * `el.setStyle(textStyle)` or `el.hoverStyle = textStyle`.
  14513. *
  14514. * Default value will be adopted and `insideRollbackOpt` will be created.
  14515. * See `applyDefaultTextStyle` `rollbackDefaultTextStyle` for more details.
  14516. *
  14517. * opt: {
  14518. * disableBox: boolean, Whether diable drawing box of block (outer most).
  14519. * isRectText: boolean,
  14520. * autoColor: string, specify a color when color is 'auto',
  14521. * for textFill, textStroke, textBackgroundColor, and textBorderColor.
  14522. * If autoColor specified, it is used as default textFill.
  14523. * useInsideStyle:
  14524. * `true`: Use inside style (textFill, textStroke, textStrokeWidth)
  14525. * if `textFill` is not specified.
  14526. * `false`: Do not use inside style.
  14527. * `null/undefined`: use inside style if `isRectText` is true and
  14528. * `textFill` is not specified and textPosition contains `'inside'`.
  14529. * forceRich: boolean
  14530. * }
  14531. */
  14532. function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) {
  14533. // Consider there will be abnormal when merge hover style to normal style if given default value.
  14534. opt = opt || EMPTY_OBJ;
  14535. if (opt.isRectText) {
  14536. var textPosition;
  14537. if (opt.getTextPosition) {
  14538. textPosition = opt.getTextPosition(textStyleModel, isEmphasis);
  14539. } else {
  14540. textPosition = textStyleModel.getShallow('position') || (isEmphasis ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used
  14541. // in bar series, and magric type should be considered.
  14542. textPosition === 'outside' && (textPosition = 'top');
  14543. }
  14544. textStyle.textPosition = textPosition;
  14545. textStyle.textOffset = textStyleModel.getShallow('offset');
  14546. var labelRotate = textStyleModel.getShallow('rotate');
  14547. labelRotate != null && (labelRotate *= Math.PI / 180);
  14548. textStyle.textRotation = labelRotate;
  14549. textStyle.textDistance = retrieve2(textStyleModel.getShallow('distance'), isEmphasis ? null : 5);
  14550. }
  14551. var ecModel = textStyleModel.ecModel;
  14552. var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case:
  14553. // {
  14554. // data: [{
  14555. // value: 12,
  14556. // label: {
  14557. // rich: {
  14558. // // no 'a' here but using parent 'a'.
  14559. // }
  14560. // }
  14561. // }],
  14562. // rich: {
  14563. // a: { ... }
  14564. // }
  14565. // }
  14566. var richItemNames = getRichItemNames(textStyleModel);
  14567. var richResult;
  14568. if (richItemNames) {
  14569. richResult = {};
  14570. for (var name in richItemNames) {
  14571. if (richItemNames.hasOwnProperty(name)) {
  14572. // Cascade is supported in rich.
  14573. var richTextStyle = textStyleModel.getModel(['rich', name]); // In rich, never `disableBox`.
  14574. // FIXME: consider `label: {formatter: '{a|xx}', color: 'blue', rich: {a: {}}}`,
  14575. // the default color `'blue'` will not be adopted if no color declared in `rich`.
  14576. // That might confuses users. So probably we should put `textStyleModel` as the
  14577. // root ancestor of the `richTextStyle`. But that would be a break change.
  14578. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis);
  14579. }
  14580. }
  14581. }
  14582. textStyle.rich = richResult;
  14583. setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true);
  14584. if (opt.forceRich && !opt.textStyle) {
  14585. opt.textStyle = {};
  14586. }
  14587. return textStyle;
  14588. } // Consider case:
  14589. // {
  14590. // data: [{
  14591. // value: 12,
  14592. // label: {
  14593. // rich: {
  14594. // // no 'a' here but using parent 'a'.
  14595. // }
  14596. // }
  14597. // }],
  14598. // rich: {
  14599. // a: { ... }
  14600. // }
  14601. // }
  14602. function getRichItemNames(textStyleModel) {
  14603. // Use object to remove duplicated names.
  14604. var richItemNameMap;
  14605. while (textStyleModel && textStyleModel !== textStyleModel.ecModel) {
  14606. var rich = (textStyleModel.option || EMPTY_OBJ).rich;
  14607. if (rich) {
  14608. richItemNameMap = richItemNameMap || {};
  14609. for (var name in rich) {
  14610. if (rich.hasOwnProperty(name)) {
  14611. richItemNameMap[name] = 1;
  14612. }
  14613. }
  14614. }
  14615. textStyleModel = textStyleModel.parentModel;
  14616. }
  14617. return richItemNameMap;
  14618. }
  14619. function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) {
  14620. // In merge mode, default value should not be given.
  14621. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ;
  14622. textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt) || globalTextStyle.color;
  14623. textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt) || globalTextStyle.textBorderColor;
  14624. textStyle.textStrokeWidth = retrieve2(textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth);
  14625. if (!isEmphasis) {
  14626. if (isBlock) {
  14627. textStyle.insideRollbackOpt = opt;
  14628. applyDefaultTextStyle(textStyle);
  14629. } // Set default finally.
  14630. if (textStyle.textFill == null) {
  14631. textStyle.textFill = opt.autoColor;
  14632. }
  14633. } // Do not use `getFont` here, because merge should be supported, where
  14634. // part of these properties may be changed in emphasis style, and the
  14635. // others should remain their original value got from normal style.
  14636. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle;
  14637. textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight;
  14638. textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize;
  14639. textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily;
  14640. textStyle.textAlign = textStyleModel.getShallow('align');
  14641. textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign') || textStyleModel.getShallow('baseline');
  14642. textStyle.textLineHeight = textStyleModel.getShallow('lineHeight');
  14643. textStyle.textWidth = textStyleModel.getShallow('width');
  14644. textStyle.textHeight = textStyleModel.getShallow('height');
  14645. textStyle.textTag = textStyleModel.getShallow('tag');
  14646. if (!isBlock || !opt.disableBox) {
  14647. textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt);
  14648. textStyle.textPadding = textStyleModel.getShallow('padding');
  14649. textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt);
  14650. textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth');
  14651. textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius');
  14652. textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor');
  14653. textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur');
  14654. textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX');
  14655. textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY');
  14656. }
  14657. textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor') || globalTextStyle.textShadowColor;
  14658. textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur') || globalTextStyle.textShadowBlur;
  14659. textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX') || globalTextStyle.textShadowOffsetX;
  14660. textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY') || globalTextStyle.textShadowOffsetY;
  14661. }
  14662. function getAutoColor(color, opt) {
  14663. return color !== 'auto' ? color : opt && opt.autoColor ? opt.autoColor : null;
  14664. }
  14665. /**
  14666. * Give some default value to the input `textStyle` object, based on the current settings
  14667. * in this `textStyle` object.
  14668. *
  14669. * The Scenario:
  14670. * when text position is `inside` and `textFill` is not specified, we show
  14671. * text border by default for better view. But it should be considered that text position
  14672. * might be changed when hovering or being emphasis, where the `insideRollback` is used to
  14673. * restore the style.
  14674. *
  14675. * Usage (& NOTICE):
  14676. * When a style object (eithor plain object or instance of `zrender/src/graphic/Style`) is
  14677. * about to be modified on its text related properties, `rollbackDefaultTextStyle` should
  14678. * be called before the modification and `applyDefaultTextStyle` should be called after that.
  14679. * (For the case that all of the text related properties is reset, like `setTextStyleCommon`
  14680. * does, `rollbackDefaultTextStyle` is not needed to be called).
  14681. */
  14682. function applyDefaultTextStyle(textStyle) {
  14683. var textPosition = textStyle.textPosition;
  14684. var opt = textStyle.insideRollbackOpt;
  14685. var insideRollback;
  14686. if (opt && textStyle.textFill == null) {
  14687. var autoColor = opt.autoColor;
  14688. var isRectText = opt.isRectText;
  14689. var useInsideStyle = opt.useInsideStyle;
  14690. var useInsideStyleCache = useInsideStyle !== false && (useInsideStyle === true || isRectText && textPosition // textPosition can be [10, 30]
  14691. && typeof textPosition === 'string' && textPosition.indexOf('inside') >= 0);
  14692. var useAutoColorCache = !useInsideStyleCache && autoColor != null; // All of the props declared in `CACHED_LABEL_STYLE_PROPERTIES` are to be cached.
  14693. if (useInsideStyleCache || useAutoColorCache) {
  14694. insideRollback = {
  14695. textFill: textStyle.textFill,
  14696. textStroke: textStyle.textStroke,
  14697. textStrokeWidth: textStyle.textStrokeWidth
  14698. };
  14699. }
  14700. if (useInsideStyleCache) {
  14701. textStyle.textFill = '#fff'; // Consider text with #fff overflow its container.
  14702. if (textStyle.textStroke == null) {
  14703. textStyle.textStroke = autoColor;
  14704. textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2);
  14705. }
  14706. }
  14707. if (useAutoColorCache) {
  14708. textStyle.textFill = autoColor;
  14709. }
  14710. } // Always set `insideRollback`, so that the previous one can be cleared.
  14711. textStyle.insideRollback = insideRollback;
  14712. }
  14713. /**
  14714. * Consider the case: in a scatter,
  14715. * label: {
  14716. * normal: {position: 'inside'},
  14717. * emphasis: {position: 'top'}
  14718. * }
  14719. * In the normal state, the `textFill` will be set as '#fff' for pretty view (see
  14720. * `applyDefaultTextStyle`), but when switching to emphasis state, the `textFill`
  14721. * should be retured to 'autoColor', but not keep '#fff'.
  14722. */
  14723. function rollbackDefaultTextStyle(style) {
  14724. var insideRollback = style.insideRollback;
  14725. if (insideRollback) {
  14726. // Reset all of the props in `CACHED_LABEL_STYLE_PROPERTIES`.
  14727. style.textFill = insideRollback.textFill;
  14728. style.textStroke = insideRollback.textStroke;
  14729. style.textStrokeWidth = insideRollback.textStrokeWidth;
  14730. style.insideRollback = null;
  14731. }
  14732. }
  14733. function getFont(opt, ecModel) {
  14734. var gTextStyleModel = ecModel && ecModel.getModel('textStyle');
  14735. return trim([// FIXME in node-canvas fontWeight is before fontStyle
  14736. opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '', opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '', (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px', opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif'].join(' '));
  14737. }
  14738. function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) {
  14739. if (typeof dataIndex === 'function') {
  14740. cb = dataIndex;
  14741. dataIndex = null;
  14742. } // Do not check 'animation' property directly here. Consider this case:
  14743. // animation model is an `itemModel`, whose does not have `isAnimationEnabled`
  14744. // but its parent model (`seriesModel`) does.
  14745. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled();
  14746. if (animationEnabled) {
  14747. var postfix = isUpdate ? 'Update' : '';
  14748. var duration = animatableModel.getShallow('animationDuration' + postfix);
  14749. var animationEasing = animatableModel.getShallow('animationEasing' + postfix);
  14750. var animationDelay = animatableModel.getShallow('animationDelay' + postfix);
  14751. if (typeof animationDelay === 'function') {
  14752. animationDelay = animationDelay(dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null);
  14753. }
  14754. if (typeof duration === 'function') {
  14755. duration = duration(dataIndex);
  14756. }
  14757. duration > 0 ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb) : (el.stopAnimation(), el.attr(props), cb && cb());
  14758. } else {
  14759. el.stopAnimation();
  14760. el.attr(props);
  14761. cb && cb();
  14762. }
  14763. }
  14764. /**
  14765. * Update graphic element properties with or without animation according to the
  14766. * configuration in series.
  14767. *
  14768. * Caution: this method will stop previous animation.
  14769. * So do not use this method to one element twice before
  14770. * animation starts, unless you know what you are doing.
  14771. *
  14772. * @param {module:zrender/Element} el
  14773. * @param {Object} props
  14774. * @param {module:echarts/model/Model} [animatableModel]
  14775. * @param {number} [dataIndex]
  14776. * @param {Function} [cb]
  14777. * @example
  14778. * graphic.updateProps(el, {
  14779. * position: [100, 100]
  14780. * }, seriesModel, dataIndex, function () { console.log('Animation done!'); });
  14781. * // Or
  14782. * graphic.updateProps(el, {
  14783. * position: [100, 100]
  14784. * }, seriesModel, function () { console.log('Animation done!'); });
  14785. */
  14786. function updateProps(el, props, animatableModel, dataIndex, cb) {
  14787. animateOrSetProps(true, el, props, animatableModel, dataIndex, cb);
  14788. }
  14789. /**
  14790. * Init graphic element properties with or without animation according to the
  14791. * configuration in series.
  14792. *
  14793. * Caution: this method will stop previous animation.
  14794. * So do not use this method to one element twice before
  14795. * animation starts, unless you know what you are doing.
  14796. *
  14797. * @param {module:zrender/Element} el
  14798. * @param {Object} props
  14799. * @param {module:echarts/model/Model} [animatableModel]
  14800. * @param {number} [dataIndex]
  14801. * @param {Function} cb
  14802. */
  14803. function initProps(el, props, animatableModel, dataIndex, cb) {
  14804. animateOrSetProps(false, el, props, animatableModel, dataIndex, cb);
  14805. }
  14806. /**
  14807. * Get transform matrix of target (param target),
  14808. * in coordinate of its ancestor (param ancestor)
  14809. *
  14810. * @param {module:zrender/mixin/Transformable} target
  14811. * @param {module:zrender/mixin/Transformable} [ancestor]
  14812. */
  14813. function getTransform(target, ancestor) {
  14814. var mat = identity([]);
  14815. while (target && target !== ancestor) {
  14816. mul$1(mat, target.getLocalTransform(), mat);
  14817. target = target.parent;
  14818. }
  14819. return mat;
  14820. }
  14821. /**
  14822. * Apply transform to an vertex.
  14823. * @param {Array.<number>} target [x, y]
  14824. * @param {Array.<number>|TypedArray.<number>|Object} transform Can be:
  14825. * + Transform matrix: like [1, 0, 0, 1, 0, 0]
  14826. * + {position, rotation, scale}, the same as `zrender/Transformable`.
  14827. * @param {boolean=} invert Whether use invert matrix.
  14828. * @return {Array.<number>} [x, y]
  14829. */
  14830. function applyTransform$1(target, transform, invert$$1) {
  14831. if (transform && !isArrayLike(transform)) {
  14832. transform = Transformable.getLocalTransform(transform);
  14833. }
  14834. if (invert$$1) {
  14835. transform = invert([], transform);
  14836. }
  14837. return applyTransform([], target, transform);
  14838. }
  14839. /**
  14840. * @param {string} direction 'left' 'right' 'top' 'bottom'
  14841. * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0]
  14842. * @param {boolean=} invert Whether use invert matrix.
  14843. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom'
  14844. */
  14845. function transformDirection(direction, transform, invert$$1) {
  14846. // Pick a base, ensure that transform result will not be (0, 0).
  14847. var hBase = transform[4] === 0 || transform[5] === 0 || transform[0] === 0 ? 1 : Math.abs(2 * transform[4] / transform[0]);
  14848. var vBase = transform[4] === 0 || transform[5] === 0 || transform[2] === 0 ? 1 : Math.abs(2 * transform[4] / transform[2]);
  14849. var vertex = [direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0];
  14850. vertex = applyTransform$1(vertex, transform, invert$$1);
  14851. return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? vertex[0] > 0 ? 'right' : 'left' : vertex[1] > 0 ? 'bottom' : 'top';
  14852. }
  14853. /**
  14854. * Apply group transition animation from g1 to g2.
  14855. * If no animatableModel, no animation.
  14856. */
  14857. function groupTransition(g1, g2, animatableModel, cb) {
  14858. if (!g1 || !g2) {
  14859. return;
  14860. }
  14861. function getElMap(g) {
  14862. var elMap = {};
  14863. g.traverse(function (el) {
  14864. if (!el.isGroup && el.anid) {
  14865. elMap[el.anid] = el;
  14866. }
  14867. });
  14868. return elMap;
  14869. }
  14870. function getAnimatableProps(el) {
  14871. var obj = {
  14872. position: clone$1(el.position),
  14873. rotation: el.rotation
  14874. };
  14875. if (el.shape) {
  14876. obj.shape = extend({}, el.shape);
  14877. }
  14878. return obj;
  14879. }
  14880. var elMap1 = getElMap(g1);
  14881. g2.traverse(function (el) {
  14882. if (!el.isGroup && el.anid) {
  14883. var oldEl = elMap1[el.anid];
  14884. if (oldEl) {
  14885. var newProp = getAnimatableProps(el);
  14886. el.attr(getAnimatableProps(oldEl));
  14887. updateProps(el, newProp, animatableModel, el.dataIndex);
  14888. } // else {
  14889. // if (el.previousProps) {
  14890. // graphic.updateProps
  14891. // }
  14892. // }
  14893. }
  14894. });
  14895. }
  14896. /**
  14897. * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...]
  14898. * @param {Object} rect {x, y, width, height}
  14899. * @return {Array.<Array.<number>>} A new clipped points.
  14900. */
  14901. function clipPointsByRect(points, rect) {
  14902. // FIXME: this way migth be incorrect when grpahic clipped by a corner.
  14903. // and when element have border.
  14904. return map(points, function (point) {
  14905. var x = point[0];
  14906. x = mathMax$1(x, rect.x);
  14907. x = mathMin$1(x, rect.x + rect.width);
  14908. var y = point[1];
  14909. y = mathMax$1(y, rect.y);
  14910. y = mathMin$1(y, rect.y + rect.height);
  14911. return [x, y];
  14912. });
  14913. }
  14914. /**
  14915. * @param {Object} targetRect {x, y, width, height}
  14916. * @param {Object} rect {x, y, width, height}
  14917. * @return {Object} A new clipped rect. If rect size are negative, return undefined.
  14918. */
  14919. function clipRectByRect(targetRect, rect) {
  14920. var x = mathMax$1(targetRect.x, rect.x);
  14921. var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width);
  14922. var y = mathMax$1(targetRect.y, rect.y);
  14923. var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height); // If the total rect is cliped, nothing, including the border,
  14924. // should be painted. So return undefined.
  14925. if (x2 >= x && y2 >= y) {
  14926. return {
  14927. x: x,
  14928. y: y,
  14929. width: x2 - x,
  14930. height: y2 - y
  14931. };
  14932. }
  14933. }
  14934. /**
  14935. * @param {string} iconStr Support 'image://' or 'path://' or direct svg path.
  14936. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`.
  14937. * @param {Object} [rect] {x, y, width, height}
  14938. * @return {module:zrender/Element} Icon path or image element.
  14939. */
  14940. function createIcon(iconStr, opt, rect) {
  14941. opt = extend({
  14942. rectHover: true
  14943. }, opt);
  14944. var style = opt.style = {
  14945. strokeNoScale: true
  14946. };
  14947. rect = rect || {
  14948. x: -1,
  14949. y: -1,
  14950. width: 2,
  14951. height: 2
  14952. };
  14953. if (iconStr) {
  14954. return iconStr.indexOf('image://') === 0 ? (style.image = iconStr.slice(8), defaults(style, rect), new ZImage(opt)) : makePath(iconStr.replace('path://', ''), opt, rect, 'center');
  14955. }
  14956. }
  14957. /**
  14958. * Return `true` if the given line (line `a`) and the given polygon
  14959. * are intersect.
  14960. * Note that we do not count colinear as intersect here because no
  14961. * requirement for that. We could do that if required in future.
  14962. *
  14963. * @param {number} a1x
  14964. * @param {number} a1y
  14965. * @param {number} a2x
  14966. * @param {number} a2y
  14967. * @param {Array.<Array.<number>>} points Points of the polygon.
  14968. * @return {boolean}
  14969. */
  14970. function linePolygonIntersect(a1x, a1y, a2x, a2y, points) {
  14971. for (var i = 0, p2 = points[points.length - 1]; i < points.length; i++) {
  14972. var p = points[i];
  14973. if (lineLineIntersect(a1x, a1y, a2x, a2y, p[0], p[1], p2[0], p2[1])) {
  14974. return true;
  14975. }
  14976. p2 = p;
  14977. }
  14978. }
  14979. /**
  14980. * Return `true` if the given two lines (line `a` and line `b`)
  14981. * are intersect.
  14982. * Note that we do not count colinear as intersect here because no
  14983. * requirement for that. We could do that if required in future.
  14984. *
  14985. * @param {number} a1x
  14986. * @param {number} a1y
  14987. * @param {number} a2x
  14988. * @param {number} a2y
  14989. * @param {number} b1x
  14990. * @param {number} b1y
  14991. * @param {number} b2x
  14992. * @param {number} b2y
  14993. * @return {boolean}
  14994. */
  14995. function lineLineIntersect(a1x, a1y, a2x, a2y, b1x, b1y, b2x, b2y) {
  14996. // let `vec_m` to be `vec_a2 - vec_a1` and `vec_n` to be `vec_b2 - vec_b1`.
  14997. var mx = a2x - a1x;
  14998. var my = a2y - a1y;
  14999. var nx = b2x - b1x;
  15000. var ny = b2y - b1y; // `vec_m` and `vec_n` are parallel iff
  15001. // exising `k` such that `vec_m = k · vec_n`, equivalent to `vec_m X vec_n = 0`.
  15002. var nmCrossProduct = crossProduct2d(nx, ny, mx, my);
  15003. if (nearZero(nmCrossProduct)) {
  15004. return false;
  15005. } // `vec_m` and `vec_n` are intersect iff
  15006. // existing `p` and `q` in [0, 1] such that `vec_a1 + p * vec_m = vec_b1 + q * vec_n`,
  15007. // such that `q = ((vec_a1 - vec_b1) X vec_m) / (vec_n X vec_m)`
  15008. // and `p = ((vec_a1 - vec_b1) X vec_n) / (vec_n X vec_m)`.
  15009. var b1a1x = a1x - b1x;
  15010. var b1a1y = a1y - b1y;
  15011. var q = crossProduct2d(b1a1x, b1a1y, mx, my) / nmCrossProduct;
  15012. if (q < 0 || q > 1) {
  15013. return false;
  15014. }
  15015. var p = crossProduct2d(b1a1x, b1a1y, nx, ny) / nmCrossProduct;
  15016. if (p < 0 || p > 1) {
  15017. return false;
  15018. }
  15019. return true;
  15020. }
  15021. /**
  15022. * Cross product of 2-dimension vector.
  15023. */
  15024. function crossProduct2d(x1, y1, x2, y2) {
  15025. return x1 * y2 - x2 * y1;
  15026. }
  15027. function nearZero(val) {
  15028. return val <= 1e-6 && val >= -1e-6;
  15029. } // Register built-in shapes. These shapes might be overwirtten
  15030. // by users, although we do not recommend that.
  15031. registerShape('circle', Circle);
  15032. registerShape('sector', Sector);
  15033. registerShape('ring', Ring);
  15034. registerShape('polygon', Polygon);
  15035. registerShape('polyline', Polyline);
  15036. registerShape('rect', Rect);
  15037. registerShape('line', Line);
  15038. registerShape('bezierCurve', BezierCurve);
  15039. registerShape('arc', Arc);
  15040. var graphic = (Object.freeze || Object)({
  15041. Z2_EMPHASIS_LIFT: Z2_EMPHASIS_LIFT,
  15042. CACHED_LABEL_STYLE_PROPERTIES: CACHED_LABEL_STYLE_PROPERTIES,
  15043. extendShape: extendShape,
  15044. extendPath: extendPath,
  15045. registerShape: registerShape,
  15046. getShapeClass: getShapeClass,
  15047. makePath: makePath,
  15048. makeImage: makeImage,
  15049. mergePath: mergePath,
  15050. resizePath: resizePath,
  15051. subPixelOptimizeLine: subPixelOptimizeLine,
  15052. subPixelOptimizeRect: subPixelOptimizeRect,
  15053. subPixelOptimize: subPixelOptimize,
  15054. setElementHoverStyle: setElementHoverStyle,
  15055. setHoverStyle: setHoverStyle,
  15056. setAsHighDownDispatcher: setAsHighDownDispatcher,
  15057. isHighDownDispatcher: isHighDownDispatcher,
  15058. getHighlightDigit: getHighlightDigit,
  15059. setLabelStyle: setLabelStyle,
  15060. modifyLabelStyle: modifyLabelStyle,
  15061. setTextStyle: setTextStyle,
  15062. setText: setText,
  15063. getFont: getFont,
  15064. updateProps: updateProps,
  15065. initProps: initProps,
  15066. getTransform: getTransform,
  15067. applyTransform: applyTransform$1,
  15068. transformDirection: transformDirection,
  15069. groupTransition: groupTransition,
  15070. clipPointsByRect: clipPointsByRect,
  15071. clipRectByRect: clipRectByRect,
  15072. createIcon: createIcon,
  15073. linePolygonIntersect: linePolygonIntersect,
  15074. lineLineIntersect: lineLineIntersect,
  15075. Group: Group,
  15076. Image: ZImage,
  15077. Text: Text,
  15078. Circle: Circle,
  15079. Sector: Sector,
  15080. Ring: Ring,
  15081. Polygon: Polygon,
  15082. Polyline: Polyline,
  15083. Rect: Rect,
  15084. Line: Line,
  15085. BezierCurve: BezierCurve,
  15086. Arc: Arc,
  15087. IncrementalDisplayable: IncrementalDisplayble,
  15088. CompoundPath: CompoundPath,
  15089. LinearGradient: LinearGradient,
  15090. RadialGradient: RadialGradient,
  15091. BoundingRect: BoundingRect
  15092. });
  15093. /*
  15094. * Licensed to the Apache Software Foundation (ASF) under one
  15095. * or more contributor license agreements. See the NOTICE file
  15096. * distributed with this work for additional information
  15097. * regarding copyright ownership. The ASF licenses this file
  15098. * to you under the Apache License, Version 2.0 (the
  15099. * "License"); you may not use this file except in compliance
  15100. * with the License. You may obtain a copy of the License at
  15101. *
  15102. * http://www.apache.org/licenses/LICENSE-2.0
  15103. *
  15104. * Unless required by applicable law or agreed to in writing,
  15105. * software distributed under the License is distributed on an
  15106. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15107. * KIND, either express or implied. See the License for the
  15108. * specific language governing permissions and limitations
  15109. * under the License.
  15110. */
  15111. var PATH_COLOR = ['textStyle', 'color'];
  15112. var textStyleMixin = {
  15113. /**
  15114. * Get color property or get color from option.textStyle.color
  15115. * @param {boolean} [isEmphasis]
  15116. * @return {string}
  15117. */
  15118. getTextColor: function (isEmphasis) {
  15119. var ecModel = this.ecModel;
  15120. return this.getShallow('color') || (!isEmphasis && ecModel ? ecModel.get(PATH_COLOR) : null);
  15121. },
  15122. /**
  15123. * Create font string from fontStyle, fontWeight, fontSize, fontFamily
  15124. * @return {string}
  15125. */
  15126. getFont: function () {
  15127. return getFont({
  15128. fontStyle: this.getShallow('fontStyle'),
  15129. fontWeight: this.getShallow('fontWeight'),
  15130. fontSize: this.getShallow('fontSize'),
  15131. fontFamily: this.getShallow('fontFamily')
  15132. }, this.ecModel);
  15133. },
  15134. getTextRect: function (text) {
  15135. return getBoundingRect(text, this.getFont(), this.getShallow('align'), this.getShallow('verticalAlign') || this.getShallow('baseline'), this.getShallow('padding'), this.getShallow('lineHeight'), this.getShallow('rich'), this.getShallow('truncateText'));
  15136. }
  15137. };
  15138. /*
  15139. * Licensed to the Apache Software Foundation (ASF) under one
  15140. * or more contributor license agreements. See the NOTICE file
  15141. * distributed with this work for additional information
  15142. * regarding copyright ownership. The ASF licenses this file
  15143. * to you under the Apache License, Version 2.0 (the
  15144. * "License"); you may not use this file except in compliance
  15145. * with the License. You may obtain a copy of the License at
  15146. *
  15147. * http://www.apache.org/licenses/LICENSE-2.0
  15148. *
  15149. * Unless required by applicable law or agreed to in writing,
  15150. * software distributed under the License is distributed on an
  15151. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15152. * KIND, either express or implied. See the License for the
  15153. * specific language governing permissions and limitations
  15154. * under the License.
  15155. */
  15156. var getItemStyle = makeStyleMapper([['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['textPosition'], ['textAlign']]);
  15157. var itemStyleMixin = {
  15158. getItemStyle: function (excludes, includes) {
  15159. var style = getItemStyle(this, excludes, includes);
  15160. var lineDash = this.getBorderLineDash();
  15161. lineDash && (style.lineDash = lineDash);
  15162. return style;
  15163. },
  15164. getBorderLineDash: function () {
  15165. var lineType = this.get('borderType');
  15166. return lineType === 'solid' || lineType == null ? null : lineType === 'dashed' ? [5, 5] : [1, 1];
  15167. }
  15168. };
  15169. /*
  15170. * Licensed to the Apache Software Foundation (ASF) under one
  15171. * or more contributor license agreements. See the NOTICE file
  15172. * distributed with this work for additional information
  15173. * regarding copyright ownership. The ASF licenses this file
  15174. * to you under the Apache License, Version 2.0 (the
  15175. * "License"); you may not use this file except in compliance
  15176. * with the License. You may obtain a copy of the License at
  15177. *
  15178. * http://www.apache.org/licenses/LICENSE-2.0
  15179. *
  15180. * Unless required by applicable law or agreed to in writing,
  15181. * software distributed under the License is distributed on an
  15182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15183. * KIND, either express or implied. See the License for the
  15184. * specific language governing permissions and limitations
  15185. * under the License.
  15186. */
  15187. /**
  15188. * @module echarts/model/Model
  15189. */
  15190. var mixin$1 = mixin;
  15191. var inner = makeInner();
  15192. /**
  15193. * @alias module:echarts/model/Model
  15194. * @constructor
  15195. * @param {Object} [option]
  15196. * @param {module:echarts/model/Model} [parentModel]
  15197. * @param {module:echarts/model/Global} [ecModel]
  15198. */
  15199. function Model(option, parentModel, ecModel) {
  15200. /**
  15201. * @type {module:echarts/model/Model}
  15202. * @readOnly
  15203. */
  15204. this.parentModel = parentModel;
  15205. /**
  15206. * @type {module:echarts/model/Global}
  15207. * @readOnly
  15208. */
  15209. this.ecModel = ecModel;
  15210. /**
  15211. * @type {Object}
  15212. * @protected
  15213. */
  15214. this.option = option; // Simple optimization
  15215. // if (this.init) {
  15216. // if (arguments.length <= 4) {
  15217. // this.init(option, parentModel, ecModel, extraOpt);
  15218. // }
  15219. // else {
  15220. // this.init.apply(this, arguments);
  15221. // }
  15222. // }
  15223. }
  15224. Model.prototype = {
  15225. constructor: Model,
  15226. /**
  15227. * Model 的初始化函数
  15228. * @param {Object} option
  15229. */
  15230. init: null,
  15231. /**
  15232. * 从新的 Option merge
  15233. */
  15234. mergeOption: function (option) {
  15235. merge(this.option, option, true);
  15236. },
  15237. /**
  15238. * @param {string|Array.<string>} path
  15239. * @param {boolean} [ignoreParent=false]
  15240. * @return {*}
  15241. */
  15242. get: function (path, ignoreParent) {
  15243. if (path == null) {
  15244. return this.option;
  15245. }
  15246. return doGet(this.option, this.parsePath(path), !ignoreParent && getParent(this, path));
  15247. },
  15248. /**
  15249. * @param {string} key
  15250. * @param {boolean} [ignoreParent=false]
  15251. * @return {*}
  15252. */
  15253. getShallow: function (key, ignoreParent) {
  15254. var option = this.option;
  15255. var val = option == null ? option : option[key];
  15256. var parentModel = !ignoreParent && getParent(this, key);
  15257. if (val == null && parentModel) {
  15258. val = parentModel.getShallow(key);
  15259. }
  15260. return val;
  15261. },
  15262. /**
  15263. * @param {string|Array.<string>} [path]
  15264. * @param {module:echarts/model/Model} [parentModel]
  15265. * @return {module:echarts/model/Model}
  15266. */
  15267. getModel: function (path, parentModel) {
  15268. var obj = path == null ? this.option : doGet(this.option, path = this.parsePath(path));
  15269. var thisParentModel;
  15270. parentModel = parentModel || (thisParentModel = getParent(this, path)) && thisParentModel.getModel(path);
  15271. return new Model(obj, parentModel, this.ecModel);
  15272. },
  15273. /**
  15274. * If model has option
  15275. */
  15276. isEmpty: function () {
  15277. return this.option == null;
  15278. },
  15279. restoreData: function () {},
  15280. // Pending
  15281. clone: function () {
  15282. var Ctor = this.constructor;
  15283. return new Ctor(clone(this.option));
  15284. },
  15285. setReadOnly: function (properties) {// clazzUtil.setReadOnly(this, properties);
  15286. },
  15287. // If path is null/undefined, return null/undefined.
  15288. parsePath: function (path) {
  15289. if (typeof path === 'string') {
  15290. path = path.split('.');
  15291. }
  15292. return path;
  15293. },
  15294. /**
  15295. * @param {Function} getParentMethod
  15296. * param {Array.<string>|string} path
  15297. * return {module:echarts/model/Model}
  15298. */
  15299. customizeGetParent: function (getParentMethod) {
  15300. inner(this).getParent = getParentMethod;
  15301. },
  15302. isAnimationEnabled: function () {
  15303. if (!env$1.node) {
  15304. if (this.option.animation != null) {
  15305. return !!this.option.animation;
  15306. } else if (this.parentModel) {
  15307. return this.parentModel.isAnimationEnabled();
  15308. }
  15309. }
  15310. }
  15311. };
  15312. function doGet(obj, pathArr, parentModel) {
  15313. for (var i = 0; i < pathArr.length; i++) {
  15314. // Ignore empty
  15315. if (!pathArr[i]) {
  15316. continue;
  15317. } // obj could be number/string/... (like 0)
  15318. obj = obj && typeof obj === 'object' ? obj[pathArr[i]] : null;
  15319. if (obj == null) {
  15320. break;
  15321. }
  15322. }
  15323. if (obj == null && parentModel) {
  15324. obj = parentModel.get(pathArr);
  15325. }
  15326. return obj;
  15327. } // `path` can be null/undefined
  15328. function getParent(model, path) {
  15329. var getParentMethod = inner(model).getParent;
  15330. return getParentMethod ? getParentMethod.call(model, path) : model.parentModel;
  15331. } // Enable Model.extend.
  15332. enableClassExtend(Model);
  15333. enableClassCheck(Model);
  15334. mixin$1(Model, lineStyleMixin);
  15335. mixin$1(Model, areaStyleMixin);
  15336. mixin$1(Model, textStyleMixin);
  15337. mixin$1(Model, itemStyleMixin);
  15338. /*
  15339. * Licensed to the Apache Software Foundation (ASF) under one
  15340. * or more contributor license agreements. See the NOTICE file
  15341. * distributed with this work for additional information
  15342. * regarding copyright ownership. The ASF licenses this file
  15343. * to you under the Apache License, Version 2.0 (the
  15344. * "License"); you may not use this file except in compliance
  15345. * with the License. You may obtain a copy of the License at
  15346. *
  15347. * http://www.apache.org/licenses/LICENSE-2.0
  15348. *
  15349. * Unless required by applicable law or agreed to in writing,
  15350. * software distributed under the License is distributed on an
  15351. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15352. * KIND, either express or implied. See the License for the
  15353. * specific language governing permissions and limitations
  15354. * under the License.
  15355. */
  15356. var base = 0;
  15357. /**
  15358. * @public
  15359. * @param {string} type
  15360. * @return {string}
  15361. */
  15362. function getUID(type) {
  15363. // Considering the case of crossing js context,
  15364. // use Math.random to make id as unique as possible.
  15365. return [type || '', base++, Math.random().toFixed(5)].join('_');
  15366. }
  15367. /**
  15368. * @inner
  15369. */
  15370. function enableSubTypeDefaulter(entity) {
  15371. var subTypeDefaulters = {};
  15372. entity.registerSubTypeDefaulter = function (componentType, defaulter) {
  15373. componentType = parseClassType$1(componentType);
  15374. subTypeDefaulters[componentType.main] = defaulter;
  15375. };
  15376. entity.determineSubType = function (componentType, option) {
  15377. var type = option.type;
  15378. if (!type) {
  15379. var componentTypeMain = parseClassType$1(componentType).main;
  15380. if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) {
  15381. type = subTypeDefaulters[componentTypeMain](option);
  15382. }
  15383. }
  15384. return type;
  15385. };
  15386. return entity;
  15387. }
  15388. /**
  15389. * Topological travel on Activity Network (Activity On Vertices).
  15390. * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis'].
  15391. *
  15392. * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology.
  15393. *
  15394. * If there is circle dependencey, Error will be thrown.
  15395. *
  15396. */
  15397. function enableTopologicalTravel(entity, dependencyGetter) {
  15398. /**
  15399. * @public
  15400. * @param {Array.<string>} targetNameList Target Component type list.
  15401. * Can be ['aa', 'bb', 'aa.xx']
  15402. * @param {Array.<string>} fullNameList By which we can build dependency graph.
  15403. * @param {Function} callback Params: componentType, dependencies.
  15404. * @param {Object} context Scope of callback.
  15405. */
  15406. entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) {
  15407. if (!targetNameList.length) {
  15408. return;
  15409. }
  15410. var result = makeDepndencyGraph(fullNameList);
  15411. var graph = result.graph;
  15412. var stack = result.noEntryList;
  15413. var targetNameSet = {};
  15414. each$1(targetNameList, function (name) {
  15415. targetNameSet[name] = true;
  15416. });
  15417. while (stack.length) {
  15418. var currComponentType = stack.pop();
  15419. var currVertex = graph[currComponentType];
  15420. var isInTargetNameSet = !!targetNameSet[currComponentType];
  15421. if (isInTargetNameSet) {
  15422. callback.call(context, currComponentType, currVertex.originalDeps.slice());
  15423. delete targetNameSet[currComponentType];
  15424. }
  15425. each$1(currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge);
  15426. }
  15427. each$1(targetNameSet, function () {
  15428. throw new Error('Circle dependency may exists');
  15429. });
  15430. function removeEdge(succComponentType) {
  15431. graph[succComponentType].entryCount--;
  15432. if (graph[succComponentType].entryCount === 0) {
  15433. stack.push(succComponentType);
  15434. }
  15435. } // Consider this case: legend depends on series, and we call
  15436. // chart.setOption({series: [...]}), where only series is in option.
  15437. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will
  15438. // not be called, but only sereis.mergeOption is called. Thus legend
  15439. // have no chance to update its local record about series (like which
  15440. // name of series is available in legend).
  15441. function removeEdgeAndAdd(succComponentType) {
  15442. targetNameSet[succComponentType] = true;
  15443. removeEdge(succComponentType);
  15444. }
  15445. };
  15446. /**
  15447. * DepndencyGraph: {Object}
  15448. * key: conponentType,
  15449. * value: {
  15450. * successor: [conponentTypes...],
  15451. * originalDeps: [conponentTypes...],
  15452. * entryCount: {number}
  15453. * }
  15454. */
  15455. function makeDepndencyGraph(fullNameList) {
  15456. var graph = {};
  15457. var noEntryList = [];
  15458. each$1(fullNameList, function (name) {
  15459. var thisItem = createDependencyGraphItem(graph, name);
  15460. var originalDeps = thisItem.originalDeps = dependencyGetter(name);
  15461. var availableDeps = getAvailableDependencies(originalDeps, fullNameList);
  15462. thisItem.entryCount = availableDeps.length;
  15463. if (thisItem.entryCount === 0) {
  15464. noEntryList.push(name);
  15465. }
  15466. each$1(availableDeps, function (dependentName) {
  15467. if (indexOf(thisItem.predecessor, dependentName) < 0) {
  15468. thisItem.predecessor.push(dependentName);
  15469. }
  15470. var thatItem = createDependencyGraphItem(graph, dependentName);
  15471. if (indexOf(thatItem.successor, dependentName) < 0) {
  15472. thatItem.successor.push(name);
  15473. }
  15474. });
  15475. });
  15476. return {
  15477. graph: graph,
  15478. noEntryList: noEntryList
  15479. };
  15480. }
  15481. function createDependencyGraphItem(graph, name) {
  15482. if (!graph[name]) {
  15483. graph[name] = {
  15484. predecessor: [],
  15485. successor: []
  15486. };
  15487. }
  15488. return graph[name];
  15489. }
  15490. function getAvailableDependencies(originalDeps, fullNameList) {
  15491. var availableDeps = [];
  15492. each$1(originalDeps, function (dep) {
  15493. indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep);
  15494. });
  15495. return availableDeps;
  15496. }
  15497. }
  15498. /*
  15499. * Licensed to the Apache Software Foundation (ASF) under one
  15500. * or more contributor license agreements. See the NOTICE file
  15501. * distributed with this work for additional information
  15502. * regarding copyright ownership. The ASF licenses this file
  15503. * to you under the Apache License, Version 2.0 (the
  15504. * "License"); you may not use this file except in compliance
  15505. * with the License. You may obtain a copy of the License at
  15506. *
  15507. * http://www.apache.org/licenses/LICENSE-2.0
  15508. *
  15509. * Unless required by applicable law or agreed to in writing,
  15510. * software distributed under the License is distributed on an
  15511. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15512. * KIND, either express or implied. See the License for the
  15513. * specific language governing permissions and limitations
  15514. * under the License.
  15515. */
  15516. /*
  15517. * A third-party license is embeded for some of the code in this file:
  15518. * The method "quantile" was copied from "d3.js".
  15519. * (See more details in the comment of the method below.)
  15520. * The use of the source code of this file is also subject to the terms
  15521. * and consitions of the license of "d3.js" (BSD-3Clause, see
  15522. * </licenses/LICENSE-d3>).
  15523. */
  15524. var RADIAN_EPSILON = 1e-4;
  15525. function _trim(str) {
  15526. return str.replace(/^\s+|\s+$/g, '');
  15527. }
  15528. /**
  15529. * Linear mapping a value from domain to range
  15530. * @memberOf module:echarts/util/number
  15531. * @param {(number|Array.<number>)} val
  15532. * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1]
  15533. * @param {Array.<number>} range Range extent range[0] can be bigger than range[1]
  15534. * @param {boolean} clamp
  15535. * @return {(number|Array.<number>}
  15536. */
  15537. function linearMap(val, domain, range, clamp) {
  15538. var subDomain = domain[1] - domain[0];
  15539. var subRange = range[1] - range[0];
  15540. if (subDomain === 0) {
  15541. return subRange === 0 ? range[0] : (range[0] + range[1]) / 2;
  15542. } // Avoid accuracy problem in edge, such as
  15543. // 146.39 - 62.83 === 83.55999999999999.
  15544. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError
  15545. // It is a little verbose for efficiency considering this method
  15546. // is a hotspot.
  15547. if (clamp) {
  15548. if (subDomain > 0) {
  15549. if (val <= domain[0]) {
  15550. return range[0];
  15551. } else if (val >= domain[1]) {
  15552. return range[1];
  15553. }
  15554. } else {
  15555. if (val >= domain[0]) {
  15556. return range[0];
  15557. } else if (val <= domain[1]) {
  15558. return range[1];
  15559. }
  15560. }
  15561. } else {
  15562. if (val === domain[0]) {
  15563. return range[0];
  15564. }
  15565. if (val === domain[1]) {
  15566. return range[1];
  15567. }
  15568. }
  15569. return (val - domain[0]) / subDomain * subRange + range[0];
  15570. }
  15571. /**
  15572. * Convert a percent string to absolute number.
  15573. * Returns NaN if percent is not a valid string or number
  15574. * @memberOf module:echarts/util/number
  15575. * @param {string|number} percent
  15576. * @param {number} all
  15577. * @return {number}
  15578. */
  15579. function parsePercent$1(percent, all) {
  15580. switch (percent) {
  15581. case 'center':
  15582. case 'middle':
  15583. percent = '50%';
  15584. break;
  15585. case 'left':
  15586. case 'top':
  15587. percent = '0%';
  15588. break;
  15589. case 'right':
  15590. case 'bottom':
  15591. percent = '100%';
  15592. break;
  15593. }
  15594. if (typeof percent === 'string') {
  15595. if (_trim(percent).match(/%$/)) {
  15596. return parseFloat(percent) / 100 * all;
  15597. }
  15598. return parseFloat(percent);
  15599. }
  15600. return percent == null ? NaN : +percent;
  15601. }
  15602. /**
  15603. * (1) Fix rounding error of float numbers.
  15604. * (2) Support return string to avoid scientific notation like '3.5e-7'.
  15605. *
  15606. * @param {number} x
  15607. * @param {number} [precision]
  15608. * @param {boolean} [returnStr]
  15609. * @return {number|string}
  15610. */
  15611. function round$1(x, precision, returnStr) {
  15612. if (precision == null) {
  15613. precision = 10;
  15614. } // Avoid range error
  15615. precision = Math.min(Math.max(0, precision), 20);
  15616. x = (+x).toFixed(precision);
  15617. return returnStr ? x : +x;
  15618. }
  15619. /**
  15620. * asc sort arr.
  15621. * The input arr will be modified.
  15622. *
  15623. * @param {Array} arr
  15624. * @return {Array} The input arr.
  15625. */
  15626. function asc(arr) {
  15627. arr.sort(function (a, b) {
  15628. return a - b;
  15629. });
  15630. return arr;
  15631. }
  15632. /**
  15633. * Get precision
  15634. * @param {number} val
  15635. */
  15636. function getPrecision(val) {
  15637. val = +val;
  15638. if (isNaN(val)) {
  15639. return 0;
  15640. } // It is much faster than methods converting number to string as follows
  15641. // var tmp = val.toString();
  15642. // return tmp.length - 1 - tmp.indexOf('.');
  15643. // especially when precision is low
  15644. var e = 1;
  15645. var count = 0;
  15646. while (Math.round(val * e) / e !== val) {
  15647. e *= 10;
  15648. count++;
  15649. }
  15650. return count;
  15651. }
  15652. /**
  15653. * @param {string|number} val
  15654. * @return {number}
  15655. */
  15656. function getPrecisionSafe(val) {
  15657. var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12'
  15658. var eIndex = str.indexOf('e');
  15659. if (eIndex > 0) {
  15660. var precision = +str.slice(eIndex + 1);
  15661. return precision < 0 ? -precision : 0;
  15662. } else {
  15663. var dotIndex = str.indexOf('.');
  15664. return dotIndex < 0 ? 0 : str.length - 1 - dotIndex;
  15665. }
  15666. }
  15667. /**
  15668. * Minimal dicernible data precisioin according to a single pixel.
  15669. *
  15670. * @param {Array.<number>} dataExtent
  15671. * @param {Array.<number>} pixelExtent
  15672. * @return {number} precision
  15673. */
  15674. function getPixelPrecision(dataExtent, pixelExtent) {
  15675. var log = Math.log;
  15676. var LN10 = Math.LN10;
  15677. var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10);
  15678. var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20.
  15679. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20);
  15680. return !isFinite(precision) ? 20 : precision;
  15681. }
  15682. /**
  15683. * Get a data of given precision, assuring the sum of percentages
  15684. * in valueList is 1.
  15685. * The largest remainer method is used.
  15686. * https://en.wikipedia.org/wiki/Largest_remainder_method
  15687. *
  15688. * @param {Array.<number>} valueList a list of all data
  15689. * @param {number} idx index of the data to be processed in valueList
  15690. * @param {number} precision integer number showing digits of precision
  15691. * @return {number} percent ranging from 0 to 100
  15692. */
  15693. function getPercentWithPrecision(valueList, idx, precision) {
  15694. if (!valueList[idx]) {
  15695. return 0;
  15696. }
  15697. var sum = reduce(valueList, function (acc, val) {
  15698. return acc + (isNaN(val) ? 0 : val);
  15699. }, 0);
  15700. if (sum === 0) {
  15701. return 0;
  15702. }
  15703. var digits = Math.pow(10, precision);
  15704. var votesPerQuota = map(valueList, function (val) {
  15705. return (isNaN(val) ? 0 : val) / sum * digits * 100;
  15706. });
  15707. var targetSeats = digits * 100;
  15708. var seats = map(votesPerQuota, function (votes) {
  15709. // Assign automatic seats.
  15710. return Math.floor(votes);
  15711. });
  15712. var currentSum = reduce(seats, function (acc, val) {
  15713. return acc + val;
  15714. }, 0);
  15715. var remainder = map(votesPerQuota, function (votes, idx) {
  15716. return votes - seats[idx];
  15717. }); // Has remainding votes.
  15718. while (currentSum < targetSeats) {
  15719. // Find next largest remainder.
  15720. var max = Number.NEGATIVE_INFINITY;
  15721. var maxId = null;
  15722. for (var i = 0, len = remainder.length; i < len; ++i) {
  15723. if (remainder[i] > max) {
  15724. max = remainder[i];
  15725. maxId = i;
  15726. }
  15727. } // Add a vote to max remainder.
  15728. ++seats[maxId];
  15729. remainder[maxId] = 0;
  15730. ++currentSum;
  15731. }
  15732. return seats[idx] / digits;
  15733. } // Number.MAX_SAFE_INTEGER, ie do not support.
  15734. var MAX_SAFE_INTEGER = 9007199254740991;
  15735. /**
  15736. * To 0 - 2 * PI, considering negative radian.
  15737. * @param {number} radian
  15738. * @return {number}
  15739. */
  15740. function remRadian(radian) {
  15741. var pi2 = Math.PI * 2;
  15742. return (radian % pi2 + pi2) % pi2;
  15743. }
  15744. /**
  15745. * @param {type} radian
  15746. * @return {boolean}
  15747. */
  15748. function isRadianAroundZero(val) {
  15749. return val > -RADIAN_EPSILON && val < RADIAN_EPSILON;
  15750. }
  15751. /* eslint-disable */
  15752. 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
  15753. /* eslint-enable */
  15754. /**
  15755. * @param {string|Date|number} value These values can be accepted:
  15756. * + An instance of Date, represent a time in its own time zone.
  15757. * + Or string in a subset of ISO 8601, only including:
  15758. * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06',
  15759. * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123',
  15760. * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00',
  15761. * all of which will be treated as local time if time zone is not specified
  15762. * (see <https://momentjs.com/>).
  15763. * + Or other string format, including (all of which will be treated as loacal time):
  15764. * '2012', '2012-3-1', '2012/3/1', '2012/03/01',
  15765. * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123'
  15766. * + a timestamp, which represent a time in UTC.
  15767. * @return {Date} date
  15768. */
  15769. function parseDate(value) {
  15770. if (value instanceof Date) {
  15771. return value;
  15772. } else if (typeof value === 'string') {
  15773. // Different browsers parse date in different way, so we parse it manually.
  15774. // Some other issues:
  15775. // new Date('1970-01-01') is UTC,
  15776. // new Date('1970/01/01') and new Date('1970-1-01') is local.
  15777. // See issue #3623
  15778. var match = TIME_REG.exec(value);
  15779. if (!match) {
  15780. // return Invalid Date.
  15781. return new Date(NaN);
  15782. } // Use local time when no timezone offset specifed.
  15783. if (!match[8]) {
  15784. // match[n] can only be string or undefined.
  15785. // But take care of '12' + 1 => '121'.
  15786. return new Date(+match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0);
  15787. } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time,
  15788. // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment).
  15789. // For example, system timezone is set as "Time Zone: America/Toronto",
  15790. // then these code will get different result:
  15791. // `new Date(1478411999999).getTimezoneOffset(); // get 240`
  15792. // `new Date(1478412000000).getTimezoneOffset(); // get 300`
  15793. // So we should not use `new Date`, but use `Date.UTC`.
  15794. else {
  15795. var hour = +match[4] || 0;
  15796. if (match[8].toUpperCase() !== 'Z') {
  15797. hour -= match[8].slice(0, 3);
  15798. }
  15799. return new Date(Date.UTC(+match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0));
  15800. }
  15801. } else if (value == null) {
  15802. return new Date(NaN);
  15803. }
  15804. return new Date(Math.round(value));
  15805. }
  15806. /**
  15807. * Quantity of a number. e.g. 0.1, 1, 10, 100
  15808. *
  15809. * @param {number} val
  15810. * @return {number}
  15811. */
  15812. function quantity(val) {
  15813. return Math.pow(10, quantityExponent(val));
  15814. }
  15815. /**
  15816. * Exponent of the quantity of a number
  15817. * e.g., 1234 equals to 1.234*10^3, so quantityExponent(1234) is 3
  15818. *
  15819. * @param {number} val non-negative value
  15820. * @return {number}
  15821. */
  15822. function quantityExponent(val) {
  15823. if (val === 0) {
  15824. return 0;
  15825. }
  15826. var exp = Math.floor(Math.log(val) / Math.LN10);
  15827. /**
  15828. * exp is expected to be the rounded-down result of the base-10 log of val.
  15829. * But due to the precision loss with Math.log(val), we need to restore it
  15830. * using 10^exp to make sure we can get val back from exp. #11249
  15831. */
  15832. if (val / Math.pow(10, exp) >= 10) {
  15833. exp++;
  15834. }
  15835. return exp;
  15836. }
  15837. /**
  15838. * find a “nice” number approximately equal to x. Round the number if round = true,
  15839. * take ceiling if round = false. The primary observation is that the “nicest”
  15840. * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers.
  15841. *
  15842. * See "Nice Numbers for Graph Labels" of Graphic Gems.
  15843. *
  15844. * @param {number} val Non-negative value.
  15845. * @param {boolean} round
  15846. * @return {number}
  15847. */
  15848. function nice(val, round) {
  15849. var exponent = quantityExponent(val);
  15850. var exp10 = Math.pow(10, exponent);
  15851. var f = val / exp10; // 1 <= f < 10
  15852. var nf;
  15853. if (round) {
  15854. if (f < 1.5) {
  15855. nf = 1;
  15856. } else if (f < 2.5) {
  15857. nf = 2;
  15858. } else if (f < 4) {
  15859. nf = 3;
  15860. } else if (f < 7) {
  15861. nf = 5;
  15862. } else {
  15863. nf = 10;
  15864. }
  15865. } else {
  15866. if (f < 1) {
  15867. nf = 1;
  15868. } else if (f < 2) {
  15869. nf = 2;
  15870. } else if (f < 3) {
  15871. nf = 3;
  15872. } else if (f < 5) {
  15873. nf = 5;
  15874. } else {
  15875. nf = 10;
  15876. }
  15877. }
  15878. val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754).
  15879. // 20 is the uppper bound of toFixed.
  15880. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val;
  15881. }
  15882. /**
  15883. * This code was copied from "d3.js"
  15884. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/arrays/quantile.js>.
  15885. * See the license statement at the head of this file.
  15886. * @param {Array.<number>} ascArr
  15887. */
  15888. function quantile(ascArr, p) {
  15889. var H = (ascArr.length - 1) * p + 1;
  15890. var h = Math.floor(H);
  15891. var v = +ascArr[h - 1];
  15892. var e = H - h;
  15893. return e ? v + e * (ascArr[h] - v) : v;
  15894. }
  15895. /**
  15896. * Order intervals asc, and split them when overlap.
  15897. * expect(numberUtil.reformIntervals([
  15898. * {interval: [18, 62], close: [1, 1]},
  15899. * {interval: [-Infinity, -70], close: [0, 0]},
  15900. * {interval: [-70, -26], close: [1, 1]},
  15901. * {interval: [-26, 18], close: [1, 1]},
  15902. * {interval: [62, 150], close: [1, 1]},
  15903. * {interval: [106, 150], close: [1, 1]},
  15904. * {interval: [150, Infinity], close: [0, 0]}
  15905. * ])).toEqual([
  15906. * {interval: [-Infinity, -70], close: [0, 0]},
  15907. * {interval: [-70, -26], close: [1, 1]},
  15908. * {interval: [-26, 18], close: [0, 1]},
  15909. * {interval: [18, 62], close: [0, 1]},
  15910. * {interval: [62, 150], close: [0, 1]},
  15911. * {interval: [150, Infinity], close: [0, 0]}
  15912. * ]);
  15913. * @param {Array.<Object>} list, where `close` mean open or close
  15914. * of the interval, and Infinity can be used.
  15915. * @return {Array.<Object>} The origin list, which has been reformed.
  15916. */
  15917. function reformIntervals(list) {
  15918. list.sort(function (a, b) {
  15919. return littleThan(a, b, 0) ? -1 : 1;
  15920. });
  15921. var curr = -Infinity;
  15922. var currClose = 1;
  15923. for (var i = 0; i < list.length;) {
  15924. var interval = list[i].interval;
  15925. var close = list[i].close;
  15926. for (var lg = 0; lg < 2; lg++) {
  15927. if (interval[lg] <= curr) {
  15928. interval[lg] = curr;
  15929. close[lg] = !lg ? 1 - currClose : 1;
  15930. }
  15931. curr = interval[lg];
  15932. currClose = close[lg];
  15933. }
  15934. if (interval[0] === interval[1] && close[0] * close[1] !== 1) {
  15935. list.splice(i, 1);
  15936. } else {
  15937. i++;
  15938. }
  15939. }
  15940. return list;
  15941. function littleThan(a, b, lg) {
  15942. return a.interval[lg] < b.interval[lg] || a.interval[lg] === b.interval[lg] && (a.close[lg] - b.close[lg] === (!lg ? 1 : -1) || !lg && littleThan(a, b, 1));
  15943. }
  15944. }
  15945. /**
  15946. * parseFloat NaNs numeric-cast false positives (null|true|false|"")
  15947. * ...but misinterprets leading-number strings, particularly hex literals ("0x...")
  15948. * subtraction forces infinities to NaN
  15949. *
  15950. * @param {*} v
  15951. * @return {boolean}
  15952. */
  15953. function isNumeric(v) {
  15954. return v - parseFloat(v) >= 0;
  15955. }
  15956. var number = (Object.freeze || Object)({
  15957. linearMap: linearMap,
  15958. parsePercent: parsePercent$1,
  15959. round: round$1,
  15960. asc: asc,
  15961. getPrecision: getPrecision,
  15962. getPrecisionSafe: getPrecisionSafe,
  15963. getPixelPrecision: getPixelPrecision,
  15964. getPercentWithPrecision: getPercentWithPrecision,
  15965. MAX_SAFE_INTEGER: MAX_SAFE_INTEGER,
  15966. remRadian: remRadian,
  15967. isRadianAroundZero: isRadianAroundZero,
  15968. parseDate: parseDate,
  15969. quantity: quantity,
  15970. quantityExponent: quantityExponent,
  15971. nice: nice,
  15972. quantile: quantile,
  15973. reformIntervals: reformIntervals,
  15974. isNumeric: isNumeric
  15975. });
  15976. /*
  15977. * Licensed to the Apache Software Foundation (ASF) under one
  15978. * or more contributor license agreements. See the NOTICE file
  15979. * distributed with this work for additional information
  15980. * regarding copyright ownership. The ASF licenses this file
  15981. * to you under the Apache License, Version 2.0 (the
  15982. * "License"); you may not use this file except in compliance
  15983. * with the License. You may obtain a copy of the License at
  15984. *
  15985. * http://www.apache.org/licenses/LICENSE-2.0
  15986. *
  15987. * Unless required by applicable law or agreed to in writing,
  15988. * software distributed under the License is distributed on an
  15989. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  15990. * KIND, either express or implied. See the License for the
  15991. * specific language governing permissions and limitations
  15992. * under the License.
  15993. */
  15994. /**
  15995. * add commas after every three numbers
  15996. * @param {string|number} x
  15997. * @return {string}
  15998. */
  15999. function addCommas(x) {
  16000. if (isNaN(x)) {
  16001. return '-';
  16002. }
  16003. x = (x + '').split('.');
  16004. return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g, '$1,') + (x.length > 1 ? '.' + x[1] : '');
  16005. }
  16006. /**
  16007. * @param {string} str
  16008. * @param {boolean} [upperCaseFirst=false]
  16009. * @return {string} str
  16010. */
  16011. function toCamelCase(str, upperCaseFirst) {
  16012. str = (str || '').toLowerCase().replace(/-(.)/g, function (match, group1) {
  16013. return group1.toUpperCase();
  16014. });
  16015. if (upperCaseFirst && str) {
  16016. str = str.charAt(0).toUpperCase() + str.slice(1);
  16017. }
  16018. return str;
  16019. }
  16020. var normalizeCssArray$1 = normalizeCssArray;
  16021. var replaceReg = /([&<>"'])/g;
  16022. var replaceMap = {
  16023. '&': '&amp;',
  16024. '<': '&lt;',
  16025. '>': '&gt;',
  16026. '"': '&quot;',
  16027. '\'': '&#39;'
  16028. };
  16029. function encodeHTML(source) {
  16030. return source == null ? '' : (source + '').replace(replaceReg, function (str, c) {
  16031. return replaceMap[c];
  16032. });
  16033. }
  16034. var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
  16035. var wrapVar = function (varName, seriesIdx) {
  16036. return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}';
  16037. };
  16038. /**
  16039. * Template formatter
  16040. * @param {string} tpl
  16041. * @param {Array.<Object>|Object} paramsList
  16042. * @param {boolean} [encode=false]
  16043. * @return {string}
  16044. */
  16045. function formatTpl(tpl, paramsList, encode) {
  16046. if (!isArray(paramsList)) {
  16047. paramsList = [paramsList];
  16048. }
  16049. var seriesLen = paramsList.length;
  16050. if (!seriesLen) {
  16051. return '';
  16052. }
  16053. var $vars = paramsList[0].$vars || [];
  16054. for (var i = 0; i < $vars.length; i++) {
  16055. var alias = TPL_VAR_ALIAS[i];
  16056. tpl = tpl.replace(wrapVar(alias), wrapVar(alias, 0));
  16057. }
  16058. for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) {
  16059. for (var k = 0; k < $vars.length; k++) {
  16060. var val = paramsList[seriesIdx][$vars[k]];
  16061. tpl = tpl.replace(wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val);
  16062. }
  16063. }
  16064. return tpl;
  16065. }
  16066. /**
  16067. * simple Template formatter
  16068. *
  16069. * @param {string} tpl
  16070. * @param {Object} param
  16071. * @param {boolean} [encode=false]
  16072. * @return {string}
  16073. */
  16074. function formatTplSimple(tpl, param, encode) {
  16075. each$1(param, function (value, key) {
  16076. tpl = tpl.replace('{' + key + '}', encode ? encodeHTML(value) : value);
  16077. });
  16078. return tpl;
  16079. }
  16080. /**
  16081. * @param {Object|string} [opt] If string, means color.
  16082. * @param {string} [opt.color]
  16083. * @param {string} [opt.extraCssText]
  16084. * @param {string} [opt.type='item'] 'item' or 'subItem'
  16085. * @param {string} [opt.renderMode='html'] render mode of tooltip, 'html' or 'richText'
  16086. * @param {string} [opt.markerId='X'] id name for marker. If only one marker is in a rich text, this can be omitted.
  16087. * @return {string}
  16088. */
  16089. function getTooltipMarker(opt, extraCssText) {
  16090. opt = isString(opt) ? {
  16091. color: opt,
  16092. extraCssText: extraCssText
  16093. } : opt || {};
  16094. var color = opt.color;
  16095. var type = opt.type;
  16096. var extraCssText = opt.extraCssText;
  16097. var renderMode = opt.renderMode || 'html';
  16098. var markerId = opt.markerId || 'X';
  16099. if (!color) {
  16100. return '';
  16101. }
  16102. if (renderMode === 'html') {
  16103. return type === 'subItem' ? '<span style="display:inline-block;vertical-align:middle;margin-right:8px;margin-left:3px;' + 'border-radius:4px;width:4px;height:4px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : '<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:10px;height:10px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>';
  16104. } else {
  16105. // Space for rich element marker
  16106. return {
  16107. renderMode: renderMode,
  16108. content: '{marker' + markerId + '|} ',
  16109. style: {
  16110. color: color
  16111. }
  16112. };
  16113. }
  16114. }
  16115. function pad(str, len) {
  16116. str += '';
  16117. return '0000'.substr(0, len - str.length) + str;
  16118. }
  16119. /**
  16120. * ISO Date format
  16121. * @param {string} tpl
  16122. * @param {number} value
  16123. * @param {boolean} [isUTC=false] Default in local time.
  16124. * see `module:echarts/scale/Time`
  16125. * and `module:echarts/util/number#parseDate`.
  16126. * @inner
  16127. */
  16128. function formatTime(tpl, value, isUTC) {
  16129. if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year') {
  16130. tpl = 'MM-dd\nyyyy';
  16131. }
  16132. var date = parseDate(value);
  16133. var utc = isUTC ? 'UTC' : '';
  16134. var y = date['get' + utc + 'FullYear']();
  16135. var M = date['get' + utc + 'Month']() + 1;
  16136. var d = date['get' + utc + 'Date']();
  16137. var h = date['get' + utc + 'Hours']();
  16138. var m = date['get' + utc + 'Minutes']();
  16139. var s = date['get' + utc + 'Seconds']();
  16140. var S = date['get' + utc + 'Milliseconds']();
  16141. tpl = tpl.replace('MM', pad(M, 2)).replace('M', M).replace('yyyy', y).replace('yy', y % 100).replace('dd', pad(d, 2)).replace('d', d).replace('hh', pad(h, 2)).replace('h', h).replace('mm', pad(m, 2)).replace('m', m).replace('ss', pad(s, 2)).replace('s', s).replace('SSS', pad(S, 3));
  16142. return tpl;
  16143. }
  16144. /**
  16145. * Capital first
  16146. * @param {string} str
  16147. * @return {string}
  16148. */
  16149. function capitalFirst(str) {
  16150. return str ? str.charAt(0).toUpperCase() + str.substr(1) : str;
  16151. }
  16152. var truncateText$1 = truncateText;
  16153. /**
  16154. * @public
  16155. * @param {Object} opt
  16156. * @param {string} opt.text
  16157. * @param {string} opt.font
  16158. * @param {string} [opt.textAlign='left']
  16159. * @param {string} [opt.textVerticalAlign='top']
  16160. * @param {Array.<number>} [opt.textPadding]
  16161. * @param {number} [opt.textLineHeight]
  16162. * @param {Object} [opt.rich]
  16163. * @param {Object} [opt.truncate]
  16164. * @return {Object} {x, y, width, height, lineHeight}
  16165. */
  16166. function getTextBoundingRect(opt) {
  16167. return getBoundingRect(opt.text, opt.font, opt.textAlign, opt.textVerticalAlign, opt.textPadding, opt.textLineHeight, opt.rich, opt.truncate);
  16168. }
  16169. /**
  16170. * @deprecated
  16171. * the `textLineHeight` was added later.
  16172. * For backward compatiblility, put it as the last parameter.
  16173. * But deprecated this interface. Please use `getTextBoundingRect` instead.
  16174. */
  16175. function getTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate, textLineHeight) {
  16176. return getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, textLineHeight, rich, truncate);
  16177. }
  16178. /**
  16179. * open new tab
  16180. * @param {string} link url
  16181. * @param {string} target blank or self
  16182. */
  16183. function windowOpen(link, target) {
  16184. if (target === '_blank' || target === 'blank') {
  16185. var blank = window.open();
  16186. blank.opener = null;
  16187. blank.location = link;
  16188. } else {
  16189. window.open(link, target);
  16190. }
  16191. }
  16192. var format = (Object.freeze || Object)({
  16193. addCommas: addCommas,
  16194. toCamelCase: toCamelCase,
  16195. normalizeCssArray: normalizeCssArray$1,
  16196. encodeHTML: encodeHTML,
  16197. formatTpl: formatTpl,
  16198. formatTplSimple: formatTplSimple,
  16199. getTooltipMarker: getTooltipMarker,
  16200. formatTime: formatTime,
  16201. capitalFirst: capitalFirst,
  16202. truncateText: truncateText$1,
  16203. getTextBoundingRect: getTextBoundingRect,
  16204. getTextRect: getTextRect,
  16205. windowOpen: windowOpen
  16206. });
  16207. /*
  16208. * Licensed to the Apache Software Foundation (ASF) under one
  16209. * or more contributor license agreements. See the NOTICE file
  16210. * distributed with this work for additional information
  16211. * regarding copyright ownership. The ASF licenses this file
  16212. * to you under the Apache License, Version 2.0 (the
  16213. * "License"); you may not use this file except in compliance
  16214. * with the License. You may obtain a copy of the License at
  16215. *
  16216. * http://www.apache.org/licenses/LICENSE-2.0
  16217. *
  16218. * Unless required by applicable law or agreed to in writing,
  16219. * software distributed under the License is distributed on an
  16220. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16221. * KIND, either express or implied. See the License for the
  16222. * specific language governing permissions and limitations
  16223. * under the License.
  16224. */
  16225. // Layout helpers for each component positioning
  16226. var each$3 = each$1;
  16227. /**
  16228. * @public
  16229. */
  16230. var LOCATION_PARAMS = ['left', 'right', 'top', 'bottom', 'width', 'height'];
  16231. /**
  16232. * @public
  16233. */
  16234. var HV_NAMES = [['width', 'left', 'right'], ['height', 'top', 'bottom']];
  16235. function boxLayout(orient, group, gap, maxWidth, maxHeight) {
  16236. var x = 0;
  16237. var y = 0;
  16238. if (maxWidth == null) {
  16239. maxWidth = Infinity;
  16240. }
  16241. if (maxHeight == null) {
  16242. maxHeight = Infinity;
  16243. }
  16244. var currentLineMaxSize = 0;
  16245. group.eachChild(function (child, idx) {
  16246. var position = child.position;
  16247. var rect = child.getBoundingRect();
  16248. var nextChild = group.childAt(idx + 1);
  16249. var nextChildRect = nextChild && nextChild.getBoundingRect();
  16250. var nextX;
  16251. var nextY;
  16252. if (orient === 'horizontal') {
  16253. var moveX = rect.width + (nextChildRect ? -nextChildRect.x + rect.x : 0);
  16254. nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group
  16255. // FIXME compare before adding gap?
  16256. if (nextX > maxWidth || child.newline) {
  16257. x = 0;
  16258. nextX = moveX;
  16259. y += currentLineMaxSize + gap;
  16260. currentLineMaxSize = rect.height;
  16261. } else {
  16262. // FIXME: consider rect.y is not `0`?
  16263. currentLineMaxSize = Math.max(currentLineMaxSize, rect.height);
  16264. }
  16265. } else {
  16266. var moveY = rect.height + (nextChildRect ? -nextChildRect.y + rect.y : 0);
  16267. nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group
  16268. if (nextY > maxHeight || child.newline) {
  16269. x += currentLineMaxSize + gap;
  16270. y = 0;
  16271. nextY = moveY;
  16272. currentLineMaxSize = rect.width;
  16273. } else {
  16274. currentLineMaxSize = Math.max(currentLineMaxSize, rect.width);
  16275. }
  16276. }
  16277. if (child.newline) {
  16278. return;
  16279. }
  16280. position[0] = x;
  16281. position[1] = y;
  16282. orient === 'horizontal' ? x = nextX + gap : y = nextY + gap;
  16283. });
  16284. }
  16285. /**
  16286. * VBox or HBox layouting
  16287. * @param {string} orient
  16288. * @param {module:zrender/container/Group} group
  16289. * @param {number} gap
  16290. * @param {number} [width=Infinity]
  16291. * @param {number} [height=Infinity]
  16292. */
  16293. var box = boxLayout;
  16294. /**
  16295. * VBox layouting
  16296. * @param {module:zrender/container/Group} group
  16297. * @param {number} gap
  16298. * @param {number} [width=Infinity]
  16299. * @param {number} [height=Infinity]
  16300. */
  16301. var vbox = curry(boxLayout, 'vertical');
  16302. /**
  16303. * HBox layouting
  16304. * @param {module:zrender/container/Group} group
  16305. * @param {number} gap
  16306. * @param {number} [width=Infinity]
  16307. * @param {number} [height=Infinity]
  16308. */
  16309. var hbox = curry(boxLayout, 'horizontal');
  16310. /**
  16311. * If x or x2 is not specified or 'center' 'left' 'right',
  16312. * the width would be as long as possible.
  16313. * If y or y2 is not specified or 'middle' 'top' 'bottom',
  16314. * the height would be as long as possible.
  16315. *
  16316. * @param {Object} positionInfo
  16317. * @param {number|string} [positionInfo.x]
  16318. * @param {number|string} [positionInfo.y]
  16319. * @param {number|string} [positionInfo.x2]
  16320. * @param {number|string} [positionInfo.y2]
  16321. * @param {Object} containerRect {width, height}
  16322. * @param {string|number} margin
  16323. * @return {Object} {width, height}
  16324. */
  16325. function getAvailableSize(positionInfo, containerRect, margin) {
  16326. var containerWidth = containerRect.width;
  16327. var containerHeight = containerRect.height;
  16328. var x = parsePercent$1(positionInfo.x, containerWidth);
  16329. var y = parsePercent$1(positionInfo.y, containerHeight);
  16330. var x2 = parsePercent$1(positionInfo.x2, containerWidth);
  16331. var y2 = parsePercent$1(positionInfo.y2, containerHeight);
  16332. (isNaN(x) || isNaN(parseFloat(positionInfo.x))) && (x = 0);
  16333. (isNaN(x2) || isNaN(parseFloat(positionInfo.x2))) && (x2 = containerWidth);
  16334. (isNaN(y) || isNaN(parseFloat(positionInfo.y))) && (y = 0);
  16335. (isNaN(y2) || isNaN(parseFloat(positionInfo.y2))) && (y2 = containerHeight);
  16336. margin = normalizeCssArray$1(margin || 0);
  16337. return {
  16338. width: Math.max(x2 - x - margin[1] - margin[3], 0),
  16339. height: Math.max(y2 - y - margin[0] - margin[2], 0)
  16340. };
  16341. }
  16342. /**
  16343. * Parse position info.
  16344. *
  16345. * @param {Object} positionInfo
  16346. * @param {number|string} [positionInfo.left]
  16347. * @param {number|string} [positionInfo.top]
  16348. * @param {number|string} [positionInfo.right]
  16349. * @param {number|string} [positionInfo.bottom]
  16350. * @param {number|string} [positionInfo.width]
  16351. * @param {number|string} [positionInfo.height]
  16352. * @param {number|string} [positionInfo.aspect] Aspect is width / height
  16353. * @param {Object} containerRect
  16354. * @param {string|number} [margin]
  16355. *
  16356. * @return {module:zrender/core/BoundingRect}
  16357. */
  16358. function getLayoutRect(positionInfo, containerRect, margin) {
  16359. margin = normalizeCssArray$1(margin || 0);
  16360. var containerWidth = containerRect.width;
  16361. var containerHeight = containerRect.height;
  16362. var left = parsePercent$1(positionInfo.left, containerWidth);
  16363. var top = parsePercent$1(positionInfo.top, containerHeight);
  16364. var right = parsePercent$1(positionInfo.right, containerWidth);
  16365. var bottom = parsePercent$1(positionInfo.bottom, containerHeight);
  16366. var width = parsePercent$1(positionInfo.width, containerWidth);
  16367. var height = parsePercent$1(positionInfo.height, containerHeight);
  16368. var verticalMargin = margin[2] + margin[0];
  16369. var horizontalMargin = margin[1] + margin[3];
  16370. var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right
  16371. if (isNaN(width)) {
  16372. width = containerWidth - right - horizontalMargin - left;
  16373. }
  16374. if (isNaN(height)) {
  16375. height = containerHeight - bottom - verticalMargin - top;
  16376. }
  16377. if (aspect != null) {
  16378. // If width and height are not given
  16379. // 1. Graph should not exceeds the container
  16380. // 2. Aspect must be keeped
  16381. // 3. Graph should take the space as more as possible
  16382. // FIXME
  16383. // Margin is not considered, because there is no case that both
  16384. // using margin and aspect so far.
  16385. if (isNaN(width) && isNaN(height)) {
  16386. if (aspect > containerWidth / containerHeight) {
  16387. width = containerWidth * 0.8;
  16388. } else {
  16389. height = containerHeight * 0.8;
  16390. }
  16391. } // Calculate width or height with given aspect
  16392. if (isNaN(width)) {
  16393. width = aspect * height;
  16394. }
  16395. if (isNaN(height)) {
  16396. height = width / aspect;
  16397. }
  16398. } // If left is not specified, calculate left from right and width
  16399. if (isNaN(left)) {
  16400. left = containerWidth - right - width - horizontalMargin;
  16401. }
  16402. if (isNaN(top)) {
  16403. top = containerHeight - bottom - height - verticalMargin;
  16404. } // Align left and top
  16405. switch (positionInfo.left || positionInfo.right) {
  16406. case 'center':
  16407. left = containerWidth / 2 - width / 2 - margin[3];
  16408. break;
  16409. case 'right':
  16410. left = containerWidth - width - horizontalMargin;
  16411. break;
  16412. }
  16413. switch (positionInfo.top || positionInfo.bottom) {
  16414. case 'middle':
  16415. case 'center':
  16416. top = containerHeight / 2 - height / 2 - margin[0];
  16417. break;
  16418. case 'bottom':
  16419. top = containerHeight - height - verticalMargin;
  16420. break;
  16421. } // If something is wrong and left, top, width, height are calculated as NaN
  16422. left = left || 0;
  16423. top = top || 0;
  16424. if (isNaN(width)) {
  16425. // Width may be NaN if only one value is given except width
  16426. width = containerWidth - horizontalMargin - left - (right || 0);
  16427. }
  16428. if (isNaN(height)) {
  16429. // Height may be NaN if only one value is given except height
  16430. height = containerHeight - verticalMargin - top - (bottom || 0);
  16431. }
  16432. var rect = new BoundingRect(left + margin[3], top + margin[0], width, height);
  16433. rect.margin = margin;
  16434. return rect;
  16435. }
  16436. /**
  16437. * Position a zr element in viewport
  16438. * Group position is specified by either
  16439. * {left, top}, {right, bottom}
  16440. * If all properties exists, right and bottom will be igonred.
  16441. *
  16442. * Logic:
  16443. * 1. Scale (against origin point in parent coord)
  16444. * 2. Rotate (against origin point in parent coord)
  16445. * 3. Traslate (with el.position by this method)
  16446. * So this method only fixes the last step 'Traslate', which does not affect
  16447. * scaling and rotating.
  16448. *
  16449. * If be called repeatly with the same input el, the same result will be gotten.
  16450. *
  16451. * @param {module:zrender/Element} el Should have `getBoundingRect` method.
  16452. * @param {Object} positionInfo
  16453. * @param {number|string} [positionInfo.left]
  16454. * @param {number|string} [positionInfo.top]
  16455. * @param {number|string} [positionInfo.right]
  16456. * @param {number|string} [positionInfo.bottom]
  16457. * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw'
  16458. * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw'
  16459. * @param {Object} containerRect
  16460. * @param {string|number} margin
  16461. * @param {Object} [opt]
  16462. * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical.
  16463. * @param {Array.<number>} [opt.boundingMode='all']
  16464. * Specify how to calculate boundingRect when locating.
  16465. * 'all': Position the boundingRect that is transformed and uioned
  16466. * both itself and its descendants.
  16467. * This mode simplies confine the elements in the bounding
  16468. * of their container (e.g., using 'right: 0').
  16469. * 'raw': Position the boundingRect that is not transformed and only itself.
  16470. * This mode is useful when you want a element can overflow its
  16471. * container. (Consider a rotated circle needs to be located in a corner.)
  16472. * In this mode positionInfo.width/height can only be number.
  16473. */
  16474. function positionElement(el, positionInfo, containerRect, margin, opt) {
  16475. var h = !opt || !opt.hv || opt.hv[0];
  16476. var v = !opt || !opt.hv || opt.hv[1];
  16477. var boundingMode = opt && opt.boundingMode || 'all';
  16478. if (!h && !v) {
  16479. return;
  16480. }
  16481. var rect;
  16482. if (boundingMode === 'raw') {
  16483. rect = el.type === 'group' ? new BoundingRect(0, 0, +positionInfo.width || 0, +positionInfo.height || 0) : el.getBoundingRect();
  16484. } else {
  16485. rect = el.getBoundingRect();
  16486. if (el.needLocalTransform()) {
  16487. var transform = el.getLocalTransform(); // Notice: raw rect may be inner object of el,
  16488. // which should not be modified.
  16489. rect = rect.clone();
  16490. rect.applyTransform(transform);
  16491. }
  16492. } // The real width and height can not be specified but calculated by the given el.
  16493. positionInfo = getLayoutRect(defaults({
  16494. width: rect.width,
  16495. height: rect.height
  16496. }, positionInfo), containerRect, margin); // Because 'tranlate' is the last step in transform
  16497. // (see zrender/core/Transformable#getLocalTransform),
  16498. // we can just only modify el.position to get final result.
  16499. var elPos = el.position;
  16500. var dx = h ? positionInfo.x - rect.x : 0;
  16501. var dy = v ? positionInfo.y - rect.y : 0;
  16502. el.attr('position', boundingMode === 'raw' ? [dx, dy] : [elPos[0] + dx, elPos[1] + dy]);
  16503. }
  16504. /**
  16505. * @param {Object} option Contains some of the properties in HV_NAMES.
  16506. * @param {number} hvIdx 0: horizontal; 1: vertical.
  16507. */
  16508. function sizeCalculable(option, hvIdx) {
  16509. return option[HV_NAMES[hvIdx][0]] != null || option[HV_NAMES[hvIdx][1]] != null && option[HV_NAMES[hvIdx][2]] != null;
  16510. }
  16511. /**
  16512. * Consider Case:
  16513. * When defulat option has {left: 0, width: 100}, and we set {right: 0}
  16514. * through setOption or media query, using normal zrUtil.merge will cause
  16515. * {right: 0} does not take effect.
  16516. *
  16517. * @example
  16518. * ComponentModel.extend({
  16519. * init: function () {
  16520. * ...
  16521. * var inputPositionParams = layout.getLayoutParams(option);
  16522. * this.mergeOption(inputPositionParams);
  16523. * },
  16524. * mergeOption: function (newOption) {
  16525. * newOption && zrUtil.merge(thisOption, newOption, true);
  16526. * layout.mergeLayoutParam(thisOption, newOption);
  16527. * }
  16528. * });
  16529. *
  16530. * @param {Object} targetOption
  16531. * @param {Object} newOption
  16532. * @param {Object|string} [opt]
  16533. * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components
  16534. * that width (or height) should not be calculated by left and right (or top and bottom).
  16535. */
  16536. function mergeLayoutParam(targetOption, newOption, opt) {
  16537. !isObject$1(opt) && (opt = {});
  16538. var ignoreSize = opt.ignoreSize;
  16539. !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]);
  16540. var hResult = merge$$1(HV_NAMES[0], 0);
  16541. var vResult = merge$$1(HV_NAMES[1], 1);
  16542. copy(HV_NAMES[0], targetOption, hResult);
  16543. copy(HV_NAMES[1], targetOption, vResult);
  16544. function merge$$1(names, hvIdx) {
  16545. var newParams = {};
  16546. var newValueCount = 0;
  16547. var merged = {};
  16548. var mergedValueCount = 0;
  16549. var enoughParamNumber = 2;
  16550. each$3(names, function (name) {
  16551. merged[name] = targetOption[name];
  16552. });
  16553. each$3(names, function (name) {
  16554. // Consider case: newOption.width is null, which is
  16555. // set by user for removing width setting.
  16556. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]);
  16557. hasValue(newParams, name) && newValueCount++;
  16558. hasValue(merged, name) && mergedValueCount++;
  16559. });
  16560. if (ignoreSize[hvIdx]) {
  16561. // Only one of left/right is premitted to exist.
  16562. if (hasValue(newOption, names[1])) {
  16563. merged[names[2]] = null;
  16564. } else if (hasValue(newOption, names[2])) {
  16565. merged[names[1]] = null;
  16566. }
  16567. return merged;
  16568. } // Case: newOption: {width: ..., right: ...},
  16569. // or targetOption: {right: ...} and newOption: {width: ...},
  16570. // There is no conflict when merged only has params count
  16571. // little than enoughParamNumber.
  16572. if (mergedValueCount === enoughParamNumber || !newValueCount) {
  16573. return merged;
  16574. } // Case: newOption: {width: ..., right: ...},
  16575. // Than we can make sure user only want those two, and ignore
  16576. // all origin params in targetOption.
  16577. else if (newValueCount >= enoughParamNumber) {
  16578. return newParams;
  16579. } else {
  16580. // Chose another param from targetOption by priority.
  16581. for (var i = 0; i < names.length; i++) {
  16582. var name = names[i];
  16583. if (!hasProp(newParams, name) && hasProp(targetOption, name)) {
  16584. newParams[name] = targetOption[name];
  16585. break;
  16586. }
  16587. }
  16588. return newParams;
  16589. }
  16590. }
  16591. function hasProp(obj, name) {
  16592. return obj.hasOwnProperty(name);
  16593. }
  16594. function hasValue(obj, name) {
  16595. return obj[name] != null && obj[name] !== 'auto';
  16596. }
  16597. function copy(names, target, source) {
  16598. each$3(names, function (name) {
  16599. target[name] = source[name];
  16600. });
  16601. }
  16602. }
  16603. /**
  16604. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16605. * @param {Object} source
  16606. * @return {Object} Result contains those props.
  16607. */
  16608. function getLayoutParams(source) {
  16609. return copyLayoutParams({}, source);
  16610. }
  16611. /**
  16612. * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object.
  16613. * @param {Object} source
  16614. * @return {Object} Result contains those props.
  16615. */
  16616. function copyLayoutParams(target, source) {
  16617. source && target && each$3(LOCATION_PARAMS, function (name) {
  16618. source.hasOwnProperty(name) && (target[name] = source[name]);
  16619. });
  16620. return target;
  16621. }
  16622. /*
  16623. * Licensed to the Apache Software Foundation (ASF) under one
  16624. * or more contributor license agreements. See the NOTICE file
  16625. * distributed with this work for additional information
  16626. * regarding copyright ownership. The ASF licenses this file
  16627. * to you under the Apache License, Version 2.0 (the
  16628. * "License"); you may not use this file except in compliance
  16629. * with the License. You may obtain a copy of the License at
  16630. *
  16631. * http://www.apache.org/licenses/LICENSE-2.0
  16632. *
  16633. * Unless required by applicable law or agreed to in writing,
  16634. * software distributed under the License is distributed on an
  16635. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16636. * KIND, either express or implied. See the License for the
  16637. * specific language governing permissions and limitations
  16638. * under the License.
  16639. */
  16640. var boxLayoutMixin = {
  16641. getBoxLayoutParams: function () {
  16642. return {
  16643. left: this.get('left'),
  16644. top: this.get('top'),
  16645. right: this.get('right'),
  16646. bottom: this.get('bottom'),
  16647. width: this.get('width'),
  16648. height: this.get('height')
  16649. };
  16650. }
  16651. };
  16652. /*
  16653. * Licensed to the Apache Software Foundation (ASF) under one
  16654. * or more contributor license agreements. See the NOTICE file
  16655. * distributed with this work for additional information
  16656. * regarding copyright ownership. The ASF licenses this file
  16657. * to you under the Apache License, Version 2.0 (the
  16658. * "License"); you may not use this file except in compliance
  16659. * with the License. You may obtain a copy of the License at
  16660. *
  16661. * http://www.apache.org/licenses/LICENSE-2.0
  16662. *
  16663. * Unless required by applicable law or agreed to in writing,
  16664. * software distributed under the License is distributed on an
  16665. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16666. * KIND, either express or implied. See the License for the
  16667. * specific language governing permissions and limitations
  16668. * under the License.
  16669. */
  16670. /**
  16671. * Component model
  16672. *
  16673. * @module echarts/model/Component
  16674. */
  16675. var inner$1 = makeInner();
  16676. /**
  16677. * @alias module:echarts/model/Component
  16678. * @constructor
  16679. * @param {Object} option
  16680. * @param {module:echarts/model/Model} parentModel
  16681. * @param {module:echarts/model/Model} ecModel
  16682. */
  16683. var ComponentModel = Model.extend({
  16684. type: 'component',
  16685. /**
  16686. * @readOnly
  16687. * @type {string}
  16688. */
  16689. id: '',
  16690. /**
  16691. * Because simplified concept is probably better, series.name (or component.name)
  16692. * has been having too many resposibilities:
  16693. * (1) Generating id (which requires name in option should not be modified).
  16694. * (2) As an index to mapping series when merging option or calling API (a name
  16695. * can refer to more then one components, which is convinient is some case).
  16696. * (3) Display.
  16697. * @readOnly
  16698. */
  16699. name: '',
  16700. /**
  16701. * @readOnly
  16702. * @type {string}
  16703. */
  16704. mainType: '',
  16705. /**
  16706. * @readOnly
  16707. * @type {string}
  16708. */
  16709. subType: '',
  16710. /**
  16711. * @readOnly
  16712. * @type {number}
  16713. */
  16714. componentIndex: 0,
  16715. /**
  16716. * @type {Object}
  16717. * @protected
  16718. */
  16719. defaultOption: null,
  16720. /**
  16721. * @type {module:echarts/model/Global}
  16722. * @readOnly
  16723. */
  16724. ecModel: null,
  16725. /**
  16726. * key: componentType
  16727. * value: Component model list, can not be null.
  16728. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  16729. * @readOnly
  16730. */
  16731. dependentModels: [],
  16732. /**
  16733. * @type {string}
  16734. * @readOnly
  16735. */
  16736. uid: null,
  16737. /**
  16738. * Support merge layout params.
  16739. * Only support 'box' now (left/right/top/bottom/width/height).
  16740. * @type {string|Object} Object can be {ignoreSize: true}
  16741. * @readOnly
  16742. */
  16743. layoutMode: null,
  16744. $constructor: function (option, parentModel, ecModel, extraOpt) {
  16745. Model.call(this, option, parentModel, ecModel, extraOpt);
  16746. this.uid = getUID('ec_cpt_model');
  16747. },
  16748. init: function (option, parentModel, ecModel, extraOpt) {
  16749. this.mergeDefaultAndTheme(option, ecModel);
  16750. },
  16751. mergeDefaultAndTheme: function (option, ecModel) {
  16752. var layoutMode = this.layoutMode;
  16753. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  16754. var themeModel = ecModel.getTheme();
  16755. merge(option, themeModel.get(this.mainType));
  16756. merge(option, this.getDefaultOption());
  16757. if (layoutMode) {
  16758. mergeLayoutParam(option, inputPositionParams, layoutMode);
  16759. }
  16760. },
  16761. mergeOption: function (option, extraOpt) {
  16762. merge(this.option, option, true);
  16763. var layoutMode = this.layoutMode;
  16764. if (layoutMode) {
  16765. mergeLayoutParam(this.option, option, layoutMode);
  16766. }
  16767. },
  16768. // Hooker after init or mergeOption
  16769. optionUpdated: function (newCptOption, isInit) {},
  16770. getDefaultOption: function () {
  16771. var fields = inner$1(this);
  16772. if (!fields.defaultOption) {
  16773. var optList = [];
  16774. var Class = this.constructor;
  16775. while (Class) {
  16776. var opt = Class.prototype.defaultOption;
  16777. opt && optList.push(opt);
  16778. Class = Class.superClass;
  16779. }
  16780. var defaultOption = {};
  16781. for (var i = optList.length - 1; i >= 0; i--) {
  16782. defaultOption = merge(defaultOption, optList[i], true);
  16783. }
  16784. fields.defaultOption = defaultOption;
  16785. }
  16786. return fields.defaultOption;
  16787. },
  16788. getReferringComponents: function (mainType) {
  16789. return this.ecModel.queryComponents({
  16790. mainType: mainType,
  16791. index: this.get(mainType + 'Index', true),
  16792. id: this.get(mainType + 'Id', true)
  16793. });
  16794. }
  16795. }); // Reset ComponentModel.extend, add preConstruct.
  16796. // clazzUtil.enableClassExtend(
  16797. // ComponentModel,
  16798. // function (option, parentModel, ecModel, extraOpt) {
  16799. // // Set dependentModels, componentIndex, name, id, mainType, subType.
  16800. // zrUtil.extend(this, extraOpt);
  16801. // this.uid = componentUtil.getUID('componentModel');
  16802. // // this.setReadOnly([
  16803. // // 'type', 'id', 'uid', 'name', 'mainType', 'subType',
  16804. // // 'dependentModels', 'componentIndex'
  16805. // // ]);
  16806. // }
  16807. // );
  16808. // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  16809. enableClassManagement(ComponentModel, {
  16810. registerWhenExtend: true
  16811. });
  16812. enableSubTypeDefaulter(ComponentModel); // Add capability of ComponentModel.topologicalTravel.
  16813. enableTopologicalTravel(ComponentModel, getDependencies);
  16814. function getDependencies(componentType) {
  16815. var deps = [];
  16816. each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) {
  16817. deps = deps.concat(Clazz.prototype.dependencies || []);
  16818. }); // Ensure main type.
  16819. deps = map(deps, function (type) {
  16820. return parseClassType$1(type).main;
  16821. }); // Hack dataset for convenience.
  16822. if (componentType !== 'dataset' && indexOf(deps, 'dataset') <= 0) {
  16823. deps.unshift('dataset');
  16824. }
  16825. return deps;
  16826. }
  16827. mixin(ComponentModel, boxLayoutMixin);
  16828. /*
  16829. * Licensed to the Apache Software Foundation (ASF) under one
  16830. * or more contributor license agreements. See the NOTICE file
  16831. * distributed with this work for additional information
  16832. * regarding copyright ownership. The ASF licenses this file
  16833. * to you under the Apache License, Version 2.0 (the
  16834. * "License"); you may not use this file except in compliance
  16835. * with the License. You may obtain a copy of the License at
  16836. *
  16837. * http://www.apache.org/licenses/LICENSE-2.0
  16838. *
  16839. * Unless required by applicable law or agreed to in writing,
  16840. * software distributed under the License is distributed on an
  16841. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16842. * KIND, either express or implied. See the License for the
  16843. * specific language governing permissions and limitations
  16844. * under the License.
  16845. */
  16846. var platform = ''; // Navigator not exists in node
  16847. if (typeof navigator !== 'undefined') {
  16848. platform = navigator.platform || '';
  16849. }
  16850. var globalDefault = {
  16851. // backgroundColor: 'rgba(0,0,0,0)',
  16852. // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization
  16853. // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'],
  16854. // Light colors:
  16855. // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'],
  16856. // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'],
  16857. // Dark colors:
  16858. color: ['#c23531', '#2f4554', '#61a0a8', '#d48265', '#91c7ae', '#749f83', '#ca8622', '#bda29a', '#6e7074', '#546570', '#c4ccd3'],
  16859. gradientColor: ['#f6efa6', '#d88273', '#bf444c'],
  16860. // If xAxis and yAxis declared, grid is created by default.
  16861. // grid: {},
  16862. textStyle: {
  16863. // color: '#000',
  16864. // decoration: 'none',
  16865. // PENDING
  16866. fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif',
  16867. // fontFamily: 'Arial, Verdana, sans-serif',
  16868. fontSize: 12,
  16869. fontStyle: 'normal',
  16870. fontWeight: 'normal'
  16871. },
  16872. // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/
  16873. // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation
  16874. // Default is source-over
  16875. blendMode: null,
  16876. animation: 'auto',
  16877. animationDuration: 1000,
  16878. animationDurationUpdate: 300,
  16879. animationEasing: 'exponentialOut',
  16880. animationEasingUpdate: 'cubicOut',
  16881. animationThreshold: 2000,
  16882. // Configuration for progressive/incremental rendering
  16883. progressiveThreshold: 3000,
  16884. progressive: 400,
  16885. // Threshold of if use single hover layer to optimize.
  16886. // It is recommended that `hoverLayerThreshold` is equivalent to or less than
  16887. // `progressiveThreshold`, otherwise hover will cause restart of progressive,
  16888. // which is unexpected.
  16889. // see example <echarts/test/heatmap-large.html>.
  16890. hoverLayerThreshold: 3000,
  16891. // See: module:echarts/scale/Time
  16892. useUTC: false
  16893. };
  16894. /*
  16895. * Licensed to the Apache Software Foundation (ASF) under one
  16896. * or more contributor license agreements. See the NOTICE file
  16897. * distributed with this work for additional information
  16898. * regarding copyright ownership. The ASF licenses this file
  16899. * to you under the Apache License, Version 2.0 (the
  16900. * "License"); you may not use this file except in compliance
  16901. * with the License. You may obtain a copy of the License at
  16902. *
  16903. * http://www.apache.org/licenses/LICENSE-2.0
  16904. *
  16905. * Unless required by applicable law or agreed to in writing,
  16906. * software distributed under the License is distributed on an
  16907. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16908. * KIND, either express or implied. See the License for the
  16909. * specific language governing permissions and limitations
  16910. * under the License.
  16911. */
  16912. var inner$2 = makeInner();
  16913. function getNearestColorPalette(colors, requestColorNum) {
  16914. var paletteNum = colors.length; // TODO colors must be in order
  16915. for (var i = 0; i < paletteNum; i++) {
  16916. if (colors[i].length > requestColorNum) {
  16917. return colors[i];
  16918. }
  16919. }
  16920. return colors[paletteNum - 1];
  16921. }
  16922. var colorPaletteMixin = {
  16923. clearColorPalette: function () {
  16924. inner$2(this).colorIdx = 0;
  16925. inner$2(this).colorNameMap = {};
  16926. },
  16927. /**
  16928. * @param {string} name MUST NOT be null/undefined. Otherwise call this function
  16929. * twise with the same parameters will get different result.
  16930. * @param {Object} [scope=this]
  16931. * @param {Object} [requestColorNum]
  16932. * @return {string} color string.
  16933. */
  16934. getColorFromPalette: function (name, scope, requestColorNum) {
  16935. scope = scope || this;
  16936. var scopeFields = inner$2(scope);
  16937. var colorIdx = scopeFields.colorIdx || 0;
  16938. var colorNameMap = scopeFields.colorNameMap = scopeFields.colorNameMap || {}; // Use `hasOwnProperty` to avoid conflict with Object.prototype.
  16939. if (colorNameMap.hasOwnProperty(name)) {
  16940. return colorNameMap[name];
  16941. }
  16942. var defaultColorPalette = normalizeToArray(this.get('color', true));
  16943. var layeredColorPalette = this.get('colorLayer', true);
  16944. var colorPalette = requestColorNum == null || !layeredColorPalette ? defaultColorPalette : getNearestColorPalette(layeredColorPalette, requestColorNum); // In case can't find in layered color palette.
  16945. colorPalette = colorPalette || defaultColorPalette;
  16946. if (!colorPalette || !colorPalette.length) {
  16947. return;
  16948. }
  16949. var color = colorPalette[colorIdx];
  16950. if (name) {
  16951. colorNameMap[name] = color;
  16952. }
  16953. scopeFields.colorIdx = (colorIdx + 1) % colorPalette.length;
  16954. return color;
  16955. }
  16956. };
  16957. /*
  16958. * Licensed to the Apache Software Foundation (ASF) under one
  16959. * or more contributor license agreements. See the NOTICE file
  16960. * distributed with this work for additional information
  16961. * regarding copyright ownership. The ASF licenses this file
  16962. * to you under the Apache License, Version 2.0 (the
  16963. * "License"); you may not use this file except in compliance
  16964. * with the License. You may obtain a copy of the License at
  16965. *
  16966. * http://www.apache.org/licenses/LICENSE-2.0
  16967. *
  16968. * Unless required by applicable law or agreed to in writing,
  16969. * software distributed under the License is distributed on an
  16970. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16971. * KIND, either express or implied. See the License for the
  16972. * specific language governing permissions and limitations
  16973. * under the License.
  16974. */
  16975. // Avoid typo.
  16976. var SOURCE_FORMAT_ORIGINAL = 'original';
  16977. var SOURCE_FORMAT_ARRAY_ROWS = 'arrayRows';
  16978. var SOURCE_FORMAT_OBJECT_ROWS = 'objectRows';
  16979. var SOURCE_FORMAT_KEYED_COLUMNS = 'keyedColumns';
  16980. var SOURCE_FORMAT_UNKNOWN = 'unknown'; // ??? CHANGE A NAME
  16981. var SOURCE_FORMAT_TYPED_ARRAY = 'typedArray';
  16982. var SERIES_LAYOUT_BY_COLUMN = 'column';
  16983. var SERIES_LAYOUT_BY_ROW = 'row';
  16984. /*
  16985. * Licensed to the Apache Software Foundation (ASF) under one
  16986. * or more contributor license agreements. See the NOTICE file
  16987. * distributed with this work for additional information
  16988. * regarding copyright ownership. The ASF licenses this file
  16989. * to you under the Apache License, Version 2.0 (the
  16990. * "License"); you may not use this file except in compliance
  16991. * with the License. You may obtain a copy of the License at
  16992. *
  16993. * http://www.apache.org/licenses/LICENSE-2.0
  16994. *
  16995. * Unless required by applicable law or agreed to in writing,
  16996. * software distributed under the License is distributed on an
  16997. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  16998. * KIND, either express or implied. See the License for the
  16999. * specific language governing permissions and limitations
  17000. * under the License.
  17001. */
  17002. /**
  17003. * [sourceFormat]
  17004. *
  17005. * + "original":
  17006. * This format is only used in series.data, where
  17007. * itemStyle can be specified in data item.
  17008. *
  17009. * + "arrayRows":
  17010. * [
  17011. * ['product', 'score', 'amount'],
  17012. * ['Matcha Latte', 89.3, 95.8],
  17013. * ['Milk Tea', 92.1, 89.4],
  17014. * ['Cheese Cocoa', 94.4, 91.2],
  17015. * ['Walnut Brownie', 85.4, 76.9]
  17016. * ]
  17017. *
  17018. * + "objectRows":
  17019. * [
  17020. * {product: 'Matcha Latte', score: 89.3, amount: 95.8},
  17021. * {product: 'Milk Tea', score: 92.1, amount: 89.4},
  17022. * {product: 'Cheese Cocoa', score: 94.4, amount: 91.2},
  17023. * {product: 'Walnut Brownie', score: 85.4, amount: 76.9}
  17024. * ]
  17025. *
  17026. * + "keyedColumns":
  17027. * {
  17028. * 'product': ['Matcha Latte', 'Milk Tea', 'Cheese Cocoa', 'Walnut Brownie'],
  17029. * 'count': [823, 235, 1042, 988],
  17030. * 'score': [95.8, 81.4, 91.2, 76.9]
  17031. * }
  17032. *
  17033. * + "typedArray"
  17034. *
  17035. * + "unknown"
  17036. */
  17037. /**
  17038. * @constructor
  17039. * @param {Object} fields
  17040. * @param {string} fields.sourceFormat
  17041. * @param {Array|Object} fields.fromDataset
  17042. * @param {Array|Object} [fields.data]
  17043. * @param {string} [seriesLayoutBy='column']
  17044. * @param {Array.<Object|string>} [dimensionsDefine]
  17045. * @param {Objet|HashMap} [encodeDefine]
  17046. * @param {number} [startIndex=0]
  17047. * @param {number} [dimensionsDetectCount]
  17048. */
  17049. function Source(fields) {
  17050. /**
  17051. * @type {boolean}
  17052. */
  17053. this.fromDataset = fields.fromDataset;
  17054. /**
  17055. * Not null/undefined.
  17056. * @type {Array|Object}
  17057. */
  17058. this.data = fields.data || (fields.sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS ? {} : []);
  17059. /**
  17060. * See also "detectSourceFormat".
  17061. * Not null/undefined.
  17062. * @type {string}
  17063. */
  17064. this.sourceFormat = fields.sourceFormat || SOURCE_FORMAT_UNKNOWN;
  17065. /**
  17066. * 'row' or 'column'
  17067. * Not null/undefined.
  17068. * @type {string} seriesLayoutBy
  17069. */
  17070. this.seriesLayoutBy = fields.seriesLayoutBy || SERIES_LAYOUT_BY_COLUMN;
  17071. /**
  17072. * dimensions definition in option.
  17073. * can be null/undefined.
  17074. * @type {Array.<Object|string>}
  17075. */
  17076. this.dimensionsDefine = fields.dimensionsDefine;
  17077. /**
  17078. * encode definition in option.
  17079. * can be null/undefined.
  17080. * @type {Objet|HashMap}
  17081. */
  17082. this.encodeDefine = fields.encodeDefine && createHashMap(fields.encodeDefine);
  17083. /**
  17084. * Not null/undefined, uint.
  17085. * @type {number}
  17086. */
  17087. this.startIndex = fields.startIndex || 0;
  17088. /**
  17089. * Can be null/undefined (when unknown), uint.
  17090. * @type {number}
  17091. */
  17092. this.dimensionsDetectCount = fields.dimensionsDetectCount;
  17093. }
  17094. /**
  17095. * Wrap original series data for some compatibility cases.
  17096. */
  17097. Source.seriesDataToSource = function (data) {
  17098. return new Source({
  17099. data: data,
  17100. sourceFormat: isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL,
  17101. fromDataset: false
  17102. });
  17103. };
  17104. enableClassCheck(Source);
  17105. /*
  17106. * Licensed to the Apache Software Foundation (ASF) under one
  17107. * or more contributor license agreements. See the NOTICE file
  17108. * distributed with this work for additional information
  17109. * regarding copyright ownership. The ASF licenses this file
  17110. * to you under the Apache License, Version 2.0 (the
  17111. * "License"); you may not use this file except in compliance
  17112. * with the License. You may obtain a copy of the License at
  17113. *
  17114. * http://www.apache.org/licenses/LICENSE-2.0
  17115. *
  17116. * Unless required by applicable law or agreed to in writing,
  17117. * software distributed under the License is distributed on an
  17118. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17119. * KIND, either express or implied. See the License for the
  17120. * specific language governing permissions and limitations
  17121. * under the License.
  17122. */
  17123. var BE_ORDINAL = {
  17124. Must: 1,
  17125. // Encounter string but not '-' and not number-like.
  17126. Might: 2,
  17127. // Encounter string but number-like.
  17128. Not: 3 // Other cases
  17129. };
  17130. var inner$3 = makeInner();
  17131. /**
  17132. * @see {module:echarts/data/Source}
  17133. * @param {module:echarts/component/dataset/DatasetModel} datasetModel
  17134. * @return {string} sourceFormat
  17135. */
  17136. function detectSourceFormat(datasetModel) {
  17137. var data = datasetModel.option.source;
  17138. var sourceFormat = SOURCE_FORMAT_UNKNOWN;
  17139. if (isTypedArray(data)) {
  17140. sourceFormat = SOURCE_FORMAT_TYPED_ARRAY;
  17141. } else if (isArray(data)) {
  17142. // FIXME Whether tolerate null in top level array?
  17143. if (data.length === 0) {
  17144. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17145. }
  17146. for (var i = 0, len = data.length; i < len; i++) {
  17147. var item = data[i];
  17148. if (item == null) {
  17149. continue;
  17150. } else if (isArray(item)) {
  17151. sourceFormat = SOURCE_FORMAT_ARRAY_ROWS;
  17152. break;
  17153. } else if (isObject$1(item)) {
  17154. sourceFormat = SOURCE_FORMAT_OBJECT_ROWS;
  17155. break;
  17156. }
  17157. }
  17158. } else if (isObject$1(data)) {
  17159. for (var key in data) {
  17160. if (data.hasOwnProperty(key) && isArrayLike(data[key])) {
  17161. sourceFormat = SOURCE_FORMAT_KEYED_COLUMNS;
  17162. break;
  17163. }
  17164. }
  17165. } else if (data != null) {
  17166. throw new Error('Invalid data');
  17167. }
  17168. inner$3(datasetModel).sourceFormat = sourceFormat;
  17169. }
  17170. /**
  17171. * [Scenarios]:
  17172. * (1) Provide source data directly:
  17173. * series: {
  17174. * encode: {...},
  17175. * dimensions: [...]
  17176. * seriesLayoutBy: 'row',
  17177. * data: [[...]]
  17178. * }
  17179. * (2) Refer to datasetModel.
  17180. * series: [{
  17181. * encode: {...}
  17182. * // Ignore datasetIndex means `datasetIndex: 0`
  17183. * // and the dimensions defination in dataset is used
  17184. * }, {
  17185. * encode: {...},
  17186. * seriesLayoutBy: 'column',
  17187. * datasetIndex: 1
  17188. * }]
  17189. *
  17190. * Get data from series itself or datset.
  17191. * @return {module:echarts/data/Source} source
  17192. */
  17193. function getSource(seriesModel) {
  17194. return inner$3(seriesModel).source;
  17195. }
  17196. /**
  17197. * MUST be called before mergeOption of all series.
  17198. * @param {module:echarts/model/Global} ecModel
  17199. */
  17200. function resetSourceDefaulter(ecModel) {
  17201. // `datasetMap` is used to make default encode.
  17202. inner$3(ecModel).datasetMap = createHashMap();
  17203. }
  17204. /**
  17205. * [Caution]:
  17206. * MUST be called after series option merged and
  17207. * before "series.getInitailData()" called.
  17208. *
  17209. * [The rule of making default encode]:
  17210. * Category axis (if exists) alway map to the first dimension.
  17211. * Each other axis occupies a subsequent dimension.
  17212. *
  17213. * [Why make default encode]:
  17214. * Simplify the typing of encode in option, avoiding the case like that:
  17215. * series: [{encode: {x: 0, y: 1}}, {encode: {x: 0, y: 2}}, {encode: {x: 0, y: 3}}],
  17216. * where the "y" have to be manually typed as "1, 2, 3, ...".
  17217. *
  17218. * @param {module:echarts/model/Series} seriesModel
  17219. */
  17220. function prepareSource(seriesModel) {
  17221. var seriesOption = seriesModel.option;
  17222. var data = seriesOption.data;
  17223. var sourceFormat = isTypedArray(data) ? SOURCE_FORMAT_TYPED_ARRAY : SOURCE_FORMAT_ORIGINAL;
  17224. var fromDataset = false;
  17225. var seriesLayoutBy = seriesOption.seriesLayoutBy;
  17226. var sourceHeader = seriesOption.sourceHeader;
  17227. var dimensionsDefine = seriesOption.dimensions;
  17228. var datasetModel = getDatasetModel(seriesModel);
  17229. if (datasetModel) {
  17230. var datasetOption = datasetModel.option;
  17231. data = datasetOption.source;
  17232. sourceFormat = inner$3(datasetModel).sourceFormat;
  17233. fromDataset = true; // These settings from series has higher priority.
  17234. seriesLayoutBy = seriesLayoutBy || datasetOption.seriesLayoutBy;
  17235. sourceHeader == null && (sourceHeader = datasetOption.sourceHeader);
  17236. dimensionsDefine = dimensionsDefine || datasetOption.dimensions;
  17237. }
  17238. var completeResult = completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine);
  17239. inner$3(seriesModel).source = new Source({
  17240. data: data,
  17241. fromDataset: fromDataset,
  17242. seriesLayoutBy: seriesLayoutBy,
  17243. sourceFormat: sourceFormat,
  17244. dimensionsDefine: completeResult.dimensionsDefine,
  17245. startIndex: completeResult.startIndex,
  17246. dimensionsDetectCount: completeResult.dimensionsDetectCount,
  17247. // Note: dataset option does not have `encode`.
  17248. encodeDefine: seriesOption.encode
  17249. });
  17250. } // return {startIndex, dimensionsDefine, dimensionsCount}
  17251. function completeBySourceData(data, sourceFormat, seriesLayoutBy, sourceHeader, dimensionsDefine) {
  17252. if (!data) {
  17253. return {
  17254. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine)
  17255. };
  17256. }
  17257. var dimensionsDetectCount;
  17258. var startIndex;
  17259. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17260. // Rule: Most of the first line are string: it is header.
  17261. // Caution: consider a line with 5 string and 1 number,
  17262. // it still can not be sure it is a head, because the
  17263. // 5 string may be 5 values of category columns.
  17264. if (sourceHeader === 'auto' || sourceHeader == null) {
  17265. arrayRowsTravelFirst(function (val) {
  17266. // '-' is regarded as null/undefined.
  17267. if (val != null && val !== '-') {
  17268. if (isString(val)) {
  17269. startIndex == null && (startIndex = 1);
  17270. } else {
  17271. startIndex = 0;
  17272. }
  17273. } // 10 is an experience number, avoid long loop.
  17274. }, seriesLayoutBy, data, 10);
  17275. } else {
  17276. startIndex = sourceHeader ? 1 : 0;
  17277. }
  17278. if (!dimensionsDefine && startIndex === 1) {
  17279. dimensionsDefine = [];
  17280. arrayRowsTravelFirst(function (val, index) {
  17281. dimensionsDefine[index] = val != null ? val : '';
  17282. }, seriesLayoutBy, data);
  17283. }
  17284. dimensionsDetectCount = dimensionsDefine ? dimensionsDefine.length : seriesLayoutBy === SERIES_LAYOUT_BY_ROW ? data.length : data[0] ? data[0].length : null;
  17285. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17286. if (!dimensionsDefine) {
  17287. dimensionsDefine = objectRowsCollectDimensions(data);
  17288. }
  17289. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17290. if (!dimensionsDefine) {
  17291. dimensionsDefine = [];
  17292. each$1(data, function (colArr, key) {
  17293. dimensionsDefine.push(key);
  17294. });
  17295. }
  17296. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17297. var value0 = getDataItemValue(data[0]);
  17298. dimensionsDetectCount = isArray(value0) && value0.length || 1;
  17299. } else if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {}
  17300. return {
  17301. startIndex: startIndex,
  17302. dimensionsDefine: normalizeDimensionsDefine(dimensionsDefine),
  17303. dimensionsDetectCount: dimensionsDetectCount
  17304. };
  17305. } // Consider dimensions defined like ['A', 'price', 'B', 'price', 'C', 'price'],
  17306. // which is reasonable. But dimension name is duplicated.
  17307. // Returns undefined or an array contains only object without null/undefiend or string.
  17308. function normalizeDimensionsDefine(dimensionsDefine) {
  17309. if (!dimensionsDefine) {
  17310. // The meaning of null/undefined is different from empty array.
  17311. return;
  17312. }
  17313. var nameMap = createHashMap();
  17314. return map(dimensionsDefine, function (item, index) {
  17315. item = extend({}, isObject$1(item) ? item : {
  17316. name: item
  17317. }); // User can set null in dimensions.
  17318. // We dont auto specify name, othewise a given name may
  17319. // cause it be refered unexpectedly.
  17320. if (item.name == null) {
  17321. return item;
  17322. } // Also consider number form like 2012.
  17323. item.name += ''; // User may also specify displayName.
  17324. // displayName will always exists except user not
  17325. // specified or dim name is not specified or detected.
  17326. // (A auto generated dim name will not be used as
  17327. // displayName).
  17328. if (item.displayName == null) {
  17329. item.displayName = item.name;
  17330. }
  17331. var exist = nameMap.get(item.name);
  17332. if (!exist) {
  17333. nameMap.set(item.name, {
  17334. count: 1
  17335. });
  17336. } else {
  17337. item.name += '-' + exist.count++;
  17338. }
  17339. return item;
  17340. });
  17341. }
  17342. function arrayRowsTravelFirst(cb, seriesLayoutBy, data, maxLoop) {
  17343. maxLoop == null && (maxLoop = Infinity);
  17344. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17345. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17346. cb(data[i] ? data[i][0] : null, i);
  17347. }
  17348. } else {
  17349. var value0 = data[0] || [];
  17350. for (var i = 0; i < value0.length && i < maxLoop; i++) {
  17351. cb(value0[i], i);
  17352. }
  17353. }
  17354. }
  17355. function objectRowsCollectDimensions(data) {
  17356. var firstIndex = 0;
  17357. var obj;
  17358. while (firstIndex < data.length && !(obj = data[firstIndex++])) {} // jshint ignore: line
  17359. if (obj) {
  17360. var dimensions = [];
  17361. each$1(obj, function (value, key) {
  17362. dimensions.push(key);
  17363. });
  17364. return dimensions;
  17365. }
  17366. }
  17367. /**
  17368. * [The strategy of the arrengment of data dimensions for dataset]:
  17369. * "value way": all axes are non-category axes. So series one by one take
  17370. * several (the number is coordSysDims.length) dimensions from dataset.
  17371. * The result of data arrengment of data dimensions like:
  17372. * | ser0_x | ser0_y | ser1_x | ser1_y | ser2_x | ser2_y |
  17373. * "category way": at least one axis is category axis. So the the first data
  17374. * dimension is always mapped to the first category axis and shared by
  17375. * all of the series. The other data dimensions are taken by series like
  17376. * "value way" does.
  17377. * The result of data arrengment of data dimensions like:
  17378. * | ser_shared_x | ser0_y | ser1_y | ser2_y |
  17379. *
  17380. * @param {Array.<Object|string>} coordDimensions [{name: <string>, type: <string>, dimsDef: <Array>}, ...]
  17381. * @param {module:model/Series} seriesModel
  17382. * @param {module:data/Source} source
  17383. * @return {Object} encode Never be `null/undefined`.
  17384. */
  17385. function makeSeriesEncodeForAxisCoordSys(coordDimensions, seriesModel, source) {
  17386. var encode = {};
  17387. var datasetModel = getDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17388. if (!datasetModel || !coordDimensions) {
  17389. return encode;
  17390. }
  17391. var encodeItemName = [];
  17392. var encodeSeriesName = [];
  17393. var ecModel = seriesModel.ecModel;
  17394. var datasetMap = inner$3(ecModel).datasetMap;
  17395. var key = datasetModel.uid + '_' + source.seriesLayoutBy;
  17396. var baseCategoryDimIndex;
  17397. var categoryWayValueDimStart;
  17398. coordDimensions = coordDimensions.slice();
  17399. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17400. !isObject$1(coordDimInfo) && (coordDimensions[coordDimIdx] = {
  17401. name: coordDimInfo
  17402. });
  17403. if (coordDimInfo.type === 'ordinal' && baseCategoryDimIndex == null) {
  17404. baseCategoryDimIndex = coordDimIdx;
  17405. categoryWayValueDimStart = getDataDimCountOnCoordDim(coordDimensions[coordDimIdx]);
  17406. }
  17407. encode[coordDimInfo.name] = [];
  17408. });
  17409. var datasetRecord = datasetMap.get(key) || datasetMap.set(key, {
  17410. categoryWayDim: categoryWayValueDimStart,
  17411. valueWayDim: 0
  17412. }); // TODO
  17413. // Auto detect first time axis and do arrangement.
  17414. each$1(coordDimensions, function (coordDimInfo, coordDimIdx) {
  17415. var coordDimName = coordDimInfo.name;
  17416. var count = getDataDimCountOnCoordDim(coordDimInfo); // In value way.
  17417. if (baseCategoryDimIndex == null) {
  17418. var start = datasetRecord.valueWayDim;
  17419. pushDim(encode[coordDimName], start, count);
  17420. pushDim(encodeSeriesName, start, count);
  17421. datasetRecord.valueWayDim += count; // ??? TODO give a better default series name rule?
  17422. // especially when encode x y specified.
  17423. // consider: when mutiple series share one dimension
  17424. // category axis, series name should better use
  17425. // the other dimsion name. On the other hand, use
  17426. // both dimensions name.
  17427. } // In category way, the first category axis.
  17428. else if (baseCategoryDimIndex === coordDimIdx) {
  17429. pushDim(encode[coordDimName], 0, count);
  17430. pushDim(encodeItemName, 0, count);
  17431. } // In category way, the other axis.
  17432. else {
  17433. var start = datasetRecord.categoryWayDim;
  17434. pushDim(encode[coordDimName], start, count);
  17435. pushDim(encodeSeriesName, start, count);
  17436. datasetRecord.categoryWayDim += count;
  17437. }
  17438. });
  17439. function pushDim(dimIdxArr, idxFrom, idxCount) {
  17440. for (var i = 0; i < idxCount; i++) {
  17441. dimIdxArr.push(idxFrom + i);
  17442. }
  17443. }
  17444. function getDataDimCountOnCoordDim(coordDimInfo) {
  17445. var dimsDef = coordDimInfo.dimsDef;
  17446. return dimsDef ? dimsDef.length : 1;
  17447. }
  17448. encodeItemName.length && (encode.itemName = encodeItemName);
  17449. encodeSeriesName.length && (encode.seriesName = encodeSeriesName);
  17450. return encode;
  17451. }
  17452. /**
  17453. * Work for data like [{name: ..., value: ...}, ...].
  17454. *
  17455. * @param {module:model/Series} seriesModel
  17456. * @param {module:data/Source} source
  17457. * @return {Object} encode Never be `null/undefined`.
  17458. */
  17459. function makeSeriesEncodeForNameBased(seriesModel, source, dimCount) {
  17460. var encode = {};
  17461. var datasetModel = getDatasetModel(seriesModel); // Currently only make default when using dataset, util more reqirements occur.
  17462. if (!datasetModel) {
  17463. return encode;
  17464. }
  17465. var sourceFormat = source.sourceFormat;
  17466. var dimensionsDefine = source.dimensionsDefine;
  17467. var potentialNameDimIndex;
  17468. if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS || sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17469. each$1(dimensionsDefine, function (dim, idx) {
  17470. if ((isObject$1(dim) ? dim.name : dim) === 'name') {
  17471. potentialNameDimIndex = idx;
  17472. }
  17473. });
  17474. } // idxResult: {v, n}.
  17475. var idxResult = function () {
  17476. var idxRes0 = {};
  17477. var idxRes1 = {};
  17478. var guessRecords = []; // 5 is an experience value.
  17479. for (var i = 0, len = Math.min(5, dimCount); i < len; i++) {
  17480. var guessResult = doGuessOrdinal(source.data, sourceFormat, source.seriesLayoutBy, dimensionsDefine, source.startIndex, i);
  17481. guessRecords.push(guessResult);
  17482. var isPureNumber = guessResult === BE_ORDINAL.Not; // [Strategy of idxRes0]: find the first BE_ORDINAL.Not as the value dim,
  17483. // and then find a name dim with the priority:
  17484. // "BE_ORDINAL.Might|BE_ORDINAL.Must" > "other dim" > "the value dim itself".
  17485. if (isPureNumber && idxRes0.v == null && i !== potentialNameDimIndex) {
  17486. idxRes0.v = i;
  17487. }
  17488. if (idxRes0.n == null || idxRes0.n === idxRes0.v || !isPureNumber && guessRecords[idxRes0.n] === BE_ORDINAL.Not) {
  17489. idxRes0.n = i;
  17490. }
  17491. if (fulfilled(idxRes0) && guessRecords[idxRes0.n] !== BE_ORDINAL.Not) {
  17492. return idxRes0;
  17493. } // [Strategy of idxRes1]: if idxRes0 not satisfied (that is, no BE_ORDINAL.Not),
  17494. // find the first BE_ORDINAL.Might as the value dim,
  17495. // and then find a name dim with the priority:
  17496. // "other dim" > "the value dim itself".
  17497. // That is for backward compat: number-like (e.g., `'3'`, `'55'`) can be
  17498. // treated as number.
  17499. if (!isPureNumber) {
  17500. if (guessResult === BE_ORDINAL.Might && idxRes1.v == null && i !== potentialNameDimIndex) {
  17501. idxRes1.v = i;
  17502. }
  17503. if (idxRes1.n == null || idxRes1.n === idxRes1.v) {
  17504. idxRes1.n = i;
  17505. }
  17506. }
  17507. }
  17508. function fulfilled(idxResult) {
  17509. return idxResult.v != null && idxResult.n != null;
  17510. }
  17511. return fulfilled(idxRes0) ? idxRes0 : fulfilled(idxRes1) ? idxRes1 : null;
  17512. }();
  17513. if (idxResult) {
  17514. encode.value = idxResult.v; // `potentialNameDimIndex` has highest priority.
  17515. var nameDimIndex = potentialNameDimIndex != null ? potentialNameDimIndex : idxResult.n; // By default, label use itemName in charts.
  17516. // So we dont set encodeLabel here.
  17517. encode.itemName = [nameDimIndex];
  17518. encode.seriesName = [nameDimIndex];
  17519. }
  17520. return encode;
  17521. }
  17522. /**
  17523. * If return null/undefined, indicate that should not use datasetModel.
  17524. */
  17525. function getDatasetModel(seriesModel) {
  17526. var option = seriesModel.option; // Caution: consider the scenario:
  17527. // A dataset is declared and a series is not expected to use the dataset,
  17528. // and at the beginning `setOption({series: { noData })` (just prepare other
  17529. // option but no data), then `setOption({series: {data: [...]}); In this case,
  17530. // the user should set an empty array to avoid that dataset is used by default.
  17531. var thisData = option.data;
  17532. if (!thisData) {
  17533. return seriesModel.ecModel.getComponent('dataset', option.datasetIndex || 0);
  17534. }
  17535. }
  17536. /**
  17537. * The rule should not be complex, otherwise user might not
  17538. * be able to known where the data is wrong.
  17539. * The code is ugly, but how to make it neat?
  17540. *
  17541. * @param {module:echars/data/Source} source
  17542. * @param {number} dimIndex
  17543. * @return {BE_ORDINAL} guess result.
  17544. */
  17545. function guessOrdinal(source, dimIndex) {
  17546. return doGuessOrdinal(source.data, source.sourceFormat, source.seriesLayoutBy, source.dimensionsDefine, source.startIndex, dimIndex);
  17547. } // dimIndex may be overflow source data.
  17548. // return {BE_ORDINAL}
  17549. function doGuessOrdinal(data, sourceFormat, seriesLayoutBy, dimensionsDefine, startIndex, dimIndex) {
  17550. var result; // Experience value.
  17551. var maxLoop = 5;
  17552. if (isTypedArray(data)) {
  17553. return BE_ORDINAL.Not;
  17554. } // When sourceType is 'objectRows' or 'keyedColumns', dimensionsDefine
  17555. // always exists in source.
  17556. var dimName;
  17557. var dimType;
  17558. if (dimensionsDefine) {
  17559. var dimDefItem = dimensionsDefine[dimIndex];
  17560. if (isObject$1(dimDefItem)) {
  17561. dimName = dimDefItem.name;
  17562. dimType = dimDefItem.type;
  17563. } else if (isString(dimDefItem)) {
  17564. dimName = dimDefItem;
  17565. }
  17566. }
  17567. if (dimType != null) {
  17568. return dimType === 'ordinal' ? BE_ORDINAL.Must : BE_ORDINAL.Not;
  17569. }
  17570. if (sourceFormat === SOURCE_FORMAT_ARRAY_ROWS) {
  17571. if (seriesLayoutBy === SERIES_LAYOUT_BY_ROW) {
  17572. var sample = data[dimIndex];
  17573. for (var i = 0; i < (sample || []).length && i < maxLoop; i++) {
  17574. if ((result = detectValue(sample[startIndex + i])) != null) {
  17575. return result;
  17576. }
  17577. }
  17578. } else {
  17579. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17580. var row = data[startIndex + i];
  17581. if (row && (result = detectValue(row[dimIndex])) != null) {
  17582. return result;
  17583. }
  17584. }
  17585. }
  17586. } else if (sourceFormat === SOURCE_FORMAT_OBJECT_ROWS) {
  17587. if (!dimName) {
  17588. return BE_ORDINAL.Not;
  17589. }
  17590. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17591. var item = data[i];
  17592. if (item && (result = detectValue(item[dimName])) != null) {
  17593. return result;
  17594. }
  17595. }
  17596. } else if (sourceFormat === SOURCE_FORMAT_KEYED_COLUMNS) {
  17597. if (!dimName) {
  17598. return BE_ORDINAL.Not;
  17599. }
  17600. var sample = data[dimName];
  17601. if (!sample || isTypedArray(sample)) {
  17602. return BE_ORDINAL.Not;
  17603. }
  17604. for (var i = 0; i < sample.length && i < maxLoop; i++) {
  17605. if ((result = detectValue(sample[i])) != null) {
  17606. return result;
  17607. }
  17608. }
  17609. } else if (sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  17610. for (var i = 0; i < data.length && i < maxLoop; i++) {
  17611. var item = data[i];
  17612. var val = getDataItemValue(item);
  17613. if (!isArray(val)) {
  17614. return BE_ORDINAL.Not;
  17615. }
  17616. if ((result = detectValue(val[dimIndex])) != null) {
  17617. return result;
  17618. }
  17619. }
  17620. }
  17621. function detectValue(val) {
  17622. var beStr = isString(val); // Consider usage convenience, '1', '2' will be treated as "number".
  17623. // `isFinit('')` get `true`.
  17624. if (val != null && isFinite(val) && val !== '') {
  17625. return beStr ? BE_ORDINAL.Might : BE_ORDINAL.Not;
  17626. } else if (beStr && val !== '-') {
  17627. return BE_ORDINAL.Must;
  17628. }
  17629. }
  17630. return BE_ORDINAL.Not;
  17631. }
  17632. /*
  17633. * Licensed to the Apache Software Foundation (ASF) under one
  17634. * or more contributor license agreements. See the NOTICE file
  17635. * distributed with this work for additional information
  17636. * regarding copyright ownership. The ASF licenses this file
  17637. * to you under the Apache License, Version 2.0 (the
  17638. * "License"); you may not use this file except in compliance
  17639. * with the License. You may obtain a copy of the License at
  17640. *
  17641. * http://www.apache.org/licenses/LICENSE-2.0
  17642. *
  17643. * Unless required by applicable law or agreed to in writing,
  17644. * software distributed under the License is distributed on an
  17645. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  17646. * KIND, either express or implied. See the License for the
  17647. * specific language governing permissions and limitations
  17648. * under the License.
  17649. */
  17650. /**
  17651. * ECharts global model
  17652. *
  17653. * @module {echarts/model/Global}
  17654. */
  17655. /**
  17656. * Caution: If the mechanism should be changed some day, these cases
  17657. * should be considered:
  17658. *
  17659. * (1) In `merge option` mode, if using the same option to call `setOption`
  17660. * many times, the result should be the same (try our best to ensure that).
  17661. * (2) In `merge option` mode, if a component has no id/name specified, it
  17662. * will be merged by index, and the result sequence of the components is
  17663. * consistent to the original sequence.
  17664. * (3) `reset` feature (in toolbox). Find detailed info in comments about
  17665. * `mergeOption` in module:echarts/model/OptionManager.
  17666. */
  17667. var OPTION_INNER_KEY = '\0_ec_inner';
  17668. /**
  17669. * @alias module:echarts/model/Global
  17670. *
  17671. * @param {Object} option
  17672. * @param {module:echarts/model/Model} parentModel
  17673. * @param {Object} theme
  17674. */
  17675. var GlobalModel = Model.extend({
  17676. init: function (option, parentModel, theme, optionManager) {
  17677. theme = theme || {};
  17678. this.option = null; // Mark as not initialized.
  17679. /**
  17680. * @type {module:echarts/model/Model}
  17681. * @private
  17682. */
  17683. this._theme = new Model(theme);
  17684. /**
  17685. * @type {module:echarts/model/OptionManager}
  17686. */
  17687. this._optionManager = optionManager;
  17688. },
  17689. setOption: function (option, optionPreprocessorFuncs) {
  17690. assert$1(!(OPTION_INNER_KEY in option), 'please use chart.getOption()');
  17691. this._optionManager.setOption(option, optionPreprocessorFuncs);
  17692. this.resetOption(null);
  17693. },
  17694. /**
  17695. * @param {string} type null/undefined: reset all.
  17696. * 'recreate': force recreate all.
  17697. * 'timeline': only reset timeline option
  17698. * 'media': only reset media query option
  17699. * @return {boolean} Whether option changed.
  17700. */
  17701. resetOption: function (type) {
  17702. var optionChanged = false;
  17703. var optionManager = this._optionManager;
  17704. if (!type || type === 'recreate') {
  17705. var baseOption = optionManager.mountOption(type === 'recreate');
  17706. if (!this.option || type === 'recreate') {
  17707. initBase.call(this, baseOption);
  17708. } else {
  17709. this.restoreData();
  17710. this.mergeOption(baseOption);
  17711. }
  17712. optionChanged = true;
  17713. }
  17714. if (type === 'timeline' || type === 'media') {
  17715. this.restoreData();
  17716. }
  17717. if (!type || type === 'recreate' || type === 'timeline') {
  17718. var timelineOption = optionManager.getTimelineOption(this);
  17719. timelineOption && (this.mergeOption(timelineOption), optionChanged = true);
  17720. }
  17721. if (!type || type === 'recreate' || type === 'media') {
  17722. var mediaOptions = optionManager.getMediaOption(this, this._api);
  17723. if (mediaOptions.length) {
  17724. each$1(mediaOptions, function (mediaOption) {
  17725. this.mergeOption(mediaOption, optionChanged = true);
  17726. }, this);
  17727. }
  17728. }
  17729. return optionChanged;
  17730. },
  17731. /**
  17732. * @protected
  17733. */
  17734. mergeOption: function (newOption) {
  17735. var option = this.option;
  17736. var componentsMap = this._componentsMap;
  17737. var newCptTypes = [];
  17738. resetSourceDefaulter(this); // If no component class, merge directly.
  17739. // For example: color, animaiton options, etc.
  17740. each$1(newOption, function (componentOption, mainType) {
  17741. if (componentOption == null) {
  17742. return;
  17743. }
  17744. if (!ComponentModel.hasClass(mainType)) {
  17745. // globalSettingTask.dirty();
  17746. option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true);
  17747. } else if (mainType) {
  17748. newCptTypes.push(mainType);
  17749. }
  17750. });
  17751. ComponentModel.topologicalTravel(newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this);
  17752. function visitComponent(mainType, dependencies) {
  17753. var newCptOptionList = normalizeToArray(newOption[mainType]);
  17754. var mapResult = mappingToExists(componentsMap.get(mainType), newCptOptionList);
  17755. makeIdAndName(mapResult); // Set mainType and complete subType.
  17756. each$1(mapResult, function (item, index) {
  17757. var opt = item.option;
  17758. if (isObject$1(opt)) {
  17759. item.keyInfo.mainType = mainType;
  17760. item.keyInfo.subType = determineSubType(mainType, opt, item.exist);
  17761. }
  17762. });
  17763. var dependentModels = getComponentsByTypes(componentsMap, dependencies);
  17764. option[mainType] = [];
  17765. componentsMap.set(mainType, []);
  17766. each$1(mapResult, function (resultItem, index) {
  17767. var componentModel = resultItem.exist;
  17768. var newCptOption = resultItem.option;
  17769. assert$1(isObject$1(newCptOption) || componentModel, 'Empty component definition'); // Consider where is no new option and should be merged using {},
  17770. // see removeEdgeAndAdd in topologicalTravel and
  17771. // ComponentModel.getAllClassMainTypes.
  17772. if (!newCptOption) {
  17773. componentModel.mergeOption({}, this);
  17774. componentModel.optionUpdated({}, false);
  17775. } else {
  17776. var ComponentModelClass = ComponentModel.getClass(mainType, resultItem.keyInfo.subType, true);
  17777. if (componentModel && componentModel.constructor === ComponentModelClass) {
  17778. componentModel.name = resultItem.keyInfo.name; // componentModel.settingTask && componentModel.settingTask.dirty();
  17779. componentModel.mergeOption(newCptOption, this);
  17780. componentModel.optionUpdated(newCptOption, false);
  17781. } else {
  17782. // PENDING Global as parent ?
  17783. var extraOpt = extend({
  17784. dependentModels: dependentModels,
  17785. componentIndex: index
  17786. }, resultItem.keyInfo);
  17787. componentModel = new ComponentModelClass(newCptOption, this, this, extraOpt);
  17788. extend(componentModel, extraOpt);
  17789. componentModel.init(newCptOption, this, this, extraOpt); // Call optionUpdated after init.
  17790. // newCptOption has been used as componentModel.option
  17791. // and may be merged with theme and default, so pass null
  17792. // to avoid confusion.
  17793. componentModel.optionUpdated(null, true);
  17794. }
  17795. }
  17796. componentsMap.get(mainType)[index] = componentModel;
  17797. option[mainType][index] = componentModel.option;
  17798. }, this); // Backup series for filtering.
  17799. if (mainType === 'series') {
  17800. createSeriesIndices(this, componentsMap.get('series'));
  17801. }
  17802. }
  17803. this._seriesIndicesMap = createHashMap(this._seriesIndices = this._seriesIndices || []);
  17804. },
  17805. /**
  17806. * Get option for output (cloned option and inner info removed)
  17807. * @public
  17808. * @return {Object}
  17809. */
  17810. getOption: function () {
  17811. var option = clone(this.option);
  17812. each$1(option, function (opts, mainType) {
  17813. if (ComponentModel.hasClass(mainType)) {
  17814. var opts = normalizeToArray(opts);
  17815. for (var i = opts.length - 1; i >= 0; i--) {
  17816. // Remove options with inner id.
  17817. if (isIdInner(opts[i])) {
  17818. opts.splice(i, 1);
  17819. }
  17820. }
  17821. option[mainType] = opts;
  17822. }
  17823. });
  17824. delete option[OPTION_INNER_KEY];
  17825. return option;
  17826. },
  17827. /**
  17828. * @return {module:echarts/model/Model}
  17829. */
  17830. getTheme: function () {
  17831. return this._theme;
  17832. },
  17833. /**
  17834. * @param {string} mainType
  17835. * @param {number} [idx=0]
  17836. * @return {module:echarts/model/Component}
  17837. */
  17838. getComponent: function (mainType, idx) {
  17839. var list = this._componentsMap.get(mainType);
  17840. if (list) {
  17841. return list[idx || 0];
  17842. }
  17843. },
  17844. /**
  17845. * If none of index and id and name used, return all components with mainType.
  17846. * @param {Object} condition
  17847. * @param {string} condition.mainType
  17848. * @param {string} [condition.subType] If ignore, only query by mainType
  17849. * @param {number|Array.<number>} [condition.index] Either input index or id or name.
  17850. * @param {string|Array.<string>} [condition.id] Either input index or id or name.
  17851. * @param {string|Array.<string>} [condition.name] Either input index or id or name.
  17852. * @return {Array.<module:echarts/model/Component>}
  17853. */
  17854. queryComponents: function (condition) {
  17855. var mainType = condition.mainType;
  17856. if (!mainType) {
  17857. return [];
  17858. }
  17859. var index = condition.index;
  17860. var id = condition.id;
  17861. var name = condition.name;
  17862. var cpts = this._componentsMap.get(mainType);
  17863. if (!cpts || !cpts.length) {
  17864. return [];
  17865. }
  17866. var result;
  17867. if (index != null) {
  17868. if (!isArray(index)) {
  17869. index = [index];
  17870. }
  17871. result = filter(map(index, function (idx) {
  17872. return cpts[idx];
  17873. }), function (val) {
  17874. return !!val;
  17875. });
  17876. } else if (id != null) {
  17877. var isIdArray = isArray(id);
  17878. result = filter(cpts, function (cpt) {
  17879. return isIdArray && indexOf(id, cpt.id) >= 0 || !isIdArray && cpt.id === id;
  17880. });
  17881. } else if (name != null) {
  17882. var isNameArray = isArray(name);
  17883. result = filter(cpts, function (cpt) {
  17884. return isNameArray && indexOf(name, cpt.name) >= 0 || !isNameArray && cpt.name === name;
  17885. });
  17886. } else {
  17887. // Return all components with mainType
  17888. result = cpts.slice();
  17889. }
  17890. return filterBySubType(result, condition);
  17891. },
  17892. /**
  17893. * The interface is different from queryComponents,
  17894. * which is convenient for inner usage.
  17895. *
  17896. * @usage
  17897. * var result = findComponents(
  17898. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}
  17899. * );
  17900. * var result = findComponents(
  17901. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}
  17902. * );
  17903. * var result = findComponents(
  17904. * {mainType: 'series',
  17905. * filter: function (model, index) {...}}
  17906. * );
  17907. * // result like [component0, componnet1, ...]
  17908. *
  17909. * @param {Object} condition
  17910. * @param {string} condition.mainType Mandatory.
  17911. * @param {string} [condition.subType] Optional.
  17912. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName},
  17913. * where xxx is mainType.
  17914. * If query attribute is null/undefined or has no index/id/name,
  17915. * do not filtering by query conditions, which is convenient for
  17916. * no-payload situations or when target of action is global.
  17917. * @param {Function} [condition.filter] parameter: component, return boolean.
  17918. * @return {Array.<module:echarts/model/Component>}
  17919. */
  17920. findComponents: function (condition) {
  17921. var query = condition.query;
  17922. var mainType = condition.mainType;
  17923. var queryCond = getQueryCond(query);
  17924. var result = queryCond ? this.queryComponents(queryCond) : this._componentsMap.get(mainType);
  17925. return doFilter(filterBySubType(result, condition));
  17926. function getQueryCond(q) {
  17927. var indexAttr = mainType + 'Index';
  17928. var idAttr = mainType + 'Id';
  17929. var nameAttr = mainType + 'Name';
  17930. return q && (q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null) ? {
  17931. mainType: mainType,
  17932. // subType will be filtered finally.
  17933. index: q[indexAttr],
  17934. id: q[idAttr],
  17935. name: q[nameAttr]
  17936. } : null;
  17937. }
  17938. function doFilter(res) {
  17939. return condition.filter ? filter(res, condition.filter) : res;
  17940. }
  17941. },
  17942. /**
  17943. * @usage
  17944. * eachComponent('legend', function (legendModel, index) {
  17945. * ...
  17946. * });
  17947. * eachComponent(function (componentType, model, index) {
  17948. * // componentType does not include subType
  17949. * // (componentType is 'xxx' but not 'xxx.aa')
  17950. * });
  17951. * eachComponent(
  17952. * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}},
  17953. * function (model, index) {...}
  17954. * );
  17955. * eachComponent(
  17956. * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}},
  17957. * function (model, index) {...}
  17958. * );
  17959. *
  17960. * @param {string|Object=} mainType When mainType is object, the definition
  17961. * is the same as the method 'findComponents'.
  17962. * @param {Function} cb
  17963. * @param {*} context
  17964. */
  17965. eachComponent: function (mainType, cb, context) {
  17966. var componentsMap = this._componentsMap;
  17967. if (typeof mainType === 'function') {
  17968. context = cb;
  17969. cb = mainType;
  17970. componentsMap.each(function (components, componentType) {
  17971. each$1(components, function (component, index) {
  17972. cb.call(context, componentType, component, index);
  17973. });
  17974. });
  17975. } else if (isString(mainType)) {
  17976. each$1(componentsMap.get(mainType), cb, context);
  17977. } else if (isObject$1(mainType)) {
  17978. var queryResult = this.findComponents(mainType);
  17979. each$1(queryResult, cb, context);
  17980. }
  17981. },
  17982. /**
  17983. * @param {string} name
  17984. * @return {Array.<module:echarts/model/Series>}
  17985. */
  17986. getSeriesByName: function (name) {
  17987. var series = this._componentsMap.get('series');
  17988. return filter(series, function (oneSeries) {
  17989. return oneSeries.name === name;
  17990. });
  17991. },
  17992. /**
  17993. * @param {number} seriesIndex
  17994. * @return {module:echarts/model/Series}
  17995. */
  17996. getSeriesByIndex: function (seriesIndex) {
  17997. return this._componentsMap.get('series')[seriesIndex];
  17998. },
  17999. /**
  18000. * Get series list before filtered by type.
  18001. * FIXME: rename to getRawSeriesByType?
  18002. *
  18003. * @param {string} subType
  18004. * @return {Array.<module:echarts/model/Series>}
  18005. */
  18006. getSeriesByType: function (subType) {
  18007. var series = this._componentsMap.get('series');
  18008. return filter(series, function (oneSeries) {
  18009. return oneSeries.subType === subType;
  18010. });
  18011. },
  18012. /**
  18013. * @return {Array.<module:echarts/model/Series>}
  18014. */
  18015. getSeries: function () {
  18016. return this._componentsMap.get('series').slice();
  18017. },
  18018. /**
  18019. * @return {number}
  18020. */
  18021. getSeriesCount: function () {
  18022. return this._componentsMap.get('series').length;
  18023. },
  18024. /**
  18025. * After filtering, series may be different
  18026. * frome raw series.
  18027. *
  18028. * @param {Function} cb
  18029. * @param {*} context
  18030. */
  18031. eachSeries: function (cb, context) {
  18032. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18033. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18034. cb.call(context, series, rawSeriesIndex);
  18035. }, this);
  18036. },
  18037. /**
  18038. * Iterate raw series before filtered.
  18039. *
  18040. * @param {Function} cb
  18041. * @param {*} context
  18042. */
  18043. eachRawSeries: function (cb, context) {
  18044. each$1(this._componentsMap.get('series'), cb, context);
  18045. },
  18046. /**
  18047. * After filtering, series may be different.
  18048. * frome raw series.
  18049. *
  18050. * @param {string} subType.
  18051. * @param {Function} cb
  18052. * @param {*} context
  18053. */
  18054. eachSeriesByType: function (subType, cb, context) {
  18055. each$1(this._seriesIndices, function (rawSeriesIndex) {
  18056. var series = this._componentsMap.get('series')[rawSeriesIndex];
  18057. if (series.subType === subType) {
  18058. cb.call(context, series, rawSeriesIndex);
  18059. }
  18060. }, this);
  18061. },
  18062. /**
  18063. * Iterate raw series before filtered of given type.
  18064. *
  18065. * @parma {string} subType
  18066. * @param {Function} cb
  18067. * @param {*} context
  18068. */
  18069. eachRawSeriesByType: function (subType, cb, context) {
  18070. return each$1(this.getSeriesByType(subType), cb, context);
  18071. },
  18072. /**
  18073. * @param {module:echarts/model/Series} seriesModel
  18074. */
  18075. isSeriesFiltered: function (seriesModel) {
  18076. return this._seriesIndicesMap.get(seriesModel.componentIndex) == null;
  18077. },
  18078. /**
  18079. * @return {Array.<number>}
  18080. */
  18081. getCurrentSeriesIndices: function () {
  18082. return (this._seriesIndices || []).slice();
  18083. },
  18084. /**
  18085. * @param {Function} cb
  18086. * @param {*} context
  18087. */
  18088. filterSeries: function (cb, context) {
  18089. var filteredSeries = filter(this._componentsMap.get('series'), cb, context);
  18090. createSeriesIndices(this, filteredSeries);
  18091. },
  18092. restoreData: function (payload) {
  18093. var componentsMap = this._componentsMap;
  18094. createSeriesIndices(this, componentsMap.get('series'));
  18095. var componentTypes = [];
  18096. componentsMap.each(function (components, componentType) {
  18097. componentTypes.push(componentType);
  18098. });
  18099. ComponentModel.topologicalTravel(componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType, dependencies) {
  18100. each$1(componentsMap.get(componentType), function (component) {
  18101. (componentType !== 'series' || !isNotTargetSeries(component, payload)) && component.restoreData();
  18102. });
  18103. });
  18104. }
  18105. });
  18106. function isNotTargetSeries(seriesModel, payload) {
  18107. if (payload) {
  18108. var index = payload.seiresIndex;
  18109. var id = payload.seriesId;
  18110. var name = payload.seriesName;
  18111. return index != null && seriesModel.componentIndex !== index || id != null && seriesModel.id !== id || name != null && seriesModel.name !== name;
  18112. }
  18113. }
  18114. /**
  18115. * @inner
  18116. */
  18117. function mergeTheme(option, theme) {
  18118. // PENDING
  18119. // NOT use `colorLayer` in theme if option has `color`
  18120. var notMergeColorLayer = option.color && !option.colorLayer;
  18121. each$1(theme, function (themeItem, name) {
  18122. if (name === 'colorLayer' && notMergeColorLayer) {
  18123. return;
  18124. } // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理
  18125. if (!ComponentModel.hasClass(name)) {
  18126. if (typeof themeItem === 'object') {
  18127. option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false);
  18128. } else {
  18129. if (option[name] == null) {
  18130. option[name] = themeItem;
  18131. }
  18132. }
  18133. }
  18134. });
  18135. }
  18136. function initBase(baseOption) {
  18137. baseOption = baseOption; // Using OPTION_INNER_KEY to mark that this option can not be used outside,
  18138. // i.e. `chart.setOption(chart.getModel().option);` is forbiden.
  18139. this.option = {};
  18140. this.option[OPTION_INNER_KEY] = 1;
  18141. /**
  18142. * Init with series: [], in case of calling findSeries method
  18143. * before series initialized.
  18144. * @type {Object.<string, Array.<module:echarts/model/Model>>}
  18145. * @private
  18146. */
  18147. this._componentsMap = createHashMap({
  18148. series: []
  18149. });
  18150. /**
  18151. * Mapping between filtered series list and raw series list.
  18152. * key: filtered series indices, value: raw series indices.
  18153. * @type {Array.<nubmer>}
  18154. * @private
  18155. */
  18156. this._seriesIndices;
  18157. this._seriesIndicesMap;
  18158. mergeTheme(baseOption, this._theme.option); // TODO Needs clone when merging to the unexisted property
  18159. merge(baseOption, globalDefault, false);
  18160. this.mergeOption(baseOption);
  18161. }
  18162. /**
  18163. * @inner
  18164. * @param {Array.<string>|string} types model types
  18165. * @return {Object} key: {string} type, value: {Array.<Object>} models
  18166. */
  18167. function getComponentsByTypes(componentsMap, types) {
  18168. if (!isArray(types)) {
  18169. types = types ? [types] : [];
  18170. }
  18171. var ret = {};
  18172. each$1(types, function (type) {
  18173. ret[type] = (componentsMap.get(type) || []).slice();
  18174. });
  18175. return ret;
  18176. }
  18177. /**
  18178. * @inner
  18179. */
  18180. function determineSubType(mainType, newCptOption, existComponent) {
  18181. var subType = newCptOption.type ? newCptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent.
  18182. : ComponentModel.determineSubType(mainType, newCptOption); // tooltip, markline, markpoint may always has no subType
  18183. return subType;
  18184. }
  18185. /**
  18186. * @inner
  18187. */
  18188. function createSeriesIndices(ecModel, seriesModels) {
  18189. ecModel._seriesIndicesMap = createHashMap(ecModel._seriesIndices = map(seriesModels, function (series) {
  18190. return series.componentIndex;
  18191. }) || []);
  18192. }
  18193. /**
  18194. * @inner
  18195. */
  18196. function filterBySubType(components, condition) {
  18197. // Using hasOwnProperty for restrict. Consider
  18198. // subType is undefined in user payload.
  18199. return condition.hasOwnProperty('subType') ? filter(components, function (cpt) {
  18200. return cpt.subType === condition.subType;
  18201. }) : components;
  18202. }
  18203. mixin(GlobalModel, colorPaletteMixin);
  18204. /*
  18205. * Licensed to the Apache Software Foundation (ASF) under one
  18206. * or more contributor license agreements. See the NOTICE file
  18207. * distributed with this work for additional information
  18208. * regarding copyright ownership. The ASF licenses this file
  18209. * to you under the Apache License, Version 2.0 (the
  18210. * "License"); you may not use this file except in compliance
  18211. * with the License. You may obtain a copy of the License at
  18212. *
  18213. * http://www.apache.org/licenses/LICENSE-2.0
  18214. *
  18215. * Unless required by applicable law or agreed to in writing,
  18216. * software distributed under the License is distributed on an
  18217. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18218. * KIND, either express or implied. See the License for the
  18219. * specific language governing permissions and limitations
  18220. * under the License.
  18221. */
  18222. var echartsAPIList = ['getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption', 'getViewOfComponentModel', 'getViewOfSeriesModel']; // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js
  18223. function ExtensionAPI(chartInstance) {
  18224. each$1(echartsAPIList, function (name) {
  18225. this[name] = bind(chartInstance[name], chartInstance);
  18226. }, this);
  18227. }
  18228. /*
  18229. * Licensed to the Apache Software Foundation (ASF) under one
  18230. * or more contributor license agreements. See the NOTICE file
  18231. * distributed with this work for additional information
  18232. * regarding copyright ownership. The ASF licenses this file
  18233. * to you under the Apache License, Version 2.0 (the
  18234. * "License"); you may not use this file except in compliance
  18235. * with the License. You may obtain a copy of the License at
  18236. *
  18237. * http://www.apache.org/licenses/LICENSE-2.0
  18238. *
  18239. * Unless required by applicable law or agreed to in writing,
  18240. * software distributed under the License is distributed on an
  18241. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18242. * KIND, either express or implied. See the License for the
  18243. * specific language governing permissions and limitations
  18244. * under the License.
  18245. */
  18246. var coordinateSystemCreators = {};
  18247. function CoordinateSystemManager() {
  18248. this._coordinateSystems = [];
  18249. }
  18250. CoordinateSystemManager.prototype = {
  18251. constructor: CoordinateSystemManager,
  18252. create: function (ecModel, api) {
  18253. var coordinateSystems = [];
  18254. each$1(coordinateSystemCreators, function (creater, type) {
  18255. var list = creater.create(ecModel, api);
  18256. coordinateSystems = coordinateSystems.concat(list || []);
  18257. });
  18258. this._coordinateSystems = coordinateSystems;
  18259. },
  18260. update: function (ecModel, api) {
  18261. each$1(this._coordinateSystems, function (coordSys) {
  18262. coordSys.update && coordSys.update(ecModel, api);
  18263. });
  18264. },
  18265. getCoordinateSystems: function () {
  18266. return this._coordinateSystems.slice();
  18267. }
  18268. };
  18269. CoordinateSystemManager.register = function (type, coordinateSystemCreator) {
  18270. coordinateSystemCreators[type] = coordinateSystemCreator;
  18271. };
  18272. CoordinateSystemManager.get = function (type) {
  18273. return coordinateSystemCreators[type];
  18274. };
  18275. /*
  18276. * Licensed to the Apache Software Foundation (ASF) under one
  18277. * or more contributor license agreements. See the NOTICE file
  18278. * distributed with this work for additional information
  18279. * regarding copyright ownership. The ASF licenses this file
  18280. * to you under the Apache License, Version 2.0 (the
  18281. * "License"); you may not use this file except in compliance
  18282. * with the License. You may obtain a copy of the License at
  18283. *
  18284. * http://www.apache.org/licenses/LICENSE-2.0
  18285. *
  18286. * Unless required by applicable law or agreed to in writing,
  18287. * software distributed under the License is distributed on an
  18288. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18289. * KIND, either express or implied. See the License for the
  18290. * specific language governing permissions and limitations
  18291. * under the License.
  18292. */
  18293. /**
  18294. * ECharts option manager
  18295. *
  18296. * @module {echarts/model/OptionManager}
  18297. */
  18298. var each$4 = each$1;
  18299. var clone$3 = clone;
  18300. var map$1 = map;
  18301. var merge$1 = merge;
  18302. var QUERY_REG = /^(min|max)?(.+)$/;
  18303. /**
  18304. * TERM EXPLANATIONS:
  18305. *
  18306. * [option]:
  18307. *
  18308. * An object that contains definitions of components. For example:
  18309. * var option = {
  18310. * title: {...},
  18311. * legend: {...},
  18312. * visualMap: {...},
  18313. * series: [
  18314. * {data: [...]},
  18315. * {data: [...]},
  18316. * ...
  18317. * ]
  18318. * };
  18319. *
  18320. * [rawOption]:
  18321. *
  18322. * An object input to echarts.setOption. 'rawOption' may be an
  18323. * 'option', or may be an object contains multi-options. For example:
  18324. * var option = {
  18325. * baseOption: {
  18326. * title: {...},
  18327. * legend: {...},
  18328. * series: [
  18329. * {data: [...]},
  18330. * {data: [...]},
  18331. * ...
  18332. * ]
  18333. * },
  18334. * timeline: {...},
  18335. * options: [
  18336. * {title: {...}, series: {data: [...]}},
  18337. * {title: {...}, series: {data: [...]}},
  18338. * ...
  18339. * ],
  18340. * media: [
  18341. * {
  18342. * query: {maxWidth: 320},
  18343. * option: {series: {x: 20}, visualMap: {show: false}}
  18344. * },
  18345. * {
  18346. * query: {minWidth: 320, maxWidth: 720},
  18347. * option: {series: {x: 500}, visualMap: {show: true}}
  18348. * },
  18349. * {
  18350. * option: {series: {x: 1200}, visualMap: {show: true}}
  18351. * }
  18352. * ]
  18353. * };
  18354. *
  18355. * @alias module:echarts/model/OptionManager
  18356. * @param {module:echarts/ExtensionAPI} api
  18357. */
  18358. function OptionManager(api) {
  18359. /**
  18360. * @private
  18361. * @type {module:echarts/ExtensionAPI}
  18362. */
  18363. this._api = api;
  18364. /**
  18365. * @private
  18366. * @type {Array.<number>}
  18367. */
  18368. this._timelineOptions = [];
  18369. /**
  18370. * @private
  18371. * @type {Array.<Object>}
  18372. */
  18373. this._mediaList = [];
  18374. /**
  18375. * @private
  18376. * @type {Object}
  18377. */
  18378. this._mediaDefault;
  18379. /**
  18380. * -1, means default.
  18381. * empty means no media.
  18382. * @private
  18383. * @type {Array.<number>}
  18384. */
  18385. this._currentMediaIndices = [];
  18386. /**
  18387. * @private
  18388. * @type {Object}
  18389. */
  18390. this._optionBackup;
  18391. /**
  18392. * @private
  18393. * @type {Object}
  18394. */
  18395. this._newBaseOption;
  18396. } // timeline.notMerge is not supported in ec3. Firstly there is rearly
  18397. // case that notMerge is needed. Secondly supporting 'notMerge' requires
  18398. // rawOption cloned and backuped when timeline changed, which does no
  18399. // good to performance. What's more, that both timeline and setOption
  18400. // method supply 'notMerge' brings complex and some problems.
  18401. // Consider this case:
  18402. // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false);
  18403. // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false);
  18404. OptionManager.prototype = {
  18405. constructor: OptionManager,
  18406. /**
  18407. * @public
  18408. * @param {Object} rawOption Raw option.
  18409. * @param {module:echarts/model/Global} ecModel
  18410. * @param {Array.<Function>} optionPreprocessorFuncs
  18411. * @return {Object} Init option
  18412. */
  18413. setOption: function (rawOption, optionPreprocessorFuncs) {
  18414. if (rawOption) {
  18415. // That set dat primitive is dangerous if user reuse the data when setOption again.
  18416. each$1(normalizeToArray(rawOption.series), function (series) {
  18417. series && series.data && isTypedArray(series.data) && setAsPrimitive(series.data);
  18418. });
  18419. } // Caution: some series modify option data, if do not clone,
  18420. // it should ensure that the repeat modify correctly
  18421. // (create a new object when modify itself).
  18422. rawOption = clone$3(rawOption); // FIXME
  18423. // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。
  18424. var oldOptionBackup = this._optionBackup;
  18425. var newParsedOption = parseRawOption.call(this, rawOption, optionPreprocessorFuncs, !oldOptionBackup);
  18426. this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode);
  18427. if (oldOptionBackup) {
  18428. // Only baseOption can be merged.
  18429. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption); // For simplicity, timeline options and media options do not support merge,
  18430. // that is, if you `setOption` twice and both has timeline options, the latter
  18431. // timeline opitons will not be merged to the formers, but just substitude them.
  18432. if (newParsedOption.timelineOptions.length) {
  18433. oldOptionBackup.timelineOptions = newParsedOption.timelineOptions;
  18434. }
  18435. if (newParsedOption.mediaList.length) {
  18436. oldOptionBackup.mediaList = newParsedOption.mediaList;
  18437. }
  18438. if (newParsedOption.mediaDefault) {
  18439. oldOptionBackup.mediaDefault = newParsedOption.mediaDefault;
  18440. }
  18441. } else {
  18442. this._optionBackup = newParsedOption;
  18443. }
  18444. },
  18445. /**
  18446. * @param {boolean} isRecreate
  18447. * @return {Object}
  18448. */
  18449. mountOption: function (isRecreate) {
  18450. var optionBackup = this._optionBackup; // TODO
  18451. // 如果没有reset功能则不clone。
  18452. this._timelineOptions = map$1(optionBackup.timelineOptions, clone$3);
  18453. this._mediaList = map$1(optionBackup.mediaList, clone$3);
  18454. this._mediaDefault = clone$3(optionBackup.mediaDefault);
  18455. this._currentMediaIndices = [];
  18456. return clone$3(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption`
  18457. // called, and is merged into every new option by inner method `mergeOption`
  18458. // each time `setOption` called, can be only used in `isRecreate`, because
  18459. // its reliability is under suspicion. In other cases option merge is
  18460. // performed by `model.mergeOption`.
  18461. ? optionBackup.baseOption : this._newBaseOption);
  18462. },
  18463. /**
  18464. * @param {module:echarts/model/Global} ecModel
  18465. * @return {Object}
  18466. */
  18467. getTimelineOption: function (ecModel) {
  18468. var option;
  18469. var timelineOptions = this._timelineOptions;
  18470. if (timelineOptions.length) {
  18471. // getTimelineOption can only be called after ecModel inited,
  18472. // so we can get currentIndex from timelineModel.
  18473. var timelineModel = ecModel.getComponent('timeline');
  18474. if (timelineModel) {
  18475. option = clone$3(timelineOptions[timelineModel.getCurrentIndex()], true);
  18476. }
  18477. }
  18478. return option;
  18479. },
  18480. /**
  18481. * @param {module:echarts/model/Global} ecModel
  18482. * @return {Array.<Object>}
  18483. */
  18484. getMediaOption: function (ecModel) {
  18485. var ecWidth = this._api.getWidth();
  18486. var ecHeight = this._api.getHeight();
  18487. var mediaList = this._mediaList;
  18488. var mediaDefault = this._mediaDefault;
  18489. var indices = [];
  18490. var result = []; // No media defined.
  18491. if (!mediaList.length && !mediaDefault) {
  18492. return result;
  18493. } // Multi media may be applied, the latter defined media has higher priority.
  18494. for (var i = 0, len = mediaList.length; i < len; i++) {
  18495. if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) {
  18496. indices.push(i);
  18497. }
  18498. } // FIXME
  18499. // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。
  18500. if (!indices.length && mediaDefault) {
  18501. indices = [-1];
  18502. }
  18503. if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) {
  18504. result = map$1(indices, function (index) {
  18505. return clone$3(index === -1 ? mediaDefault.option : mediaList[index].option);
  18506. });
  18507. } // Otherwise return nothing.
  18508. this._currentMediaIndices = indices;
  18509. return result;
  18510. }
  18511. };
  18512. function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) {
  18513. var timelineOptions = [];
  18514. var mediaList = [];
  18515. var mediaDefault;
  18516. var baseOption; // Compatible with ec2.
  18517. var timelineOpt = rawOption.timeline;
  18518. if (rawOption.baseOption) {
  18519. baseOption = rawOption.baseOption;
  18520. } // For timeline
  18521. if (timelineOpt || rawOption.options) {
  18522. baseOption = baseOption || {};
  18523. timelineOptions = (rawOption.options || []).slice();
  18524. } // For media query
  18525. if (rawOption.media) {
  18526. baseOption = baseOption || {};
  18527. var media = rawOption.media;
  18528. each$4(media, function (singleMedia) {
  18529. if (singleMedia && singleMedia.option) {
  18530. if (singleMedia.query) {
  18531. mediaList.push(singleMedia);
  18532. } else if (!mediaDefault) {
  18533. // Use the first media default.
  18534. mediaDefault = singleMedia;
  18535. }
  18536. }
  18537. });
  18538. } // For normal option
  18539. if (!baseOption) {
  18540. baseOption = rawOption;
  18541. } // Set timelineOpt to baseOption in ec3,
  18542. // which is convenient for merge option.
  18543. if (!baseOption.timeline) {
  18544. baseOption.timeline = timelineOpt;
  18545. } // Preprocess.
  18546. each$4([baseOption].concat(timelineOptions).concat(map(mediaList, function (media) {
  18547. return media.option;
  18548. })), function (option) {
  18549. each$4(optionPreprocessorFuncs, function (preProcess) {
  18550. preProcess(option, isNew);
  18551. });
  18552. });
  18553. return {
  18554. baseOption: baseOption,
  18555. timelineOptions: timelineOptions,
  18556. mediaDefault: mediaDefault,
  18557. mediaList: mediaList
  18558. };
  18559. }
  18560. /**
  18561. * @see <http://www.w3.org/TR/css3-mediaqueries/#media1>
  18562. * Support: width, height, aspectRatio
  18563. * Can use max or min as prefix.
  18564. */
  18565. function applyMediaQuery(query, ecWidth, ecHeight) {
  18566. var realMap = {
  18567. width: ecWidth,
  18568. height: ecHeight,
  18569. aspectratio: ecWidth / ecHeight // lowser case for convenientce.
  18570. };
  18571. var applicatable = true;
  18572. each$1(query, function (value, attr) {
  18573. var matched = attr.match(QUERY_REG);
  18574. if (!matched || !matched[1] || !matched[2]) {
  18575. return;
  18576. }
  18577. var operator = matched[1];
  18578. var realAttr = matched[2].toLowerCase();
  18579. if (!compare(realMap[realAttr], value, operator)) {
  18580. applicatable = false;
  18581. }
  18582. });
  18583. return applicatable;
  18584. }
  18585. function compare(real, expect, operator) {
  18586. if (operator === 'min') {
  18587. return real >= expect;
  18588. } else if (operator === 'max') {
  18589. return real <= expect;
  18590. } else {
  18591. // Equals
  18592. return real === expect;
  18593. }
  18594. }
  18595. function indicesEquals(indices1, indices2) {
  18596. // indices is always order by asc and has only finite number.
  18597. return indices1.join(',') === indices2.join(',');
  18598. }
  18599. /**
  18600. * Consider case:
  18601. * `chart.setOption(opt1);`
  18602. * Then user do some interaction like dataZoom, dataView changing.
  18603. * `chart.setOption(opt2);`
  18604. * Then user press 'reset button' in toolbox.
  18605. *
  18606. * After doing that all of the interaction effects should be reset, the
  18607. * chart should be the same as the result of invoke
  18608. * `chart.setOption(opt1); chart.setOption(opt2);`.
  18609. *
  18610. * Although it is not able ensure that
  18611. * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to
  18612. * `chart.setOption(merge(opt1, opt2));` exactly,
  18613. * this might be the only simple way to implement that feature.
  18614. *
  18615. * MEMO: We've considered some other approaches:
  18616. * 1. Each model handle its self restoration but not uniform treatment.
  18617. * (Too complex in logic and error-prone)
  18618. * 2. Use a shadow ecModel. (Performace expensive)
  18619. */
  18620. function mergeOption(oldOption, newOption) {
  18621. newOption = newOption || {};
  18622. each$4(newOption, function (newCptOpt, mainType) {
  18623. if (newCptOpt == null) {
  18624. return;
  18625. }
  18626. var oldCptOpt = oldOption[mainType];
  18627. if (!ComponentModel.hasClass(mainType)) {
  18628. oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true);
  18629. } else {
  18630. newCptOpt = normalizeToArray(newCptOpt);
  18631. oldCptOpt = normalizeToArray(oldCptOpt);
  18632. var mapResult = mappingToExists(oldCptOpt, newCptOpt);
  18633. oldOption[mainType] = map$1(mapResult, function (item) {
  18634. return item.option && item.exist ? merge$1(item.exist, item.option, true) : item.exist || item.option;
  18635. });
  18636. }
  18637. });
  18638. }
  18639. /*
  18640. * Licensed to the Apache Software Foundation (ASF) under one
  18641. * or more contributor license agreements. See the NOTICE file
  18642. * distributed with this work for additional information
  18643. * regarding copyright ownership. The ASF licenses this file
  18644. * to you under the Apache License, Version 2.0 (the
  18645. * "License"); you may not use this file except in compliance
  18646. * with the License. You may obtain a copy of the License at
  18647. *
  18648. * http://www.apache.org/licenses/LICENSE-2.0
  18649. *
  18650. * Unless required by applicable law or agreed to in writing,
  18651. * software distributed under the License is distributed on an
  18652. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18653. * KIND, either express or implied. See the License for the
  18654. * specific language governing permissions and limitations
  18655. * under the License.
  18656. */
  18657. var each$5 = each$1;
  18658. var isObject$3 = isObject$1;
  18659. var POSSIBLE_STYLES = ['areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine'];
  18660. function compatEC2ItemStyle(opt) {
  18661. var itemStyleOpt = opt && opt.itemStyle;
  18662. if (!itemStyleOpt) {
  18663. return;
  18664. }
  18665. for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) {
  18666. var styleName = POSSIBLE_STYLES[i];
  18667. var normalItemStyleOpt = itemStyleOpt.normal;
  18668. var emphasisItemStyleOpt = itemStyleOpt.emphasis;
  18669. if (normalItemStyleOpt && normalItemStyleOpt[styleName]) {
  18670. opt[styleName] = opt[styleName] || {};
  18671. if (!opt[styleName].normal) {
  18672. opt[styleName].normal = normalItemStyleOpt[styleName];
  18673. } else {
  18674. merge(opt[styleName].normal, normalItemStyleOpt[styleName]);
  18675. }
  18676. normalItemStyleOpt[styleName] = null;
  18677. }
  18678. if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) {
  18679. opt[styleName] = opt[styleName] || {};
  18680. if (!opt[styleName].emphasis) {
  18681. opt[styleName].emphasis = emphasisItemStyleOpt[styleName];
  18682. } else {
  18683. merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]);
  18684. }
  18685. emphasisItemStyleOpt[styleName] = null;
  18686. }
  18687. }
  18688. }
  18689. function convertNormalEmphasis(opt, optType, useExtend) {
  18690. if (opt && opt[optType] && (opt[optType].normal || opt[optType].emphasis)) {
  18691. var normalOpt = opt[optType].normal;
  18692. var emphasisOpt = opt[optType].emphasis;
  18693. if (normalOpt) {
  18694. // Timeline controlStyle has other properties besides normal and emphasis
  18695. if (useExtend) {
  18696. opt[optType].normal = opt[optType].emphasis = null;
  18697. defaults(opt[optType], normalOpt);
  18698. } else {
  18699. opt[optType] = normalOpt;
  18700. }
  18701. }
  18702. if (emphasisOpt) {
  18703. opt.emphasis = opt.emphasis || {};
  18704. opt.emphasis[optType] = emphasisOpt;
  18705. }
  18706. }
  18707. }
  18708. function removeEC3NormalStatus(opt) {
  18709. convertNormalEmphasis(opt, 'itemStyle');
  18710. convertNormalEmphasis(opt, 'lineStyle');
  18711. convertNormalEmphasis(opt, 'areaStyle');
  18712. convertNormalEmphasis(opt, 'label');
  18713. convertNormalEmphasis(opt, 'labelLine'); // treemap
  18714. convertNormalEmphasis(opt, 'upperLabel'); // graph
  18715. convertNormalEmphasis(opt, 'edgeLabel');
  18716. }
  18717. function compatTextStyle(opt, propName) {
  18718. // Check whether is not object (string\null\undefined ...)
  18719. var labelOptSingle = isObject$3(opt) && opt[propName];
  18720. var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle;
  18721. if (textStyle) {
  18722. for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) {
  18723. var propName = TEXT_STYLE_OPTIONS[i];
  18724. if (textStyle.hasOwnProperty(propName)) {
  18725. labelOptSingle[propName] = textStyle[propName];
  18726. }
  18727. }
  18728. }
  18729. }
  18730. function compatEC3CommonStyles(opt) {
  18731. if (opt) {
  18732. removeEC3NormalStatus(opt);
  18733. compatTextStyle(opt, 'label');
  18734. opt.emphasis && compatTextStyle(opt.emphasis, 'label');
  18735. }
  18736. }
  18737. function processSeries(seriesOpt) {
  18738. if (!isObject$3(seriesOpt)) {
  18739. return;
  18740. }
  18741. compatEC2ItemStyle(seriesOpt);
  18742. removeEC3NormalStatus(seriesOpt);
  18743. compatTextStyle(seriesOpt, 'label'); // treemap
  18744. compatTextStyle(seriesOpt, 'upperLabel'); // graph
  18745. compatTextStyle(seriesOpt, 'edgeLabel');
  18746. if (seriesOpt.emphasis) {
  18747. compatTextStyle(seriesOpt.emphasis, 'label'); // treemap
  18748. compatTextStyle(seriesOpt.emphasis, 'upperLabel'); // graph
  18749. compatTextStyle(seriesOpt.emphasis, 'edgeLabel');
  18750. }
  18751. var markPoint = seriesOpt.markPoint;
  18752. if (markPoint) {
  18753. compatEC2ItemStyle(markPoint);
  18754. compatEC3CommonStyles(markPoint);
  18755. }
  18756. var markLine = seriesOpt.markLine;
  18757. if (markLine) {
  18758. compatEC2ItemStyle(markLine);
  18759. compatEC3CommonStyles(markLine);
  18760. }
  18761. var markArea = seriesOpt.markArea;
  18762. if (markArea) {
  18763. compatEC3CommonStyles(markArea);
  18764. }
  18765. var data = seriesOpt.data; // Break with ec3: if `setOption` again, there may be no `type` in option,
  18766. // then the backward compat based on option type will not be performed.
  18767. if (seriesOpt.type === 'graph') {
  18768. data = data || seriesOpt.nodes;
  18769. var edgeData = seriesOpt.links || seriesOpt.edges;
  18770. if (edgeData && !isTypedArray(edgeData)) {
  18771. for (var i = 0; i < edgeData.length; i++) {
  18772. compatEC3CommonStyles(edgeData[i]);
  18773. }
  18774. }
  18775. each$1(seriesOpt.categories, function (opt) {
  18776. removeEC3NormalStatus(opt);
  18777. });
  18778. }
  18779. if (data && !isTypedArray(data)) {
  18780. for (var i = 0; i < data.length; i++) {
  18781. compatEC3CommonStyles(data[i]);
  18782. }
  18783. } // mark point data
  18784. var markPoint = seriesOpt.markPoint;
  18785. if (markPoint && markPoint.data) {
  18786. var mpData = markPoint.data;
  18787. for (var i = 0; i < mpData.length; i++) {
  18788. compatEC3CommonStyles(mpData[i]);
  18789. }
  18790. } // mark line data
  18791. var markLine = seriesOpt.markLine;
  18792. if (markLine && markLine.data) {
  18793. var mlData = markLine.data;
  18794. for (var i = 0; i < mlData.length; i++) {
  18795. if (isArray(mlData[i])) {
  18796. compatEC3CommonStyles(mlData[i][0]);
  18797. compatEC3CommonStyles(mlData[i][1]);
  18798. } else {
  18799. compatEC3CommonStyles(mlData[i]);
  18800. }
  18801. }
  18802. } // Series
  18803. if (seriesOpt.type === 'gauge') {
  18804. compatTextStyle(seriesOpt, 'axisLabel');
  18805. compatTextStyle(seriesOpt, 'title');
  18806. compatTextStyle(seriesOpt, 'detail');
  18807. } else if (seriesOpt.type === 'treemap') {
  18808. convertNormalEmphasis(seriesOpt.breadcrumb, 'itemStyle');
  18809. each$1(seriesOpt.levels, function (opt) {
  18810. removeEC3NormalStatus(opt);
  18811. });
  18812. } else if (seriesOpt.type === 'tree') {
  18813. removeEC3NormalStatus(seriesOpt.leaves);
  18814. } // sunburst starts from ec4, so it does not need to compat levels.
  18815. }
  18816. function toArr(o) {
  18817. return isArray(o) ? o : o ? [o] : [];
  18818. }
  18819. function toObj(o) {
  18820. return (isArray(o) ? o[0] : o) || {};
  18821. }
  18822. var compatStyle = function (option, isTheme) {
  18823. each$5(toArr(option.series), function (seriesOpt) {
  18824. isObject$3(seriesOpt) && processSeries(seriesOpt);
  18825. });
  18826. var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar'];
  18827. isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis');
  18828. each$5(axes, function (axisName) {
  18829. each$5(toArr(option[axisName]), function (axisOpt) {
  18830. if (axisOpt) {
  18831. compatTextStyle(axisOpt, 'axisLabel');
  18832. compatTextStyle(axisOpt.axisPointer, 'label');
  18833. }
  18834. });
  18835. });
  18836. each$5(toArr(option.parallel), function (parallelOpt) {
  18837. var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault;
  18838. compatTextStyle(parallelAxisDefault, 'axisLabel');
  18839. compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label');
  18840. });
  18841. each$5(toArr(option.calendar), function (calendarOpt) {
  18842. convertNormalEmphasis(calendarOpt, 'itemStyle');
  18843. compatTextStyle(calendarOpt, 'dayLabel');
  18844. compatTextStyle(calendarOpt, 'monthLabel');
  18845. compatTextStyle(calendarOpt, 'yearLabel');
  18846. }); // radar.name.textStyle
  18847. each$5(toArr(option.radar), function (radarOpt) {
  18848. compatTextStyle(radarOpt, 'name');
  18849. });
  18850. each$5(toArr(option.geo), function (geoOpt) {
  18851. if (isObject$3(geoOpt)) {
  18852. compatEC3CommonStyles(geoOpt);
  18853. each$5(toArr(geoOpt.regions), function (regionObj) {
  18854. compatEC3CommonStyles(regionObj);
  18855. });
  18856. }
  18857. });
  18858. each$5(toArr(option.timeline), function (timelineOpt) {
  18859. compatEC3CommonStyles(timelineOpt);
  18860. convertNormalEmphasis(timelineOpt, 'label');
  18861. convertNormalEmphasis(timelineOpt, 'itemStyle');
  18862. convertNormalEmphasis(timelineOpt, 'controlStyle', true);
  18863. var data = timelineOpt.data;
  18864. isArray(data) && each$1(data, function (item) {
  18865. if (isObject$1(item)) {
  18866. convertNormalEmphasis(item, 'label');
  18867. convertNormalEmphasis(item, 'itemStyle');
  18868. }
  18869. });
  18870. });
  18871. each$5(toArr(option.toolbox), function (toolboxOpt) {
  18872. convertNormalEmphasis(toolboxOpt, 'iconStyle');
  18873. each$5(toolboxOpt.feature, function (featureOpt) {
  18874. convertNormalEmphasis(featureOpt, 'iconStyle');
  18875. });
  18876. });
  18877. compatTextStyle(toObj(option.axisPointer), 'label');
  18878. compatTextStyle(toObj(option.tooltip).axisPointer, 'label');
  18879. };
  18880. /*
  18881. * Licensed to the Apache Software Foundation (ASF) under one
  18882. * or more contributor license agreements. See the NOTICE file
  18883. * distributed with this work for additional information
  18884. * regarding copyright ownership. The ASF licenses this file
  18885. * to you under the Apache License, Version 2.0 (the
  18886. * "License"); you may not use this file except in compliance
  18887. * with the License. You may obtain a copy of the License at
  18888. *
  18889. * http://www.apache.org/licenses/LICENSE-2.0
  18890. *
  18891. * Unless required by applicable law or agreed to in writing,
  18892. * software distributed under the License is distributed on an
  18893. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18894. * KIND, either express or implied. See the License for the
  18895. * specific language governing permissions and limitations
  18896. * under the License.
  18897. */
  18898. // Compatitable with 2.0
  18899. function get(opt, path) {
  18900. path = path.split(',');
  18901. var obj = opt;
  18902. for (var i = 0; i < path.length; i++) {
  18903. obj = obj && obj[path[i]];
  18904. if (obj == null) {
  18905. break;
  18906. }
  18907. }
  18908. return obj;
  18909. }
  18910. function set$1(opt, path, val, overwrite) {
  18911. path = path.split(',');
  18912. var obj = opt;
  18913. var key;
  18914. for (var i = 0; i < path.length - 1; i++) {
  18915. key = path[i];
  18916. if (obj[key] == null) {
  18917. obj[key] = {};
  18918. }
  18919. obj = obj[key];
  18920. }
  18921. if (overwrite || obj[path[i]] == null) {
  18922. obj[path[i]] = val;
  18923. }
  18924. }
  18925. function compatLayoutProperties(option) {
  18926. each$1(LAYOUT_PROPERTIES, function (prop) {
  18927. if (prop[0] in option && !(prop[1] in option)) {
  18928. option[prop[1]] = option[prop[0]];
  18929. }
  18930. });
  18931. }
  18932. var LAYOUT_PROPERTIES = [['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom']];
  18933. var COMPATITABLE_COMPONENTS = ['grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline'];
  18934. var backwardCompat = function (option, isTheme) {
  18935. compatStyle(option, isTheme); // Make sure series array for model initialization.
  18936. option.series = normalizeToArray(option.series);
  18937. each$1(option.series, function (seriesOpt) {
  18938. if (!isObject$1(seriesOpt)) {
  18939. return;
  18940. }
  18941. var seriesType = seriesOpt.type;
  18942. if (seriesType === 'line') {
  18943. if (seriesOpt.clipOverflow != null) {
  18944. seriesOpt.clip = seriesOpt.clipOverflow;
  18945. }
  18946. } else if (seriesType === 'pie' || seriesType === 'gauge') {
  18947. if (seriesOpt.clockWise != null) {
  18948. seriesOpt.clockwise = seriesOpt.clockWise;
  18949. }
  18950. } else if (seriesType === 'gauge') {
  18951. var pointerColor = get(seriesOpt, 'pointer.color');
  18952. pointerColor != null && set$1(seriesOpt, 'itemStyle.color', pointerColor);
  18953. }
  18954. compatLayoutProperties(seriesOpt);
  18955. }); // dataRange has changed to visualMap
  18956. if (option.dataRange) {
  18957. option.visualMap = option.dataRange;
  18958. }
  18959. each$1(COMPATITABLE_COMPONENTS, function (componentName) {
  18960. var options = option[componentName];
  18961. if (options) {
  18962. if (!isArray(options)) {
  18963. options = [options];
  18964. }
  18965. each$1(options, function (option) {
  18966. compatLayoutProperties(option);
  18967. });
  18968. }
  18969. });
  18970. };
  18971. /*
  18972. * Licensed to the Apache Software Foundation (ASF) under one
  18973. * or more contributor license agreements. See the NOTICE file
  18974. * distributed with this work for additional information
  18975. * regarding copyright ownership. The ASF licenses this file
  18976. * to you under the Apache License, Version 2.0 (the
  18977. * "License"); you may not use this file except in compliance
  18978. * with the License. You may obtain a copy of the License at
  18979. *
  18980. * http://www.apache.org/licenses/LICENSE-2.0
  18981. *
  18982. * Unless required by applicable law or agreed to in writing,
  18983. * software distributed under the License is distributed on an
  18984. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  18985. * KIND, either express or implied. See the License for the
  18986. * specific language governing permissions and limitations
  18987. * under the License.
  18988. */
  18989. // data processing stage is blocked in stream.
  18990. // See <module:echarts/stream/Scheduler#performDataProcessorTasks>
  18991. // (2) Only register once when import repeatly.
  18992. // Should be executed after series filtered and before stack calculation.
  18993. var dataStack = function (ecModel) {
  18994. var stackInfoMap = createHashMap();
  18995. ecModel.eachSeries(function (seriesModel) {
  18996. var stack = seriesModel.get('stack'); // Compatibal: when `stack` is set as '', do not stack.
  18997. if (stack) {
  18998. var stackInfoList = stackInfoMap.get(stack) || stackInfoMap.set(stack, []);
  18999. var data = seriesModel.getData();
  19000. var stackInfo = {
  19001. // Used for calculate axis extent automatically.
  19002. stackResultDimension: data.getCalculationInfo('stackResultDimension'),
  19003. stackedOverDimension: data.getCalculationInfo('stackedOverDimension'),
  19004. stackedDimension: data.getCalculationInfo('stackedDimension'),
  19005. stackedByDimension: data.getCalculationInfo('stackedByDimension'),
  19006. isStackedByIndex: data.getCalculationInfo('isStackedByIndex'),
  19007. data: data,
  19008. seriesModel: seriesModel
  19009. }; // If stacked on axis that do not support data stack.
  19010. if (!stackInfo.stackedDimension || !(stackInfo.isStackedByIndex || stackInfo.stackedByDimension)) {
  19011. return;
  19012. }
  19013. stackInfoList.length && data.setCalculationInfo('stackedOnSeries', stackInfoList[stackInfoList.length - 1].seriesModel);
  19014. stackInfoList.push(stackInfo);
  19015. }
  19016. });
  19017. stackInfoMap.each(calculateStack);
  19018. };
  19019. function calculateStack(stackInfoList) {
  19020. each$1(stackInfoList, function (targetStackInfo, idxInStack) {
  19021. var resultVal = [];
  19022. var resultNaN = [NaN, NaN];
  19023. var dims = [targetStackInfo.stackResultDimension, targetStackInfo.stackedOverDimension];
  19024. var targetData = targetStackInfo.data;
  19025. var isStackedByIndex = targetStackInfo.isStackedByIndex; // Should not write on raw data, because stack series model list changes
  19026. // depending on legend selection.
  19027. var newData = targetData.map(dims, function (v0, v1, dataIndex) {
  19028. var sum = targetData.get(targetStackInfo.stackedDimension, dataIndex); // Consider `connectNulls` of line area, if value is NaN, stackedOver
  19029. // should also be NaN, to draw a appropriate belt area.
  19030. if (isNaN(sum)) {
  19031. return resultNaN;
  19032. }
  19033. var byValue;
  19034. var stackedDataRawIndex;
  19035. if (isStackedByIndex) {
  19036. stackedDataRawIndex = targetData.getRawIndex(dataIndex);
  19037. } else {
  19038. byValue = targetData.get(targetStackInfo.stackedByDimension, dataIndex);
  19039. } // If stackOver is NaN, chart view will render point on value start.
  19040. var stackedOver = NaN;
  19041. for (var j = idxInStack - 1; j >= 0; j--) {
  19042. var stackInfo = stackInfoList[j]; // Has been optimized by inverted indices on `stackedByDimension`.
  19043. if (!isStackedByIndex) {
  19044. stackedDataRawIndex = stackInfo.data.rawIndexOf(stackInfo.stackedByDimension, byValue);
  19045. }
  19046. if (stackedDataRawIndex >= 0) {
  19047. var val = stackInfo.data.getByRawIndex(stackInfo.stackResultDimension, stackedDataRawIndex); // Considering positive stack, negative stack and empty data
  19048. if (sum >= 0 && val > 0 || // Positive stack
  19049. sum <= 0 && val < 0 // Negative stack
  19050. ) {
  19051. sum += val;
  19052. stackedOver = val;
  19053. break;
  19054. }
  19055. }
  19056. }
  19057. resultVal[0] = sum;
  19058. resultVal[1] = stackedOver;
  19059. return resultVal;
  19060. });
  19061. targetData.hostModel.setData(newData); // Update for consequent calculation
  19062. targetStackInfo.data = newData;
  19063. });
  19064. }
  19065. /*
  19066. * Licensed to the Apache Software Foundation (ASF) under one
  19067. * or more contributor license agreements. See the NOTICE file
  19068. * distributed with this work for additional information
  19069. * regarding copyright ownership. The ASF licenses this file
  19070. * to you under the Apache License, Version 2.0 (the
  19071. * "License"); you may not use this file except in compliance
  19072. * with the License. You may obtain a copy of the License at
  19073. *
  19074. * http://www.apache.org/licenses/LICENSE-2.0
  19075. *
  19076. * Unless required by applicable law or agreed to in writing,
  19077. * software distributed under the License is distributed on an
  19078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19079. * KIND, either express or implied. See the License for the
  19080. * specific language governing permissions and limitations
  19081. * under the License.
  19082. */
  19083. // TODO
  19084. // ??? refactor? check the outer usage of data provider.
  19085. // merge with defaultDimValueGetter?
  19086. /**
  19087. * If normal array used, mutable chunk size is supported.
  19088. * If typed array used, chunk size must be fixed.
  19089. */
  19090. function DefaultDataProvider(source, dimSize) {
  19091. if (!Source.isInstance(source)) {
  19092. source = Source.seriesDataToSource(source);
  19093. }
  19094. this._source = source;
  19095. var data = this._data = source.data;
  19096. var sourceFormat = source.sourceFormat; // Typed array. TODO IE10+?
  19097. if (sourceFormat === SOURCE_FORMAT_TYPED_ARRAY) {
  19098. this._offset = 0;
  19099. this._dimSize = dimSize;
  19100. this._data = data;
  19101. }
  19102. var methods = providerMethods[sourceFormat === SOURCE_FORMAT_ARRAY_ROWS ? sourceFormat + '_' + source.seriesLayoutBy : sourceFormat];
  19103. extend(this, methods);
  19104. }
  19105. var providerProto = DefaultDataProvider.prototype; // If data is pure without style configuration
  19106. providerProto.pure = false; // If data is persistent and will not be released after use.
  19107. providerProto.persistent = true; // ???! FIXME legacy data provider do not has method getSource
  19108. providerProto.getSource = function () {
  19109. return this._source;
  19110. };
  19111. var providerMethods = {
  19112. 'arrayRows_column': {
  19113. pure: true,
  19114. count: function () {
  19115. return Math.max(0, this._data.length - this._source.startIndex);
  19116. },
  19117. getItem: function (idx) {
  19118. return this._data[idx + this._source.startIndex];
  19119. },
  19120. appendData: appendDataSimply
  19121. },
  19122. 'arrayRows_row': {
  19123. pure: true,
  19124. count: function () {
  19125. var row = this._data[0];
  19126. return row ? Math.max(0, row.length - this._source.startIndex) : 0;
  19127. },
  19128. getItem: function (idx) {
  19129. idx += this._source.startIndex;
  19130. var item = [];
  19131. var data = this._data;
  19132. for (var i = 0; i < data.length; i++) {
  19133. var row = data[i];
  19134. item.push(row ? row[idx] : null);
  19135. }
  19136. return item;
  19137. },
  19138. appendData: function () {
  19139. throw new Error('Do not support appendData when set seriesLayoutBy: "row".');
  19140. }
  19141. },
  19142. 'objectRows': {
  19143. pure: true,
  19144. count: countSimply,
  19145. getItem: getItemSimply,
  19146. appendData: appendDataSimply
  19147. },
  19148. 'keyedColumns': {
  19149. pure: true,
  19150. count: function () {
  19151. var dimName = this._source.dimensionsDefine[0].name;
  19152. var col = this._data[dimName];
  19153. return col ? col.length : 0;
  19154. },
  19155. getItem: function (idx) {
  19156. var item = [];
  19157. var dims = this._source.dimensionsDefine;
  19158. for (var i = 0; i < dims.length; i++) {
  19159. var col = this._data[dims[i].name];
  19160. item.push(col ? col[idx] : null);
  19161. }
  19162. return item;
  19163. },
  19164. appendData: function (newData) {
  19165. var data = this._data;
  19166. each$1(newData, function (newCol, key) {
  19167. var oldCol = data[key] || (data[key] = []);
  19168. for (var i = 0; i < (newCol || []).length; i++) {
  19169. oldCol.push(newCol[i]);
  19170. }
  19171. });
  19172. }
  19173. },
  19174. 'original': {
  19175. count: countSimply,
  19176. getItem: getItemSimply,
  19177. appendData: appendDataSimply
  19178. },
  19179. 'typedArray': {
  19180. persistent: false,
  19181. pure: true,
  19182. count: function () {
  19183. return this._data ? this._data.length / this._dimSize : 0;
  19184. },
  19185. getItem: function (idx, out) {
  19186. idx = idx - this._offset;
  19187. out = out || [];
  19188. var offset = this._dimSize * idx;
  19189. for (var i = 0; i < this._dimSize; i++) {
  19190. out[i] = this._data[offset + i];
  19191. }
  19192. return out;
  19193. },
  19194. appendData: function (newData) {
  19195. this._data = newData;
  19196. },
  19197. // Clean self if data is already used.
  19198. clean: function () {
  19199. // PENDING
  19200. this._offset += this.count();
  19201. this._data = null;
  19202. }
  19203. }
  19204. };
  19205. function countSimply() {
  19206. return this._data.length;
  19207. }
  19208. function getItemSimply(idx) {
  19209. return this._data[idx];
  19210. }
  19211. function appendDataSimply(newData) {
  19212. for (var i = 0; i < newData.length; i++) {
  19213. this._data.push(newData[i]);
  19214. }
  19215. }
  19216. var rawValueGetters = {
  19217. arrayRows: getRawValueSimply,
  19218. objectRows: function (dataItem, dataIndex, dimIndex, dimName) {
  19219. return dimIndex != null ? dataItem[dimName] : dataItem;
  19220. },
  19221. keyedColumns: getRawValueSimply,
  19222. original: function (dataItem, dataIndex, dimIndex, dimName) {
  19223. // FIXME
  19224. // In some case (markpoint in geo (geo-map.html)), dataItem
  19225. // is {coord: [...]}
  19226. var value = getDataItemValue(dataItem);
  19227. return dimIndex == null || !(value instanceof Array) ? value : value[dimIndex];
  19228. },
  19229. typedArray: getRawValueSimply
  19230. };
  19231. function getRawValueSimply(dataItem, dataIndex, dimIndex, dimName) {
  19232. return dimIndex != null ? dataItem[dimIndex] : dataItem;
  19233. }
  19234. var defaultDimValueGetters = {
  19235. arrayRows: getDimValueSimply,
  19236. objectRows: function (dataItem, dimName, dataIndex, dimIndex) {
  19237. return converDataValue(dataItem[dimName], this._dimensionInfos[dimName]);
  19238. },
  19239. keyedColumns: getDimValueSimply,
  19240. original: function (dataItem, dimName, dataIndex, dimIndex) {
  19241. // Performance sensitive, do not use modelUtil.getDataItemValue.
  19242. // If dataItem is an plain object with no value field, the var `value`
  19243. // will be assigned with the object, but it will be tread correctly
  19244. // in the `convertDataValue`.
  19245. var value = dataItem && (dataItem.value == null ? dataItem : dataItem.value); // If any dataItem is like { value: 10 }
  19246. if (!this._rawData.pure && isDataItemOption(dataItem)) {
  19247. this.hasItemOption = true;
  19248. }
  19249. return converDataValue(value instanceof Array ? value[dimIndex] // If value is a single number or something else not array.
  19250. : value, this._dimensionInfos[dimName]);
  19251. },
  19252. typedArray: function (dataItem, dimName, dataIndex, dimIndex) {
  19253. return dataItem[dimIndex];
  19254. }
  19255. };
  19256. function getDimValueSimply(dataItem, dimName, dataIndex, dimIndex) {
  19257. return converDataValue(dataItem[dimIndex], this._dimensionInfos[dimName]);
  19258. }
  19259. /**
  19260. * This helper method convert value in data.
  19261. * @param {string|number|Date} value
  19262. * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'.
  19263. * If "dimInfo.ordinalParseAndSave", ordinal value can be parsed.
  19264. */
  19265. function converDataValue(value, dimInfo) {
  19266. // Performance sensitive.
  19267. var dimType = dimInfo && dimInfo.type;
  19268. if (dimType === 'ordinal') {
  19269. // If given value is a category string
  19270. var ordinalMeta = dimInfo && dimInfo.ordinalMeta;
  19271. return ordinalMeta ? ordinalMeta.parseAndCollect(value) : value;
  19272. }
  19273. if (dimType === 'time' // spead up when using timestamp
  19274. && typeof value !== 'number' && value != null && value !== '-') {
  19275. value = +parseDate(value);
  19276. } // dimType defaults 'number'.
  19277. // If dimType is not ordinal and value is null or undefined or NaN or '-',
  19278. // parse to NaN.
  19279. return value == null || value === '' ? NaN // If string (like '-'), using '+' parse to NaN
  19280. // If object, also parse to NaN
  19281. : +value;
  19282. } // ??? FIXME can these logic be more neat: getRawValue, getRawDataItem,
  19283. // Consider persistent.
  19284. // Caution: why use raw value to display on label or tooltip?
  19285. // A reason is to avoid format. For example time value we do not know
  19286. // how to format is expected. More over, if stack is used, calculated
  19287. // value may be 0.91000000001, which have brings trouble to display.
  19288. // TODO: consider how to treat null/undefined/NaN when display?
  19289. /**
  19290. * @param {module:echarts/data/List} data
  19291. * @param {number} dataIndex
  19292. * @param {string|number} [dim] dimName or dimIndex
  19293. * @return {Array.<number>|string|number} can be null/undefined.
  19294. */
  19295. function retrieveRawValue(data, dataIndex, dim) {
  19296. if (!data) {
  19297. return;
  19298. } // Consider data may be not persistent.
  19299. var dataItem = data.getRawDataItem(dataIndex);
  19300. if (dataItem == null) {
  19301. return;
  19302. }
  19303. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19304. var dimName;
  19305. var dimIndex;
  19306. var dimInfo = data.getDimensionInfo(dim);
  19307. if (dimInfo) {
  19308. dimName = dimInfo.name;
  19309. dimIndex = dimInfo.index;
  19310. }
  19311. return rawValueGetters[sourceFormat](dataItem, dataIndex, dimIndex, dimName);
  19312. }
  19313. /**
  19314. * Compatible with some cases (in pie, map) like:
  19315. * data: [{name: 'xx', value: 5, selected: true}, ...]
  19316. * where only sourceFormat is 'original' and 'objectRows' supported.
  19317. *
  19318. * ??? TODO
  19319. * Supported detail options in data item when using 'arrayRows'.
  19320. *
  19321. * @param {module:echarts/data/List} data
  19322. * @param {number} dataIndex
  19323. * @param {string} attr like 'selected'
  19324. */
  19325. function retrieveRawAttr(data, dataIndex, attr) {
  19326. if (!data) {
  19327. return;
  19328. }
  19329. var sourceFormat = data.getProvider().getSource().sourceFormat;
  19330. if (sourceFormat !== SOURCE_FORMAT_ORIGINAL && sourceFormat !== SOURCE_FORMAT_OBJECT_ROWS) {
  19331. return;
  19332. }
  19333. var dataItem = data.getRawDataItem(dataIndex);
  19334. if (sourceFormat === SOURCE_FORMAT_ORIGINAL && !isObject$1(dataItem)) {
  19335. dataItem = null;
  19336. }
  19337. if (dataItem) {
  19338. return dataItem[attr];
  19339. }
  19340. }
  19341. /*
  19342. * Licensed to the Apache Software Foundation (ASF) under one
  19343. * or more contributor license agreements. See the NOTICE file
  19344. * distributed with this work for additional information
  19345. * regarding copyright ownership. The ASF licenses this file
  19346. * to you under the Apache License, Version 2.0 (the
  19347. * "License"); you may not use this file except in compliance
  19348. * with the License. You may obtain a copy of the License at
  19349. *
  19350. * http://www.apache.org/licenses/LICENSE-2.0
  19351. *
  19352. * Unless required by applicable law or agreed to in writing,
  19353. * software distributed under the License is distributed on an
  19354. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19355. * KIND, either express or implied. See the License for the
  19356. * specific language governing permissions and limitations
  19357. * under the License.
  19358. */
  19359. var DIMENSION_LABEL_REG = /\{@(.+?)\}/g; // PENDING A little ugly
  19360. var dataFormatMixin = {
  19361. /**
  19362. * Get params for formatter
  19363. * @param {number} dataIndex
  19364. * @param {string} [dataType]
  19365. * @return {Object}
  19366. */
  19367. getDataParams: function (dataIndex, dataType) {
  19368. var data = this.getData(dataType);
  19369. var rawValue = this.getRawValue(dataIndex, dataType);
  19370. var rawDataIndex = data.getRawIndex(dataIndex);
  19371. var name = data.getName(dataIndex);
  19372. var itemOpt = data.getRawDataItem(dataIndex);
  19373. var color = data.getItemVisual(dataIndex, 'color');
  19374. var borderColor = data.getItemVisual(dataIndex, 'borderColor');
  19375. var tooltipModel = this.ecModel.getComponent('tooltip');
  19376. var renderModeOption = tooltipModel && tooltipModel.get('renderMode');
  19377. var renderMode = getTooltipRenderMode(renderModeOption);
  19378. var mainType = this.mainType;
  19379. var isSeries = mainType === 'series';
  19380. var userOutput = data.userOutput;
  19381. return {
  19382. componentType: mainType,
  19383. componentSubType: this.subType,
  19384. componentIndex: this.componentIndex,
  19385. seriesType: isSeries ? this.subType : null,
  19386. seriesIndex: this.seriesIndex,
  19387. seriesId: isSeries ? this.id : null,
  19388. seriesName: isSeries ? this.name : null,
  19389. name: name,
  19390. dataIndex: rawDataIndex,
  19391. data: itemOpt,
  19392. dataType: dataType,
  19393. value: rawValue,
  19394. color: color,
  19395. borderColor: borderColor,
  19396. dimensionNames: userOutput ? userOutput.dimensionNames : null,
  19397. encode: userOutput ? userOutput.encode : null,
  19398. marker: getTooltipMarker({
  19399. color: color,
  19400. renderMode: renderMode
  19401. }),
  19402. // Param name list for mapping `a`, `b`, `c`, `d`, `e`
  19403. $vars: ['seriesName', 'name', 'value']
  19404. };
  19405. },
  19406. /**
  19407. * Format label
  19408. * @param {number} dataIndex
  19409. * @param {string} [status='normal'] 'normal' or 'emphasis'
  19410. * @param {string} [dataType]
  19411. * @param {number} [dimIndex] Only used in some chart that
  19412. * use formatter in different dimensions, like radar.
  19413. * @param {string} [labelProp='label']
  19414. * @return {string} If not formatter, return null/undefined
  19415. */
  19416. getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) {
  19417. status = status || 'normal';
  19418. var data = this.getData(dataType);
  19419. var itemModel = data.getItemModel(dataIndex);
  19420. var params = this.getDataParams(dataIndex, dataType);
  19421. if (dimIndex != null && params.value instanceof Array) {
  19422. params.value = params.value[dimIndex];
  19423. }
  19424. var formatter = itemModel.get(status === 'normal' ? [labelProp || 'label', 'formatter'] : [status, labelProp || 'label', 'formatter']);
  19425. if (typeof formatter === 'function') {
  19426. params.status = status;
  19427. params.dimensionIndex = dimIndex;
  19428. return formatter(params);
  19429. } else if (typeof formatter === 'string') {
  19430. var str = formatTpl(formatter, params); // Support 'aaa{@[3]}bbb{@product}ccc'.
  19431. // Do not support '}' in dim name util have to.
  19432. return str.replace(DIMENSION_LABEL_REG, function (origin, dim) {
  19433. var len = dim.length;
  19434. if (dim.charAt(0) === '[' && dim.charAt(len - 1) === ']') {
  19435. dim = +dim.slice(1, len - 1); // Also: '[]' => 0
  19436. }
  19437. return retrieveRawValue(data, dataIndex, dim);
  19438. });
  19439. }
  19440. },
  19441. /**
  19442. * Get raw value in option
  19443. * @param {number} idx
  19444. * @param {string} [dataType]
  19445. * @return {Array|number|string}
  19446. */
  19447. getRawValue: function (idx, dataType) {
  19448. return retrieveRawValue(this.getData(dataType), idx);
  19449. },
  19450. /**
  19451. * Should be implemented.
  19452. * @param {number} dataIndex
  19453. * @param {boolean} [multipleSeries=false]
  19454. * @param {number} [dataType]
  19455. * @return {string} tooltip string
  19456. */
  19457. formatTooltip: function () {// Empty function
  19458. }
  19459. };
  19460. /*
  19461. * Licensed to the Apache Software Foundation (ASF) under one
  19462. * or more contributor license agreements. See the NOTICE file
  19463. * distributed with this work for additional information
  19464. * regarding copyright ownership. The ASF licenses this file
  19465. * to you under the Apache License, Version 2.0 (the
  19466. * "License"); you may not use this file except in compliance
  19467. * with the License. You may obtain a copy of the License at
  19468. *
  19469. * http://www.apache.org/licenses/LICENSE-2.0
  19470. *
  19471. * Unless required by applicable law or agreed to in writing,
  19472. * software distributed under the License is distributed on an
  19473. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19474. * KIND, either express or implied. See the License for the
  19475. * specific language governing permissions and limitations
  19476. * under the License.
  19477. */
  19478. /**
  19479. * @param {Object} define
  19480. * @return See the return of `createTask`.
  19481. */
  19482. function createTask(define) {
  19483. return new Task(define);
  19484. }
  19485. /**
  19486. * @constructor
  19487. * @param {Object} define
  19488. * @param {Function} define.reset Custom reset
  19489. * @param {Function} [define.plan] Returns 'reset' indicate reset immediately.
  19490. * @param {Function} [define.count] count is used to determin data task.
  19491. * @param {Function} [define.onDirty] count is used to determin data task.
  19492. */
  19493. function Task(define) {
  19494. define = define || {};
  19495. this._reset = define.reset;
  19496. this._plan = define.plan;
  19497. this._count = define.count;
  19498. this._onDirty = define.onDirty;
  19499. this._dirty = true; // Context must be specified implicitly, to
  19500. // avoid miss update context when model changed.
  19501. this.context;
  19502. }
  19503. var taskProto = Task.prototype;
  19504. /**
  19505. * @param {Object} performArgs
  19506. * @param {number} [performArgs.step] Specified step.
  19507. * @param {number} [performArgs.skip] Skip customer perform call.
  19508. * @param {number} [performArgs.modBy] Sampling window size.
  19509. * @param {number} [performArgs.modDataCount] Sampling count.
  19510. */
  19511. taskProto.perform = function (performArgs) {
  19512. var upTask = this._upstream;
  19513. var skip = performArgs && performArgs.skip; // TODO some refactor.
  19514. // Pull data. Must pull data each time, because context.data
  19515. // may be updated by Series.setData.
  19516. if (this._dirty && upTask) {
  19517. var context = this.context;
  19518. context.data = context.outputData = upTask.context.outputData;
  19519. }
  19520. if (this.__pipeline) {
  19521. this.__pipeline.currentTask = this;
  19522. }
  19523. var planResult;
  19524. if (this._plan && !skip) {
  19525. planResult = this._plan(this.context);
  19526. } // Support sharding by mod, which changes the render sequence and makes the rendered graphic
  19527. // elements uniformed distributed when progress, especially when moving or zooming.
  19528. var lastModBy = normalizeModBy(this._modBy);
  19529. var lastModDataCount = this._modDataCount || 0;
  19530. var modBy = normalizeModBy(performArgs && performArgs.modBy);
  19531. var modDataCount = performArgs && performArgs.modDataCount || 0;
  19532. if (lastModBy !== modBy || lastModDataCount !== modDataCount) {
  19533. planResult = 'reset';
  19534. }
  19535. function normalizeModBy(val) {
  19536. !(val >= 1) && (val = 1); // jshint ignore:line
  19537. return val;
  19538. }
  19539. var forceFirstProgress;
  19540. if (this._dirty || planResult === 'reset') {
  19541. this._dirty = false;
  19542. forceFirstProgress = reset(this, skip);
  19543. }
  19544. this._modBy = modBy;
  19545. this._modDataCount = modDataCount;
  19546. var step = performArgs && performArgs.step;
  19547. if (upTask) {
  19548. this._dueEnd = upTask._outputDueEnd;
  19549. } // DataTask or overallTask
  19550. else {
  19551. this._dueEnd = this._count ? this._count(this.context) : Infinity;
  19552. } // Note: Stubs, that its host overall task let it has progress, has progress.
  19553. // If no progress, pass index from upstream to downstream each time plan called.
  19554. if (this._progress) {
  19555. var start = this._dueIndex;
  19556. var end = Math.min(step != null ? this._dueIndex + step : Infinity, this._dueEnd);
  19557. if (!skip && (forceFirstProgress || start < end)) {
  19558. var progress = this._progress;
  19559. if (isArray(progress)) {
  19560. for (var i = 0; i < progress.length; i++) {
  19561. doProgress(this, progress[i], start, end, modBy, modDataCount);
  19562. }
  19563. } else {
  19564. doProgress(this, progress, start, end, modBy, modDataCount);
  19565. }
  19566. }
  19567. this._dueIndex = end; // If no `outputDueEnd`, assume that output data and
  19568. // input data is the same, so use `dueIndex` as `outputDueEnd`.
  19569. var outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : end;
  19570. this._outputDueEnd = outputDueEnd;
  19571. } else {
  19572. // (1) Some overall task has no progress.
  19573. // (2) Stubs, that its host overall task do not let it has progress, has no progress.
  19574. // This should always be performed so it can be passed to downstream.
  19575. this._dueIndex = this._outputDueEnd = this._settedOutputEnd != null ? this._settedOutputEnd : this._dueEnd;
  19576. }
  19577. return this.unfinished();
  19578. };
  19579. var iterator = function () {
  19580. var end;
  19581. var current;
  19582. var modBy;
  19583. var modDataCount;
  19584. var winCount;
  19585. var it = {
  19586. reset: function (s, e, sStep, sCount) {
  19587. current = s;
  19588. end = e;
  19589. modBy = sStep;
  19590. modDataCount = sCount;
  19591. winCount = Math.ceil(modDataCount / modBy);
  19592. it.next = modBy > 1 && modDataCount > 0 ? modNext : sequentialNext;
  19593. }
  19594. };
  19595. return it;
  19596. function sequentialNext() {
  19597. return current < end ? current++ : null;
  19598. }
  19599. function modNext() {
  19600. var dataIndex = current % winCount * modBy + Math.ceil(current / winCount);
  19601. var result = current >= end ? null : dataIndex < modDataCount ? dataIndex // If modDataCount is smaller than data.count() (consider `appendData` case),
  19602. // Use normal linear rendering mode.
  19603. : current;
  19604. current++;
  19605. return result;
  19606. }
  19607. }();
  19608. taskProto.dirty = function () {
  19609. this._dirty = true;
  19610. this._onDirty && this._onDirty(this.context);
  19611. };
  19612. function doProgress(taskIns, progress, start, end, modBy, modDataCount) {
  19613. iterator.reset(start, end, modBy, modDataCount);
  19614. taskIns._callingProgress = progress;
  19615. taskIns._callingProgress({
  19616. start: start,
  19617. end: end,
  19618. count: end - start,
  19619. next: iterator.next
  19620. }, taskIns.context);
  19621. }
  19622. function reset(taskIns, skip) {
  19623. taskIns._dueIndex = taskIns._outputDueEnd = taskIns._dueEnd = 0;
  19624. taskIns._settedOutputEnd = null;
  19625. var progress;
  19626. var forceFirstProgress;
  19627. if (!skip && taskIns._reset) {
  19628. progress = taskIns._reset(taskIns.context);
  19629. if (progress && progress.progress) {
  19630. forceFirstProgress = progress.forceFirstProgress;
  19631. progress = progress.progress;
  19632. } // To simplify no progress checking, array must has item.
  19633. if (isArray(progress) && !progress.length) {
  19634. progress = null;
  19635. }
  19636. }
  19637. taskIns._progress = progress;
  19638. taskIns._modBy = taskIns._modDataCount = null;
  19639. var downstream = taskIns._downstream;
  19640. downstream && downstream.dirty();
  19641. return forceFirstProgress;
  19642. }
  19643. /**
  19644. * @return {boolean}
  19645. */
  19646. taskProto.unfinished = function () {
  19647. return this._progress && this._dueIndex < this._dueEnd;
  19648. };
  19649. /**
  19650. * @param {Object} downTask The downstream task.
  19651. * @return {Object} The downstream task.
  19652. */
  19653. taskProto.pipe = function (downTask) {
  19654. // If already downstream, do not dirty downTask.
  19655. if (this._downstream !== downTask || this._dirty) {
  19656. this._downstream = downTask;
  19657. downTask._upstream = this;
  19658. downTask.dirty();
  19659. }
  19660. };
  19661. taskProto.dispose = function () {
  19662. if (this._disposed) {
  19663. return;
  19664. }
  19665. this._upstream && (this._upstream._downstream = null);
  19666. this._downstream && (this._downstream._upstream = null);
  19667. this._dirty = false;
  19668. this._disposed = true;
  19669. };
  19670. taskProto.getUpstream = function () {
  19671. return this._upstream;
  19672. };
  19673. taskProto.getDownstream = function () {
  19674. return this._downstream;
  19675. };
  19676. taskProto.setOutputEnd = function (end) {
  19677. // This only happend in dataTask, dataZoom, map, currently.
  19678. // where dataZoom do not set end each time, but only set
  19679. // when reset. So we should record the setted end, in case
  19680. // that the stub of dataZoom perform again and earse the
  19681. // setted end by upstream.
  19682. this._outputDueEnd = this._settedOutputEnd = end;
  19683. }; ///////////////////////////////////////////////////////////
  19684. // For stream debug (Should be commented out after used!)
  19685. // Usage: printTask(this, 'begin');
  19686. // Usage: printTask(this, null, {someExtraProp});
  19687. // function printTask(task, prefix, extra) {
  19688. // window.ecTaskUID == null && (window.ecTaskUID = 0);
  19689. // task.uidDebug == null && (task.uidDebug = `task_${window.ecTaskUID++}`);
  19690. // task.agent && task.agent.uidDebug == null && (task.agent.uidDebug = `task_${window.ecTaskUID++}`);
  19691. // var props = [];
  19692. // if (task.__pipeline) {
  19693. // var val = `${task.__idxInPipeline}/${task.__pipeline.tail.__idxInPipeline} ${task.agent ? '(stub)' : ''}`;
  19694. // props.push({text: 'idx', value: val});
  19695. // } else {
  19696. // var stubCount = 0;
  19697. // task.agentStubMap.each(() => stubCount++);
  19698. // props.push({text: 'idx', value: `overall (stubs: ${stubCount})`});
  19699. // }
  19700. // props.push({text: 'uid', value: task.uidDebug});
  19701. // if (task.__pipeline) {
  19702. // props.push({text: 'pid', value: task.__pipeline.id});
  19703. // task.agent && props.push(
  19704. // {text: 'stubFor', value: task.agent.uidDebug}
  19705. // );
  19706. // }
  19707. // props.push(
  19708. // {text: 'dirty', value: task._dirty},
  19709. // {text: 'dueIndex', value: task._dueIndex},
  19710. // {text: 'dueEnd', value: task._dueEnd},
  19711. // {text: 'outputDueEnd', value: task._outputDueEnd}
  19712. // );
  19713. // if (extra) {
  19714. // Object.keys(extra).forEach(key => {
  19715. // props.push({text: key, value: extra[key]});
  19716. // });
  19717. // }
  19718. // var args = ['color: blue'];
  19719. // var msg = `%c[${prefix || 'T'}] %c` + props.map(item => (
  19720. // args.push('color: black', 'color: red'),
  19721. // `${item.text}: %c${item.value}`
  19722. // )).join('%c, ');
  19723. // console.log.apply(console, [msg].concat(args));
  19724. // // console.log(this);
  19725. // }
  19726. /*
  19727. * Licensed to the Apache Software Foundation (ASF) under one
  19728. * or more contributor license agreements. See the NOTICE file
  19729. * distributed with this work for additional information
  19730. * regarding copyright ownership. The ASF licenses this file
  19731. * to you under the Apache License, Version 2.0 (the
  19732. * "License"); you may not use this file except in compliance
  19733. * with the License. You may obtain a copy of the License at
  19734. *
  19735. * http://www.apache.org/licenses/LICENSE-2.0
  19736. *
  19737. * Unless required by applicable law or agreed to in writing,
  19738. * software distributed under the License is distributed on an
  19739. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  19740. * KIND, either express or implied. See the License for the
  19741. * specific language governing permissions and limitations
  19742. * under the License.
  19743. */
  19744. var inner$4 = makeInner();
  19745. var SeriesModel = ComponentModel.extend({
  19746. type: 'series.__base__',
  19747. /**
  19748. * @readOnly
  19749. */
  19750. seriesIndex: 0,
  19751. // coodinateSystem will be injected in the echarts/CoordinateSystem
  19752. coordinateSystem: null,
  19753. /**
  19754. * @type {Object}
  19755. * @protected
  19756. */
  19757. defaultOption: null,
  19758. /**
  19759. * legend visual provider to the legend component
  19760. * @type {Object}
  19761. */
  19762. // PENDING
  19763. legendVisualProvider: null,
  19764. /**
  19765. * Access path of color for visual
  19766. */
  19767. visualColorAccessPath: 'itemStyle.color',
  19768. /**
  19769. * Access path of borderColor for visual
  19770. */
  19771. visualBorderColorAccessPath: 'itemStyle.borderColor',
  19772. /**
  19773. * Support merge layout params.
  19774. * Only support 'box' now (left/right/top/bottom/width/height).
  19775. * @type {string|Object} Object can be {ignoreSize: true}
  19776. * @readOnly
  19777. */
  19778. layoutMode: null,
  19779. init: function (option, parentModel, ecModel, extraOpt) {
  19780. /**
  19781. * @type {number}
  19782. * @readOnly
  19783. */
  19784. this.seriesIndex = this.componentIndex;
  19785. this.dataTask = createTask({
  19786. count: dataTaskCount,
  19787. reset: dataTaskReset
  19788. });
  19789. this.dataTask.context = {
  19790. model: this
  19791. };
  19792. this.mergeDefaultAndTheme(option, ecModel);
  19793. prepareSource(this);
  19794. var data = this.getInitialData(option, ecModel);
  19795. wrapData(data, this);
  19796. this.dataTask.context.data = data;
  19797. /**
  19798. * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph}
  19799. * @private
  19800. */
  19801. inner$4(this).dataBeforeProcessed = data; // If we reverse the order (make data firstly, and then make
  19802. // dataBeforeProcessed by cloneShallow), cloneShallow will
  19803. // cause data.graph.data !== data when using
  19804. // module:echarts/data/Graph or module:echarts/data/Tree.
  19805. // See module:echarts/data/helper/linkList
  19806. // Theoretically, it is unreasonable to call `seriesModel.getData()` in the model
  19807. // init or merge stage, because the data can be restored. So we do not `restoreData`
  19808. // and `setData` here, which forbids calling `seriesModel.getData()` in this stage.
  19809. // Call `seriesModel.getRawData()` instead.
  19810. // this.restoreData();
  19811. autoSeriesName(this);
  19812. },
  19813. /**
  19814. * Util for merge default and theme to option
  19815. * @param {Object} option
  19816. * @param {module:echarts/model/Global} ecModel
  19817. */
  19818. mergeDefaultAndTheme: function (option, ecModel) {
  19819. var layoutMode = this.layoutMode;
  19820. var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme.
  19821. // But if name duplicate between series subType
  19822. // (for example: parallel) add component mainType,
  19823. // add suffix 'Series'.
  19824. var themeSubType = this.subType;
  19825. if (ComponentModel.hasClass(themeSubType)) {
  19826. themeSubType += 'Series';
  19827. }
  19828. merge(option, ecModel.getTheme().get(this.subType));
  19829. merge(option, this.getDefaultOption()); // Default label emphasis `show`
  19830. defaultEmphasis(option, 'label', ['show']);
  19831. this.fillDataTextStyle(option.data);
  19832. if (layoutMode) {
  19833. mergeLayoutParam(option, inputPositionParams, layoutMode);
  19834. }
  19835. },
  19836. mergeOption: function (newSeriesOption, ecModel) {
  19837. // this.settingTask.dirty();
  19838. newSeriesOption = merge(this.option, newSeriesOption, true);
  19839. this.fillDataTextStyle(newSeriesOption.data);
  19840. var layoutMode = this.layoutMode;
  19841. if (layoutMode) {
  19842. mergeLayoutParam(this.option, newSeriesOption, layoutMode);
  19843. }
  19844. prepareSource(this);
  19845. var data = this.getInitialData(newSeriesOption, ecModel);
  19846. wrapData(data, this);
  19847. this.dataTask.dirty();
  19848. this.dataTask.context.data = data;
  19849. inner$4(this).dataBeforeProcessed = data;
  19850. autoSeriesName(this);
  19851. },
  19852. fillDataTextStyle: function (data) {
  19853. // Default data label emphasis `show`
  19854. // FIXME Tree structure data ?
  19855. // FIXME Performance ?
  19856. if (data && !isTypedArray(data)) {
  19857. var props = ['show'];
  19858. for (var i = 0; i < data.length; i++) {
  19859. if (data[i] && data[i].label) {
  19860. defaultEmphasis(data[i], 'label', props);
  19861. }
  19862. }
  19863. }
  19864. },
  19865. /**
  19866. * Init a data structure from data related option in series
  19867. * Must be overwritten
  19868. */
  19869. getInitialData: function () {},
  19870. /**
  19871. * Append data to list
  19872. * @param {Object} params
  19873. * @param {Array|TypedArray} params.data
  19874. */
  19875. appendData: function (params) {
  19876. // FIXME ???
  19877. // (1) If data from dataset, forbidden append.
  19878. // (2) support append data of dataset.
  19879. var data = this.getRawData();
  19880. data.appendData(params.data);
  19881. },
  19882. /**
  19883. * Consider some method like `filter`, `map` need make new data,
  19884. * We should make sure that `seriesModel.getData()` get correct
  19885. * data in the stream procedure. So we fetch data from upstream
  19886. * each time `task.perform` called.
  19887. * @param {string} [dataType]
  19888. * @return {module:echarts/data/List}
  19889. */
  19890. getData: function (dataType) {
  19891. var task = getCurrentTask(this);
  19892. if (task) {
  19893. var data = task.context.data;
  19894. return dataType == null ? data : data.getLinkedData(dataType);
  19895. } else {
  19896. // When series is not alive (that may happen when click toolbox
  19897. // restore or setOption with not merge mode), series data may
  19898. // be still need to judge animation or something when graphic
  19899. // elements want to know whether fade out.
  19900. return inner$4(this).data;
  19901. }
  19902. },
  19903. /**
  19904. * @param {module:echarts/data/List} data
  19905. */
  19906. setData: function (data) {
  19907. var task = getCurrentTask(this);
  19908. if (task) {
  19909. var context = task.context; // Consider case: filter, data sample.
  19910. if (context.data !== data && task.modifyOutputEnd) {
  19911. task.setOutputEnd(data.count());
  19912. }
  19913. context.outputData = data; // Caution: setData should update context.data,
  19914. // Because getData may be called multiply in a
  19915. // single stage and expect to get the data just
  19916. // set. (For example, AxisProxy, x y both call
  19917. // getData and setDate sequentially).
  19918. // So the context.data should be fetched from
  19919. // upstream each time when a stage starts to be
  19920. // performed.
  19921. if (task !== this.dataTask) {
  19922. context.data = data;
  19923. }
  19924. }
  19925. inner$4(this).data = data;
  19926. },
  19927. /**
  19928. * @see {module:echarts/data/helper/sourceHelper#getSource}
  19929. * @return {module:echarts/data/Source} source
  19930. */
  19931. getSource: function () {
  19932. return getSource(this);
  19933. },
  19934. /**
  19935. * Get data before processed
  19936. * @return {module:echarts/data/List}
  19937. */
  19938. getRawData: function () {
  19939. return inner$4(this).dataBeforeProcessed;
  19940. },
  19941. /**
  19942. * Get base axis if has coordinate system and has axis.
  19943. * By default use coordSys.getBaseAxis();
  19944. * Can be overrided for some chart.
  19945. * @return {type} description
  19946. */
  19947. getBaseAxis: function () {
  19948. var coordSys = this.coordinateSystem;
  19949. return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis();
  19950. },
  19951. // FIXME
  19952. /**
  19953. * Default tooltip formatter
  19954. *
  19955. * @param {number} dataIndex
  19956. * @param {boolean} [multipleSeries=false]
  19957. * @param {number} [dataType]
  19958. * @param {string} [renderMode='html'] valid values: 'html' and 'richText'.
  19959. * 'html' is used for rendering tooltip in extra DOM form, and the result
  19960. * string is used as DOM HTML content.
  19961. * 'richText' is used for rendering tooltip in rich text form, for those where
  19962. * DOM operation is not supported.
  19963. * @return {Object} formatted tooltip with `html` and `markers`
  19964. */
  19965. formatTooltip: function (dataIndex, multipleSeries, dataType, renderMode) {
  19966. var series = this;
  19967. renderMode = renderMode || 'html';
  19968. var newLine = renderMode === 'html' ? '<br/>' : '\n';
  19969. var isRichText = renderMode === 'richText';
  19970. var markers = {};
  19971. var markerId = 0;
  19972. function formatArrayValue(value) {
  19973. // ??? TODO refactor these logic.
  19974. // check: category-no-encode-has-axis-data in dataset.html
  19975. var vertially = reduce(value, function (vertially, val, idx) {
  19976. var dimItem = data.getDimensionInfo(idx);
  19977. return vertially |= dimItem && dimItem.tooltip !== false && dimItem.displayName != null;
  19978. }, 0);
  19979. var result = [];
  19980. tooltipDims.length ? each$1(tooltipDims, function (dim) {
  19981. setEachItem(retrieveRawValue(data, dataIndex, dim), dim);
  19982. }) // By default, all dims is used on tooltip.
  19983. : each$1(value, setEachItem);
  19984. function setEachItem(val, dim) {
  19985. var dimInfo = data.getDimensionInfo(dim); // If `dimInfo.tooltip` is not set, show tooltip.
  19986. if (!dimInfo || dimInfo.otherDims.tooltip === false) {
  19987. return;
  19988. }
  19989. var dimType = dimInfo.type;
  19990. var markName = 'sub' + series.seriesIndex + 'at' + markerId;
  19991. var dimHead = getTooltipMarker({
  19992. color: color,
  19993. type: 'subItem',
  19994. renderMode: renderMode,
  19995. markerId: markName
  19996. });
  19997. var dimHeadStr = typeof dimHead === 'string' ? dimHead : dimHead.content;
  19998. var valStr = (vertially ? dimHeadStr + encodeHTML(dimInfo.displayName || '-') + ': ' : '') + // FIXME should not format time for raw data?
  19999. encodeHTML(dimType === 'ordinal' ? val + '' : dimType === 'time' ? multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val) : addCommas(val));
  20000. valStr && result.push(valStr);
  20001. if (isRichText) {
  20002. markers[markName] = color;
  20003. ++markerId;
  20004. }
  20005. }
  20006. var newLine = vertially ? isRichText ? '\n' : '<br/>' : '';
  20007. var content = newLine + result.join(newLine || ', ');
  20008. return {
  20009. renderMode: renderMode,
  20010. content: content,
  20011. style: markers
  20012. };
  20013. }
  20014. function formatSingleValue(val) {
  20015. // return encodeHTML(addCommas(val));
  20016. return {
  20017. renderMode: renderMode,
  20018. content: encodeHTML(addCommas(val)),
  20019. style: markers
  20020. };
  20021. }
  20022. var data = this.getData();
  20023. var tooltipDims = data.mapDimension('defaultedTooltip', true);
  20024. var tooltipDimLen = tooltipDims.length;
  20025. var value = this.getRawValue(dataIndex);
  20026. var isValueArr = isArray(value);
  20027. var color = data.getItemVisual(dataIndex, 'color');
  20028. if (isObject$1(color) && color.colorStops) {
  20029. color = (color.colorStops[0] || {}).color;
  20030. }
  20031. color = color || 'transparent'; // Complicated rule for pretty tooltip.
  20032. var formattedValue = tooltipDimLen > 1 || isValueArr && !tooltipDimLen ? formatArrayValue(value) : tooltipDimLen ? formatSingleValue(retrieveRawValue(data, dataIndex, tooltipDims[0])) : formatSingleValue(isValueArr ? value[0] : value);
  20033. var content = formattedValue.content;
  20034. var markName = series.seriesIndex + 'at' + markerId;
  20035. var colorEl = getTooltipMarker({
  20036. color: color,
  20037. type: 'item',
  20038. renderMode: renderMode,
  20039. markerId: markName
  20040. });
  20041. markers[markName] = color;
  20042. ++markerId;
  20043. var name = data.getName(dataIndex);
  20044. var seriesName = this.name;
  20045. if (!isNameSpecified(this)) {
  20046. seriesName = '';
  20047. }
  20048. seriesName = seriesName ? encodeHTML(seriesName) + (!multipleSeries ? newLine : ': ') : '';
  20049. var colorStr = typeof colorEl === 'string' ? colorEl : colorEl.content;
  20050. var html = !multipleSeries ? seriesName + colorStr + (name ? encodeHTML(name) + ': ' + content : content) : colorStr + seriesName + content;
  20051. return {
  20052. html: html,
  20053. markers: markers
  20054. };
  20055. },
  20056. /**
  20057. * @return {boolean}
  20058. */
  20059. isAnimationEnabled: function () {
  20060. if (env$1.node) {
  20061. return false;
  20062. }
  20063. var animationEnabled = this.getShallow('animation');
  20064. if (animationEnabled) {
  20065. if (this.getData().count() > this.getShallow('animationThreshold')) {
  20066. animationEnabled = false;
  20067. }
  20068. }
  20069. return animationEnabled;
  20070. },
  20071. restoreData: function () {
  20072. this.dataTask.dirty();
  20073. },
  20074. getColorFromPalette: function (name, scope, requestColorNum) {
  20075. var ecModel = this.ecModel; // PENDING
  20076. var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope, requestColorNum);
  20077. if (!color) {
  20078. color = ecModel.getColorFromPalette(name, scope, requestColorNum);
  20079. }
  20080. return color;
  20081. },
  20082. /**
  20083. * Use `data.mapDimension(coordDim, true)` instead.
  20084. * @deprecated
  20085. */
  20086. coordDimToDataDim: function (coordDim) {
  20087. return this.getRawData().mapDimension(coordDim, true);
  20088. },
  20089. /**
  20090. * Get progressive rendering count each step
  20091. * @return {number}
  20092. */
  20093. getProgressive: function () {
  20094. return this.get('progressive');
  20095. },
  20096. /**
  20097. * Get progressive rendering count each step
  20098. * @return {number}
  20099. */
  20100. getProgressiveThreshold: function () {
  20101. return this.get('progressiveThreshold');
  20102. },
  20103. /**
  20104. * Get data indices for show tooltip content. See tooltip.
  20105. * @abstract
  20106. * @param {Array.<string>|string} dim
  20107. * @param {Array.<number>} value
  20108. * @param {module:echarts/coord/single/SingleAxis} baseAxis
  20109. * @return {Object} {dataIndices, nestestValue}.
  20110. */
  20111. getAxisTooltipData: null,
  20112. /**
  20113. * See tooltip.
  20114. * @abstract
  20115. * @param {number} dataIndex
  20116. * @return {Array.<number>} Point of tooltip. null/undefined can be returned.
  20117. */
  20118. getTooltipPosition: null,
  20119. /**
  20120. * @see {module:echarts/stream/Scheduler}
  20121. */
  20122. pipeTask: null,
  20123. /**
  20124. * Convinient for override in extended class.
  20125. * @protected
  20126. * @type {Function}
  20127. */
  20128. preventIncremental: null,
  20129. /**
  20130. * @public
  20131. * @readOnly
  20132. * @type {Object}
  20133. */
  20134. pipelineContext: null
  20135. });
  20136. mixin(SeriesModel, dataFormatMixin);
  20137. mixin(SeriesModel, colorPaletteMixin);
  20138. /**
  20139. * MUST be called after `prepareSource` called
  20140. * Here we need to make auto series, especially for auto legend. But we
  20141. * do not modify series.name in option to avoid side effects.
  20142. */
  20143. function autoSeriesName(seriesModel) {
  20144. // User specified name has higher priority, otherwise it may cause
  20145. // series can not be queried unexpectedly.
  20146. var name = seriesModel.name;
  20147. if (!isNameSpecified(seriesModel)) {
  20148. seriesModel.name = getSeriesAutoName(seriesModel) || name;
  20149. }
  20150. }
  20151. function getSeriesAutoName(seriesModel) {
  20152. var data = seriesModel.getRawData();
  20153. var dataDims = data.mapDimension('seriesName', true);
  20154. var nameArr = [];
  20155. each$1(dataDims, function (dataDim) {
  20156. var dimInfo = data.getDimensionInfo(dataDim);
  20157. dimInfo.displayName && nameArr.push(dimInfo.displayName);
  20158. });
  20159. return nameArr.join(' ');
  20160. }
  20161. function dataTaskCount(context) {
  20162. return context.model.getRawData().count();
  20163. }
  20164. function dataTaskReset(context) {
  20165. var seriesModel = context.model;
  20166. seriesModel.setData(seriesModel.getRawData().cloneShallow());
  20167. return dataTaskProgress;
  20168. }
  20169. function dataTaskProgress(param, context) {
  20170. // Avoid repead cloneShallow when data just created in reset.
  20171. if (context.outputData && param.end > context.outputData.count()) {
  20172. context.model.getRawData().cloneShallow(context.outputData);
  20173. }
  20174. } // TODO refactor
  20175. function wrapData(data, seriesModel) {
  20176. each$1(data.CHANGABLE_METHODS, function (methodName) {
  20177. data.wrapMethod(methodName, curry(onDataSelfChange, seriesModel));
  20178. });
  20179. }
  20180. function onDataSelfChange(seriesModel) {
  20181. var task = getCurrentTask(seriesModel);
  20182. if (task) {
  20183. // Consider case: filter, selectRange
  20184. task.setOutputEnd(this.count());
  20185. }
  20186. }
  20187. function getCurrentTask(seriesModel) {
  20188. var scheduler = (seriesModel.ecModel || {}).scheduler;
  20189. var pipeline = scheduler && scheduler.getPipeline(seriesModel.uid);
  20190. if (pipeline) {
  20191. // When pipline finished, the currrentTask keep the last
  20192. // task (renderTask).
  20193. var task = pipeline.currentTask;
  20194. if (task) {
  20195. var agentStubMap = task.agentStubMap;
  20196. if (agentStubMap) {
  20197. task = agentStubMap.get(seriesModel.uid);
  20198. }
  20199. }
  20200. return task;
  20201. }
  20202. }
  20203. /*
  20204. * Licensed to the Apache Software Foundation (ASF) under one
  20205. * or more contributor license agreements. See the NOTICE file
  20206. * distributed with this work for additional information
  20207. * regarding copyright ownership. The ASF licenses this file
  20208. * to you under the Apache License, Version 2.0 (the
  20209. * "License"); you may not use this file except in compliance
  20210. * with the License. You may obtain a copy of the License at
  20211. *
  20212. * http://www.apache.org/licenses/LICENSE-2.0
  20213. *
  20214. * Unless required by applicable law or agreed to in writing,
  20215. * software distributed under the License is distributed on an
  20216. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20217. * KIND, either express or implied. See the License for the
  20218. * specific language governing permissions and limitations
  20219. * under the License.
  20220. */
  20221. var Component$1 = function () {
  20222. /**
  20223. * @type {module:zrender/container/Group}
  20224. * @readOnly
  20225. */
  20226. this.group = new Group();
  20227. /**
  20228. * @type {string}
  20229. * @readOnly
  20230. */
  20231. this.uid = getUID('viewComponent');
  20232. };
  20233. Component$1.prototype = {
  20234. constructor: Component$1,
  20235. init: function (ecModel, api) {},
  20236. render: function (componentModel, ecModel, api, payload) {},
  20237. dispose: function () {},
  20238. /**
  20239. * @param {string} eventType
  20240. * @param {Object} query
  20241. * @param {module:zrender/Element} targetEl
  20242. * @param {Object} packedEvent
  20243. * @return {boolen} Pass only when return `true`.
  20244. */
  20245. filterForExposedEvent: null
  20246. };
  20247. var componentProto = Component$1.prototype;
  20248. componentProto.updateView = componentProto.updateLayout = componentProto.updateVisual = function (seriesModel, ecModel, api, payload) {// Do nothing;
  20249. }; // Enable Component.extend.
  20250. enableClassExtend(Component$1); // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20251. enableClassManagement(Component$1, {
  20252. registerWhenExtend: true
  20253. });
  20254. /*
  20255. * Licensed to the Apache Software Foundation (ASF) under one
  20256. * or more contributor license agreements. See the NOTICE file
  20257. * distributed with this work for additional information
  20258. * regarding copyright ownership. The ASF licenses this file
  20259. * to you under the Apache License, Version 2.0 (the
  20260. * "License"); you may not use this file except in compliance
  20261. * with the License. You may obtain a copy of the License at
  20262. *
  20263. * http://www.apache.org/licenses/LICENSE-2.0
  20264. *
  20265. * Unless required by applicable law or agreed to in writing,
  20266. * software distributed under the License is distributed on an
  20267. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20268. * KIND, either express or implied. See the License for the
  20269. * specific language governing permissions and limitations
  20270. * under the License.
  20271. */
  20272. /**
  20273. * @return {string} If large mode changed, return string 'reset';
  20274. */
  20275. var createRenderPlanner = function () {
  20276. var inner = makeInner();
  20277. return function (seriesModel) {
  20278. var fields = inner(seriesModel);
  20279. var pipelineContext = seriesModel.pipelineContext;
  20280. var originalLarge = fields.large;
  20281. var originalProgressive = fields.progressiveRender; // FIXME: if the planner works on a filtered series, `pipelineContext` does not
  20282. // exists. See #11611 . Probably we need to modify this structure, see the comment
  20283. // on `performRawSeries` in `Schedular.js`.
  20284. var large = fields.large = pipelineContext && pipelineContext.large;
  20285. var progressive = fields.progressiveRender = pipelineContext && pipelineContext.progressiveRender;
  20286. return !!(originalLarge ^ large || originalProgressive ^ progressive) && 'reset';
  20287. };
  20288. };
  20289. /*
  20290. * Licensed to the Apache Software Foundation (ASF) under one
  20291. * or more contributor license agreements. See the NOTICE file
  20292. * distributed with this work for additional information
  20293. * regarding copyright ownership. The ASF licenses this file
  20294. * to you under the Apache License, Version 2.0 (the
  20295. * "License"); you may not use this file except in compliance
  20296. * with the License. You may obtain a copy of the License at
  20297. *
  20298. * http://www.apache.org/licenses/LICENSE-2.0
  20299. *
  20300. * Unless required by applicable law or agreed to in writing,
  20301. * software distributed under the License is distributed on an
  20302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20303. * KIND, either express or implied. See the License for the
  20304. * specific language governing permissions and limitations
  20305. * under the License.
  20306. */
  20307. var inner$5 = makeInner();
  20308. var renderPlanner = createRenderPlanner();
  20309. function Chart() {
  20310. /**
  20311. * @type {module:zrender/container/Group}
  20312. * @readOnly
  20313. */
  20314. this.group = new Group();
  20315. /**
  20316. * @type {string}
  20317. * @readOnly
  20318. */
  20319. this.uid = getUID('viewChart');
  20320. this.renderTask = createTask({
  20321. plan: renderTaskPlan,
  20322. reset: renderTaskReset
  20323. });
  20324. this.renderTask.context = {
  20325. view: this
  20326. };
  20327. }
  20328. Chart.prototype = {
  20329. type: 'chart',
  20330. /**
  20331. * Init the chart.
  20332. * @param {module:echarts/model/Global} ecModel
  20333. * @param {module:echarts/ExtensionAPI} api
  20334. */
  20335. init: function (ecModel, api) {},
  20336. /**
  20337. * Render the chart.
  20338. * @param {module:echarts/model/Series} seriesModel
  20339. * @param {module:echarts/model/Global} ecModel
  20340. * @param {module:echarts/ExtensionAPI} api
  20341. * @param {Object} payload
  20342. */
  20343. render: function (seriesModel, ecModel, api, payload) {},
  20344. /**
  20345. * Highlight series or specified data item.
  20346. * @param {module:echarts/model/Series} seriesModel
  20347. * @param {module:echarts/model/Global} ecModel
  20348. * @param {module:echarts/ExtensionAPI} api
  20349. * @param {Object} payload
  20350. */
  20351. highlight: function (seriesModel, ecModel, api, payload) {
  20352. toggleHighlight(seriesModel.getData(), payload, 'emphasis');
  20353. },
  20354. /**
  20355. * Downplay series or specified data item.
  20356. * @param {module:echarts/model/Series} seriesModel
  20357. * @param {module:echarts/model/Global} ecModel
  20358. * @param {module:echarts/ExtensionAPI} api
  20359. * @param {Object} payload
  20360. */
  20361. downplay: function (seriesModel, ecModel, api, payload) {
  20362. toggleHighlight(seriesModel.getData(), payload, 'normal');
  20363. },
  20364. /**
  20365. * Remove self.
  20366. * @param {module:echarts/model/Global} ecModel
  20367. * @param {module:echarts/ExtensionAPI} api
  20368. */
  20369. remove: function (ecModel, api) {
  20370. this.group.removeAll();
  20371. },
  20372. /**
  20373. * Dispose self.
  20374. * @param {module:echarts/model/Global} ecModel
  20375. * @param {module:echarts/ExtensionAPI} api
  20376. */
  20377. dispose: function () {},
  20378. /**
  20379. * Rendering preparation in progressive mode.
  20380. * @param {module:echarts/model/Series} seriesModel
  20381. * @param {module:echarts/model/Global} ecModel
  20382. * @param {module:echarts/ExtensionAPI} api
  20383. * @param {Object} payload
  20384. */
  20385. incrementalPrepareRender: null,
  20386. /**
  20387. * Render in progressive mode.
  20388. * @param {Object} params See taskParams in `stream/task.js`
  20389. * @param {module:echarts/model/Series} seriesModel
  20390. * @param {module:echarts/model/Global} ecModel
  20391. * @param {module:echarts/ExtensionAPI} api
  20392. * @param {Object} payload
  20393. */
  20394. incrementalRender: null,
  20395. /**
  20396. * Update transform directly.
  20397. * @param {module:echarts/model/Series} seriesModel
  20398. * @param {module:echarts/model/Global} ecModel
  20399. * @param {module:echarts/ExtensionAPI} api
  20400. * @param {Object} payload
  20401. * @return {Object} {update: true}
  20402. */
  20403. updateTransform: null,
  20404. /**
  20405. * The view contains the given point.
  20406. * @interface
  20407. * @param {Array.<number>} point
  20408. * @return {boolean}
  20409. */
  20410. // containPoint: function () {}
  20411. /**
  20412. * @param {string} eventType
  20413. * @param {Object} query
  20414. * @param {module:zrender/Element} targetEl
  20415. * @param {Object} packedEvent
  20416. * @return {boolen} Pass only when return `true`.
  20417. */
  20418. filterForExposedEvent: null
  20419. };
  20420. var chartProto = Chart.prototype;
  20421. chartProto.updateView = chartProto.updateLayout = chartProto.updateVisual = function (seriesModel, ecModel, api, payload) {
  20422. this.render(seriesModel, ecModel, api, payload);
  20423. };
  20424. /**
  20425. * Set state of single element
  20426. * @param {module:zrender/Element} el
  20427. * @param {string} state 'normal'|'emphasis'
  20428. * @param {number} highlightDigit
  20429. */
  20430. function elSetState(el, state, highlightDigit) {
  20431. if (el) {
  20432. el.trigger(state, highlightDigit);
  20433. if (el.isGroup // Simple optimize.
  20434. && !isHighDownDispatcher(el)) {
  20435. for (var i = 0, len = el.childCount(); i < len; i++) {
  20436. elSetState(el.childAt(i), state, highlightDigit);
  20437. }
  20438. }
  20439. }
  20440. }
  20441. /**
  20442. * @param {module:echarts/data/List} data
  20443. * @param {Object} payload
  20444. * @param {string} state 'normal'|'emphasis'
  20445. */
  20446. function toggleHighlight(data, payload, state) {
  20447. var dataIndex = queryDataIndex(data, payload);
  20448. var highlightDigit = payload && payload.highlightKey != null ? getHighlightDigit(payload.highlightKey) : null;
  20449. if (dataIndex != null) {
  20450. each$1(normalizeToArray(dataIndex), function (dataIdx) {
  20451. elSetState(data.getItemGraphicEl(dataIdx), state, highlightDigit);
  20452. });
  20453. } else {
  20454. data.eachItemGraphicEl(function (el) {
  20455. elSetState(el, state, highlightDigit);
  20456. });
  20457. }
  20458. } // Enable Chart.extend.
  20459. enableClassExtend(Chart, ['dispose']); // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on.
  20460. enableClassManagement(Chart, {
  20461. registerWhenExtend: true
  20462. });
  20463. Chart.markUpdateMethod = function (payload, methodName) {
  20464. inner$5(payload).updateMethod = methodName;
  20465. };
  20466. function renderTaskPlan(context) {
  20467. return renderPlanner(context.model);
  20468. }
  20469. function renderTaskReset(context) {
  20470. var seriesModel = context.model;
  20471. var ecModel = context.ecModel;
  20472. var api = context.api;
  20473. var payload = context.payload; // ???! remove updateView updateVisual
  20474. var progressiveRender = seriesModel.pipelineContext.progressiveRender;
  20475. var view = context.view;
  20476. var updateMethod = payload && inner$5(payload).updateMethod;
  20477. var methodName = progressiveRender ? 'incrementalPrepareRender' : updateMethod && view[updateMethod] ? updateMethod // `appendData` is also supported when data amount
  20478. // is less than progressive threshold.
  20479. : 'render';
  20480. if (methodName !== 'render') {
  20481. view[methodName](seriesModel, ecModel, api, payload);
  20482. }
  20483. return progressMethodMap[methodName];
  20484. }
  20485. var progressMethodMap = {
  20486. incrementalPrepareRender: {
  20487. progress: function (params, context) {
  20488. context.view.incrementalRender(params, context.model, context.ecModel, context.api, context.payload);
  20489. }
  20490. },
  20491. render: {
  20492. // Put view.render in `progress` to support appendData. But in this case
  20493. // view.render should not be called in reset, otherwise it will be called
  20494. // twise. Use `forceFirstProgress` to make sure that view.render is called
  20495. // in any cases.
  20496. forceFirstProgress: true,
  20497. progress: function (params, context) {
  20498. context.view.render(context.model, context.ecModel, context.api, context.payload);
  20499. }
  20500. }
  20501. };
  20502. /*
  20503. * Licensed to the Apache Software Foundation (ASF) under one
  20504. * or more contributor license agreements. See the NOTICE file
  20505. * distributed with this work for additional information
  20506. * regarding copyright ownership. The ASF licenses this file
  20507. * to you under the Apache License, Version 2.0 (the
  20508. * "License"); you may not use this file except in compliance
  20509. * with the License. You may obtain a copy of the License at
  20510. *
  20511. * http://www.apache.org/licenses/LICENSE-2.0
  20512. *
  20513. * Unless required by applicable law or agreed to in writing,
  20514. * software distributed under the License is distributed on an
  20515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20516. * KIND, either express or implied. See the License for the
  20517. * specific language governing permissions and limitations
  20518. * under the License.
  20519. */
  20520. var ORIGIN_METHOD = '\0__throttleOriginMethod';
  20521. var RATE = '\0__throttleRate';
  20522. var THROTTLE_TYPE = '\0__throttleType';
  20523. /**
  20524. * @public
  20525. * @param {(Function)} fn
  20526. * @param {number} [delay=0] Unit: ms.
  20527. * @param {boolean} [debounce=false]
  20528. * true: If call interval less than `delay`, only the last call works.
  20529. * false: If call interval less than `delay, call works on fixed rate.
  20530. * @return {(Function)} throttled fn.
  20531. */
  20532. function throttle(fn, delay, debounce) {
  20533. var currCall;
  20534. var lastCall = 0;
  20535. var lastExec = 0;
  20536. var timer = null;
  20537. var diff;
  20538. var scope;
  20539. var args;
  20540. var debounceNextCall;
  20541. delay = delay || 0;
  20542. function exec() {
  20543. lastExec = new Date().getTime();
  20544. timer = null;
  20545. fn.apply(scope, args || []);
  20546. }
  20547. var cb = function () {
  20548. currCall = new Date().getTime();
  20549. scope = this;
  20550. args = arguments;
  20551. var thisDelay = debounceNextCall || delay;
  20552. var thisDebounce = debounceNextCall || debounce;
  20553. debounceNextCall = null;
  20554. diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay;
  20555. clearTimeout(timer); // Here we should make sure that: the `exec` SHOULD NOT be called later
  20556. // than a new call of `cb`, that is, preserving the command order. Consider
  20557. // calculating "scale rate" when roaming as an example. When a call of `cb`
  20558. // happens, either the `exec` is called dierectly, or the call is delayed.
  20559. // But the delayed call should never be later than next call of `cb`. Under
  20560. // this assurance, we can simply update view state each time `dispatchAction`
  20561. // triggered by user roaming, but not need to add extra code to avoid the
  20562. // state being "rolled-back".
  20563. if (thisDebounce) {
  20564. timer = setTimeout(exec, thisDelay);
  20565. } else {
  20566. if (diff >= 0) {
  20567. exec();
  20568. } else {
  20569. timer = setTimeout(exec, -diff);
  20570. }
  20571. }
  20572. lastCall = currCall;
  20573. };
  20574. /**
  20575. * Clear throttle.
  20576. * @public
  20577. */
  20578. cb.clear = function () {
  20579. if (timer) {
  20580. clearTimeout(timer);
  20581. timer = null;
  20582. }
  20583. };
  20584. /**
  20585. * Enable debounce once.
  20586. */
  20587. cb.debounceNextCall = function (debounceDelay) {
  20588. debounceNextCall = debounceDelay;
  20589. };
  20590. return cb;
  20591. }
  20592. /**
  20593. * Create throttle method or update throttle rate.
  20594. *
  20595. * @example
  20596. * ComponentView.prototype.render = function () {
  20597. * ...
  20598. * throttle.createOrUpdate(
  20599. * this,
  20600. * '_dispatchAction',
  20601. * this.model.get('throttle'),
  20602. * 'fixRate'
  20603. * );
  20604. * };
  20605. * ComponentView.prototype.remove = function () {
  20606. * throttle.clear(this, '_dispatchAction');
  20607. * };
  20608. * ComponentView.prototype.dispose = function () {
  20609. * throttle.clear(this, '_dispatchAction');
  20610. * };
  20611. *
  20612. * @public
  20613. * @param {Object} obj
  20614. * @param {string} fnAttr
  20615. * @param {number} [rate]
  20616. * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce'
  20617. * @return {Function} throttled function.
  20618. */
  20619. function createOrUpdate(obj, fnAttr, rate, throttleType) {
  20620. var fn = obj[fnAttr];
  20621. if (!fn) {
  20622. return;
  20623. }
  20624. var originFn = fn[ORIGIN_METHOD] || fn;
  20625. var lastThrottleType = fn[THROTTLE_TYPE];
  20626. var lastRate = fn[RATE];
  20627. if (lastRate !== rate || lastThrottleType !== throttleType) {
  20628. if (rate == null || !throttleType) {
  20629. return obj[fnAttr] = originFn;
  20630. }
  20631. fn = obj[fnAttr] = throttle(originFn, rate, throttleType === 'debounce');
  20632. fn[ORIGIN_METHOD] = originFn;
  20633. fn[THROTTLE_TYPE] = throttleType;
  20634. fn[RATE] = rate;
  20635. }
  20636. return fn;
  20637. }
  20638. /**
  20639. * Clear throttle. Example see throttle.createOrUpdate.
  20640. *
  20641. * @public
  20642. * @param {Object} obj
  20643. * @param {string} fnAttr
  20644. */
  20645. function clear(obj, fnAttr) {
  20646. var fn = obj[fnAttr];
  20647. if (fn && fn[ORIGIN_METHOD]) {
  20648. obj[fnAttr] = fn[ORIGIN_METHOD];
  20649. }
  20650. }
  20651. /*
  20652. * Licensed to the Apache Software Foundation (ASF) under one
  20653. * or more contributor license agreements. See the NOTICE file
  20654. * distributed with this work for additional information
  20655. * regarding copyright ownership. The ASF licenses this file
  20656. * to you under the Apache License, Version 2.0 (the
  20657. * "License"); you may not use this file except in compliance
  20658. * with the License. You may obtain a copy of the License at
  20659. *
  20660. * http://www.apache.org/licenses/LICENSE-2.0
  20661. *
  20662. * Unless required by applicable law or agreed to in writing,
  20663. * software distributed under the License is distributed on an
  20664. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20665. * KIND, either express or implied. See the License for the
  20666. * specific language governing permissions and limitations
  20667. * under the License.
  20668. */
  20669. var seriesColor = {
  20670. createOnAllSeries: true,
  20671. performRawSeries: true,
  20672. reset: function (seriesModel, ecModel) {
  20673. var data = seriesModel.getData();
  20674. var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.color').split('.'); // Set in itemStyle
  20675. var color = seriesModel.get(colorAccessPath);
  20676. var colorCallback = isFunction$1(color) && !(color instanceof Gradient) ? color : null; // Default color
  20677. if (!color || colorCallback) {
  20678. color = seriesModel.getColorFromPalette( // TODO series count changed.
  20679. seriesModel.name, null, ecModel.getSeriesCount());
  20680. }
  20681. data.setVisual('color', color);
  20682. var borderColorAccessPath = (seriesModel.visualBorderColorAccessPath || 'itemStyle.borderColor').split('.');
  20683. var borderColor = seriesModel.get(borderColorAccessPath);
  20684. data.setVisual('borderColor', borderColor); // Only visible series has each data be visual encoded
  20685. if (!ecModel.isSeriesFiltered(seriesModel)) {
  20686. if (colorCallback) {
  20687. data.each(function (idx) {
  20688. data.setItemVisual(idx, 'color', colorCallback(seriesModel.getDataParams(idx)));
  20689. });
  20690. } // itemStyle in each data item
  20691. var dataEach = function (data, idx) {
  20692. var itemModel = data.getItemModel(idx);
  20693. var color = itemModel.get(colorAccessPath, true);
  20694. var borderColor = itemModel.get(borderColorAccessPath, true);
  20695. if (color != null) {
  20696. data.setItemVisual(idx, 'color', color);
  20697. }
  20698. if (borderColor != null) {
  20699. data.setItemVisual(idx, 'borderColor', borderColor);
  20700. }
  20701. };
  20702. return {
  20703. dataEach: data.hasItemOption ? dataEach : null
  20704. };
  20705. }
  20706. }
  20707. };
  20708. /*
  20709. * Licensed to the Apache Software Foundation (ASF) under one
  20710. * or more contributor license agreements. See the NOTICE file
  20711. * distributed with this work for additional information
  20712. * regarding copyright ownership. The ASF licenses this file
  20713. * to you under the Apache License, Version 2.0 (the
  20714. * "License"); you may not use this file except in compliance
  20715. * with the License. You may obtain a copy of the License at
  20716. *
  20717. * http://www.apache.org/licenses/LICENSE-2.0
  20718. *
  20719. * Unless required by applicable law or agreed to in writing,
  20720. * software distributed under the License is distributed on an
  20721. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20722. * KIND, either express or implied. See the License for the
  20723. * specific language governing permissions and limitations
  20724. * under the License.
  20725. */
  20726. /**
  20727. * Language: (Simplified) Chinese.
  20728. */
  20729. var lang = {
  20730. legend: {
  20731. selector: {
  20732. all: '全选',
  20733. inverse: '反选'
  20734. }
  20735. },
  20736. toolbox: {
  20737. brush: {
  20738. title: {
  20739. rect: '矩形选择',
  20740. polygon: '圈选',
  20741. lineX: '横向选择',
  20742. lineY: '纵向选择',
  20743. keep: '保持选择',
  20744. clear: '清除选择'
  20745. }
  20746. },
  20747. dataView: {
  20748. title: '数据视图',
  20749. lang: ['数据视图', '关闭', '刷新']
  20750. },
  20751. dataZoom: {
  20752. title: {
  20753. zoom: '区域缩放',
  20754. back: '区域缩放还原'
  20755. }
  20756. },
  20757. magicType: {
  20758. title: {
  20759. line: '切换为折线图',
  20760. bar: '切换为柱状图',
  20761. stack: '切换为堆叠',
  20762. tiled: '切换为平铺'
  20763. }
  20764. },
  20765. restore: {
  20766. title: '还原'
  20767. },
  20768. saveAsImage: {
  20769. title: '保存为图片',
  20770. lang: ['右键另存为图片']
  20771. }
  20772. },
  20773. series: {
  20774. typeNames: {
  20775. pie: '饼图',
  20776. bar: '柱状图',
  20777. line: '折线图',
  20778. scatter: '散点图',
  20779. effectScatter: '涟漪散点图',
  20780. radar: '雷达图',
  20781. tree: '树图',
  20782. treemap: '矩形树图',
  20783. boxplot: '箱型图',
  20784. candlestick: 'K线图',
  20785. k: 'K线图',
  20786. heatmap: '热力图',
  20787. map: '地图',
  20788. parallel: '平行坐标图',
  20789. lines: '线图',
  20790. graph: '关系图',
  20791. sankey: '桑基图',
  20792. funnel: '漏斗图',
  20793. gauge: '仪表盘图',
  20794. pictorialBar: '象形柱图',
  20795. themeRiver: '主题河流图',
  20796. sunburst: '旭日图'
  20797. }
  20798. },
  20799. aria: {
  20800. general: {
  20801. withTitle: '这是一个关于“{title}”的图表。',
  20802. withoutTitle: '这是一个图表,'
  20803. },
  20804. series: {
  20805. single: {
  20806. prefix: '',
  20807. withName: '图表类型是{seriesType},表示{seriesName}。',
  20808. withoutName: '图表类型是{seriesType}。'
  20809. },
  20810. multiple: {
  20811. prefix: '它由{seriesCount}个图表系列组成。',
  20812. withName: '第{seriesId}个系列是一个表示{seriesName}的{seriesType},',
  20813. withoutName: '第{seriesId}个系列是一个{seriesType},',
  20814. separator: {
  20815. middle: ';',
  20816. end: '。'
  20817. }
  20818. }
  20819. },
  20820. data: {
  20821. allData: '其数据是——',
  20822. partialData: '其中,前{displayCnt}项是——',
  20823. withName: '{name}的数据是{value}',
  20824. withoutName: '{value}',
  20825. separator: {
  20826. middle: ',',
  20827. end: ''
  20828. }
  20829. }
  20830. }
  20831. };
  20832. /*
  20833. * Licensed to the Apache Software Foundation (ASF) under one
  20834. * or more contributor license agreements. See the NOTICE file
  20835. * distributed with this work for additional information
  20836. * regarding copyright ownership. The ASF licenses this file
  20837. * to you under the Apache License, Version 2.0 (the
  20838. * "License"); you may not use this file except in compliance
  20839. * with the License. You may obtain a copy of the License at
  20840. *
  20841. * http://www.apache.org/licenses/LICENSE-2.0
  20842. *
  20843. * Unless required by applicable law or agreed to in writing,
  20844. * software distributed under the License is distributed on an
  20845. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20846. * KIND, either express or implied. See the License for the
  20847. * specific language governing permissions and limitations
  20848. * under the License.
  20849. */
  20850. var aria = function (dom, ecModel) {
  20851. var ariaModel = ecModel.getModel('aria');
  20852. if (!ariaModel.get('show')) {
  20853. return;
  20854. } else if (ariaModel.get('description')) {
  20855. dom.setAttribute('aria-label', ariaModel.get('description'));
  20856. return;
  20857. }
  20858. var seriesCnt = 0;
  20859. ecModel.eachSeries(function (seriesModel, idx) {
  20860. ++seriesCnt;
  20861. }, this);
  20862. var maxDataCnt = ariaModel.get('data.maxCount') || 10;
  20863. var maxSeriesCnt = ariaModel.get('series.maxCount') || 10;
  20864. var displaySeriesCnt = Math.min(seriesCnt, maxSeriesCnt);
  20865. var ariaLabel;
  20866. if (seriesCnt < 1) {
  20867. // No series, no aria label
  20868. return;
  20869. } else {
  20870. var title = getTitle();
  20871. if (title) {
  20872. ariaLabel = replace(getConfig('general.withTitle'), {
  20873. title: title
  20874. });
  20875. } else {
  20876. ariaLabel = getConfig('general.withoutTitle');
  20877. }
  20878. var seriesLabels = [];
  20879. var prefix = seriesCnt > 1 ? 'series.multiple.prefix' : 'series.single.prefix';
  20880. ariaLabel += replace(getConfig(prefix), {
  20881. seriesCount: seriesCnt
  20882. });
  20883. ecModel.eachSeries(function (seriesModel, idx) {
  20884. if (idx < displaySeriesCnt) {
  20885. var seriesLabel;
  20886. var seriesName = seriesModel.get('name');
  20887. var seriesTpl = 'series.' + (seriesCnt > 1 ? 'multiple' : 'single') + '.';
  20888. seriesLabel = getConfig(seriesName ? seriesTpl + 'withName' : seriesTpl + 'withoutName');
  20889. seriesLabel = replace(seriesLabel, {
  20890. seriesId: seriesModel.seriesIndex,
  20891. seriesName: seriesModel.get('name'),
  20892. seriesType: getSeriesTypeName(seriesModel.subType)
  20893. });
  20894. var data = seriesModel.getData();
  20895. window.data = data;
  20896. if (data.count() > maxDataCnt) {
  20897. // Show part of data
  20898. seriesLabel += replace(getConfig('data.partialData'), {
  20899. displayCnt: maxDataCnt
  20900. });
  20901. } else {
  20902. seriesLabel += getConfig('data.allData');
  20903. }
  20904. var dataLabels = [];
  20905. for (var i = 0; i < data.count(); i++) {
  20906. if (i < maxDataCnt) {
  20907. var name = data.getName(i);
  20908. var value = retrieveRawValue(data, i);
  20909. dataLabels.push(replace(name ? getConfig('data.withName') : getConfig('data.withoutName'), {
  20910. name: name,
  20911. value: value
  20912. }));
  20913. }
  20914. }
  20915. seriesLabel += dataLabels.join(getConfig('data.separator.middle')) + getConfig('data.separator.end');
  20916. seriesLabels.push(seriesLabel);
  20917. }
  20918. });
  20919. ariaLabel += seriesLabels.join(getConfig('series.multiple.separator.middle')) + getConfig('series.multiple.separator.end');
  20920. dom.setAttribute('aria-label', ariaLabel);
  20921. }
  20922. function replace(str, keyValues) {
  20923. if (typeof str !== 'string') {
  20924. return str;
  20925. }
  20926. var result = str;
  20927. each$1(keyValues, function (value, key) {
  20928. result = result.replace(new RegExp('\\{\\s*' + key + '\\s*\\}', 'g'), value);
  20929. });
  20930. return result;
  20931. }
  20932. function getConfig(path) {
  20933. var userConfig = ariaModel.get(path);
  20934. if (userConfig == null) {
  20935. var pathArr = path.split('.');
  20936. var result = lang.aria;
  20937. for (var i = 0; i < pathArr.length; ++i) {
  20938. result = result[pathArr[i]];
  20939. }
  20940. return result;
  20941. } else {
  20942. return userConfig;
  20943. }
  20944. }
  20945. function getTitle() {
  20946. var title = ecModel.getModel('title').option;
  20947. if (title && title.length) {
  20948. title = title[0];
  20949. }
  20950. return title && title.text;
  20951. }
  20952. function getSeriesTypeName(type) {
  20953. return lang.series.typeNames[type] || '自定义图';
  20954. }
  20955. };
  20956. /*
  20957. * Licensed to the Apache Software Foundation (ASF) under one
  20958. * or more contributor license agreements. See the NOTICE file
  20959. * distributed with this work for additional information
  20960. * regarding copyright ownership. The ASF licenses this file
  20961. * to you under the Apache License, Version 2.0 (the
  20962. * "License"); you may not use this file except in compliance
  20963. * with the License. You may obtain a copy of the License at
  20964. *
  20965. * http://www.apache.org/licenses/LICENSE-2.0
  20966. *
  20967. * Unless required by applicable law or agreed to in writing,
  20968. * software distributed under the License is distributed on an
  20969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  20970. * KIND, either express or implied. See the License for the
  20971. * specific language governing permissions and limitations
  20972. * under the License.
  20973. */
  20974. var PI$1 = Math.PI;
  20975. /**
  20976. * @param {module:echarts/ExtensionAPI} api
  20977. * @param {Object} [opts]
  20978. * @param {string} [opts.text]
  20979. * @param {string} [opts.color]
  20980. * @param {string} [opts.textColor]
  20981. * @return {module:zrender/Element}
  20982. */
  20983. var loadingDefault = function (api, opts) {
  20984. opts = opts || {};
  20985. defaults(opts, {
  20986. text: 'loading',
  20987. textColor: '#000',
  20988. fontSize: '12px',
  20989. maskColor: 'rgba(255, 255, 255, 0.8)',
  20990. showSpinner: true,
  20991. color: '#c23531',
  20992. spinnerRadius: 10,
  20993. lineWidth: 5,
  20994. zlevel: 0
  20995. });
  20996. var group = new Group();
  20997. var mask = new Rect({
  20998. style: {
  20999. fill: opts.maskColor
  21000. },
  21001. zlevel: opts.zlevel,
  21002. z: 10000
  21003. });
  21004. group.add(mask);
  21005. var font = opts.fontSize + ' sans-serif';
  21006. var labelRect = new Rect({
  21007. style: {
  21008. fill: 'none',
  21009. text: opts.text,
  21010. font: font,
  21011. textPosition: 'right',
  21012. textDistance: 10,
  21013. textFill: opts.textColor
  21014. },
  21015. zlevel: opts.zlevel,
  21016. z: 10001
  21017. });
  21018. group.add(labelRect);
  21019. if (opts.showSpinner) {
  21020. var arc = new Arc({
  21021. shape: {
  21022. startAngle: -PI$1 / 2,
  21023. endAngle: -PI$1 / 2 + 0.1,
  21024. r: opts.spinnerRadius
  21025. },
  21026. style: {
  21027. stroke: opts.color,
  21028. lineCap: 'round',
  21029. lineWidth: opts.lineWidth
  21030. },
  21031. zlevel: opts.zlevel,
  21032. z: 10001
  21033. });
  21034. arc.animateShape(true).when(1000, {
  21035. endAngle: PI$1 * 3 / 2
  21036. }).start('circularInOut');
  21037. arc.animateShape(true).when(1000, {
  21038. startAngle: PI$1 * 3 / 2
  21039. }).delay(300).start('circularInOut');
  21040. group.add(arc);
  21041. } // Inject resize
  21042. group.resize = function () {
  21043. var textWidth = getWidth(opts.text, font);
  21044. var r = opts.showSpinner ? opts.spinnerRadius : 0; // cx = (containerWidth - arcDiameter - textDistance - textWidth) / 2
  21045. // textDistance needs to be calculated when both animation and text exist
  21046. var cx = (api.getWidth() - r * 2 - (opts.showSpinner && textWidth ? 10 : 0) - textWidth) / 2 // only show the text
  21047. - (opts.showSpinner ? 0 : textWidth / 2);
  21048. var cy = api.getHeight() / 2;
  21049. opts.showSpinner && arc.setShape({
  21050. cx: cx,
  21051. cy: cy
  21052. });
  21053. labelRect.setShape({
  21054. x: cx - r,
  21055. y: cy - r,
  21056. width: r * 2,
  21057. height: r * 2
  21058. });
  21059. mask.setShape({
  21060. x: 0,
  21061. y: 0,
  21062. width: api.getWidth(),
  21063. height: api.getHeight()
  21064. });
  21065. };
  21066. group.resize();
  21067. return group;
  21068. };
  21069. /*
  21070. * Licensed to the Apache Software Foundation (ASF) under one
  21071. * or more contributor license agreements. See the NOTICE file
  21072. * distributed with this work for additional information
  21073. * regarding copyright ownership. The ASF licenses this file
  21074. * to you under the Apache License, Version 2.0 (the
  21075. * "License"); you may not use this file except in compliance
  21076. * with the License. You may obtain a copy of the License at
  21077. *
  21078. * http://www.apache.org/licenses/LICENSE-2.0
  21079. *
  21080. * Unless required by applicable law or agreed to in writing,
  21081. * software distributed under the License is distributed on an
  21082. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21083. * KIND, either express or implied. See the License for the
  21084. * specific language governing permissions and limitations
  21085. * under the License.
  21086. */
  21087. /**
  21088. * @module echarts/stream/Scheduler
  21089. */
  21090. /**
  21091. * @constructor
  21092. */
  21093. function Scheduler(ecInstance, api, dataProcessorHandlers, visualHandlers) {
  21094. this.ecInstance = ecInstance;
  21095. this.api = api;
  21096. this.unfinished; // Fix current processors in case that in some rear cases that
  21097. // processors might be registered after echarts instance created.
  21098. // Register processors incrementally for a echarts instance is
  21099. // not supported by this stream architecture.
  21100. var dataProcessorHandlers = this._dataProcessorHandlers = dataProcessorHandlers.slice();
  21101. var visualHandlers = this._visualHandlers = visualHandlers.slice();
  21102. this._allHandlers = dataProcessorHandlers.concat(visualHandlers);
  21103. /**
  21104. * @private
  21105. * @type {
  21106. * [handlerUID: string]: {
  21107. * seriesTaskMap?: {
  21108. * [seriesUID: string]: Task
  21109. * },
  21110. * overallTask?: Task
  21111. * }
  21112. * }
  21113. */
  21114. this._stageTaskMap = createHashMap();
  21115. }
  21116. var proto = Scheduler.prototype;
  21117. /**
  21118. * @param {module:echarts/model/Global} ecModel
  21119. * @param {Object} payload
  21120. */
  21121. proto.restoreData = function (ecModel, payload) {
  21122. // TODO: Only restroe needed series and components, but not all components.
  21123. // Currently `restoreData` of all of the series and component will be called.
  21124. // But some independent components like `title`, `legend`, `graphic`, `toolbox`,
  21125. // `tooltip`, `axisPointer`, etc, do not need series refresh when `setOption`,
  21126. // and some components like coordinate system, axes, dataZoom, visualMap only
  21127. // need their target series refresh.
  21128. // (1) If we are implementing this feature some day, we should consider these cases:
  21129. // if a data processor depends on a component (e.g., dataZoomProcessor depends
  21130. // on the settings of `dataZoom`), it should be re-performed if the component
  21131. // is modified by `setOption`.
  21132. // (2) If a processor depends on sevral series, speicified by its `getTargetSeries`,
  21133. // it should be re-performed when the result array of `getTargetSeries` changed.
  21134. // We use `dependencies` to cover these issues.
  21135. // (3) How to update target series when coordinate system related components modified.
  21136. // TODO: simply the dirty mechanism? Check whether only the case here can set tasks dirty,
  21137. // and this case all of the tasks will be set as dirty.
  21138. ecModel.restoreData(payload); // Theoretically an overall task not only depends on each of its target series, but also
  21139. // depends on all of the series.
  21140. // The overall task is not in pipeline, and `ecModel.restoreData` only set pipeline tasks
  21141. // dirty. If `getTargetSeries` of an overall task returns nothing, we should also ensure
  21142. // that the overall task is set as dirty and to be performed, otherwise it probably cause
  21143. // state chaos. So we have to set dirty of all of the overall tasks manually, otherwise it
  21144. // probably cause state chaos (consider `dataZoomProcessor`).
  21145. this._stageTaskMap.each(function (taskRecord) {
  21146. var overallTask = taskRecord.overallTask;
  21147. overallTask && overallTask.dirty();
  21148. });
  21149. }; // If seriesModel provided, incremental threshold is check by series data.
  21150. proto.getPerformArgs = function (task, isBlock) {
  21151. // For overall task
  21152. if (!task.__pipeline) {
  21153. return;
  21154. }
  21155. var pipeline = this._pipelineMap.get(task.__pipeline.id);
  21156. var pCtx = pipeline.context;
  21157. var incremental = !isBlock && pipeline.progressiveEnabled && (!pCtx || pCtx.progressiveRender) && task.__idxInPipeline > pipeline.blockIndex;
  21158. var step = incremental ? pipeline.step : null;
  21159. var modDataCount = pCtx && pCtx.modDataCount;
  21160. var modBy = modDataCount != null ? Math.ceil(modDataCount / step) : null;
  21161. return {
  21162. step: step,
  21163. modBy: modBy,
  21164. modDataCount: modDataCount
  21165. };
  21166. };
  21167. proto.getPipeline = function (pipelineId) {
  21168. return this._pipelineMap.get(pipelineId);
  21169. };
  21170. /**
  21171. * Current, progressive rendering starts from visual and layout.
  21172. * Always detect render mode in the same stage, avoiding that incorrect
  21173. * detection caused by data filtering.
  21174. * Caution:
  21175. * `updateStreamModes` use `seriesModel.getData()`.
  21176. */
  21177. proto.updateStreamModes = function (seriesModel, view) {
  21178. var pipeline = this._pipelineMap.get(seriesModel.uid);
  21179. var data = seriesModel.getData();
  21180. var dataLen = data.count(); // `progressiveRender` means that can render progressively in each
  21181. // animation frame. Note that some types of series do not provide
  21182. // `view.incrementalPrepareRender` but support `chart.appendData`. We
  21183. // use the term `incremental` but not `progressive` to describe the
  21184. // case that `chart.appendData`.
  21185. var progressiveRender = pipeline.progressiveEnabled && view.incrementalPrepareRender && dataLen >= pipeline.threshold;
  21186. var large = seriesModel.get('large') && dataLen >= seriesModel.get('largeThreshold'); // TODO: modDataCount should not updated if `appendData`, otherwise cause whole repaint.
  21187. // see `test/candlestick-large3.html`
  21188. var modDataCount = seriesModel.get('progressiveChunkMode') === 'mod' ? dataLen : null;
  21189. seriesModel.pipelineContext = pipeline.context = {
  21190. progressiveRender: progressiveRender,
  21191. modDataCount: modDataCount,
  21192. large: large
  21193. };
  21194. };
  21195. proto.restorePipelines = function (ecModel) {
  21196. var scheduler = this;
  21197. var pipelineMap = scheduler._pipelineMap = createHashMap();
  21198. ecModel.eachSeries(function (seriesModel) {
  21199. var progressive = seriesModel.getProgressive();
  21200. var pipelineId = seriesModel.uid;
  21201. pipelineMap.set(pipelineId, {
  21202. id: pipelineId,
  21203. head: null,
  21204. tail: null,
  21205. threshold: seriesModel.getProgressiveThreshold(),
  21206. progressiveEnabled: progressive && !(seriesModel.preventIncremental && seriesModel.preventIncremental()),
  21207. blockIndex: -1,
  21208. step: Math.round(progressive || 700),
  21209. count: 0
  21210. });
  21211. pipe(scheduler, seriesModel, seriesModel.dataTask);
  21212. });
  21213. };
  21214. proto.prepareStageTasks = function () {
  21215. var stageTaskMap = this._stageTaskMap;
  21216. var ecModel = this.ecInstance.getModel();
  21217. var api = this.api;
  21218. each$1(this._allHandlers, function (handler) {
  21219. var record = stageTaskMap.get(handler.uid) || stageTaskMap.set(handler.uid, []);
  21220. handler.reset && createSeriesStageTask(this, handler, record, ecModel, api);
  21221. handler.overallReset && createOverallStageTask(this, handler, record, ecModel, api);
  21222. }, this);
  21223. };
  21224. proto.prepareView = function (view, model, ecModel, api) {
  21225. var renderTask = view.renderTask;
  21226. var context = renderTask.context;
  21227. context.model = model;
  21228. context.ecModel = ecModel;
  21229. context.api = api;
  21230. renderTask.__block = !view.incrementalPrepareRender;
  21231. pipe(this, model, renderTask);
  21232. };
  21233. proto.performDataProcessorTasks = function (ecModel, payload) {
  21234. // If we do not use `block` here, it should be considered when to update modes.
  21235. performStageTasks(this, this._dataProcessorHandlers, ecModel, payload, {
  21236. block: true
  21237. });
  21238. }; // opt
  21239. // opt.visualType: 'visual' or 'layout'
  21240. // opt.setDirty
  21241. proto.performVisualTasks = function (ecModel, payload, opt) {
  21242. performStageTasks(this, this._visualHandlers, ecModel, payload, opt);
  21243. };
  21244. function performStageTasks(scheduler, stageHandlers, ecModel, payload, opt) {
  21245. opt = opt || {};
  21246. var unfinished;
  21247. each$1(stageHandlers, function (stageHandler, idx) {
  21248. if (opt.visualType && opt.visualType !== stageHandler.visualType) {
  21249. return;
  21250. }
  21251. var stageHandlerRecord = scheduler._stageTaskMap.get(stageHandler.uid);
  21252. var seriesTaskMap = stageHandlerRecord.seriesTaskMap;
  21253. var overallTask = stageHandlerRecord.overallTask;
  21254. if (overallTask) {
  21255. var overallNeedDirty;
  21256. var agentStubMap = overallTask.agentStubMap;
  21257. agentStubMap.each(function (stub) {
  21258. if (needSetDirty(opt, stub)) {
  21259. stub.dirty();
  21260. overallNeedDirty = true;
  21261. }
  21262. });
  21263. overallNeedDirty && overallTask.dirty();
  21264. updatePayload(overallTask, payload);
  21265. var performArgs = scheduler.getPerformArgs(overallTask, opt.block); // Execute stubs firstly, which may set the overall task dirty,
  21266. // then execute the overall task. And stub will call seriesModel.setData,
  21267. // which ensures that in the overallTask seriesModel.getData() will not
  21268. // return incorrect data.
  21269. agentStubMap.each(function (stub) {
  21270. stub.perform(performArgs);
  21271. });
  21272. unfinished |= overallTask.perform(performArgs);
  21273. } else if (seriesTaskMap) {
  21274. seriesTaskMap.each(function (task, pipelineId) {
  21275. if (needSetDirty(opt, task)) {
  21276. task.dirty();
  21277. }
  21278. var performArgs = scheduler.getPerformArgs(task, opt.block); // FIXME
  21279. // if intending to decalare `performRawSeries` in handlers, only
  21280. // stream-independent (specifically, data item independent) operations can be
  21281. // performed. Because is a series is filtered, most of the tasks will not
  21282. // be performed. A stream-dependent operation probably cause wrong biz logic.
  21283. // Perhaps we should not provide a separate callback for this case instead
  21284. // of providing the config `performRawSeries`. The stream-dependent operaions
  21285. // and stream-independent operations should better not be mixed.
  21286. performArgs.skip = !stageHandler.performRawSeries && ecModel.isSeriesFiltered(task.context.model);
  21287. updatePayload(task, payload);
  21288. unfinished |= task.perform(performArgs);
  21289. });
  21290. }
  21291. });
  21292. function needSetDirty(opt, task) {
  21293. return opt.setDirty && (!opt.dirtyMap || opt.dirtyMap.get(task.__pipeline.id));
  21294. }
  21295. scheduler.unfinished |= unfinished;
  21296. }
  21297. proto.performSeriesTasks = function (ecModel) {
  21298. var unfinished;
  21299. ecModel.eachSeries(function (seriesModel) {
  21300. // Progress to the end for dataInit and dataRestore.
  21301. unfinished |= seriesModel.dataTask.perform();
  21302. });
  21303. this.unfinished |= unfinished;
  21304. };
  21305. proto.plan = function () {
  21306. // Travel pipelines, check block.
  21307. this._pipelineMap.each(function (pipeline) {
  21308. var task = pipeline.tail;
  21309. do {
  21310. if (task.__block) {
  21311. pipeline.blockIndex = task.__idxInPipeline;
  21312. break;
  21313. }
  21314. task = task.getUpstream();
  21315. } while (task);
  21316. });
  21317. };
  21318. var updatePayload = proto.updatePayload = function (task, payload) {
  21319. payload !== 'remain' && (task.context.payload = payload);
  21320. };
  21321. function createSeriesStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21322. var seriesTaskMap = stageHandlerRecord.seriesTaskMap || (stageHandlerRecord.seriesTaskMap = createHashMap());
  21323. var seriesType = stageHandler.seriesType;
  21324. var getTargetSeries = stageHandler.getTargetSeries; // If a stageHandler should cover all series, `createOnAllSeries` should be declared mandatorily,
  21325. // to avoid some typo or abuse. Otherwise if an extension do not specify a `seriesType`,
  21326. // it works but it may cause other irrelevant charts blocked.
  21327. if (stageHandler.createOnAllSeries) {
  21328. ecModel.eachRawSeries(create);
  21329. } else if (seriesType) {
  21330. ecModel.eachRawSeriesByType(seriesType, create);
  21331. } else if (getTargetSeries) {
  21332. getTargetSeries(ecModel, api).each(create);
  21333. }
  21334. function create(seriesModel) {
  21335. var pipelineId = seriesModel.uid; // Init tasks for each seriesModel only once.
  21336. // Reuse original task instance.
  21337. var task = seriesTaskMap.get(pipelineId) || seriesTaskMap.set(pipelineId, createTask({
  21338. plan: seriesTaskPlan,
  21339. reset: seriesTaskReset,
  21340. count: seriesTaskCount
  21341. }));
  21342. task.context = {
  21343. model: seriesModel,
  21344. ecModel: ecModel,
  21345. api: api,
  21346. useClearVisual: stageHandler.isVisual && !stageHandler.isLayout,
  21347. plan: stageHandler.plan,
  21348. reset: stageHandler.reset,
  21349. scheduler: scheduler
  21350. };
  21351. pipe(scheduler, seriesModel, task);
  21352. } // Clear unused series tasks.
  21353. var pipelineMap = scheduler._pipelineMap;
  21354. seriesTaskMap.each(function (task, pipelineId) {
  21355. if (!pipelineMap.get(pipelineId)) {
  21356. task.dispose();
  21357. seriesTaskMap.removeKey(pipelineId);
  21358. }
  21359. });
  21360. }
  21361. function createOverallStageTask(scheduler, stageHandler, stageHandlerRecord, ecModel, api) {
  21362. var overallTask = stageHandlerRecord.overallTask = stageHandlerRecord.overallTask // For overall task, the function only be called on reset stage.
  21363. || createTask({
  21364. reset: overallTaskReset
  21365. });
  21366. overallTask.context = {
  21367. ecModel: ecModel,
  21368. api: api,
  21369. overallReset: stageHandler.overallReset,
  21370. scheduler: scheduler
  21371. }; // Reuse orignal stubs.
  21372. var agentStubMap = overallTask.agentStubMap = overallTask.agentStubMap || createHashMap();
  21373. var seriesType = stageHandler.seriesType;
  21374. var getTargetSeries = stageHandler.getTargetSeries;
  21375. var overallProgress = true;
  21376. var modifyOutputEnd = stageHandler.modifyOutputEnd; // An overall task with seriesType detected or has `getTargetSeries`, we add
  21377. // stub in each pipelines, it will set the overall task dirty when the pipeline
  21378. // progress. Moreover, to avoid call the overall task each frame (too frequent),
  21379. // we set the pipeline block.
  21380. if (seriesType) {
  21381. ecModel.eachRawSeriesByType(seriesType, createStub);
  21382. } else if (getTargetSeries) {
  21383. getTargetSeries(ecModel, api).each(createStub);
  21384. } // Otherwise, (usually it is legancy case), the overall task will only be
  21385. // executed when upstream dirty. Otherwise the progressive rendering of all
  21386. // pipelines will be disabled unexpectedly. But it still needs stubs to receive
  21387. // dirty info from upsteam.
  21388. else {
  21389. overallProgress = false;
  21390. each$1(ecModel.getSeries(), createStub);
  21391. }
  21392. function createStub(seriesModel) {
  21393. var pipelineId = seriesModel.uid;
  21394. var stub = agentStubMap.get(pipelineId);
  21395. if (!stub) {
  21396. stub = agentStubMap.set(pipelineId, createTask({
  21397. reset: stubReset,
  21398. onDirty: stubOnDirty
  21399. })); // When the result of `getTargetSeries` changed, the overallTask
  21400. // should be set as dirty and re-performed.
  21401. overallTask.dirty();
  21402. }
  21403. stub.context = {
  21404. model: seriesModel,
  21405. overallProgress: overallProgress,
  21406. modifyOutputEnd: modifyOutputEnd
  21407. };
  21408. stub.agent = overallTask;
  21409. stub.__block = overallProgress;
  21410. pipe(scheduler, seriesModel, stub);
  21411. } // Clear unused stubs.
  21412. var pipelineMap = scheduler._pipelineMap;
  21413. agentStubMap.each(function (stub, pipelineId) {
  21414. if (!pipelineMap.get(pipelineId)) {
  21415. stub.dispose(); // When the result of `getTargetSeries` changed, the overallTask
  21416. // should be set as dirty and re-performed.
  21417. overallTask.dirty();
  21418. agentStubMap.removeKey(pipelineId);
  21419. }
  21420. });
  21421. }
  21422. function overallTaskReset(context) {
  21423. context.overallReset(context.ecModel, context.api, context.payload);
  21424. }
  21425. function stubReset(context, upstreamContext) {
  21426. return context.overallProgress && stubProgress;
  21427. }
  21428. function stubProgress() {
  21429. this.agent.dirty();
  21430. this.getDownstream().dirty();
  21431. }
  21432. function stubOnDirty() {
  21433. this.agent && this.agent.dirty();
  21434. }
  21435. function seriesTaskPlan(context) {
  21436. return context.plan && context.plan(context.model, context.ecModel, context.api, context.payload);
  21437. }
  21438. function seriesTaskReset(context) {
  21439. if (context.useClearVisual) {
  21440. context.data.clearAllVisual();
  21441. }
  21442. var resetDefines = context.resetDefines = normalizeToArray(context.reset(context.model, context.ecModel, context.api, context.payload));
  21443. return resetDefines.length > 1 ? map(resetDefines, function (v, idx) {
  21444. return makeSeriesTaskProgress(idx);
  21445. }) : singleSeriesTaskProgress;
  21446. }
  21447. var singleSeriesTaskProgress = makeSeriesTaskProgress(0);
  21448. function makeSeriesTaskProgress(resetDefineIdx) {
  21449. return function (params, context) {
  21450. var data = context.data;
  21451. var resetDefine = context.resetDefines[resetDefineIdx];
  21452. if (resetDefine && resetDefine.dataEach) {
  21453. for (var i = params.start; i < params.end; i++) {
  21454. resetDefine.dataEach(data, i);
  21455. }
  21456. } else if (resetDefine && resetDefine.progress) {
  21457. resetDefine.progress(params, data);
  21458. }
  21459. };
  21460. }
  21461. function seriesTaskCount(context) {
  21462. return context.data.count();
  21463. }
  21464. function pipe(scheduler, seriesModel, task) {
  21465. var pipelineId = seriesModel.uid;
  21466. var pipeline = scheduler._pipelineMap.get(pipelineId);
  21467. !pipeline.head && (pipeline.head = task);
  21468. pipeline.tail && pipeline.tail.pipe(task);
  21469. pipeline.tail = task;
  21470. task.__idxInPipeline = pipeline.count++;
  21471. task.__pipeline = pipeline;
  21472. }
  21473. Scheduler.wrapStageHandler = function (stageHandler, visualType) {
  21474. if (isFunction$1(stageHandler)) {
  21475. stageHandler = {
  21476. overallReset: stageHandler,
  21477. seriesType: detectSeriseType(stageHandler)
  21478. };
  21479. }
  21480. stageHandler.uid = getUID('stageHandler');
  21481. visualType && (stageHandler.visualType = visualType);
  21482. return stageHandler;
  21483. };
  21484. /**
  21485. * Only some legacy stage handlers (usually in echarts extensions) are pure function.
  21486. * To ensure that they can work normally, they should work in block mode, that is,
  21487. * they should not be started util the previous tasks finished. So they cause the
  21488. * progressive rendering disabled. We try to detect the series type, to narrow down
  21489. * the block range to only the series type they concern, but not all series.
  21490. */
  21491. function detectSeriseType(legacyFunc) {
  21492. seriesType = null;
  21493. try {
  21494. // Assume there is no async when calling `eachSeriesByType`.
  21495. legacyFunc(ecModelMock, apiMock);
  21496. } catch (e) {}
  21497. return seriesType;
  21498. }
  21499. var ecModelMock = {};
  21500. var apiMock = {};
  21501. var seriesType;
  21502. mockMethods(ecModelMock, GlobalModel);
  21503. mockMethods(apiMock, ExtensionAPI);
  21504. ecModelMock.eachSeriesByType = ecModelMock.eachRawSeriesByType = function (type) {
  21505. seriesType = type;
  21506. };
  21507. ecModelMock.eachComponent = function (cond) {
  21508. if (cond.mainType === 'series' && cond.subType) {
  21509. seriesType = cond.subType;
  21510. }
  21511. };
  21512. function mockMethods(target, Clz) {
  21513. /* eslint-disable */
  21514. for (var name in Clz.prototype) {
  21515. // Do not use hasOwnProperty
  21516. target[name] = noop;
  21517. }
  21518. /* eslint-enable */
  21519. }
  21520. /*
  21521. * Licensed to the Apache Software Foundation (ASF) under one
  21522. * or more contributor license agreements. See the NOTICE file
  21523. * distributed with this work for additional information
  21524. * regarding copyright ownership. The ASF licenses this file
  21525. * to you under the Apache License, Version 2.0 (the
  21526. * "License"); you may not use this file except in compliance
  21527. * with the License. You may obtain a copy of the License at
  21528. *
  21529. * http://www.apache.org/licenses/LICENSE-2.0
  21530. *
  21531. * Unless required by applicable law or agreed to in writing,
  21532. * software distributed under the License is distributed on an
  21533. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21534. * KIND, either express or implied. See the License for the
  21535. * specific language governing permissions and limitations
  21536. * under the License.
  21537. */
  21538. var colorAll = ['#37A2DA', '#32C5E9', '#67E0E3', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#E062AE', '#E690D1', '#e7bcf3', '#9d96f5', '#8378EA', '#96BFFF'];
  21539. var lightTheme = {
  21540. color: colorAll,
  21541. colorLayer: [['#37A2DA', '#ffd85c', '#fd7b5f'], ['#37A2DA', '#67E0E3', '#FFDB5C', '#ff9f7f', '#E062AE', '#9d96f5'], ['#37A2DA', '#32C5E9', '#9FE6B8', '#FFDB5C', '#ff9f7f', '#fb7293', '#e7bcf3', '#8378EA', '#96BFFF'], colorAll]
  21542. };
  21543. /*
  21544. * Licensed to the Apache Software Foundation (ASF) under one
  21545. * or more contributor license agreements. See the NOTICE file
  21546. * distributed with this work for additional information
  21547. * regarding copyright ownership. The ASF licenses this file
  21548. * to you under the Apache License, Version 2.0 (the
  21549. * "License"); you may not use this file except in compliance
  21550. * with the License. You may obtain a copy of the License at
  21551. *
  21552. * http://www.apache.org/licenses/LICENSE-2.0
  21553. *
  21554. * Unless required by applicable law or agreed to in writing,
  21555. * software distributed under the License is distributed on an
  21556. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21557. * KIND, either express or implied. See the License for the
  21558. * specific language governing permissions and limitations
  21559. * under the License.
  21560. */
  21561. var contrastColor = '#eee';
  21562. var axisCommon = function () {
  21563. return {
  21564. axisLine: {
  21565. lineStyle: {
  21566. color: contrastColor
  21567. }
  21568. },
  21569. axisTick: {
  21570. lineStyle: {
  21571. color: contrastColor
  21572. }
  21573. },
  21574. axisLabel: {
  21575. textStyle: {
  21576. color: contrastColor
  21577. }
  21578. },
  21579. splitLine: {
  21580. lineStyle: {
  21581. type: 'dashed',
  21582. color: '#aaa'
  21583. }
  21584. },
  21585. splitArea: {
  21586. areaStyle: {
  21587. color: contrastColor
  21588. }
  21589. }
  21590. };
  21591. };
  21592. var colorPalette = ['#dd6b66', '#759aa0', '#e69d87', '#8dc1a9', '#ea7e53', '#eedd78', '#73a373', '#73b9bc', '#7289ab', '#91ca8c', '#f49f42'];
  21593. var theme = {
  21594. color: colorPalette,
  21595. backgroundColor: '#333',
  21596. tooltip: {
  21597. axisPointer: {
  21598. lineStyle: {
  21599. color: contrastColor
  21600. },
  21601. crossStyle: {
  21602. color: contrastColor
  21603. },
  21604. label: {
  21605. color: '#000'
  21606. }
  21607. }
  21608. },
  21609. legend: {
  21610. textStyle: {
  21611. color: contrastColor
  21612. }
  21613. },
  21614. textStyle: {
  21615. color: contrastColor
  21616. },
  21617. title: {
  21618. textStyle: {
  21619. color: contrastColor
  21620. }
  21621. },
  21622. toolbox: {
  21623. iconStyle: {
  21624. normal: {
  21625. borderColor: contrastColor
  21626. }
  21627. }
  21628. },
  21629. dataZoom: {
  21630. textStyle: {
  21631. color: contrastColor
  21632. }
  21633. },
  21634. visualMap: {
  21635. textStyle: {
  21636. color: contrastColor
  21637. }
  21638. },
  21639. timeline: {
  21640. lineStyle: {
  21641. color: contrastColor
  21642. },
  21643. itemStyle: {
  21644. normal: {
  21645. color: colorPalette[1]
  21646. }
  21647. },
  21648. label: {
  21649. normal: {
  21650. textStyle: {
  21651. color: contrastColor
  21652. }
  21653. }
  21654. },
  21655. controlStyle: {
  21656. normal: {
  21657. color: contrastColor,
  21658. borderColor: contrastColor
  21659. }
  21660. }
  21661. },
  21662. timeAxis: axisCommon(),
  21663. logAxis: axisCommon(),
  21664. valueAxis: axisCommon(),
  21665. categoryAxis: axisCommon(),
  21666. line: {
  21667. symbol: 'circle'
  21668. },
  21669. graph: {
  21670. color: colorPalette
  21671. },
  21672. gauge: {
  21673. title: {
  21674. textStyle: {
  21675. color: contrastColor
  21676. }
  21677. }
  21678. },
  21679. candlestick: {
  21680. itemStyle: {
  21681. normal: {
  21682. color: '#FD1050',
  21683. color0: '#0CF49B',
  21684. borderColor: '#FD1050',
  21685. borderColor0: '#0CF49B'
  21686. }
  21687. }
  21688. }
  21689. };
  21690. theme.categoryAxis.splitLine.show = false;
  21691. /*
  21692. * Licensed to the Apache Software Foundation (ASF) under one
  21693. * or more contributor license agreements. See the NOTICE file
  21694. * distributed with this work for additional information
  21695. * regarding copyright ownership. The ASF licenses this file
  21696. * to you under the Apache License, Version 2.0 (the
  21697. * "License"); you may not use this file except in compliance
  21698. * with the License. You may obtain a copy of the License at
  21699. *
  21700. * http://www.apache.org/licenses/LICENSE-2.0
  21701. *
  21702. * Unless required by applicable law or agreed to in writing,
  21703. * software distributed under the License is distributed on an
  21704. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  21705. * KIND, either express or implied. See the License for the
  21706. * specific language governing permissions and limitations
  21707. * under the License.
  21708. */
  21709. /**
  21710. * This module is imported by echarts directly.
  21711. *
  21712. * Notice:
  21713. * Always keep this file exists for backward compatibility.
  21714. * Because before 4.1.0, dataset is an optional component,
  21715. * some users may import this module manually.
  21716. */
  21717. ComponentModel.extend({
  21718. type: 'dataset',
  21719. /**
  21720. * @protected
  21721. */
  21722. defaultOption: {
  21723. // 'row', 'column'
  21724. seriesLayoutBy: SERIES_LAYOUT_BY_COLUMN,
  21725. // null/'auto': auto detect header, see "module:echarts/data/helper/sourceHelper"
  21726. sourceHeader: null,
  21727. dimensions: null,
  21728. source: null
  21729. },
  21730. optionUpdated: function () {
  21731. detectSourceFormat(this);
  21732. }
  21733. });
  21734. Component$1.extend({
  21735. type: 'dataset'
  21736. });
  21737. /**
  21738. * 椭圆形状
  21739. * @module zrender/graphic/shape/Ellipse
  21740. */
  21741. var Ellipse = Path.extend({
  21742. type: 'ellipse',
  21743. shape: {
  21744. cx: 0,
  21745. cy: 0,
  21746. rx: 0,
  21747. ry: 0
  21748. },
  21749. buildPath: function (ctx, shape) {
  21750. var k = 0.5522848;
  21751. var x = shape.cx;
  21752. var y = shape.cy;
  21753. var a = shape.rx;
  21754. var b = shape.ry;
  21755. var ox = a * k; // 水平控制点偏移量
  21756. var oy = b * k; // 垂直控制点偏移量
  21757. // 从椭圆的左端点开始顺时针绘制四条三次贝塞尔曲线
  21758. ctx.moveTo(x - a, y);
  21759. ctx.bezierCurveTo(x - a, y - oy, x - ox, y - b, x, y - b);
  21760. ctx.bezierCurveTo(x + ox, y - b, x + a, y - oy, x + a, y);
  21761. ctx.bezierCurveTo(x + a, y + oy, x + ox, y + b, x, y + b);
  21762. ctx.bezierCurveTo(x - ox, y + b, x - a, y + oy, x - a, y);
  21763. ctx.closePath();
  21764. }
  21765. });
  21766. // import Pattern from '../graphic/Pattern';
  21767. var DILIMITER_REG = /[\s,]+/;
  21768. /**
  21769. * For big svg string, this method might be time consuming.
  21770. *
  21771. * @param {string} svg xml string
  21772. * @return {Object} xml root.
  21773. */
  21774. function parseXML(svg) {
  21775. if (isString(svg)) {
  21776. var parser = new DOMParser();
  21777. svg = parser.parseFromString(svg, 'text/xml');
  21778. } // Document node. If using $.get, doc node may be input.
  21779. if (svg.nodeType === 9) {
  21780. svg = svg.firstChild;
  21781. } // nodeName of <!DOCTYPE svg> is also 'svg'.
  21782. while (svg.nodeName.toLowerCase() !== 'svg' || svg.nodeType !== 1) {
  21783. svg = svg.nextSibling;
  21784. }
  21785. return svg;
  21786. }
  21787. function SVGParser() {
  21788. this._defs = {};
  21789. this._root = null;
  21790. this._isDefine = false;
  21791. this._isText = false;
  21792. }
  21793. SVGParser.prototype.parse = function (xml, opt) {
  21794. opt = opt || {};
  21795. var svg = parseXML(xml);
  21796. if (!svg) {
  21797. throw new Error('Illegal svg');
  21798. }
  21799. var root = new Group();
  21800. this._root = root; // parse view port
  21801. var viewBox = svg.getAttribute('viewBox') || ''; // If width/height not specified, means "100%" of `opt.width/height`.
  21802. // TODO: Other percent value not supported yet.
  21803. var width = parseFloat(svg.getAttribute('width') || opt.width);
  21804. var height = parseFloat(svg.getAttribute('height') || opt.height); // If width/height not specified, set as null for output.
  21805. isNaN(width) && (width = null);
  21806. isNaN(height) && (height = null); // Apply inline style on svg element.
  21807. parseAttributes(svg, root, null, true);
  21808. var child = svg.firstChild;
  21809. while (child) {
  21810. this._parseNode(child, root);
  21811. child = child.nextSibling;
  21812. }
  21813. var viewBoxRect;
  21814. var viewBoxTransform;
  21815. if (viewBox) {
  21816. var viewBoxArr = trim(viewBox).split(DILIMITER_REG); // Some invalid case like viewBox: 'none'.
  21817. if (viewBoxArr.length >= 4) {
  21818. viewBoxRect = {
  21819. x: parseFloat(viewBoxArr[0] || 0),
  21820. y: parseFloat(viewBoxArr[1] || 0),
  21821. width: parseFloat(viewBoxArr[2]),
  21822. height: parseFloat(viewBoxArr[3])
  21823. };
  21824. }
  21825. }
  21826. if (viewBoxRect && width != null && height != null) {
  21827. viewBoxTransform = makeViewBoxTransform(viewBoxRect, width, height);
  21828. if (!opt.ignoreViewBox) {
  21829. // If set transform on the output group, it probably bring trouble when
  21830. // some users only intend to show the clipped content inside the viewBox,
  21831. // but not intend to transform the output group. So we keep the output
  21832. // group no transform. If the user intend to use the viewBox as a
  21833. // camera, just set `opt.ignoreViewBox` as `true` and set transfrom
  21834. // manually according to the viewBox info in the output of this method.
  21835. var elRoot = root;
  21836. root = new Group();
  21837. root.add(elRoot);
  21838. elRoot.scale = viewBoxTransform.scale.slice();
  21839. elRoot.position = viewBoxTransform.position.slice();
  21840. }
  21841. } // Some shapes might be overflow the viewport, which should be
  21842. // clipped despite whether the viewBox is used, as the SVG does.
  21843. if (!opt.ignoreRootClip && width != null && height != null) {
  21844. root.setClipPath(new Rect({
  21845. shape: {
  21846. x: 0,
  21847. y: 0,
  21848. width: width,
  21849. height: height
  21850. }
  21851. }));
  21852. } // Set width/height on group just for output the viewport size.
  21853. return {
  21854. root: root,
  21855. width: width,
  21856. height: height,
  21857. viewBoxRect: viewBoxRect,
  21858. viewBoxTransform: viewBoxTransform
  21859. };
  21860. };
  21861. SVGParser.prototype._parseNode = function (xmlNode, parentGroup) {
  21862. var nodeName = xmlNode.nodeName.toLowerCase(); // TODO
  21863. // support <style>...</style> in svg, where nodeName is 'style',
  21864. // CSS classes is defined globally wherever the style tags are declared.
  21865. if (nodeName === 'defs') {
  21866. // define flag
  21867. this._isDefine = true;
  21868. } else if (nodeName === 'text') {
  21869. this._isText = true;
  21870. }
  21871. var el;
  21872. if (this._isDefine) {
  21873. var parser = defineParsers[nodeName];
  21874. if (parser) {
  21875. var def = parser.call(this, xmlNode);
  21876. var id = xmlNode.getAttribute('id');
  21877. if (id) {
  21878. this._defs[id] = def;
  21879. }
  21880. }
  21881. } else {
  21882. var parser = nodeParsers[nodeName];
  21883. if (parser) {
  21884. el = parser.call(this, xmlNode, parentGroup);
  21885. parentGroup.add(el);
  21886. }
  21887. }
  21888. var child = xmlNode.firstChild;
  21889. while (child) {
  21890. if (child.nodeType === 1) {
  21891. this._parseNode(child, el);
  21892. } // Is text
  21893. if (child.nodeType === 3 && this._isText) {
  21894. this._parseText(child, el);
  21895. }
  21896. child = child.nextSibling;
  21897. } // Quit define
  21898. if (nodeName === 'defs') {
  21899. this._isDefine = false;
  21900. } else if (nodeName === 'text') {
  21901. this._isText = false;
  21902. }
  21903. };
  21904. SVGParser.prototype._parseText = function (xmlNode, parentGroup) {
  21905. if (xmlNode.nodeType === 1) {
  21906. var dx = xmlNode.getAttribute('dx') || 0;
  21907. var dy = xmlNode.getAttribute('dy') || 0;
  21908. this._textX += parseFloat(dx);
  21909. this._textY += parseFloat(dy);
  21910. }
  21911. var text = new Text({
  21912. style: {
  21913. text: xmlNode.textContent,
  21914. transformText: true
  21915. },
  21916. position: [this._textX || 0, this._textY || 0]
  21917. });
  21918. inheritStyle(parentGroup, text);
  21919. parseAttributes(xmlNode, text, this._defs);
  21920. var fontSize = text.style.fontSize;
  21921. if (fontSize && fontSize < 9) {
  21922. // PENDING
  21923. text.style.fontSize = 9;
  21924. text.scale = text.scale || [1, 1];
  21925. text.scale[0] *= fontSize / 9;
  21926. text.scale[1] *= fontSize / 9;
  21927. }
  21928. var rect = text.getBoundingRect();
  21929. this._textX += rect.width;
  21930. parentGroup.add(text);
  21931. return text;
  21932. };
  21933. var nodeParsers = {
  21934. 'g': function (xmlNode, parentGroup) {
  21935. var g = new Group();
  21936. inheritStyle(parentGroup, g);
  21937. parseAttributes(xmlNode, g, this._defs);
  21938. return g;
  21939. },
  21940. 'rect': function (xmlNode, parentGroup) {
  21941. var rect = new Rect();
  21942. inheritStyle(parentGroup, rect);
  21943. parseAttributes(xmlNode, rect, this._defs);
  21944. rect.setShape({
  21945. x: parseFloat(xmlNode.getAttribute('x') || 0),
  21946. y: parseFloat(xmlNode.getAttribute('y') || 0),
  21947. width: parseFloat(xmlNode.getAttribute('width') || 0),
  21948. height: parseFloat(xmlNode.getAttribute('height') || 0)
  21949. }); // console.log(xmlNode.getAttribute('transform'));
  21950. // console.log(rect.transform);
  21951. return rect;
  21952. },
  21953. 'circle': function (xmlNode, parentGroup) {
  21954. var circle = new Circle();
  21955. inheritStyle(parentGroup, circle);
  21956. parseAttributes(xmlNode, circle, this._defs);
  21957. circle.setShape({
  21958. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  21959. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  21960. r: parseFloat(xmlNode.getAttribute('r') || 0)
  21961. });
  21962. return circle;
  21963. },
  21964. 'line': function (xmlNode, parentGroup) {
  21965. var line = new Line();
  21966. inheritStyle(parentGroup, line);
  21967. parseAttributes(xmlNode, line, this._defs);
  21968. line.setShape({
  21969. x1: parseFloat(xmlNode.getAttribute('x1') || 0),
  21970. y1: parseFloat(xmlNode.getAttribute('y1') || 0),
  21971. x2: parseFloat(xmlNode.getAttribute('x2') || 0),
  21972. y2: parseFloat(xmlNode.getAttribute('y2') || 0)
  21973. });
  21974. return line;
  21975. },
  21976. 'ellipse': function (xmlNode, parentGroup) {
  21977. var ellipse = new Ellipse();
  21978. inheritStyle(parentGroup, ellipse);
  21979. parseAttributes(xmlNode, ellipse, this._defs);
  21980. ellipse.setShape({
  21981. cx: parseFloat(xmlNode.getAttribute('cx') || 0),
  21982. cy: parseFloat(xmlNode.getAttribute('cy') || 0),
  21983. rx: parseFloat(xmlNode.getAttribute('rx') || 0),
  21984. ry: parseFloat(xmlNode.getAttribute('ry') || 0)
  21985. });
  21986. return ellipse;
  21987. },
  21988. 'polygon': function (xmlNode, parentGroup) {
  21989. var points = xmlNode.getAttribute('points');
  21990. if (points) {
  21991. points = parsePoints(points);
  21992. }
  21993. var polygon = new Polygon({
  21994. shape: {
  21995. points: points || []
  21996. }
  21997. });
  21998. inheritStyle(parentGroup, polygon);
  21999. parseAttributes(xmlNode, polygon, this._defs);
  22000. return polygon;
  22001. },
  22002. 'polyline': function (xmlNode, parentGroup) {
  22003. var path = new Path();
  22004. inheritStyle(parentGroup, path);
  22005. parseAttributes(xmlNode, path, this._defs);
  22006. var points = xmlNode.getAttribute('points');
  22007. if (points) {
  22008. points = parsePoints(points);
  22009. }
  22010. var polyline = new Polyline({
  22011. shape: {
  22012. points: points || []
  22013. }
  22014. });
  22015. return polyline;
  22016. },
  22017. 'image': function (xmlNode, parentGroup) {
  22018. var img = new ZImage();
  22019. inheritStyle(parentGroup, img);
  22020. parseAttributes(xmlNode, img, this._defs);
  22021. img.setStyle({
  22022. image: xmlNode.getAttribute('xlink:href'),
  22023. x: xmlNode.getAttribute('x'),
  22024. y: xmlNode.getAttribute('y'),
  22025. width: xmlNode.getAttribute('width'),
  22026. height: xmlNode.getAttribute('height')
  22027. });
  22028. return img;
  22029. },
  22030. 'text': function (xmlNode, parentGroup) {
  22031. var x = xmlNode.getAttribute('x') || 0;
  22032. var y = xmlNode.getAttribute('y') || 0;
  22033. var dx = xmlNode.getAttribute('dx') || 0;
  22034. var dy = xmlNode.getAttribute('dy') || 0;
  22035. this._textX = parseFloat(x) + parseFloat(dx);
  22036. this._textY = parseFloat(y) + parseFloat(dy);
  22037. var g = new Group();
  22038. inheritStyle(parentGroup, g);
  22039. parseAttributes(xmlNode, g, this._defs);
  22040. return g;
  22041. },
  22042. 'tspan': function (xmlNode, parentGroup) {
  22043. var x = xmlNode.getAttribute('x');
  22044. var y = xmlNode.getAttribute('y');
  22045. if (x != null) {
  22046. // new offset x
  22047. this._textX = parseFloat(x);
  22048. }
  22049. if (y != null) {
  22050. // new offset y
  22051. this._textY = parseFloat(y);
  22052. }
  22053. var dx = xmlNode.getAttribute('dx') || 0;
  22054. var dy = xmlNode.getAttribute('dy') || 0;
  22055. var g = new Group();
  22056. inheritStyle(parentGroup, g);
  22057. parseAttributes(xmlNode, g, this._defs);
  22058. this._textX += dx;
  22059. this._textY += dy;
  22060. return g;
  22061. },
  22062. 'path': function (xmlNode, parentGroup) {
  22063. // TODO svg fill rule
  22064. // https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/fill-rule
  22065. // path.style.globalCompositeOperation = 'xor';
  22066. var d = xmlNode.getAttribute('d') || ''; // Performance sensitive.
  22067. var path = createFromString(d);
  22068. inheritStyle(parentGroup, path);
  22069. parseAttributes(xmlNode, path, this._defs);
  22070. return path;
  22071. }
  22072. };
  22073. var defineParsers = {
  22074. 'lineargradient': function (xmlNode) {
  22075. var x1 = parseInt(xmlNode.getAttribute('x1') || 0, 10);
  22076. var y1 = parseInt(xmlNode.getAttribute('y1') || 0, 10);
  22077. var x2 = parseInt(xmlNode.getAttribute('x2') || 10, 10);
  22078. var y2 = parseInt(xmlNode.getAttribute('y2') || 0, 10);
  22079. var gradient = new LinearGradient(x1, y1, x2, y2);
  22080. _parseGradientColorStops(xmlNode, gradient);
  22081. return gradient;
  22082. },
  22083. 'radialgradient': function (xmlNode) {}
  22084. };
  22085. function _parseGradientColorStops(xmlNode, gradient) {
  22086. var stop = xmlNode.firstChild;
  22087. while (stop) {
  22088. if (stop.nodeType === 1) {
  22089. var offset = stop.getAttribute('offset');
  22090. if (offset.indexOf('%') > 0) {
  22091. // percentage
  22092. offset = parseInt(offset, 10) / 100;
  22093. } else if (offset) {
  22094. // number from 0 to 1
  22095. offset = parseFloat(offset);
  22096. } else {
  22097. offset = 0;
  22098. }
  22099. var stopColor = stop.getAttribute('stop-color') || '#000000';
  22100. gradient.addColorStop(offset, stopColor);
  22101. }
  22102. stop = stop.nextSibling;
  22103. }
  22104. }
  22105. function inheritStyle(parent, child) {
  22106. if (parent && parent.__inheritedStyle) {
  22107. if (!child.__inheritedStyle) {
  22108. child.__inheritedStyle = {};
  22109. }
  22110. defaults(child.__inheritedStyle, parent.__inheritedStyle);
  22111. }
  22112. }
  22113. function parsePoints(pointsString) {
  22114. var list = trim(pointsString).split(DILIMITER_REG);
  22115. var points = [];
  22116. for (var i = 0; i < list.length; i += 2) {
  22117. var x = parseFloat(list[i]);
  22118. var y = parseFloat(list[i + 1]);
  22119. points.push([x, y]);
  22120. }
  22121. return points;
  22122. }
  22123. var attributesMap = {
  22124. 'fill': 'fill',
  22125. 'stroke': 'stroke',
  22126. 'stroke-width': 'lineWidth',
  22127. 'opacity': 'opacity',
  22128. 'fill-opacity': 'fillOpacity',
  22129. 'stroke-opacity': 'strokeOpacity',
  22130. 'stroke-dasharray': 'lineDash',
  22131. 'stroke-dashoffset': 'lineDashOffset',
  22132. 'stroke-linecap': 'lineCap',
  22133. 'stroke-linejoin': 'lineJoin',
  22134. 'stroke-miterlimit': 'miterLimit',
  22135. 'font-family': 'fontFamily',
  22136. 'font-size': 'fontSize',
  22137. 'font-style': 'fontStyle',
  22138. 'font-weight': 'fontWeight',
  22139. 'text-align': 'textAlign',
  22140. 'alignment-baseline': 'textBaseline'
  22141. };
  22142. function parseAttributes(xmlNode, el, defs, onlyInlineStyle) {
  22143. var zrStyle = el.__inheritedStyle || {};
  22144. var isTextEl = el.type === 'text'; // TODO Shadow
  22145. if (xmlNode.nodeType === 1) {
  22146. parseTransformAttribute(xmlNode, el);
  22147. extend(zrStyle, parseStyleAttribute(xmlNode));
  22148. if (!onlyInlineStyle) {
  22149. for (var svgAttrName in attributesMap) {
  22150. if (attributesMap.hasOwnProperty(svgAttrName)) {
  22151. var attrValue = xmlNode.getAttribute(svgAttrName);
  22152. if (attrValue != null) {
  22153. zrStyle[attributesMap[svgAttrName]] = attrValue;
  22154. }
  22155. }
  22156. }
  22157. }
  22158. }
  22159. var elFillProp = isTextEl ? 'textFill' : 'fill';
  22160. var elStrokeProp = isTextEl ? 'textStroke' : 'stroke';
  22161. el.style = el.style || new Style();
  22162. var elStyle = el.style;
  22163. zrStyle.fill != null && elStyle.set(elFillProp, getPaint(zrStyle.fill, defs));
  22164. zrStyle.stroke != null && elStyle.set(elStrokeProp, getPaint(zrStyle.stroke, defs));
  22165. each$1(['lineWidth', 'opacity', 'fillOpacity', 'strokeOpacity', 'miterLimit', 'fontSize'], function (propName) {
  22166. var elPropName = propName === 'lineWidth' && isTextEl ? 'textStrokeWidth' : propName;
  22167. zrStyle[propName] != null && elStyle.set(elPropName, parseFloat(zrStyle[propName]));
  22168. });
  22169. if (!zrStyle.textBaseline || zrStyle.textBaseline === 'auto') {
  22170. zrStyle.textBaseline = 'alphabetic';
  22171. }
  22172. if (zrStyle.textBaseline === 'alphabetic') {
  22173. zrStyle.textBaseline = 'bottom';
  22174. }
  22175. if (zrStyle.textAlign === 'start') {
  22176. zrStyle.textAlign = 'left';
  22177. }
  22178. if (zrStyle.textAlign === 'end') {
  22179. zrStyle.textAlign = 'right';
  22180. }
  22181. each$1(['lineDashOffset', 'lineCap', 'lineJoin', 'fontWeight', 'fontFamily', 'fontStyle', 'textAlign', 'textBaseline'], function (propName) {
  22182. zrStyle[propName] != null && elStyle.set(propName, zrStyle[propName]);
  22183. });
  22184. if (zrStyle.lineDash) {
  22185. el.style.lineDash = trim(zrStyle.lineDash).split(DILIMITER_REG);
  22186. }
  22187. if (elStyle[elStrokeProp] && elStyle[elStrokeProp] !== 'none') {
  22188. // enable stroke
  22189. el[elStrokeProp] = true;
  22190. }
  22191. el.__inheritedStyle = zrStyle;
  22192. }
  22193. var urlRegex = /url\(\s*#(.*?)\)/;
  22194. function getPaint(str, defs) {
  22195. // if (str === 'none') {
  22196. // return;
  22197. // }
  22198. var urlMatch = defs && str && str.match(urlRegex);
  22199. if (urlMatch) {
  22200. var url = trim(urlMatch[1]);
  22201. var def = defs[url];
  22202. return def;
  22203. }
  22204. return str;
  22205. }
  22206. var transformRegex = /(translate|scale|rotate|skewX|skewY|matrix)\(([\-\s0-9\.e,]*)\)/g;
  22207. function parseTransformAttribute(xmlNode, node) {
  22208. var transform = xmlNode.getAttribute('transform');
  22209. if (transform) {
  22210. transform = transform.replace(/,/g, ' ');
  22211. var m = null;
  22212. var transformOps = [];
  22213. transform.replace(transformRegex, function (str, type, value) {
  22214. transformOps.push(type, value);
  22215. });
  22216. for (var i = transformOps.length - 1; i > 0; i -= 2) {
  22217. var value = transformOps[i];
  22218. var type = transformOps[i - 1];
  22219. m = m || create$1();
  22220. switch (type) {
  22221. case 'translate':
  22222. value = trim(value).split(DILIMITER_REG);
  22223. translate(m, m, [parseFloat(value[0]), parseFloat(value[1] || 0)]);
  22224. break;
  22225. case 'scale':
  22226. value = trim(value).split(DILIMITER_REG);
  22227. scale$1(m, m, [parseFloat(value[0]), parseFloat(value[1] || value[0])]);
  22228. break;
  22229. case 'rotate':
  22230. value = trim(value).split(DILIMITER_REG);
  22231. rotate(m, m, parseFloat(value[0]));
  22232. break;
  22233. case 'skew':
  22234. value = trim(value).split(DILIMITER_REG);
  22235. console.warn('Skew transform is not supported yet');
  22236. break;
  22237. case 'matrix':
  22238. var value = trim(value).split(DILIMITER_REG);
  22239. m[0] = parseFloat(value[0]);
  22240. m[1] = parseFloat(value[1]);
  22241. m[2] = parseFloat(value[2]);
  22242. m[3] = parseFloat(value[3]);
  22243. m[4] = parseFloat(value[4]);
  22244. m[5] = parseFloat(value[5]);
  22245. break;
  22246. }
  22247. }
  22248. node.setLocalTransform(m);
  22249. }
  22250. } // Value may contain space.
  22251. var styleRegex = /([^\s:;]+)\s*:\s*([^:;]+)/g;
  22252. function parseStyleAttribute(xmlNode) {
  22253. var style = xmlNode.getAttribute('style');
  22254. var result = {};
  22255. if (!style) {
  22256. return result;
  22257. }
  22258. var styleList = {};
  22259. styleRegex.lastIndex = 0;
  22260. var styleRegResult;
  22261. while ((styleRegResult = styleRegex.exec(style)) != null) {
  22262. styleList[styleRegResult[1]] = styleRegResult[2];
  22263. }
  22264. for (var svgAttrName in attributesMap) {
  22265. if (attributesMap.hasOwnProperty(svgAttrName) && styleList[svgAttrName] != null) {
  22266. result[attributesMap[svgAttrName]] = styleList[svgAttrName];
  22267. }
  22268. }
  22269. return result;
  22270. }
  22271. /**
  22272. * @param {Array.<number>} viewBoxRect
  22273. * @param {number} width
  22274. * @param {number} height
  22275. * @return {Object} {scale, position}
  22276. */
  22277. function makeViewBoxTransform(viewBoxRect, width, height) {
  22278. var scaleX = width / viewBoxRect.width;
  22279. var scaleY = height / viewBoxRect.height;
  22280. var scale = Math.min(scaleX, scaleY); // preserveAspectRatio 'xMidYMid'
  22281. var viewBoxScale = [scale, scale];
  22282. var viewBoxPosition = [-(viewBoxRect.x + viewBoxRect.width / 2) * scale + width / 2, -(viewBoxRect.y + viewBoxRect.height / 2) * scale + height / 2];
  22283. return {
  22284. scale: viewBoxScale,
  22285. position: viewBoxPosition
  22286. };
  22287. }
  22288. /**
  22289. * @param {string|XMLElement} xml
  22290. * @param {Object} [opt]
  22291. * @param {number} [opt.width] Default width if svg width not specified or is a percent value.
  22292. * @param {number} [opt.height] Default height if svg height not specified or is a percent value.
  22293. * @param {boolean} [opt.ignoreViewBox]
  22294. * @param {boolean} [opt.ignoreRootClip]
  22295. * @return {Object} result:
  22296. * {
  22297. * root: Group, The root of the the result tree of zrender shapes,
  22298. * width: number, the viewport width of the SVG,
  22299. * height: number, the viewport height of the SVG,
  22300. * viewBoxRect: {x, y, width, height}, the declared viewBox rect of the SVG, if exists,
  22301. * viewBoxTransform: the {scale, position} calculated by viewBox and viewport, is exists.
  22302. * }
  22303. */
  22304. function parseSVG(xml, opt) {
  22305. var parser = new SVGParser();
  22306. return parser.parse(xml, opt);
  22307. }
  22308. /*
  22309. * Licensed to the Apache Software Foundation (ASF) under one
  22310. * or more contributor license agreements. See the NOTICE file
  22311. * distributed with this work for additional information
  22312. * regarding copyright ownership. The ASF licenses this file
  22313. * to you under the Apache License, Version 2.0 (the
  22314. * "License"); you may not use this file except in compliance
  22315. * with the License. You may obtain a copy of the License at
  22316. *
  22317. * http://www.apache.org/licenses/LICENSE-2.0
  22318. *
  22319. * Unless required by applicable law or agreed to in writing,
  22320. * software distributed under the License is distributed on an
  22321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22322. * KIND, either express or implied. See the License for the
  22323. * specific language governing permissions and limitations
  22324. * under the License.
  22325. */
  22326. var storage = createHashMap(); // For minimize the code size of common echarts package,
  22327. // do not put too much logic in this module.
  22328. var mapDataStorage = {
  22329. // The format of record: see `echarts.registerMap`.
  22330. // Compatible with previous `echarts.registerMap`.
  22331. registerMap: function (mapName, rawGeoJson, rawSpecialAreas) {
  22332. var records;
  22333. if (isArray(rawGeoJson)) {
  22334. records = rawGeoJson;
  22335. } else if (rawGeoJson.svg) {
  22336. records = [{
  22337. type: 'svg',
  22338. source: rawGeoJson.svg,
  22339. specialAreas: rawGeoJson.specialAreas
  22340. }];
  22341. } else {
  22342. // Backward compatibility.
  22343. if (rawGeoJson.geoJson && !rawGeoJson.features) {
  22344. rawSpecialAreas = rawGeoJson.specialAreas;
  22345. rawGeoJson = rawGeoJson.geoJson;
  22346. }
  22347. records = [{
  22348. type: 'geoJSON',
  22349. source: rawGeoJson,
  22350. specialAreas: rawSpecialAreas
  22351. }];
  22352. }
  22353. each$1(records, function (record) {
  22354. var type = record.type;
  22355. type === 'geoJson' && (type = record.type = 'geoJSON');
  22356. var parse = parsers[type];
  22357. parse(record);
  22358. });
  22359. return storage.set(mapName, records);
  22360. },
  22361. retrieveMap: function (mapName) {
  22362. return storage.get(mapName);
  22363. }
  22364. };
  22365. var parsers = {
  22366. geoJSON: function (record) {
  22367. var source = record.source;
  22368. record.geoJSON = !isString(source) ? source : typeof JSON !== 'undefined' && JSON.parse ? JSON.parse(source) : new Function('return (' + source + ');')();
  22369. },
  22370. // Only perform parse to XML object here, which might be time
  22371. // consiming for large SVG.
  22372. // Although convert XML to zrender element is also time consiming,
  22373. // if we do it here, the clone of zrender elements has to be
  22374. // required. So we do it once for each geo instance, util real
  22375. // performance issues call for optimizing it.
  22376. svg: function (record) {
  22377. record.svgXML = parseXML(record.source);
  22378. }
  22379. };
  22380. /*
  22381. * Licensed to the Apache Software Foundation (ASF) under one
  22382. * or more contributor license agreements. See the NOTICE file
  22383. * distributed with this work for additional information
  22384. * regarding copyright ownership. The ASF licenses this file
  22385. * to you under the Apache License, Version 2.0 (the
  22386. * "License"); you may not use this file except in compliance
  22387. * with the License. You may obtain a copy of the License at
  22388. *
  22389. * http://www.apache.org/licenses/LICENSE-2.0
  22390. *
  22391. * Unless required by applicable law or agreed to in writing,
  22392. * software distributed under the License is distributed on an
  22393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  22394. * KIND, either express or implied. See the License for the
  22395. * specific language governing permissions and limitations
  22396. * under the License.
  22397. */
  22398. var assert = assert$1;
  22399. var each = each$1;
  22400. var isFunction = isFunction$1;
  22401. var isObject = isObject$1;
  22402. var parseClassType = ComponentModel.parseClassType;
  22403. var version = '4.8.0';
  22404. var dependencies = {
  22405. zrender: '4.3.1'
  22406. };
  22407. var TEST_FRAME_REMAIN_TIME = 1;
  22408. var PRIORITY_PROCESSOR_FILTER = 1000;
  22409. var PRIORITY_PROCESSOR_SERIES_FILTER = 800;
  22410. var PRIORITY_PROCESSOR_DATASTACK = 900;
  22411. var PRIORITY_PROCESSOR_STATISTIC = 5000;
  22412. var PRIORITY_VISUAL_LAYOUT = 1000;
  22413. var PRIORITY_VISUAL_PROGRESSIVE_LAYOUT = 1100;
  22414. var PRIORITY_VISUAL_GLOBAL = 2000;
  22415. var PRIORITY_VISUAL_CHART = 3000;
  22416. var PRIORITY_VISUAL_POST_CHART_LAYOUT = 3500;
  22417. var PRIORITY_VISUAL_COMPONENT = 4000; // FIXME
  22418. // necessary?
  22419. var PRIORITY_VISUAL_BRUSH = 5000;
  22420. var PRIORITY = {
  22421. PROCESSOR: {
  22422. FILTER: PRIORITY_PROCESSOR_FILTER,
  22423. SERIES_FILTER: PRIORITY_PROCESSOR_SERIES_FILTER,
  22424. STATISTIC: PRIORITY_PROCESSOR_STATISTIC
  22425. },
  22426. VISUAL: {
  22427. LAYOUT: PRIORITY_VISUAL_LAYOUT,
  22428. PROGRESSIVE_LAYOUT: PRIORITY_VISUAL_PROGRESSIVE_LAYOUT,
  22429. GLOBAL: PRIORITY_VISUAL_GLOBAL,
  22430. CHART: PRIORITY_VISUAL_CHART,
  22431. POST_CHART_LAYOUT: PRIORITY_VISUAL_POST_CHART_LAYOUT,
  22432. COMPONENT: PRIORITY_VISUAL_COMPONENT,
  22433. BRUSH: PRIORITY_VISUAL_BRUSH
  22434. }
  22435. }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`,
  22436. // where they must not be invoked nestedly, except the only case: invoke
  22437. // dispatchAction with updateMethod "none" in main process.
  22438. // This flag is used to carry out this rule.
  22439. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]).
  22440. var IN_MAIN_PROCESS = '__flagInMainProcess';
  22441. var OPTION_UPDATED = '__optionUpdated';
  22442. var ACTION_REG = /^[a-zA-Z0-9_]+$/;
  22443. function createRegisterEventWithLowercaseName(method, ignoreDisposed) {
  22444. return function (eventName, handler, context) {
  22445. if (!ignoreDisposed && this._disposed) {
  22446. return;
  22447. } // Event name is all lowercase
  22448. eventName = eventName && eventName.toLowerCase();
  22449. Eventful.prototype[method].call(this, eventName, handler, context);
  22450. };
  22451. }
  22452. /**
  22453. * @module echarts~MessageCenter
  22454. */
  22455. function MessageCenter() {
  22456. Eventful.call(this);
  22457. }
  22458. MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on', true);
  22459. MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off', true);
  22460. MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one', true);
  22461. mixin(MessageCenter, Eventful);
  22462. /**
  22463. * @module echarts~ECharts
  22464. */
  22465. function ECharts(dom, theme$$1, opts) {
  22466. opts = opts || {}; // Get theme by name
  22467. if (typeof theme$$1 === 'string') {
  22468. theme$$1 = themeStorage[theme$$1];
  22469. }
  22470. /**
  22471. * @type {string}
  22472. */
  22473. this.id;
  22474. /**
  22475. * Group id
  22476. * @type {string}
  22477. */
  22478. this.group;
  22479. /**
  22480. * @type {HTMLElement}
  22481. * @private
  22482. */
  22483. this._dom = dom;
  22484. var defaultRenderer = 'canvas';
  22485. /**
  22486. * @type {module:zrender/ZRender}
  22487. * @private
  22488. */
  22489. var zr = this._zr = init$1(dom, {
  22490. renderer: opts.renderer || defaultRenderer,
  22491. devicePixelRatio: opts.devicePixelRatio,
  22492. width: opts.width,
  22493. height: opts.height
  22494. });
  22495. /**
  22496. * Expect 60 fps.
  22497. * @type {Function}
  22498. * @private
  22499. */
  22500. this._throttledZrFlush = throttle(bind(zr.flush, zr), 17);
  22501. var theme$$1 = clone(theme$$1);
  22502. theme$$1 && backwardCompat(theme$$1, true);
  22503. /**
  22504. * @type {Object}
  22505. * @private
  22506. */
  22507. this._theme = theme$$1;
  22508. /**
  22509. * @type {Array.<module:echarts/view/Chart>}
  22510. * @private
  22511. */
  22512. this._chartsViews = [];
  22513. /**
  22514. * @type {Object.<string, module:echarts/view/Chart>}
  22515. * @private
  22516. */
  22517. this._chartsMap = {};
  22518. /**
  22519. * @type {Array.<module:echarts/view/Component>}
  22520. * @private
  22521. */
  22522. this._componentsViews = [];
  22523. /**
  22524. * @type {Object.<string, module:echarts/view/Component>}
  22525. * @private
  22526. */
  22527. this._componentsMap = {};
  22528. /**
  22529. * @type {module:echarts/CoordinateSystem}
  22530. * @private
  22531. */
  22532. this._coordSysMgr = new CoordinateSystemManager();
  22533. /**
  22534. * @type {module:echarts/ExtensionAPI}
  22535. * @private
  22536. */
  22537. var api = this._api = createExtensionAPI(this); // Sort on demand
  22538. function prioritySortFunc(a, b) {
  22539. return a.__prio - b.__prio;
  22540. }
  22541. sort(visualFuncs, prioritySortFunc);
  22542. sort(dataProcessorFuncs, prioritySortFunc);
  22543. /**
  22544. * @type {module:echarts/stream/Scheduler}
  22545. */
  22546. this._scheduler = new Scheduler(this, api, dataProcessorFuncs, visualFuncs);
  22547. Eventful.call(this, this._ecEventProcessor = new EventProcessor());
  22548. /**
  22549. * @type {module:echarts~MessageCenter}
  22550. * @private
  22551. */
  22552. this._messageCenter = new MessageCenter(); // Init mouse events
  22553. this._initEvents(); // In case some people write `window.onresize = chart.resize`
  22554. this.resize = bind(this.resize, this); // Can't dispatch action during rendering procedure
  22555. this._pendingActions = [];
  22556. zr.animation.on('frame', this._onframe, this);
  22557. bindRenderedEvent(zr, this); // ECharts instance can be used as value.
  22558. setAsPrimitive(this);
  22559. }
  22560. var echartsProto = ECharts.prototype;
  22561. echartsProto._onframe = function () {
  22562. if (this._disposed) {
  22563. return;
  22564. }
  22565. var scheduler = this._scheduler; // Lazy update
  22566. if (this[OPTION_UPDATED]) {
  22567. var silent = this[OPTION_UPDATED].silent;
  22568. this[IN_MAIN_PROCESS] = true;
  22569. prepare(this);
  22570. updateMethods.update.call(this);
  22571. this[IN_MAIN_PROCESS] = false;
  22572. this[OPTION_UPDATED] = false;
  22573. flushPendingActions.call(this, silent);
  22574. triggerUpdatedEvent.call(this, silent);
  22575. } // Avoid do both lazy update and progress in one frame.
  22576. else if (scheduler.unfinished) {
  22577. // Stream progress.
  22578. var remainTime = TEST_FRAME_REMAIN_TIME;
  22579. var ecModel = this._model;
  22580. var api = this._api;
  22581. scheduler.unfinished = false;
  22582. do {
  22583. var startTime = +new Date();
  22584. scheduler.performSeriesTasks(ecModel); // Currently dataProcessorFuncs do not check threshold.
  22585. scheduler.performDataProcessorTasks(ecModel);
  22586. updateStreamModes(this, ecModel); // Do not update coordinate system here. Because that coord system update in
  22587. // each frame is not a good user experience. So we follow the rule that
  22588. // the extent of the coordinate system is determin in the first frame (the
  22589. // frame is executed immedietely after task reset.
  22590. // this._coordSysMgr.update(ecModel, api);
  22591. // console.log('--- ec frame visual ---', remainTime);
  22592. scheduler.performVisualTasks(ecModel);
  22593. renderSeries(this, this._model, api, 'remain');
  22594. remainTime -= +new Date() - startTime;
  22595. } while (remainTime > 0 && scheduler.unfinished); // Call flush explicitly for trigger finished event.
  22596. if (!scheduler.unfinished) {
  22597. this._zr.flush();
  22598. } // Else, zr flushing be ensue within the same frame,
  22599. // because zr flushing is after onframe event.
  22600. }
  22601. };
  22602. /**
  22603. * @return {HTMLElement}
  22604. */
  22605. echartsProto.getDom = function () {
  22606. return this._dom;
  22607. };
  22608. /**
  22609. * @return {module:zrender~ZRender}
  22610. */
  22611. echartsProto.getZr = function () {
  22612. return this._zr;
  22613. };
  22614. /**
  22615. * Usage:
  22616. * chart.setOption(option, notMerge, lazyUpdate);
  22617. * chart.setOption(option, {
  22618. * notMerge: ...,
  22619. * lazyUpdate: ...,
  22620. * silent: ...
  22621. * });
  22622. *
  22623. * @param {Object} option
  22624. * @param {Object|boolean} [opts] opts or notMerge.
  22625. * @param {boolean} [opts.notMerge=false]
  22626. * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently.
  22627. */
  22628. echartsProto.setOption = function (option, notMerge, lazyUpdate) {
  22629. if (this._disposed) {
  22630. return;
  22631. }
  22632. var silent;
  22633. if (isObject(notMerge)) {
  22634. lazyUpdate = notMerge.lazyUpdate;
  22635. silent = notMerge.silent;
  22636. notMerge = notMerge.notMerge;
  22637. }
  22638. this[IN_MAIN_PROCESS] = true;
  22639. if (!this._model || notMerge) {
  22640. var optionManager = new OptionManager(this._api);
  22641. var theme$$1 = this._theme;
  22642. var ecModel = this._model = new GlobalModel();
  22643. ecModel.scheduler = this._scheduler;
  22644. ecModel.init(null, null, theme$$1, optionManager);
  22645. }
  22646. this._model.setOption(option, optionPreprocessorFuncs);
  22647. if (lazyUpdate) {
  22648. this[OPTION_UPDATED] = {
  22649. silent: silent
  22650. };
  22651. this[IN_MAIN_PROCESS] = false;
  22652. } else {
  22653. prepare(this);
  22654. updateMethods.update.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be
  22655. // fetched after `setOption`.
  22656. this._zr.flush();
  22657. this[OPTION_UPDATED] = false;
  22658. this[IN_MAIN_PROCESS] = false;
  22659. flushPendingActions.call(this, silent);
  22660. triggerUpdatedEvent.call(this, silent);
  22661. }
  22662. };
  22663. /**
  22664. * @DEPRECATED
  22665. */
  22666. echartsProto.setTheme = function () {
  22667. console.error('ECharts#setTheme() is DEPRECATED in ECharts 3.0');
  22668. };
  22669. /**
  22670. * @return {module:echarts/model/Global}
  22671. */
  22672. echartsProto.getModel = function () {
  22673. return this._model;
  22674. };
  22675. /**
  22676. * @return {Object}
  22677. */
  22678. echartsProto.getOption = function () {
  22679. return this._model && this._model.getOption();
  22680. };
  22681. /**
  22682. * @return {number}
  22683. */
  22684. echartsProto.getWidth = function () {
  22685. return this._zr.getWidth();
  22686. };
  22687. /**
  22688. * @return {number}
  22689. */
  22690. echartsProto.getHeight = function () {
  22691. return this._zr.getHeight();
  22692. };
  22693. /**
  22694. * @return {number}
  22695. */
  22696. echartsProto.getDevicePixelRatio = function () {
  22697. return this._zr.painter.dpr || window.devicePixelRatio || 1;
  22698. };
  22699. /**
  22700. * Get canvas which has all thing rendered
  22701. * @param {Object} opts
  22702. * @param {string} [opts.backgroundColor]
  22703. * @return {string}
  22704. */
  22705. echartsProto.getRenderedCanvas = function (opts) {
  22706. if (!env$1.canvasSupported) {
  22707. return;
  22708. }
  22709. opts = opts || {};
  22710. opts.pixelRatio = opts.pixelRatio || 1;
  22711. opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor');
  22712. var zr = this._zr; // var list = zr.storage.getDisplayList();
  22713. // Stop animations
  22714. // Never works before in init animation, so remove it.
  22715. // zrUtil.each(list, function (el) {
  22716. // el.stopAnimation(true);
  22717. // });
  22718. return zr.painter.getRenderedCanvas(opts);
  22719. };
  22720. /**
  22721. * Get svg data url
  22722. * @return {string}
  22723. */
  22724. echartsProto.getSvgDataURL = function () {
  22725. if (!env$1.svgSupported) {
  22726. return;
  22727. }
  22728. var zr = this._zr;
  22729. var list = zr.storage.getDisplayList(); // Stop animations
  22730. each$1(list, function (el) {
  22731. el.stopAnimation(true);
  22732. });
  22733. return zr.painter.toDataURL();
  22734. };
  22735. /**
  22736. * @return {string}
  22737. * @param {Object} opts
  22738. * @param {string} [opts.type='png']
  22739. * @param {string} [opts.pixelRatio=1]
  22740. * @param {string} [opts.backgroundColor]
  22741. * @param {string} [opts.excludeComponents]
  22742. */
  22743. echartsProto.getDataURL = function (opts) {
  22744. if (this._disposed) {
  22745. return;
  22746. }
  22747. opts = opts || {};
  22748. var excludeComponents = opts.excludeComponents;
  22749. var ecModel = this._model;
  22750. var excludesComponentViews = [];
  22751. var self = this;
  22752. each(excludeComponents, function (componentType) {
  22753. ecModel.eachComponent({
  22754. mainType: componentType
  22755. }, function (component) {
  22756. var view = self._componentsMap[component.__viewId];
  22757. if (!view.group.ignore) {
  22758. excludesComponentViews.push(view);
  22759. view.group.ignore = true;
  22760. }
  22761. });
  22762. });
  22763. var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataURL() : this.getRenderedCanvas(opts).toDataURL('image/' + (opts && opts.type || 'png'));
  22764. each(excludesComponentViews, function (view) {
  22765. view.group.ignore = false;
  22766. });
  22767. return url;
  22768. };
  22769. /**
  22770. * @return {string}
  22771. * @param {Object} opts
  22772. * @param {string} [opts.type='png']
  22773. * @param {string} [opts.pixelRatio=1]
  22774. * @param {string} [opts.backgroundColor]
  22775. */
  22776. echartsProto.getConnectedDataURL = function (opts) {
  22777. if (this._disposed) {
  22778. return;
  22779. }
  22780. if (!env$1.canvasSupported) {
  22781. return;
  22782. }
  22783. var isSvg = opts.type === 'svg';
  22784. var groupId = this.group;
  22785. var mathMin = Math.min;
  22786. var mathMax = Math.max;
  22787. var MAX_NUMBER = Infinity;
  22788. if (connectedGroups[groupId]) {
  22789. var left = MAX_NUMBER;
  22790. var top = MAX_NUMBER;
  22791. var right = -MAX_NUMBER;
  22792. var bottom = -MAX_NUMBER;
  22793. var canvasList = [];
  22794. var dpr = opts && opts.pixelRatio || 1;
  22795. each$1(instances, function (chart, id) {
  22796. if (chart.group === groupId) {
  22797. var canvas = isSvg ? chart.getZr().painter.getSvgDom().innerHTML : chart.getRenderedCanvas(clone(opts));
  22798. var boundingRect = chart.getDom().getBoundingClientRect();
  22799. left = mathMin(boundingRect.left, left);
  22800. top = mathMin(boundingRect.top, top);
  22801. right = mathMax(boundingRect.right, right);
  22802. bottom = mathMax(boundingRect.bottom, bottom);
  22803. canvasList.push({
  22804. dom: canvas,
  22805. left: boundingRect.left,
  22806. top: boundingRect.top
  22807. });
  22808. }
  22809. });
  22810. left *= dpr;
  22811. top *= dpr;
  22812. right *= dpr;
  22813. bottom *= dpr;
  22814. var width = right - left;
  22815. var height = bottom - top;
  22816. var targetCanvas = createCanvas();
  22817. var zr = init$1(targetCanvas, {
  22818. renderer: isSvg ? 'svg' : 'canvas'
  22819. });
  22820. zr.resize({
  22821. width: width,
  22822. height: height
  22823. });
  22824. if (isSvg) {
  22825. var content = '';
  22826. each(canvasList, function (item) {
  22827. var x = item.left - left;
  22828. var y = item.top - top;
  22829. content += '<g transform="translate(' + x + ',' + y + ')">' + item.dom + '</g>';
  22830. });
  22831. zr.painter.getSvgRoot().innerHTML = content;
  22832. if (opts.connectedBackgroundColor) {
  22833. zr.painter.setBackgroundColor(opts.connectedBackgroundColor);
  22834. }
  22835. zr.refreshImmediately();
  22836. return zr.painter.toDataURL();
  22837. } else {
  22838. // Background between the charts
  22839. if (opts.connectedBackgroundColor) {
  22840. zr.add(new Rect({
  22841. shape: {
  22842. x: 0,
  22843. y: 0,
  22844. width: width,
  22845. height: height
  22846. },
  22847. style: {
  22848. fill: opts.connectedBackgroundColor
  22849. }
  22850. }));
  22851. }
  22852. each(canvasList, function (item) {
  22853. var img = new ZImage({
  22854. style: {
  22855. x: item.left * dpr - left,
  22856. y: item.top * dpr - top,
  22857. image: item.dom
  22858. }
  22859. });
  22860. zr.add(img);
  22861. });
  22862. zr.refreshImmediately();
  22863. return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png'));
  22864. }
  22865. } else {
  22866. return this.getDataURL(opts);
  22867. }
  22868. };
  22869. /**
  22870. * Convert from logical coordinate system to pixel coordinate system.
  22871. * See CoordinateSystem#convertToPixel.
  22872. * @param {string|Object} finder
  22873. * If string, e.g., 'geo', means {geoIndex: 0}.
  22874. * If Object, could contain some of these properties below:
  22875. * {
  22876. * seriesIndex / seriesId / seriesName,
  22877. * geoIndex / geoId, geoName,
  22878. * bmapIndex / bmapId / bmapName,
  22879. * xAxisIndex / xAxisId / xAxisName,
  22880. * yAxisIndex / yAxisId / yAxisName,
  22881. * gridIndex / gridId / gridName,
  22882. * ... (can be extended)
  22883. * }
  22884. * @param {Array|number} value
  22885. * @return {Array|number} result
  22886. */
  22887. echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel');
  22888. /**
  22889. * Convert from pixel coordinate system to logical coordinate system.
  22890. * See CoordinateSystem#convertFromPixel.
  22891. * @param {string|Object} finder
  22892. * If string, e.g., 'geo', means {geoIndex: 0}.
  22893. * If Object, could contain some of these properties below:
  22894. * {
  22895. * seriesIndex / seriesId / seriesName,
  22896. * geoIndex / geoId / geoName,
  22897. * bmapIndex / bmapId / bmapName,
  22898. * xAxisIndex / xAxisId / xAxisName,
  22899. * yAxisIndex / yAxisId / yAxisName
  22900. * gridIndex / gridId / gridName,
  22901. * ... (can be extended)
  22902. * }
  22903. * @param {Array|number} value
  22904. * @return {Array|number} result
  22905. */
  22906. echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel');
  22907. function doConvertPixel(methodName, finder, value) {
  22908. if (this._disposed) {
  22909. return;
  22910. }
  22911. var ecModel = this._model;
  22912. var coordSysList = this._coordSysMgr.getCoordinateSystems();
  22913. var result;
  22914. finder = parseFinder(ecModel, finder);
  22915. for (var i = 0; i < coordSysList.length; i++) {
  22916. var coordSys = coordSysList[i];
  22917. if (coordSys[methodName] && (result = coordSys[methodName](ecModel, finder, value)) != null) {
  22918. return result;
  22919. }
  22920. }
  22921. }
  22922. /**
  22923. * Is the specified coordinate systems or components contain the given pixel point.
  22924. * @param {string|Object} finder
  22925. * If string, e.g., 'geo', means {geoIndex: 0}.
  22926. * If Object, could contain some of these properties below:
  22927. * {
  22928. * seriesIndex / seriesId / seriesName,
  22929. * geoIndex / geoId / geoName,
  22930. * bmapIndex / bmapId / bmapName,
  22931. * xAxisIndex / xAxisId / xAxisName,
  22932. * yAxisIndex / yAxisId / yAxisName,
  22933. * gridIndex / gridId / gridName,
  22934. * ... (can be extended)
  22935. * }
  22936. * @param {Array|number} value
  22937. * @return {boolean} result
  22938. */
  22939. echartsProto.containPixel = function (finder, value) {
  22940. if (this._disposed) {
  22941. return;
  22942. }
  22943. var ecModel = this._model;
  22944. var result;
  22945. finder = parseFinder(ecModel, finder);
  22946. each$1(finder, function (models, key) {
  22947. key.indexOf('Models') >= 0 && each$1(models, function (model) {
  22948. var coordSys = model.coordinateSystem;
  22949. if (coordSys && coordSys.containPoint) {
  22950. result |= !!coordSys.containPoint(value);
  22951. } else if (key === 'seriesModels') {
  22952. var view = this._chartsMap[model.__viewId];
  22953. if (view && view.containPoint) {
  22954. result |= view.containPoint(value, model);
  22955. } else {}
  22956. } else {}
  22957. }, this);
  22958. }, this);
  22959. return !!result;
  22960. };
  22961. /**
  22962. * Get visual from series or data.
  22963. * @param {string|Object} finder
  22964. * If string, e.g., 'series', means {seriesIndex: 0}.
  22965. * If Object, could contain some of these properties below:
  22966. * {
  22967. * seriesIndex / seriesId / seriesName,
  22968. * dataIndex / dataIndexInside
  22969. * }
  22970. * If dataIndex is not specified, series visual will be fetched,
  22971. * but not data item visual.
  22972. * If all of seriesIndex, seriesId, seriesName are not specified,
  22973. * visual will be fetched from first series.
  22974. * @param {string} visualType 'color', 'symbol', 'symbolSize'
  22975. */
  22976. echartsProto.getVisual = function (finder, visualType) {
  22977. var ecModel = this._model;
  22978. finder = parseFinder(ecModel, finder, {
  22979. defaultMainType: 'series'
  22980. });
  22981. var seriesModel = finder.seriesModel;
  22982. var data = seriesModel.getData();
  22983. var dataIndexInside = finder.hasOwnProperty('dataIndexInside') ? finder.dataIndexInside : finder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(finder.dataIndex) : null;
  22984. return dataIndexInside != null ? data.getItemVisual(dataIndexInside, visualType) : data.getVisual(visualType);
  22985. };
  22986. /**
  22987. * Get view of corresponding component model
  22988. * @param {module:echarts/model/Component} componentModel
  22989. * @return {module:echarts/view/Component}
  22990. */
  22991. echartsProto.getViewOfComponentModel = function (componentModel) {
  22992. return this._componentsMap[componentModel.__viewId];
  22993. };
  22994. /**
  22995. * Get view of corresponding series model
  22996. * @param {module:echarts/model/Series} seriesModel
  22997. * @return {module:echarts/view/Chart}
  22998. */
  22999. echartsProto.getViewOfSeriesModel = function (seriesModel) {
  23000. return this._chartsMap[seriesModel.__viewId];
  23001. };
  23002. var updateMethods = {
  23003. prepareAndUpdate: function (payload) {
  23004. prepare(this);
  23005. updateMethods.update.call(this, payload);
  23006. },
  23007. /**
  23008. * @param {Object} payload
  23009. * @private
  23010. */
  23011. update: function (payload) {
  23012. // console.profile && console.profile('update');
  23013. var ecModel = this._model;
  23014. var api = this._api;
  23015. var zr = this._zr;
  23016. var coordSysMgr = this._coordSysMgr;
  23017. var scheduler = this._scheduler; // update before setOption
  23018. if (!ecModel) {
  23019. return;
  23020. }
  23021. scheduler.restoreData(ecModel, payload);
  23022. scheduler.performSeriesTasks(ecModel); // TODO
  23023. // Save total ecModel here for undo/redo (after restoring data and before processing data).
  23024. // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call.
  23025. // Create new coordinate system each update
  23026. // In LineView may save the old coordinate system and use it to get the orignal point
  23027. coordSysMgr.create(ecModel, api);
  23028. scheduler.performDataProcessorTasks(ecModel, payload); // Current stream render is not supported in data process. So we can update
  23029. // stream modes after data processing, where the filtered data is used to
  23030. // deteming whether use progressive rendering.
  23031. updateStreamModes(this, ecModel); // We update stream modes before coordinate system updated, then the modes info
  23032. // can be fetched when coord sys updating (consider the barGrid extent fix). But
  23033. // the drawback is the full coord info can not be fetched. Fortunately this full
  23034. // coord is not requied in stream mode updater currently.
  23035. coordSysMgr.update(ecModel, api);
  23036. clearColorPalette(ecModel);
  23037. scheduler.performVisualTasks(ecModel, payload);
  23038. render(this, ecModel, api, payload); // Set background
  23039. var backgroundColor = ecModel.get('backgroundColor') || 'transparent'; // In IE8
  23040. if (!env$1.canvasSupported) {
  23041. var colorArr = parse(backgroundColor);
  23042. backgroundColor = stringify(colorArr, 'rgb');
  23043. if (colorArr[3] === 0) {
  23044. backgroundColor = 'transparent';
  23045. }
  23046. } else {
  23047. zr.setBackgroundColor(backgroundColor);
  23048. }
  23049. performPostUpdateFuncs(ecModel, api); // console.profile && console.profileEnd('update');
  23050. },
  23051. /**
  23052. * @param {Object} payload
  23053. * @private
  23054. */
  23055. updateTransform: function (payload) {
  23056. var ecModel = this._model;
  23057. var ecIns = this;
  23058. var api = this._api; // update before setOption
  23059. if (!ecModel) {
  23060. return;
  23061. } // ChartView.markUpdateMethod(payload, 'updateTransform');
  23062. var componentDirtyList = [];
  23063. ecModel.eachComponent(function (componentType, componentModel) {
  23064. var componentView = ecIns.getViewOfComponentModel(componentModel);
  23065. if (componentView && componentView.__alive) {
  23066. if (componentView.updateTransform) {
  23067. var result = componentView.updateTransform(componentModel, ecModel, api, payload);
  23068. result && result.update && componentDirtyList.push(componentView);
  23069. } else {
  23070. componentDirtyList.push(componentView);
  23071. }
  23072. }
  23073. });
  23074. var seriesDirtyMap = createHashMap();
  23075. ecModel.eachSeries(function (seriesModel) {
  23076. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23077. if (chartView.updateTransform) {
  23078. var result = chartView.updateTransform(seriesModel, ecModel, api, payload);
  23079. result && result.update && seriesDirtyMap.set(seriesModel.uid, 1);
  23080. } else {
  23081. seriesDirtyMap.set(seriesModel.uid, 1);
  23082. }
  23083. });
  23084. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23085. // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23086. this._scheduler.performVisualTasks(ecModel, payload, {
  23087. setDirty: true,
  23088. dirtyMap: seriesDirtyMap
  23089. }); // Currently, not call render of components. Geo render cost a lot.
  23090. // renderComponents(ecIns, ecModel, api, payload, componentDirtyList);
  23091. renderSeries(ecIns, ecModel, api, payload, seriesDirtyMap);
  23092. performPostUpdateFuncs(ecModel, this._api);
  23093. },
  23094. /**
  23095. * @param {Object} payload
  23096. * @private
  23097. */
  23098. updateView: function (payload) {
  23099. var ecModel = this._model; // update before setOption
  23100. if (!ecModel) {
  23101. return;
  23102. }
  23103. Chart.markUpdateMethod(payload, 'updateView');
  23104. clearColorPalette(ecModel); // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23105. this._scheduler.performVisualTasks(ecModel, payload, {
  23106. setDirty: true
  23107. });
  23108. render(this, this._model, this._api, payload);
  23109. performPostUpdateFuncs(ecModel, this._api);
  23110. },
  23111. /**
  23112. * @param {Object} payload
  23113. * @private
  23114. */
  23115. updateVisual: function (payload) {
  23116. updateMethods.update.call(this, payload); // var ecModel = this._model;
  23117. // // update before setOption
  23118. // if (!ecModel) {
  23119. // return;
  23120. // }
  23121. // ChartView.markUpdateMethod(payload, 'updateVisual');
  23122. // clearColorPalette(ecModel);
  23123. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23124. // this._scheduler.performVisualTasks(ecModel, payload, {visualType: 'visual', setDirty: true});
  23125. // render(this, this._model, this._api, payload);
  23126. // performPostUpdateFuncs(ecModel, this._api);
  23127. },
  23128. /**
  23129. * @param {Object} payload
  23130. * @private
  23131. */
  23132. updateLayout: function (payload) {
  23133. updateMethods.update.call(this, payload); // var ecModel = this._model;
  23134. // // update before setOption
  23135. // if (!ecModel) {
  23136. // return;
  23137. // }
  23138. // ChartView.markUpdateMethod(payload, 'updateLayout');
  23139. // // Keep pipe to the exist pipeline because it depends on the render task of the full pipeline.
  23140. // // this._scheduler.performVisualTasks(ecModel, payload, 'layout', true);
  23141. // this._scheduler.performVisualTasks(ecModel, payload, {setDirty: true});
  23142. // render(this, this._model, this._api, payload);
  23143. // performPostUpdateFuncs(ecModel, this._api);
  23144. }
  23145. };
  23146. function prepare(ecIns) {
  23147. var ecModel = ecIns._model;
  23148. var scheduler = ecIns._scheduler;
  23149. scheduler.restorePipelines(ecModel);
  23150. scheduler.prepareStageTasks();
  23151. prepareView(ecIns, 'component', ecModel, scheduler);
  23152. prepareView(ecIns, 'chart', ecModel, scheduler);
  23153. scheduler.plan();
  23154. }
  23155. /**
  23156. * @private
  23157. */
  23158. function updateDirectly(ecIns, method, payload, mainType, subType) {
  23159. var ecModel = ecIns._model; // broadcast
  23160. if (!mainType) {
  23161. // FIXME
  23162. // Chart will not be update directly here, except set dirty.
  23163. // But there is no such scenario now.
  23164. each(ecIns._componentsViews.concat(ecIns._chartsViews), callView);
  23165. return;
  23166. }
  23167. var query = {};
  23168. query[mainType + 'Id'] = payload[mainType + 'Id'];
  23169. query[mainType + 'Index'] = payload[mainType + 'Index'];
  23170. query[mainType + 'Name'] = payload[mainType + 'Name'];
  23171. var condition = {
  23172. mainType: mainType,
  23173. query: query
  23174. };
  23175. subType && (condition.subType = subType); // subType may be '' by parseClassType;
  23176. var excludeSeriesId = payload.excludeSeriesId;
  23177. if (excludeSeriesId != null) {
  23178. excludeSeriesId = createHashMap(normalizeToArray(excludeSeriesId));
  23179. } // If dispatchAction before setOption, do nothing.
  23180. ecModel && ecModel.eachComponent(condition, function (model) {
  23181. if (!excludeSeriesId || excludeSeriesId.get(model.id) == null) {
  23182. callView(ecIns[mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId]);
  23183. }
  23184. }, ecIns);
  23185. function callView(view) {
  23186. view && view.__alive && view[method] && view[method](view.__model, ecModel, ecIns._api, payload);
  23187. }
  23188. }
  23189. /**
  23190. * Resize the chart
  23191. * @param {Object} opts
  23192. * @param {number} [opts.width] Can be 'auto' (the same as null/undefined)
  23193. * @param {number} [opts.height] Can be 'auto' (the same as null/undefined)
  23194. * @param {boolean} [opts.silent=false]
  23195. */
  23196. echartsProto.resize = function (opts) {
  23197. if (this._disposed) {
  23198. return;
  23199. }
  23200. this._zr.resize(opts);
  23201. var ecModel = this._model; // Resize loading effect
  23202. this._loadingFX && this._loadingFX.resize();
  23203. if (!ecModel) {
  23204. return;
  23205. }
  23206. var optionChanged = ecModel.resetOption('media');
  23207. var silent = opts && opts.silent;
  23208. this[IN_MAIN_PROCESS] = true;
  23209. optionChanged && prepare(this);
  23210. updateMethods.update.call(this);
  23211. this[IN_MAIN_PROCESS] = false;
  23212. flushPendingActions.call(this, silent);
  23213. triggerUpdatedEvent.call(this, silent);
  23214. };
  23215. function updateStreamModes(ecIns, ecModel) {
  23216. var chartsMap = ecIns._chartsMap;
  23217. var scheduler = ecIns._scheduler;
  23218. ecModel.eachSeries(function (seriesModel) {
  23219. scheduler.updateStreamModes(seriesModel, chartsMap[seriesModel.__viewId]);
  23220. });
  23221. }
  23222. /**
  23223. * Show loading effect
  23224. * @param {string} [name='default']
  23225. * @param {Object} [cfg]
  23226. */
  23227. echartsProto.showLoading = function (name, cfg) {
  23228. if (this._disposed) {
  23229. return;
  23230. }
  23231. if (isObject(name)) {
  23232. cfg = name;
  23233. name = '';
  23234. }
  23235. name = name || 'default';
  23236. this.hideLoading();
  23237. if (!loadingEffects[name]) {
  23238. return;
  23239. }
  23240. var el = loadingEffects[name](this._api, cfg);
  23241. var zr = this._zr;
  23242. this._loadingFX = el;
  23243. zr.add(el);
  23244. };
  23245. /**
  23246. * Hide loading effect
  23247. */
  23248. echartsProto.hideLoading = function () {
  23249. if (this._disposed) {
  23250. return;
  23251. }
  23252. this._loadingFX && this._zr.remove(this._loadingFX);
  23253. this._loadingFX = null;
  23254. };
  23255. /**
  23256. * @param {Object} eventObj
  23257. * @return {Object}
  23258. */
  23259. echartsProto.makeActionFromEvent = function (eventObj) {
  23260. var payload = extend({}, eventObj);
  23261. payload.type = eventActionMap[eventObj.type];
  23262. return payload;
  23263. };
  23264. /**
  23265. * @pubilc
  23266. * @param {Object} payload
  23267. * @param {string} [payload.type] Action type
  23268. * @param {Object|boolean} [opt] If pass boolean, means opt.silent
  23269. * @param {boolean} [opt.silent=false] Whether trigger events.
  23270. * @param {boolean} [opt.flush=undefined]
  23271. * true: Flush immediately, and then pixel in canvas can be fetched
  23272. * immediately. Caution: it might affect performance.
  23273. * false: Not flush.
  23274. * undefined: Auto decide whether perform flush.
  23275. */
  23276. echartsProto.dispatchAction = function (payload, opt) {
  23277. if (this._disposed) {
  23278. return;
  23279. }
  23280. if (!isObject(opt)) {
  23281. opt = {
  23282. silent: !!opt
  23283. };
  23284. }
  23285. if (!actions[payload.type]) {
  23286. return;
  23287. } // Avoid dispatch action before setOption. Especially in `connect`.
  23288. if (!this._model) {
  23289. return;
  23290. } // May dispatchAction in rendering procedure
  23291. if (this[IN_MAIN_PROCESS]) {
  23292. this._pendingActions.push(payload);
  23293. return;
  23294. }
  23295. doDispatchAction.call(this, payload, opt.silent);
  23296. if (opt.flush) {
  23297. this._zr.flush(true);
  23298. } else if (opt.flush !== false && env$1.browser.weChat) {
  23299. // In WeChat embeded browser, `requestAnimationFrame` and `setInterval`
  23300. // hang when sliding page (on touch event), which cause that zr does not
  23301. // refresh util user interaction finished, which is not expected.
  23302. // But `dispatchAction` may be called too frequently when pan on touch
  23303. // screen, which impacts performance if do not throttle them.
  23304. this._throttledZrFlush();
  23305. }
  23306. flushPendingActions.call(this, opt.silent);
  23307. triggerUpdatedEvent.call(this, opt.silent);
  23308. };
  23309. function doDispatchAction(payload, silent) {
  23310. var payloadType = payload.type;
  23311. var escapeConnect = payload.escapeConnect;
  23312. var actionWrap = actions[payloadType];
  23313. var actionInfo = actionWrap.actionInfo;
  23314. var cptType = (actionInfo.update || 'update').split(':');
  23315. var updateMethod = cptType.pop();
  23316. cptType = cptType[0] != null && parseClassType(cptType[0]);
  23317. this[IN_MAIN_PROCESS] = true;
  23318. var payloads = [payload];
  23319. var batched = false; // Batch action
  23320. if (payload.batch) {
  23321. batched = true;
  23322. payloads = map(payload.batch, function (item) {
  23323. item = defaults(extend({}, item), payload);
  23324. item.batch = null;
  23325. return item;
  23326. });
  23327. }
  23328. var eventObjBatch = [];
  23329. var eventObj;
  23330. var isHighDown = payloadType === 'highlight' || payloadType === 'downplay';
  23331. each(payloads, function (batchItem) {
  23332. // Action can specify the event by return it.
  23333. eventObj = actionWrap.action(batchItem, this._model, this._api); // Emit event outside
  23334. eventObj = eventObj || extend({}, batchItem); // Convert type to eventType
  23335. eventObj.type = actionInfo.event || eventObj.type;
  23336. eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual.
  23337. if (isHighDown) {
  23338. // method, payload, mainType, subType
  23339. updateDirectly(this, updateMethod, batchItem, 'series');
  23340. } else if (cptType) {
  23341. updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub);
  23342. }
  23343. }, this);
  23344. if (updateMethod !== 'none' && !isHighDown && !cptType) {
  23345. // Still dirty
  23346. if (this[OPTION_UPDATED]) {
  23347. // FIXME Pass payload ?
  23348. prepare(this);
  23349. updateMethods.update.call(this, payload);
  23350. this[OPTION_UPDATED] = false;
  23351. } else {
  23352. updateMethods[updateMethod].call(this, payload);
  23353. }
  23354. } // Follow the rule of action batch
  23355. if (batched) {
  23356. eventObj = {
  23357. type: actionInfo.event || payloadType,
  23358. escapeConnect: escapeConnect,
  23359. batch: eventObjBatch
  23360. };
  23361. } else {
  23362. eventObj = eventObjBatch[0];
  23363. }
  23364. this[IN_MAIN_PROCESS] = false;
  23365. !silent && this._messageCenter.trigger(eventObj.type, eventObj);
  23366. }
  23367. function flushPendingActions(silent) {
  23368. var pendingActions = this._pendingActions;
  23369. while (pendingActions.length) {
  23370. var payload = pendingActions.shift();
  23371. doDispatchAction.call(this, payload, silent);
  23372. }
  23373. }
  23374. function triggerUpdatedEvent(silent) {
  23375. !silent && this.trigger('updated');
  23376. }
  23377. /**
  23378. * Event `rendered` is triggered when zr
  23379. * rendered. It is useful for realtime
  23380. * snapshot (reflect animation).
  23381. *
  23382. * Event `finished` is triggered when:
  23383. * (1) zrender rendering finished.
  23384. * (2) initial animation finished.
  23385. * (3) progressive rendering finished.
  23386. * (4) no pending action.
  23387. * (5) no delayed setOption needs to be processed.
  23388. */
  23389. function bindRenderedEvent(zr, ecIns) {
  23390. zr.on('rendered', function () {
  23391. ecIns.trigger('rendered'); // The `finished` event should not be triggered repeatly,
  23392. // so it should only be triggered when rendering indeed happend
  23393. // in zrender. (Consider the case that dipatchAction is keep
  23394. // triggering when mouse move).
  23395. if ( // Although zr is dirty if initial animation is not finished
  23396. // and this checking is called on frame, we also check
  23397. // animation finished for robustness.
  23398. zr.animation.isFinished() && !ecIns[OPTION_UPDATED] && !ecIns._scheduler.unfinished && !ecIns._pendingActions.length) {
  23399. ecIns.trigger('finished');
  23400. }
  23401. });
  23402. }
  23403. /**
  23404. * @param {Object} params
  23405. * @param {number} params.seriesIndex
  23406. * @param {Array|TypedArray} params.data
  23407. */
  23408. echartsProto.appendData = function (params) {
  23409. if (this._disposed) {
  23410. return;
  23411. }
  23412. var seriesIndex = params.seriesIndex;
  23413. var ecModel = this.getModel();
  23414. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  23415. seriesModel.appendData(params); // Note: `appendData` does not support that update extent of coordinate
  23416. // system, util some scenario require that. In the expected usage of
  23417. // `appendData`, the initial extent of coordinate system should better
  23418. // be fixed by axis `min`/`max` setting or initial data, otherwise if
  23419. // the extent changed while `appendData`, the location of the painted
  23420. // graphic elements have to be changed, which make the usage of
  23421. // `appendData` meaningless.
  23422. this._scheduler.unfinished = true;
  23423. };
  23424. /**
  23425. * Register event
  23426. * @method
  23427. */
  23428. echartsProto.on = createRegisterEventWithLowercaseName('on', false);
  23429. echartsProto.off = createRegisterEventWithLowercaseName('off', false);
  23430. echartsProto.one = createRegisterEventWithLowercaseName('one', false);
  23431. /**
  23432. * Prepare view instances of charts and components
  23433. * @param {module:echarts/model/Global} ecModel
  23434. * @private
  23435. */
  23436. function prepareView(ecIns, type, ecModel, scheduler) {
  23437. var isComponent = type === 'component';
  23438. var viewList = isComponent ? ecIns._componentsViews : ecIns._chartsViews;
  23439. var viewMap = isComponent ? ecIns._componentsMap : ecIns._chartsMap;
  23440. var zr = ecIns._zr;
  23441. var api = ecIns._api;
  23442. for (var i = 0; i < viewList.length; i++) {
  23443. viewList[i].__alive = false;
  23444. }
  23445. isComponent ? ecModel.eachComponent(function (componentType, model) {
  23446. componentType !== 'series' && doPrepare(model);
  23447. }) : ecModel.eachSeries(doPrepare);
  23448. function doPrepare(model) {
  23449. // Consider: id same and type changed.
  23450. var viewId = '_ec_' + model.id + '_' + model.type;
  23451. var view = viewMap[viewId];
  23452. if (!view) {
  23453. var classType = parseClassType(model.type);
  23454. var Clazz = isComponent ? Component$1.getClass(classType.main, classType.sub) : Chart.getClass(classType.sub);
  23455. view = new Clazz();
  23456. view.init(ecModel, api);
  23457. viewMap[viewId] = view;
  23458. viewList.push(view);
  23459. zr.add(view.group);
  23460. }
  23461. model.__viewId = view.__id = viewId;
  23462. view.__alive = true;
  23463. view.__model = model;
  23464. view.group.__ecComponentInfo = {
  23465. mainType: model.mainType,
  23466. index: model.componentIndex
  23467. };
  23468. !isComponent && scheduler.prepareView(view, model, ecModel, api);
  23469. }
  23470. for (var i = 0; i < viewList.length;) {
  23471. var view = viewList[i];
  23472. if (!view.__alive) {
  23473. !isComponent && view.renderTask.dispose();
  23474. zr.remove(view.group);
  23475. view.dispose(ecModel, api);
  23476. viewList.splice(i, 1);
  23477. delete viewMap[view.__id];
  23478. view.__id = view.group.__ecComponentInfo = null;
  23479. } else {
  23480. i++;
  23481. }
  23482. }
  23483. } // /**
  23484. // * Encode visual infomation from data after data processing
  23485. // *
  23486. // * @param {module:echarts/model/Global} ecModel
  23487. // * @param {object} layout
  23488. // * @param {boolean} [layoutFilter] `true`: only layout,
  23489. // * `false`: only not layout,
  23490. // * `null`/`undefined`: all.
  23491. // * @param {string} taskBaseTag
  23492. // * @private
  23493. // */
  23494. // function startVisualEncoding(ecIns, ecModel, api, payload, layoutFilter) {
  23495. // each(visualFuncs, function (visual, index) {
  23496. // var isLayout = visual.isLayout;
  23497. // if (layoutFilter == null
  23498. // || (layoutFilter === false && !isLayout)
  23499. // || (layoutFilter === true && isLayout)
  23500. // ) {
  23501. // visual.func(ecModel, api, payload);
  23502. // }
  23503. // });
  23504. // }
  23505. function clearColorPalette(ecModel) {
  23506. ecModel.clearColorPalette();
  23507. ecModel.eachSeries(function (seriesModel) {
  23508. seriesModel.clearColorPalette();
  23509. });
  23510. }
  23511. function render(ecIns, ecModel, api, payload) {
  23512. renderComponents(ecIns, ecModel, api, payload);
  23513. each(ecIns._chartsViews, function (chart) {
  23514. chart.__alive = false;
  23515. });
  23516. renderSeries(ecIns, ecModel, api, payload); // Remove groups of unrendered charts
  23517. each(ecIns._chartsViews, function (chart) {
  23518. if (!chart.__alive) {
  23519. chart.remove(ecModel, api);
  23520. }
  23521. });
  23522. }
  23523. function renderComponents(ecIns, ecModel, api, payload, dirtyList) {
  23524. each(dirtyList || ecIns._componentsViews, function (componentView) {
  23525. var componentModel = componentView.__model;
  23526. componentView.render(componentModel, ecModel, api, payload);
  23527. updateZ(componentModel, componentView);
  23528. });
  23529. }
  23530. /**
  23531. * Render each chart and component
  23532. * @private
  23533. */
  23534. function renderSeries(ecIns, ecModel, api, payload, dirtyMap) {
  23535. // Render all charts
  23536. var scheduler = ecIns._scheduler;
  23537. var unfinished;
  23538. ecModel.eachSeries(function (seriesModel) {
  23539. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23540. chartView.__alive = true;
  23541. var renderTask = chartView.renderTask;
  23542. scheduler.updatePayload(renderTask, payload);
  23543. if (dirtyMap && dirtyMap.get(seriesModel.uid)) {
  23544. renderTask.dirty();
  23545. }
  23546. unfinished |= renderTask.perform(scheduler.getPerformArgs(renderTask));
  23547. chartView.group.silent = !!seriesModel.get('silent');
  23548. updateZ(seriesModel, chartView);
  23549. updateBlend(seriesModel, chartView);
  23550. });
  23551. scheduler.unfinished |= unfinished; // If use hover layer
  23552. updateHoverLayerStatus(ecIns, ecModel); // Add aria
  23553. aria(ecIns._zr.dom, ecModel);
  23554. }
  23555. function performPostUpdateFuncs(ecModel, api) {
  23556. each(postUpdateFuncs, function (func) {
  23557. func(ecModel, api);
  23558. });
  23559. }
  23560. var MOUSE_EVENT_NAMES = ['click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu'];
  23561. /**
  23562. * @private
  23563. */
  23564. echartsProto._initEvents = function () {
  23565. each(MOUSE_EVENT_NAMES, function (eveName) {
  23566. var handler = function (e) {
  23567. var ecModel = this.getModel();
  23568. var el = e.target;
  23569. var params;
  23570. var isGlobalOut = eveName === 'globalout'; // no e.target when 'globalout'.
  23571. if (isGlobalOut) {
  23572. params = {};
  23573. } else if (el && el.dataIndex != null) {
  23574. var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex);
  23575. params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType, el) || {};
  23576. } // If element has custom eventData of components
  23577. else if (el && el.eventData) {
  23578. params = extend({}, el.eventData);
  23579. } // Contract: if params prepared in mouse event,
  23580. // these properties must be specified:
  23581. // {
  23582. // componentType: string (component main type)
  23583. // componentIndex: number
  23584. // }
  23585. // Otherwise event query can not work.
  23586. if (params) {
  23587. var componentType = params.componentType;
  23588. var componentIndex = params.componentIndex; // Special handling for historic reason: when trigger by
  23589. // markLine/markPoint/markArea, the componentType is
  23590. // 'markLine'/'markPoint'/'markArea', but we should better
  23591. // enable them to be queried by seriesIndex, since their
  23592. // option is set in each series.
  23593. if (componentType === 'markLine' || componentType === 'markPoint' || componentType === 'markArea') {
  23594. componentType = 'series';
  23595. componentIndex = params.seriesIndex;
  23596. }
  23597. var model = componentType && componentIndex != null && ecModel.getComponent(componentType, componentIndex);
  23598. var view = model && this[model.mainType === 'series' ? '_chartsMap' : '_componentsMap'][model.__viewId];
  23599. params.event = e;
  23600. params.type = eveName;
  23601. this._ecEventProcessor.eventInfo = {
  23602. targetEl: el,
  23603. packedEvent: params,
  23604. model: model,
  23605. view: view
  23606. };
  23607. this.trigger(eveName, params);
  23608. }
  23609. }; // Consider that some component (like tooltip, brush, ...)
  23610. // register zr event handler, but user event handler might
  23611. // do anything, such as call `setOption` or `dispatchAction`,
  23612. // which probably update any of the content and probably
  23613. // cause problem if it is called previous other inner handlers.
  23614. handler.zrEventfulCallAtLast = true;
  23615. this._zr.on(eveName, handler, this);
  23616. }, this);
  23617. each(eventActionMap, function (actionType, eventType) {
  23618. this._messageCenter.on(eventType, function (event) {
  23619. this.trigger(eventType, event);
  23620. }, this);
  23621. }, this);
  23622. };
  23623. /**
  23624. * @return {boolean}
  23625. */
  23626. echartsProto.isDisposed = function () {
  23627. return this._disposed;
  23628. };
  23629. /**
  23630. * Clear
  23631. */
  23632. echartsProto.clear = function () {
  23633. if (this._disposed) {
  23634. return;
  23635. }
  23636. this.setOption({
  23637. series: []
  23638. }, true);
  23639. };
  23640. /**
  23641. * Dispose instance
  23642. */
  23643. echartsProto.dispose = function () {
  23644. if (this._disposed) {
  23645. return;
  23646. }
  23647. this._disposed = true;
  23648. setAttribute(this.getDom(), DOM_ATTRIBUTE_KEY, '');
  23649. var api = this._api;
  23650. var ecModel = this._model;
  23651. each(this._componentsViews, function (component) {
  23652. component.dispose(ecModel, api);
  23653. });
  23654. each(this._chartsViews, function (chart) {
  23655. chart.dispose(ecModel, api);
  23656. }); // Dispose after all views disposed
  23657. this._zr.dispose();
  23658. delete instances[this.id];
  23659. };
  23660. mixin(ECharts, Eventful);
  23661. function updateHoverLayerStatus(ecIns, ecModel) {
  23662. var zr = ecIns._zr;
  23663. var storage = zr.storage;
  23664. var elCount = 0;
  23665. storage.traverse(function (el) {
  23666. elCount++;
  23667. });
  23668. if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) {
  23669. ecModel.eachSeries(function (seriesModel) {
  23670. if (seriesModel.preventUsingHoverLayer) {
  23671. return;
  23672. }
  23673. var chartView = ecIns._chartsMap[seriesModel.__viewId];
  23674. if (chartView.__alive) {
  23675. chartView.group.traverse(function (el) {
  23676. // Don't switch back.
  23677. el.useHoverLayer = true;
  23678. });
  23679. }
  23680. });
  23681. }
  23682. }
  23683. /**
  23684. * Update chart progressive and blend.
  23685. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23686. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23687. */
  23688. function updateBlend(seriesModel, chartView) {
  23689. var blendMode = seriesModel.get('blendMode') || null;
  23690. chartView.group.traverse(function (el) {
  23691. // FIXME marker and other components
  23692. if (!el.isGroup) {
  23693. // Only set if blendMode is changed. In case element is incremental and don't wan't to rerender.
  23694. if (el.style.blend !== blendMode) {
  23695. el.setStyle('blend', blendMode);
  23696. }
  23697. }
  23698. if (el.eachPendingDisplayable) {
  23699. el.eachPendingDisplayable(function (displayable) {
  23700. displayable.setStyle('blend', blendMode);
  23701. });
  23702. }
  23703. });
  23704. }
  23705. /**
  23706. * @param {module:echarts/model/Series|module:echarts/model/Component} model
  23707. * @param {module:echarts/view/Component|module:echarts/view/Chart} view
  23708. */
  23709. function updateZ(model, view) {
  23710. var z = model.get('z');
  23711. var zlevel = model.get('zlevel'); // Set z and zlevel
  23712. view.group.traverse(function (el) {
  23713. if (el.type !== 'group') {
  23714. z != null && (el.z = z);
  23715. zlevel != null && (el.zlevel = zlevel);
  23716. }
  23717. });
  23718. }
  23719. function createExtensionAPI(ecInstance) {
  23720. var coordSysMgr = ecInstance._coordSysMgr;
  23721. return extend(new ExtensionAPI(ecInstance), {
  23722. // Inject methods
  23723. getCoordinateSystems: bind(coordSysMgr.getCoordinateSystems, coordSysMgr),
  23724. getComponentByElement: function (el) {
  23725. while (el) {
  23726. var modelInfo = el.__ecComponentInfo;
  23727. if (modelInfo != null) {
  23728. return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index);
  23729. }
  23730. el = el.parent;
  23731. }
  23732. }
  23733. });
  23734. }
  23735. /**
  23736. * @class
  23737. * Usage of query:
  23738. * `chart.on('click', query, handler);`
  23739. * The `query` can be:
  23740. * + The component type query string, only `mainType` or `mainType.subType`,
  23741. * like: 'xAxis', 'series', 'xAxis.category' or 'series.line'.
  23742. * + The component query object, like:
  23743. * `{seriesIndex: 2}`, `{seriesName: 'xx'}`, `{seriesId: 'some'}`,
  23744. * `{xAxisIndex: 2}`, `{xAxisName: 'xx'}`, `{xAxisId: 'some'}`.
  23745. * + The data query object, like:
  23746. * `{dataIndex: 123}`, `{dataType: 'link'}`, `{name: 'some'}`.
  23747. * + The other query object (cmponent customized query), like:
  23748. * `{element: 'some'}` (only available in custom series).
  23749. *
  23750. * Caveat: If a prop in the `query` object is `null/undefined`, it is the
  23751. * same as there is no such prop in the `query` object.
  23752. */
  23753. function EventProcessor() {
  23754. // These info required: targetEl, packedEvent, model, view
  23755. this.eventInfo;
  23756. }
  23757. EventProcessor.prototype = {
  23758. constructor: EventProcessor,
  23759. normalizeQuery: function (query) {
  23760. var cptQuery = {};
  23761. var dataQuery = {};
  23762. var otherQuery = {}; // `query` is `mainType` or `mainType.subType` of component.
  23763. if (isString(query)) {
  23764. var condCptType = parseClassType(query); // `.main` and `.sub` may be ''.
  23765. cptQuery.mainType = condCptType.main || null;
  23766. cptQuery.subType = condCptType.sub || null;
  23767. } // `query` is an object, convert to {mainType, index, name, id}.
  23768. else {
  23769. // `xxxIndex`, `xxxName`, `xxxId`, `name`, `dataIndex`, `dataType` is reserved,
  23770. // can not be used in `compomentModel.filterForExposedEvent`.
  23771. var suffixes = ['Index', 'Name', 'Id'];
  23772. var dataKeys = {
  23773. name: 1,
  23774. dataIndex: 1,
  23775. dataType: 1
  23776. };
  23777. each$1(query, function (val, key) {
  23778. var reserved = false;
  23779. for (var i = 0; i < suffixes.length; i++) {
  23780. var propSuffix = suffixes[i];
  23781. var suffixPos = key.lastIndexOf(propSuffix);
  23782. if (suffixPos > 0 && suffixPos === key.length - propSuffix.length) {
  23783. var mainType = key.slice(0, suffixPos); // Consider `dataIndex`.
  23784. if (mainType !== 'data') {
  23785. cptQuery.mainType = mainType;
  23786. cptQuery[propSuffix.toLowerCase()] = val;
  23787. reserved = true;
  23788. }
  23789. }
  23790. }
  23791. if (dataKeys.hasOwnProperty(key)) {
  23792. dataQuery[key] = val;
  23793. reserved = true;
  23794. }
  23795. if (!reserved) {
  23796. otherQuery[key] = val;
  23797. }
  23798. });
  23799. }
  23800. return {
  23801. cptQuery: cptQuery,
  23802. dataQuery: dataQuery,
  23803. otherQuery: otherQuery
  23804. };
  23805. },
  23806. filter: function (eventType, query, args) {
  23807. // They should be assigned before each trigger call.
  23808. var eventInfo = this.eventInfo;
  23809. if (!eventInfo) {
  23810. return true;
  23811. }
  23812. var targetEl = eventInfo.targetEl;
  23813. var packedEvent = eventInfo.packedEvent;
  23814. var model = eventInfo.model;
  23815. var view = eventInfo.view; // For event like 'globalout'.
  23816. if (!model || !view) {
  23817. return true;
  23818. }
  23819. var cptQuery = query.cptQuery;
  23820. var dataQuery = query.dataQuery;
  23821. return check(cptQuery, model, 'mainType') && check(cptQuery, model, 'subType') && check(cptQuery, model, 'index', 'componentIndex') && check(cptQuery, model, 'name') && check(cptQuery, model, 'id') && check(dataQuery, packedEvent, 'name') && check(dataQuery, packedEvent, 'dataIndex') && check(dataQuery, packedEvent, 'dataType') && (!view.filterForExposedEvent || view.filterForExposedEvent(eventType, query.otherQuery, targetEl, packedEvent));
  23822. function check(query, host, prop, propOnHost) {
  23823. return query[prop] == null || host[propOnHost || prop] === query[prop];
  23824. }
  23825. },
  23826. afterTrigger: function () {
  23827. // Make sure the eventInfo wont be used in next trigger.
  23828. this.eventInfo = null;
  23829. }
  23830. };
  23831. /**
  23832. * @type {Object} key: actionType.
  23833. * @inner
  23834. */
  23835. var actions = {};
  23836. /**
  23837. * Map eventType to actionType
  23838. * @type {Object}
  23839. */
  23840. var eventActionMap = {};
  23841. /**
  23842. * Data processor functions of each stage
  23843. * @type {Array.<Object.<string, Function>>}
  23844. * @inner
  23845. */
  23846. var dataProcessorFuncs = [];
  23847. /**
  23848. * @type {Array.<Function>}
  23849. * @inner
  23850. */
  23851. var optionPreprocessorFuncs = [];
  23852. /**
  23853. * @type {Array.<Function>}
  23854. * @inner
  23855. */
  23856. var postUpdateFuncs = [];
  23857. /**
  23858. * Visual encoding functions of each stage
  23859. * @type {Array.<Object.<string, Function>>}
  23860. */
  23861. var visualFuncs = [];
  23862. /**
  23863. * Theme storage
  23864. * @type {Object.<key, Object>}
  23865. */
  23866. var themeStorage = {};
  23867. /**
  23868. * Loading effects
  23869. */
  23870. var loadingEffects = {};
  23871. var instances = {};
  23872. var connectedGroups = {};
  23873. var idBase = new Date() - 0;
  23874. var groupIdBase = new Date() - 0;
  23875. var DOM_ATTRIBUTE_KEY = '_echarts_instance_';
  23876. function enableConnect(chart) {
  23877. var STATUS_PENDING = 0;
  23878. var STATUS_UPDATING = 1;
  23879. var STATUS_UPDATED = 2;
  23880. var STATUS_KEY = '__connectUpdateStatus';
  23881. function updateConnectedChartsStatus(charts, status) {
  23882. for (var i = 0; i < charts.length; i++) {
  23883. var otherChart = charts[i];
  23884. otherChart[STATUS_KEY] = status;
  23885. }
  23886. }
  23887. each(eventActionMap, function (actionType, eventType) {
  23888. chart._messageCenter.on(eventType, function (event) {
  23889. if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) {
  23890. if (event && event.escapeConnect) {
  23891. return;
  23892. }
  23893. var action = chart.makeActionFromEvent(event);
  23894. var otherCharts = [];
  23895. each(instances, function (otherChart) {
  23896. if (otherChart !== chart && otherChart.group === chart.group) {
  23897. otherCharts.push(otherChart);
  23898. }
  23899. });
  23900. updateConnectedChartsStatus(otherCharts, STATUS_PENDING);
  23901. each(otherCharts, function (otherChart) {
  23902. if (otherChart[STATUS_KEY] !== STATUS_UPDATING) {
  23903. otherChart.dispatchAction(action);
  23904. }
  23905. });
  23906. updateConnectedChartsStatus(otherCharts, STATUS_UPDATED);
  23907. }
  23908. });
  23909. });
  23910. }
  23911. /**
  23912. * @param {HTMLElement} dom
  23913. * @param {Object} [theme]
  23914. * @param {Object} opts
  23915. * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default
  23916. * @param {string} [opts.renderer] Can choose 'canvas' or 'svg' to render the chart.
  23917. * @param {number} [opts.width] Use clientWidth of the input `dom` by default.
  23918. * Can be 'auto' (the same as null/undefined)
  23919. * @param {number} [opts.height] Use clientHeight of the input `dom` by default.
  23920. * Can be 'auto' (the same as null/undefined)
  23921. */
  23922. function init(dom, theme$$1, opts) {
  23923. var existInstance = getInstanceByDom(dom);
  23924. if (existInstance) {
  23925. return existInstance;
  23926. }
  23927. var chart = new ECharts(dom, theme$$1, opts);
  23928. chart.id = 'ec_' + idBase++;
  23929. instances[chart.id] = chart;
  23930. setAttribute(dom, DOM_ATTRIBUTE_KEY, chart.id);
  23931. enableConnect(chart);
  23932. return chart;
  23933. }
  23934. /**
  23935. * @return {string|Array.<module:echarts~ECharts>} groupId
  23936. */
  23937. function connect(groupId) {
  23938. // Is array of charts
  23939. if (isArray(groupId)) {
  23940. var charts = groupId;
  23941. groupId = null; // If any chart has group
  23942. each(charts, function (chart) {
  23943. if (chart.group != null) {
  23944. groupId = chart.group;
  23945. }
  23946. });
  23947. groupId = groupId || 'g_' + groupIdBase++;
  23948. each(charts, function (chart) {
  23949. chart.group = groupId;
  23950. });
  23951. }
  23952. connectedGroups[groupId] = true;
  23953. return groupId;
  23954. }
  23955. /**
  23956. * @DEPRECATED
  23957. * @return {string} groupId
  23958. */
  23959. function disConnect(groupId) {
  23960. connectedGroups[groupId] = false;
  23961. }
  23962. /**
  23963. * @return {string} groupId
  23964. */
  23965. var disconnect = disConnect;
  23966. /**
  23967. * Dispose a chart instance
  23968. * @param {module:echarts~ECharts|HTMLDomElement|string} chart
  23969. */
  23970. function dispose(chart) {
  23971. if (typeof chart === 'string') {
  23972. chart = instances[chart];
  23973. } else if (!(chart instanceof ECharts)) {
  23974. // Try to treat as dom
  23975. chart = getInstanceByDom(chart);
  23976. }
  23977. if (chart instanceof ECharts && !chart.isDisposed()) {
  23978. chart.dispose();
  23979. }
  23980. }
  23981. /**
  23982. * @param {HTMLElement} dom
  23983. * @return {echarts~ECharts}
  23984. */
  23985. function getInstanceByDom(dom) {
  23986. return instances[getAttribute(dom, DOM_ATTRIBUTE_KEY)];
  23987. }
  23988. /**
  23989. * @param {string} key
  23990. * @return {echarts~ECharts}
  23991. */
  23992. function getInstanceById(key) {
  23993. return instances[key];
  23994. }
  23995. /**
  23996. * Register theme
  23997. */
  23998. function registerTheme(name, theme$$1) {
  23999. themeStorage[name] = theme$$1;
  24000. }
  24001. /**
  24002. * Register option preprocessor
  24003. * @param {Function} preprocessorFunc
  24004. */
  24005. function registerPreprocessor(preprocessorFunc) {
  24006. optionPreprocessorFuncs.push(preprocessorFunc);
  24007. }
  24008. /**
  24009. * @param {number} [priority=1000]
  24010. * @param {Object|Function} processor
  24011. */
  24012. function registerProcessor(priority, processor) {
  24013. normalizeRegister(dataProcessorFuncs, priority, processor, PRIORITY_PROCESSOR_FILTER);
  24014. }
  24015. /**
  24016. * Register postUpdater
  24017. * @param {Function} postUpdateFunc
  24018. */
  24019. function registerPostUpdate(postUpdateFunc) {
  24020. postUpdateFuncs.push(postUpdateFunc);
  24021. }
  24022. /**
  24023. * Usage:
  24024. * registerAction('someAction', 'someEvent', function () { ... });
  24025. * registerAction('someAction', function () { ... });
  24026. * registerAction(
  24027. * {type: 'someAction', event: 'someEvent', update: 'updateView'},
  24028. * function () { ... }
  24029. * );
  24030. *
  24031. * @param {(string|Object)} actionInfo
  24032. * @param {string} actionInfo.type
  24033. * @param {string} [actionInfo.event]
  24034. * @param {string} [actionInfo.update]
  24035. * @param {string} [eventName]
  24036. * @param {Function} action
  24037. */
  24038. function registerAction(actionInfo, eventName, action) {
  24039. if (typeof eventName === 'function') {
  24040. action = eventName;
  24041. eventName = '';
  24042. }
  24043. var actionType = isObject(actionInfo) ? actionInfo.type : [actionInfo, actionInfo = {
  24044. event: eventName
  24045. }][0]; // Event name is all lowercase
  24046. actionInfo.event = (actionInfo.event || actionType).toLowerCase();
  24047. eventName = actionInfo.event; // Validate action type and event name.
  24048. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName));
  24049. if (!actions[actionType]) {
  24050. actions[actionType] = {
  24051. action: action,
  24052. actionInfo: actionInfo
  24053. };
  24054. }
  24055. eventActionMap[eventName] = actionType;
  24056. }
  24057. /**
  24058. * @param {string} type
  24059. * @param {*} CoordinateSystem
  24060. */
  24061. function registerCoordinateSystem(type, CoordinateSystem$$1) {
  24062. CoordinateSystemManager.register(type, CoordinateSystem$$1);
  24063. }
  24064. /**
  24065. * Get dimensions of specified coordinate system.
  24066. * @param {string} type
  24067. * @return {Array.<string|Object>}
  24068. */
  24069. function getCoordinateSystemDimensions(type) {
  24070. var coordSysCreator = CoordinateSystemManager.get(type);
  24071. if (coordSysCreator) {
  24072. return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice();
  24073. }
  24074. }
  24075. /**
  24076. * Layout is a special stage of visual encoding
  24077. * Most visual encoding like color are common for different chart
  24078. * But each chart has it's own layout algorithm
  24079. *
  24080. * @param {number} [priority=1000]
  24081. * @param {Function} layoutTask
  24082. */
  24083. function registerLayout(priority, layoutTask) {
  24084. normalizeRegister(visualFuncs, priority, layoutTask, PRIORITY_VISUAL_LAYOUT, 'layout');
  24085. }
  24086. /**
  24087. * @param {number} [priority=3000]
  24088. * @param {module:echarts/stream/Task} visualTask
  24089. */
  24090. function registerVisual(priority, visualTask) {
  24091. normalizeRegister(visualFuncs, priority, visualTask, PRIORITY_VISUAL_CHART, 'visual');
  24092. }
  24093. /**
  24094. * @param {Object|Function} fn: {seriesType, createOnAllSeries, performRawSeries, reset}
  24095. */
  24096. function normalizeRegister(targetList, priority, fn, defaultPriority, visualType) {
  24097. if (isFunction(priority) || isObject(priority)) {
  24098. fn = priority;
  24099. priority = defaultPriority;
  24100. }
  24101. var stageHandler = Scheduler.wrapStageHandler(fn, visualType);
  24102. stageHandler.__prio = priority;
  24103. stageHandler.__raw = fn;
  24104. targetList.push(stageHandler);
  24105. return stageHandler;
  24106. }
  24107. /**
  24108. * @param {string} name
  24109. */
  24110. function registerLoading(name, loadingFx) {
  24111. loadingEffects[name] = loadingFx;
  24112. }
  24113. /**
  24114. * @param {Object} opts
  24115. * @param {string} [superClass]
  24116. */
  24117. function extendComponentModel(opts
  24118. /*, superClass*/
  24119. ) {
  24120. // var Clazz = ComponentModel;
  24121. // if (superClass) {
  24122. // var classType = parseClassType(superClass);
  24123. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24124. // }
  24125. return ComponentModel.extend(opts);
  24126. }
  24127. /**
  24128. * @param {Object} opts
  24129. * @param {string} [superClass]
  24130. */
  24131. function extendComponentView(opts
  24132. /*, superClass*/
  24133. ) {
  24134. // var Clazz = ComponentView;
  24135. // if (superClass) {
  24136. // var classType = parseClassType(superClass);
  24137. // Clazz = ComponentView.getClass(classType.main, classType.sub, true);
  24138. // }
  24139. return Component$1.extend(opts);
  24140. }
  24141. /**
  24142. * @param {Object} opts
  24143. * @param {string} [superClass]
  24144. */
  24145. function extendSeriesModel(opts
  24146. /*, superClass*/
  24147. ) {
  24148. // var Clazz = SeriesModel;
  24149. // if (superClass) {
  24150. // superClass = 'series.' + superClass.replace('series.', '');
  24151. // var classType = parseClassType(superClass);
  24152. // Clazz = ComponentModel.getClass(classType.main, classType.sub, true);
  24153. // }
  24154. return SeriesModel.extend(opts);
  24155. }
  24156. /**
  24157. * @param {Object} opts
  24158. * @param {string} [superClass]
  24159. */
  24160. function extendChartView(opts
  24161. /*, superClass*/
  24162. ) {
  24163. // var Clazz = ChartView;
  24164. // if (superClass) {
  24165. // superClass = superClass.replace('series.', '');
  24166. // var classType = parseClassType(superClass);
  24167. // Clazz = ChartView.getClass(classType.main, true);
  24168. // }
  24169. return Chart.extend(opts);
  24170. }
  24171. /**
  24172. * ZRender need a canvas context to do measureText.
  24173. * But in node environment canvas may be created by node-canvas.
  24174. * So we need to specify how to create a canvas instead of using document.createElement('canvas')
  24175. *
  24176. * Be careful of using it in the browser.
  24177. *
  24178. * @param {Function} creator
  24179. * @example
  24180. * var Canvas = require('canvas');
  24181. * var echarts = require('echarts');
  24182. * echarts.setCanvasCreator(function () {
  24183. * // Small size is enough.
  24184. * return new Canvas(32, 32);
  24185. * });
  24186. */
  24187. function setCanvasCreator(creator) {
  24188. $override('createCanvas', creator);
  24189. }
  24190. /**
  24191. * @param {string} mapName
  24192. * @param {Array.<Object>|Object|string} geoJson
  24193. * @param {Object} [specialAreas]
  24194. *
  24195. * @example GeoJSON
  24196. * $.get('USA.json', function (geoJson) {
  24197. * echarts.registerMap('USA', geoJson);
  24198. * // Or
  24199. * echarts.registerMap('USA', {
  24200. * geoJson: geoJson,
  24201. * specialAreas: {}
  24202. * })
  24203. * });
  24204. *
  24205. * $.get('airport.svg', function (svg) {
  24206. * echarts.registerMap('airport', {
  24207. * svg: svg
  24208. * }
  24209. * });
  24210. *
  24211. * echarts.registerMap('eu', [
  24212. * {svg: eu-topographic.svg},
  24213. * {geoJSON: eu.json}
  24214. * ])
  24215. */
  24216. function registerMap(mapName, geoJson, specialAreas) {
  24217. mapDataStorage.registerMap(mapName, geoJson, specialAreas);
  24218. }
  24219. /**
  24220. * @param {string} mapName
  24221. * @return {Object}
  24222. */
  24223. function getMap(mapName) {
  24224. // For backward compatibility, only return the first one.
  24225. var records = mapDataStorage.retrieveMap(mapName);
  24226. return records && records[0] && {
  24227. geoJson: records[0].geoJSON,
  24228. specialAreas: records[0].specialAreas
  24229. };
  24230. }
  24231. registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor);
  24232. registerPreprocessor(backwardCompat);
  24233. registerProcessor(PRIORITY_PROCESSOR_DATASTACK, dataStack);
  24234. registerLoading('default', loadingDefault); // Default actions
  24235. registerAction({
  24236. type: 'highlight',
  24237. event: 'highlight',
  24238. update: 'highlight'
  24239. }, noop);
  24240. registerAction({
  24241. type: 'downplay',
  24242. event: 'downplay',
  24243. update: 'downplay'
  24244. }, noop); // Default theme
  24245. registerTheme('light', lightTheme);
  24246. registerTheme('dark', theme); // For backward compatibility, where the namespace `dataTool` will
  24247. // be mounted on `echarts` is the extension `dataTool` is imported.
  24248. var dataTool = {};
  24249. /*
  24250. * Licensed to the Apache Software Foundation (ASF) under one
  24251. * or more contributor license agreements. See the NOTICE file
  24252. * distributed with this work for additional information
  24253. * regarding copyright ownership. The ASF licenses this file
  24254. * to you under the Apache License, Version 2.0 (the
  24255. * "License"); you may not use this file except in compliance
  24256. * with the License. You may obtain a copy of the License at
  24257. *
  24258. * http://www.apache.org/licenses/LICENSE-2.0
  24259. *
  24260. * Unless required by applicable law or agreed to in writing,
  24261. * software distributed under the License is distributed on an
  24262. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24263. * KIND, either express or implied. See the License for the
  24264. * specific language governing permissions and limitations
  24265. * under the License.
  24266. */
  24267. function defaultKeyGetter(item) {
  24268. return item;
  24269. }
  24270. /**
  24271. * @param {Array} oldArr
  24272. * @param {Array} newArr
  24273. * @param {Function} oldKeyGetter
  24274. * @param {Function} newKeyGetter
  24275. * @param {Object} [context] Can be visited by this.context in callback.
  24276. */
  24277. function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) {
  24278. this._old = oldArr;
  24279. this._new = newArr;
  24280. this._oldKeyGetter = oldKeyGetter || defaultKeyGetter;
  24281. this._newKeyGetter = newKeyGetter || defaultKeyGetter;
  24282. this.context = context;
  24283. }
  24284. DataDiffer.prototype = {
  24285. constructor: DataDiffer,
  24286. /**
  24287. * Callback function when add a data
  24288. */
  24289. add: function (func) {
  24290. this._add = func;
  24291. return this;
  24292. },
  24293. /**
  24294. * Callback function when update a data
  24295. */
  24296. update: function (func) {
  24297. this._update = func;
  24298. return this;
  24299. },
  24300. /**
  24301. * Callback function when remove a data
  24302. */
  24303. remove: function (func) {
  24304. this._remove = func;
  24305. return this;
  24306. },
  24307. execute: function () {
  24308. var oldArr = this._old;
  24309. var newArr = this._new;
  24310. var oldDataIndexMap = {};
  24311. var newDataIndexMap = {};
  24312. var oldDataKeyArr = [];
  24313. var newDataKeyArr = [];
  24314. var i;
  24315. initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this);
  24316. initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this);
  24317. for (i = 0; i < oldArr.length; i++) {
  24318. var key = oldDataKeyArr[i];
  24319. var idx = newDataIndexMap[key]; // idx can never be empty array here. see 'set null' logic below.
  24320. if (idx != null) {
  24321. // Consider there is duplicate key (for example, use dataItem.name as key).
  24322. // We should make sure every item in newArr and oldArr can be visited.
  24323. var len = idx.length;
  24324. if (len) {
  24325. len === 1 && (newDataIndexMap[key] = null);
  24326. idx = idx.shift();
  24327. } else {
  24328. newDataIndexMap[key] = null;
  24329. }
  24330. this._update && this._update(idx, i);
  24331. } else {
  24332. this._remove && this._remove(i);
  24333. }
  24334. }
  24335. for (var i = 0; i < newDataKeyArr.length; i++) {
  24336. var key = newDataKeyArr[i];
  24337. if (newDataIndexMap.hasOwnProperty(key)) {
  24338. var idx = newDataIndexMap[key];
  24339. if (idx == null) {
  24340. continue;
  24341. } // idx can never be empty array here. see 'set null' logic above.
  24342. if (!idx.length) {
  24343. this._add && this._add(idx);
  24344. } else {
  24345. for (var j = 0, len = idx.length; j < len; j++) {
  24346. this._add && this._add(idx[j]);
  24347. }
  24348. }
  24349. }
  24350. }
  24351. }
  24352. };
  24353. function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) {
  24354. for (var i = 0; i < arr.length; i++) {
  24355. // Add prefix to avoid conflict with Object.prototype.
  24356. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i);
  24357. var existence = map[key];
  24358. if (existence == null) {
  24359. keyArr.push(key);
  24360. map[key] = i;
  24361. } else {
  24362. if (!existence.length) {
  24363. map[key] = existence = [existence];
  24364. }
  24365. existence.push(i);
  24366. }
  24367. }
  24368. }
  24369. /*
  24370. * Licensed to the Apache Software Foundation (ASF) under one
  24371. * or more contributor license agreements. See the NOTICE file
  24372. * distributed with this work for additional information
  24373. * regarding copyright ownership. The ASF licenses this file
  24374. * to you under the Apache License, Version 2.0 (the
  24375. * "License"); you may not use this file except in compliance
  24376. * with the License. You may obtain a copy of the License at
  24377. *
  24378. * http://www.apache.org/licenses/LICENSE-2.0
  24379. *
  24380. * Unless required by applicable law or agreed to in writing,
  24381. * software distributed under the License is distributed on an
  24382. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24383. * KIND, either express or implied. See the License for the
  24384. * specific language governing permissions and limitations
  24385. * under the License.
  24386. */
  24387. var OTHER_DIMENSIONS = createHashMap(['tooltip', 'label', 'itemName', 'itemId', 'seriesName']);
  24388. function summarizeDimensions(data) {
  24389. var summary = {};
  24390. var encode = summary.encode = {};
  24391. var notExtraCoordDimMap = createHashMap();
  24392. var defaultedLabel = [];
  24393. var defaultedTooltip = []; // See the comment of `List.js#userOutput`.
  24394. var userOutput = summary.userOutput = {
  24395. dimensionNames: data.dimensions.slice(),
  24396. encode: {}
  24397. };
  24398. each$1(data.dimensions, function (dimName) {
  24399. var dimItem = data.getDimensionInfo(dimName);
  24400. var coordDim = dimItem.coordDim;
  24401. if (coordDim) {
  24402. var coordDimIndex = dimItem.coordDimIndex;
  24403. getOrCreateEncodeArr(encode, coordDim)[coordDimIndex] = dimName;
  24404. if (!dimItem.isExtraCoord) {
  24405. notExtraCoordDimMap.set(coordDim, 1); // Use the last coord dim (and label friendly) as default label,
  24406. // because when dataset is used, it is hard to guess which dimension
  24407. // can be value dimension. If both show x, y on label is not look good,
  24408. // and conventionally y axis is focused more.
  24409. if (mayLabelDimType(dimItem.type)) {
  24410. defaultedLabel[0] = dimName;
  24411. } // User output encode do not contain generated coords.
  24412. // And it only has index. User can use index to retrieve value from the raw item array.
  24413. getOrCreateEncodeArr(userOutput.encode, coordDim)[coordDimIndex] = dimItem.index;
  24414. }
  24415. if (dimItem.defaultTooltip) {
  24416. defaultedTooltip.push(dimName);
  24417. }
  24418. }
  24419. OTHER_DIMENSIONS.each(function (v, otherDim) {
  24420. var encodeArr = getOrCreateEncodeArr(encode, otherDim);
  24421. var dimIndex = dimItem.otherDims[otherDim];
  24422. if (dimIndex != null && dimIndex !== false) {
  24423. encodeArr[dimIndex] = dimItem.name;
  24424. }
  24425. });
  24426. });
  24427. var dataDimsOnCoord = [];
  24428. var encodeFirstDimNotExtra = {};
  24429. notExtraCoordDimMap.each(function (v, coordDim) {
  24430. var dimArr = encode[coordDim]; // ??? FIXME extra coord should not be set in dataDimsOnCoord.
  24431. // But should fix the case that radar axes: simplify the logic
  24432. // of `completeDimension`, remove `extraPrefix`.
  24433. encodeFirstDimNotExtra[coordDim] = dimArr[0]; // Not necessary to remove duplicate, because a data
  24434. // dim canot on more than one coordDim.
  24435. dataDimsOnCoord = dataDimsOnCoord.concat(dimArr);
  24436. });
  24437. summary.dataDimsOnCoord = dataDimsOnCoord;
  24438. summary.encodeFirstDimNotExtra = encodeFirstDimNotExtra;
  24439. var encodeLabel = encode.label; // FIXME `encode.label` is not recommanded, because formatter can not be set
  24440. // in this way. Use label.formatter instead. May be remove this approach someday.
  24441. if (encodeLabel && encodeLabel.length) {
  24442. defaultedLabel = encodeLabel.slice();
  24443. }
  24444. var encodeTooltip = encode.tooltip;
  24445. if (encodeTooltip && encodeTooltip.length) {
  24446. defaultedTooltip = encodeTooltip.slice();
  24447. } else if (!defaultedTooltip.length) {
  24448. defaultedTooltip = defaultedLabel.slice();
  24449. }
  24450. encode.defaultedLabel = defaultedLabel;
  24451. encode.defaultedTooltip = defaultedTooltip;
  24452. return summary;
  24453. }
  24454. function getOrCreateEncodeArr(encode, dim) {
  24455. if (!encode.hasOwnProperty(dim)) {
  24456. encode[dim] = [];
  24457. }
  24458. return encode[dim];
  24459. }
  24460. function getDimensionTypeByAxis(axisType) {
  24461. return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float';
  24462. }
  24463. function mayLabelDimType(dimType) {
  24464. // In most cases, ordinal and time do not suitable for label.
  24465. // Ordinal info can be displayed on axis. Time is too long.
  24466. return !(dimType === 'ordinal' || dimType === 'time');
  24467. } // function findTheLastDimMayLabel(data) {
  24468. // // Get last value dim
  24469. // var dimensions = data.dimensions.slice();
  24470. // var valueType;
  24471. // var valueDim;
  24472. // while (dimensions.length && (
  24473. // valueDim = dimensions.pop(),
  24474. // valueType = data.getDimensionInfo(valueDim).type,
  24475. // valueType === 'ordinal' || valueType === 'time'
  24476. // )) {} // jshint ignore:line
  24477. // return valueDim;
  24478. // }
  24479. /*
  24480. * Licensed to the Apache Software Foundation (ASF) under one
  24481. * or more contributor license agreements. See the NOTICE file
  24482. * distributed with this work for additional information
  24483. * regarding copyright ownership. The ASF licenses this file
  24484. * to you under the Apache License, Version 2.0 (the
  24485. * "License"); you may not use this file except in compliance
  24486. * with the License. You may obtain a copy of the License at
  24487. *
  24488. * http://www.apache.org/licenses/LICENSE-2.0
  24489. *
  24490. * Unless required by applicable law or agreed to in writing,
  24491. * software distributed under the License is distributed on an
  24492. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24493. * KIND, either express or implied. See the License for the
  24494. * specific language governing permissions and limitations
  24495. * under the License.
  24496. */
  24497. /**
  24498. * @class
  24499. * @param {Object|DataDimensionInfo} [opt] All of the fields will be shallow copied.
  24500. */
  24501. function DataDimensionInfo(opt) {
  24502. if (opt != null) {
  24503. extend(this, opt);
  24504. }
  24505. /**
  24506. * Dimension name.
  24507. * Mandatory.
  24508. * @type {string}
  24509. */
  24510. // this.name;
  24511. /**
  24512. * The origin name in dimsDef, see source helper.
  24513. * If displayName given, the tooltip will displayed vertically.
  24514. * Optional.
  24515. * @type {string}
  24516. */
  24517. // this.displayName;
  24518. /**
  24519. * Which coordSys dimension this dimension mapped to.
  24520. * A `coordDim` can be a "coordSysDim" that the coordSys required
  24521. * (for example, an item in `coordSysDims` of `model/referHelper#CoordSysInfo`),
  24522. * or an generated "extra coord name" if does not mapped to any "coordSysDim"
  24523. * (That is determined by whether `isExtraCoord` is `true`).
  24524. * Mandatory.
  24525. * @type {string}
  24526. */
  24527. // this.coordDim;
  24528. /**
  24529. * The index of this dimension in `series.encode[coordDim]`.
  24530. * Mandatory.
  24531. * @type {number}
  24532. */
  24533. // this.coordDimIndex;
  24534. /**
  24535. * Dimension type. The enumerable values are the key of
  24536. * `dataCtors` of `data/List`.
  24537. * Optional.
  24538. * @type {string}
  24539. */
  24540. // this.type;
  24541. /**
  24542. * This index of this dimension info in `data/List#_dimensionInfos`.
  24543. * Mandatory after added to `data/List`.
  24544. * @type {number}
  24545. */
  24546. // this.index;
  24547. /**
  24548. * The format of `otherDims` is:
  24549. * ```js
  24550. * {
  24551. * tooltip: number optional,
  24552. * label: number optional,
  24553. * itemName: number optional,
  24554. * seriesName: number optional,
  24555. * }
  24556. * ```
  24557. *
  24558. * A `series.encode` can specified these fields:
  24559. * ```js
  24560. * encode: {
  24561. * // "3, 1, 5" is the index of data dimension.
  24562. * tooltip: [3, 1, 5],
  24563. * label: [0, 3],
  24564. * ...
  24565. * }
  24566. * ```
  24567. * `otherDims` is the parse result of the `series.encode` above, like:
  24568. * ```js
  24569. * // Suppose the index of this data dimension is `3`.
  24570. * this.otherDims = {
  24571. * // `3` is at the index `0` of the `encode.tooltip`
  24572. * tooltip: 0,
  24573. * // `3` is at the index `1` of the `encode.tooltip`
  24574. * label: 1
  24575. * };
  24576. * ```
  24577. *
  24578. * This prop should never be `null`/`undefined` after initialized.
  24579. * @type {Object}
  24580. */
  24581. this.otherDims = {};
  24582. /**
  24583. * Be `true` if this dimension is not mapped to any "coordSysDim" that the
  24584. * "coordSys" required.
  24585. * Mandatory.
  24586. * @type {boolean}
  24587. */
  24588. // this.isExtraCoord;
  24589. /**
  24590. * @type {module:data/OrdinalMeta}
  24591. */
  24592. // this.ordinalMeta;
  24593. /**
  24594. * Whether to create inverted indices.
  24595. * @type {boolean}
  24596. */
  24597. // this.createInvertedIndices;
  24598. }
  24599. /*
  24600. * Licensed to the Apache Software Foundation (ASF) under one
  24601. * or more contributor license agreements. See the NOTICE file
  24602. * distributed with this work for additional information
  24603. * regarding copyright ownership. The ASF licenses this file
  24604. * to you under the Apache License, Version 2.0 (the
  24605. * "License"); you may not use this file except in compliance
  24606. * with the License. You may obtain a copy of the License at
  24607. *
  24608. * http://www.apache.org/licenses/LICENSE-2.0
  24609. *
  24610. * Unless required by applicable law or agreed to in writing,
  24611. * software distributed under the License is distributed on an
  24612. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  24613. * KIND, either express or implied. See the License for the
  24614. * specific language governing permissions and limitations
  24615. * under the License.
  24616. */
  24617. /* global Float64Array, Int32Array, Uint32Array, Uint16Array */
  24618. /**
  24619. * List for data storage
  24620. * @module echarts/data/List
  24621. */
  24622. var isObject$4 = isObject$1;
  24623. var UNDEFINED = 'undefined';
  24624. var INDEX_NOT_FOUND = -1; // Use prefix to avoid index to be the same as otherIdList[idx],
  24625. // which will cause weird udpate animation.
  24626. var ID_PREFIX = 'e\0\0';
  24627. var dataCtors = {
  24628. 'float': typeof Float64Array === UNDEFINED ? Array : Float64Array,
  24629. 'int': typeof Int32Array === UNDEFINED ? Array : Int32Array,
  24630. // Ordinal data type can be string or int
  24631. 'ordinal': Array,
  24632. 'number': Array,
  24633. 'time': Array
  24634. }; // Caution: MUST not use `new CtorUint32Array(arr, 0, len)`, because the Ctor of array is
  24635. // different from the Ctor of typed array.
  24636. var CtorUint32Array = typeof Uint32Array === UNDEFINED ? Array : Uint32Array;
  24637. var CtorInt32Array = typeof Int32Array === UNDEFINED ? Array : Int32Array;
  24638. var CtorUint16Array = typeof Uint16Array === UNDEFINED ? Array : Uint16Array;
  24639. function getIndicesCtor(list) {
  24640. // The possible max value in this._indicies is always this._rawCount despite of filtering.
  24641. return list._rawCount > 65535 ? CtorUint32Array : CtorUint16Array;
  24642. }
  24643. function cloneChunk(originalChunk) {
  24644. var Ctor = originalChunk.constructor; // Only shallow clone is enough when Array.
  24645. return Ctor === Array ? originalChunk.slice() : new Ctor(originalChunk);
  24646. }
  24647. var TRANSFERABLE_PROPERTIES = ['hasItemOption', '_nameList', '_idList', '_invertedIndicesMap', '_rawData', '_chunkSize', '_chunkCount', '_dimValueGetter', '_count', '_rawCount', '_nameDimIdx', '_idDimIdx'];
  24648. var CLONE_PROPERTIES = ['_extent', '_approximateExtent', '_rawExtent'];
  24649. function transferProperties(target, source) {
  24650. each$1(TRANSFERABLE_PROPERTIES.concat(source.__wrappedMethods || []), function (propName) {
  24651. if (source.hasOwnProperty(propName)) {
  24652. target[propName] = source[propName];
  24653. }
  24654. });
  24655. target.__wrappedMethods = source.__wrappedMethods;
  24656. each$1(CLONE_PROPERTIES, function (propName) {
  24657. target[propName] = clone(source[propName]);
  24658. });
  24659. target._calculationInfo = extend(source._calculationInfo);
  24660. }
  24661. /**
  24662. * @constructor
  24663. * @alias module:echarts/data/List
  24664. *
  24665. * @param {Array.<string|Object|module:data/DataDimensionInfo>} dimensions
  24666. * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...].
  24667. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius
  24668. * @param {module:echarts/model/Model} hostModel
  24669. */
  24670. var List = function (dimensions, hostModel) {
  24671. dimensions = dimensions || ['x', 'y'];
  24672. var dimensionInfos = {};
  24673. var dimensionNames = [];
  24674. var invertedIndicesMap = {};
  24675. for (var i = 0; i < dimensions.length; i++) {
  24676. // Use the original dimensions[i], where other flag props may exists.
  24677. var dimensionInfo = dimensions[i];
  24678. if (isString(dimensionInfo)) {
  24679. dimensionInfo = new DataDimensionInfo({
  24680. name: dimensionInfo
  24681. });
  24682. } else if (!(dimensionInfo instanceof DataDimensionInfo)) {
  24683. dimensionInfo = new DataDimensionInfo(dimensionInfo);
  24684. }
  24685. var dimensionName = dimensionInfo.name;
  24686. dimensionInfo.type = dimensionInfo.type || 'float';
  24687. if (!dimensionInfo.coordDim) {
  24688. dimensionInfo.coordDim = dimensionName;
  24689. dimensionInfo.coordDimIndex = 0;
  24690. }
  24691. dimensionInfo.otherDims = dimensionInfo.otherDims || {};
  24692. dimensionNames.push(dimensionName);
  24693. dimensionInfos[dimensionName] = dimensionInfo;
  24694. dimensionInfo.index = i;
  24695. if (dimensionInfo.createInvertedIndices) {
  24696. invertedIndicesMap[dimensionName] = [];
  24697. }
  24698. }
  24699. /**
  24700. * @readOnly
  24701. * @type {Array.<string>}
  24702. */
  24703. this.dimensions = dimensionNames;
  24704. /**
  24705. * Infomation of each data dimension, like data type.
  24706. * @type {Object}
  24707. */
  24708. this._dimensionInfos = dimensionInfos;
  24709. /**
  24710. * @type {module:echarts/model/Model}
  24711. */
  24712. this.hostModel = hostModel;
  24713. /**
  24714. * @type {module:echarts/model/Model}
  24715. */
  24716. this.dataType;
  24717. /**
  24718. * Indices stores the indices of data subset after filtered.
  24719. * This data subset will be used in chart.
  24720. * @type {Array.<number>}
  24721. * @readOnly
  24722. */
  24723. this._indices = null;
  24724. this._count = 0;
  24725. this._rawCount = 0;
  24726. /**
  24727. * Data storage
  24728. * @type {Object.<key, Array.<TypedArray|Array>>}
  24729. * @private
  24730. */
  24731. this._storage = {};
  24732. /**
  24733. * @type {Array.<string>}
  24734. */
  24735. this._nameList = [];
  24736. /**
  24737. * @type {Array.<string>}
  24738. */
  24739. this._idList = [];
  24740. /**
  24741. * Models of data option is stored sparse for optimizing memory cost
  24742. * @type {Array.<module:echarts/model/Model>}
  24743. * @private
  24744. */
  24745. this._optionModels = [];
  24746. /**
  24747. * Global visual properties after visual coding
  24748. * @type {Object}
  24749. * @private
  24750. */
  24751. this._visual = {};
  24752. /**
  24753. * Globel layout properties.
  24754. * @type {Object}
  24755. * @private
  24756. */
  24757. this._layout = {};
  24758. /**
  24759. * Item visual properties after visual coding
  24760. * @type {Array.<Object>}
  24761. * @private
  24762. */
  24763. this._itemVisuals = [];
  24764. /**
  24765. * Key: visual type, Value: boolean
  24766. * @type {Object}
  24767. * @readOnly
  24768. */
  24769. this.hasItemVisual = {};
  24770. /**
  24771. * Item layout properties after layout
  24772. * @type {Array.<Object>}
  24773. * @private
  24774. */
  24775. this._itemLayouts = [];
  24776. /**
  24777. * Graphic elemnents
  24778. * @type {Array.<module:zrender/Element>}
  24779. * @private
  24780. */
  24781. this._graphicEls = [];
  24782. /**
  24783. * Max size of each chunk.
  24784. * @type {number}
  24785. * @private
  24786. */
  24787. this._chunkSize = 1e5;
  24788. /**
  24789. * @type {number}
  24790. * @private
  24791. */
  24792. this._chunkCount = 0;
  24793. /**
  24794. * @type {Array.<Array|Object>}
  24795. * @private
  24796. */
  24797. this._rawData;
  24798. /**
  24799. * Raw extent will not be cloned, but only transfered.
  24800. * It will not be calculated util needed.
  24801. * key: dim,
  24802. * value: {end: number, extent: Array.<number>}
  24803. * @type {Object}
  24804. * @private
  24805. */
  24806. this._rawExtent = {};
  24807. /**
  24808. * @type {Object}
  24809. * @private
  24810. */
  24811. this._extent = {};
  24812. /**
  24813. * key: dim
  24814. * value: extent
  24815. * @type {Object}
  24816. * @private
  24817. */
  24818. this._approximateExtent = {};
  24819. /**
  24820. * Cache summary info for fast visit. See "dimensionHelper".
  24821. * @type {Object}
  24822. * @private
  24823. */
  24824. this._dimensionsSummary = summarizeDimensions(this);
  24825. /**
  24826. * @type {Object.<Array|TypedArray>}
  24827. * @private
  24828. */
  24829. this._invertedIndicesMap = invertedIndicesMap;
  24830. /**
  24831. * @type {Object}
  24832. * @private
  24833. */
  24834. this._calculationInfo = {};
  24835. /**
  24836. * User output info of this data.
  24837. * DO NOT use it in other places!
  24838. *
  24839. * When preparing user params for user callbacks, we have
  24840. * to clone these inner data structures to prevent users
  24841. * from modifying them to effect built-in logic. And for
  24842. * performance consideration we make this `userOutput` to
  24843. * avoid clone them too many times.
  24844. *
  24845. * @type {Object}
  24846. * @readOnly
  24847. */
  24848. this.userOutput = this._dimensionsSummary.userOutput;
  24849. };
  24850. var listProto = List.prototype;
  24851. listProto.type = 'list';
  24852. /**
  24853. * If each data item has it's own option
  24854. * @type {boolean}
  24855. */
  24856. listProto.hasItemOption = true;
  24857. /**
  24858. * The meanings of the input parameter `dim`:
  24859. *
  24860. * + If dim is a number (e.g., `1`), it means the index of the dimension.
  24861. * For example, `getDimension(0)` will return 'x' or 'lng' or 'radius'.
  24862. * + If dim is a number-like string (e.g., `"1"`):
  24863. * + If there is the same concrete dim name defined in `this.dimensions`, it means that concrete name.
  24864. * + If not, it will be converted to a number, which means the index of the dimension.
  24865. * (why? because of the backward compatbility. We have been tolerating number-like string in
  24866. * dimension setting, although now it seems that it is not a good idea.)
  24867. * For example, `visualMap[i].dimension: "1"` is the same meaning as `visualMap[i].dimension: 1`,
  24868. * if no dimension name is defined as `"1"`.
  24869. * + If dim is a not-number-like string, it means the concrete dim name.
  24870. * For example, it can be be default name `"x"`, `"y"`, `"z"`, `"lng"`, `"lat"`, `"angle"`, `"radius"`,
  24871. * or customized in `dimensions` property of option like `"age"`.
  24872. *
  24873. * Get dimension name
  24874. * @param {string|number} dim See above.
  24875. * @return {string} Concrete dim name.
  24876. */
  24877. listProto.getDimension = function (dim) {
  24878. if (typeof dim === 'number' // If being a number-like string but not being defined a dimension name.
  24879. || !isNaN(dim) && !this._dimensionInfos.hasOwnProperty(dim)) {
  24880. dim = this.dimensions[dim];
  24881. }
  24882. return dim;
  24883. };
  24884. /**
  24885. * Get type and calculation info of particular dimension
  24886. * @param {string|number} dim
  24887. * Dimension can be concrete names like x, y, z, lng, lat, angle, radius
  24888. * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius'
  24889. */
  24890. listProto.getDimensionInfo = function (dim) {
  24891. // Do not clone, because there may be categories in dimInfo.
  24892. return this._dimensionInfos[this.getDimension(dim)];
  24893. };
  24894. /**
  24895. * @return {Array.<string>} concrete dimension name list on coord.
  24896. */
  24897. listProto.getDimensionsOnCoord = function () {
  24898. return this._dimensionsSummary.dataDimsOnCoord.slice();
  24899. };
  24900. /**
  24901. * @param {string} coordDim
  24902. * @param {number} [idx] A coordDim may map to more than one data dim.
  24903. * If idx is `true`, return a array of all mapped dims.
  24904. * If idx is not specified, return the first dim not extra.
  24905. * @return {string|Array.<string>} concrete data dim.
  24906. * If idx is number, and not found, return null/undefined.
  24907. * If idx is `true`, and not found, return empty array (always return array).
  24908. */
  24909. listProto.mapDimension = function (coordDim, idx) {
  24910. var dimensionsSummary = this._dimensionsSummary;
  24911. if (idx == null) {
  24912. return dimensionsSummary.encodeFirstDimNotExtra[coordDim];
  24913. }
  24914. var dims = dimensionsSummary.encode[coordDim];
  24915. return idx === true // always return array if idx is `true`
  24916. ? (dims || []).slice() : dims && dims[idx];
  24917. };
  24918. /**
  24919. * Initialize from data
  24920. * @param {Array.<Object|number|Array>} data source or data or data provider.
  24921. * @param {Array.<string>} [nameLIst] The name of a datum is used on data diff and
  24922. * defualt label/tooltip.
  24923. * A name can be specified in encode.itemName,
  24924. * or dataItem.name (only for series option data),
  24925. * or provided in nameList from outside.
  24926. * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number
  24927. */
  24928. listProto.initData = function (data, nameList, dimValueGetter) {
  24929. var notProvider = Source.isInstance(data) || isArrayLike(data);
  24930. if (notProvider) {
  24931. data = new DefaultDataProvider(data, this.dimensions.length);
  24932. }
  24933. this._rawData = data; // Clear
  24934. this._storage = {};
  24935. this._indices = null;
  24936. this._nameList = nameList || [];
  24937. this._idList = [];
  24938. this._nameRepeatCount = {};
  24939. if (!dimValueGetter) {
  24940. this.hasItemOption = false;
  24941. }
  24942. /**
  24943. * @readOnly
  24944. */
  24945. this.defaultDimValueGetter = defaultDimValueGetters[this._rawData.getSource().sourceFormat]; // Default dim value getter
  24946. this._dimValueGetter = dimValueGetter = dimValueGetter || this.defaultDimValueGetter;
  24947. this._dimValueGetterArrayRows = defaultDimValueGetters.arrayRows; // Reset raw extent.
  24948. this._rawExtent = {};
  24949. this._initDataFromProvider(0, data.count()); // If data has no item option.
  24950. if (data.pure) {
  24951. this.hasItemOption = false;
  24952. }
  24953. };
  24954. listProto.getProvider = function () {
  24955. return this._rawData;
  24956. };
  24957. /**
  24958. * Caution: Can be only called on raw data (before `this._indices` created).
  24959. */
  24960. listProto.appendData = function (data) {
  24961. var rawData = this._rawData;
  24962. var start = this.count();
  24963. rawData.appendData(data);
  24964. var end = rawData.count();
  24965. if (!rawData.persistent) {
  24966. end += start;
  24967. }
  24968. this._initDataFromProvider(start, end);
  24969. };
  24970. /**
  24971. * Caution: Can be only called on raw data (before `this._indices` created).
  24972. * This method does not modify `rawData` (`dataProvider`), but only
  24973. * add values to storage.
  24974. *
  24975. * The final count will be increased by `Math.max(values.length, names.length)`.
  24976. *
  24977. * @param {Array.<Array.<*>>} values That is the SourceType: 'arrayRows', like
  24978. * [
  24979. * [12, 33, 44],
  24980. * [NaN, 43, 1],
  24981. * ['-', 'asdf', 0]
  24982. * ]
  24983. * Each item is exaclty cooresponding to a dimension.
  24984. * @param {Array.<string>} [names]
  24985. */
  24986. listProto.appendValues = function (values, names) {
  24987. var chunkSize = this._chunkSize;
  24988. var storage = this._storage;
  24989. var dimensions = this.dimensions;
  24990. var dimLen = dimensions.length;
  24991. var rawExtent = this._rawExtent;
  24992. var start = this.count();
  24993. var end = start + Math.max(values.length, names ? names.length : 0);
  24994. var originalChunkCount = this._chunkCount;
  24995. for (var i = 0; i < dimLen; i++) {
  24996. var dim = dimensions[i];
  24997. if (!rawExtent[dim]) {
  24998. rawExtent[dim] = getInitialExtent();
  24999. }
  25000. if (!storage[dim]) {
  25001. storage[dim] = [];
  25002. }
  25003. prepareChunks(storage, this._dimensionInfos[dim], chunkSize, originalChunkCount, end);
  25004. this._chunkCount = storage[dim].length;
  25005. }
  25006. var emptyDataItem = new Array(dimLen);
  25007. for (var idx = start; idx < end; idx++) {
  25008. var sourceIdx = idx - start;
  25009. var chunkIndex = Math.floor(idx / chunkSize);
  25010. var chunkOffset = idx % chunkSize; // Store the data by dimensions
  25011. for (var k = 0; k < dimLen; k++) {
  25012. var dim = dimensions[k];
  25013. var val = this._dimValueGetterArrayRows(values[sourceIdx] || emptyDataItem, dim, sourceIdx, k);
  25014. storage[dim][chunkIndex][chunkOffset] = val;
  25015. var dimRawExtent = rawExtent[dim];
  25016. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25017. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25018. }
  25019. if (names) {
  25020. this._nameList[idx] = names[sourceIdx];
  25021. }
  25022. }
  25023. this._rawCount = this._count = end; // Reset data extent
  25024. this._extent = {};
  25025. prepareInvertedIndex(this);
  25026. };
  25027. listProto._initDataFromProvider = function (start, end) {
  25028. // Optimize.
  25029. if (start >= end) {
  25030. return;
  25031. }
  25032. var chunkSize = this._chunkSize;
  25033. var rawData = this._rawData;
  25034. var storage = this._storage;
  25035. var dimensions = this.dimensions;
  25036. var dimLen = dimensions.length;
  25037. var dimensionInfoMap = this._dimensionInfos;
  25038. var nameList = this._nameList;
  25039. var idList = this._idList;
  25040. var rawExtent = this._rawExtent;
  25041. var nameRepeatCount = this._nameRepeatCount = {};
  25042. var nameDimIdx;
  25043. var originalChunkCount = this._chunkCount;
  25044. for (var i = 0; i < dimLen; i++) {
  25045. var dim = dimensions[i];
  25046. if (!rawExtent[dim]) {
  25047. rawExtent[dim] = getInitialExtent();
  25048. }
  25049. var dimInfo = dimensionInfoMap[dim];
  25050. if (dimInfo.otherDims.itemName === 0) {
  25051. nameDimIdx = this._nameDimIdx = i;
  25052. }
  25053. if (dimInfo.otherDims.itemId === 0) {
  25054. this._idDimIdx = i;
  25055. }
  25056. if (!storage[dim]) {
  25057. storage[dim] = [];
  25058. }
  25059. prepareChunks(storage, dimInfo, chunkSize, originalChunkCount, end);
  25060. this._chunkCount = storage[dim].length;
  25061. }
  25062. var dataItem = new Array(dimLen);
  25063. for (var idx = start; idx < end; idx++) {
  25064. // NOTICE: Try not to write things into dataItem
  25065. dataItem = rawData.getItem(idx, dataItem); // Each data item is value
  25066. // [1, 2]
  25067. // 2
  25068. // Bar chart, line chart which uses category axis
  25069. // only gives the 'y' value. 'x' value is the indices of category
  25070. // Use a tempValue to normalize the value to be a (x, y) value
  25071. var chunkIndex = Math.floor(idx / chunkSize);
  25072. var chunkOffset = idx % chunkSize; // Store the data by dimensions
  25073. for (var k = 0; k < dimLen; k++) {
  25074. var dim = dimensions[k];
  25075. var dimStorage = storage[dim][chunkIndex]; // PENDING NULL is empty or zero
  25076. var val = this._dimValueGetter(dataItem, dim, idx, k);
  25077. dimStorage[chunkOffset] = val;
  25078. var dimRawExtent = rawExtent[dim];
  25079. val < dimRawExtent[0] && (dimRawExtent[0] = val);
  25080. val > dimRawExtent[1] && (dimRawExtent[1] = val);
  25081. } // ??? FIXME not check by pure but sourceFormat?
  25082. // TODO refactor these logic.
  25083. if (!rawData.pure) {
  25084. var name = nameList[idx];
  25085. if (dataItem && name == null) {
  25086. // If dataItem is {name: ...}, it has highest priority.
  25087. // That is appropriate for many common cases.
  25088. if (dataItem.name != null) {
  25089. // There is no other place to persistent dataItem.name,
  25090. // so save it to nameList.
  25091. nameList[idx] = name = dataItem.name;
  25092. } else if (nameDimIdx != null) {
  25093. var nameDim = dimensions[nameDimIdx];
  25094. var nameDimChunk = storage[nameDim][chunkIndex];
  25095. if (nameDimChunk) {
  25096. name = nameDimChunk[chunkOffset];
  25097. var ordinalMeta = dimensionInfoMap[nameDim].ordinalMeta;
  25098. if (ordinalMeta && ordinalMeta.categories.length) {
  25099. name = ordinalMeta.categories[name];
  25100. }
  25101. }
  25102. }
  25103. } // Try using the id in option
  25104. // id or name is used on dynamical data, mapping old and new items.
  25105. var id = dataItem == null ? null : dataItem.id;
  25106. if (id == null && name != null) {
  25107. // Use name as id and add counter to avoid same name
  25108. nameRepeatCount[name] = nameRepeatCount[name] || 0;
  25109. id = name;
  25110. if (nameRepeatCount[name] > 0) {
  25111. id += '__ec__' + nameRepeatCount[name];
  25112. }
  25113. nameRepeatCount[name]++;
  25114. }
  25115. id != null && (idList[idx] = id);
  25116. }
  25117. }
  25118. if (!rawData.persistent && rawData.clean) {
  25119. // Clean unused data if data source is typed array.
  25120. rawData.clean();
  25121. }
  25122. this._rawCount = this._count = end; // Reset data extent
  25123. this._extent = {};
  25124. prepareInvertedIndex(this);
  25125. };
  25126. function prepareChunks(storage, dimInfo, chunkSize, chunkCount, end) {
  25127. var DataCtor = dataCtors[dimInfo.type];
  25128. var lastChunkIndex = chunkCount - 1;
  25129. var dim = dimInfo.name;
  25130. var resizeChunkArray = storage[dim][lastChunkIndex];
  25131. if (resizeChunkArray && resizeChunkArray.length < chunkSize) {
  25132. var newStore = new DataCtor(Math.min(end - lastChunkIndex * chunkSize, chunkSize)); // The cost of the copy is probably inconsiderable
  25133. // within the initial chunkSize.
  25134. for (var j = 0; j < resizeChunkArray.length; j++) {
  25135. newStore[j] = resizeChunkArray[j];
  25136. }
  25137. storage[dim][lastChunkIndex] = newStore;
  25138. } // Create new chunks.
  25139. for (var k = chunkCount * chunkSize; k < end; k += chunkSize) {
  25140. storage[dim].push(new DataCtor(Math.min(end - k, chunkSize)));
  25141. }
  25142. }
  25143. function prepareInvertedIndex(list) {
  25144. var invertedIndicesMap = list._invertedIndicesMap;
  25145. each$1(invertedIndicesMap, function (invertedIndices, dim) {
  25146. var dimInfo = list._dimensionInfos[dim]; // Currently, only dimensions that has ordinalMeta can create inverted indices.
  25147. var ordinalMeta = dimInfo.ordinalMeta;
  25148. if (ordinalMeta) {
  25149. invertedIndices = invertedIndicesMap[dim] = new CtorInt32Array(ordinalMeta.categories.length); // The default value of TypedArray is 0. To avoid miss
  25150. // mapping to 0, we should set it as INDEX_NOT_FOUND.
  25151. for (var i = 0; i < invertedIndices.length; i++) {
  25152. invertedIndices[i] = INDEX_NOT_FOUND;
  25153. }
  25154. for (var i = 0; i < list._count; i++) {
  25155. // Only support the case that all values are distinct.
  25156. invertedIndices[list.get(dim, i)] = i;
  25157. }
  25158. }
  25159. });
  25160. }
  25161. function getRawValueFromStore(list, dimIndex, rawIndex) {
  25162. var val;
  25163. if (dimIndex != null) {
  25164. var chunkSize = list._chunkSize;
  25165. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25166. var chunkOffset = rawIndex % chunkSize;
  25167. var dim = list.dimensions[dimIndex];
  25168. var chunk = list._storage[dim][chunkIndex];
  25169. if (chunk) {
  25170. val = chunk[chunkOffset];
  25171. var ordinalMeta = list._dimensionInfos[dim].ordinalMeta;
  25172. if (ordinalMeta && ordinalMeta.categories.length) {
  25173. val = ordinalMeta.categories[val];
  25174. }
  25175. }
  25176. }
  25177. return val;
  25178. }
  25179. /**
  25180. * @return {number}
  25181. */
  25182. listProto.count = function () {
  25183. return this._count;
  25184. };
  25185. listProto.getIndices = function () {
  25186. var newIndices;
  25187. var indices = this._indices;
  25188. if (indices) {
  25189. var Ctor = indices.constructor;
  25190. var thisCount = this._count; // `new Array(a, b, c)` is different from `new Uint32Array(a, b, c)`.
  25191. if (Ctor === Array) {
  25192. newIndices = new Ctor(thisCount);
  25193. for (var i = 0; i < thisCount; i++) {
  25194. newIndices[i] = indices[i];
  25195. }
  25196. } else {
  25197. newIndices = new Ctor(indices.buffer, 0, thisCount);
  25198. }
  25199. } else {
  25200. var Ctor = getIndicesCtor(this);
  25201. var newIndices = new Ctor(this.count());
  25202. for (var i = 0; i < newIndices.length; i++) {
  25203. newIndices[i] = i;
  25204. }
  25205. }
  25206. return newIndices;
  25207. };
  25208. /**
  25209. * Get value. Return NaN if idx is out of range.
  25210. * @param {string} dim Dim must be concrete name.
  25211. * @param {number} idx
  25212. * @param {boolean} stack
  25213. * @return {number}
  25214. */
  25215. listProto.get = function (dim, idx
  25216. /*, stack */
  25217. ) {
  25218. if (!(idx >= 0 && idx < this._count)) {
  25219. return NaN;
  25220. }
  25221. var storage = this._storage;
  25222. if (!storage[dim]) {
  25223. // TODO Warn ?
  25224. return NaN;
  25225. }
  25226. idx = this.getRawIndex(idx);
  25227. var chunkIndex = Math.floor(idx / this._chunkSize);
  25228. var chunkOffset = idx % this._chunkSize;
  25229. var chunkStore = storage[dim][chunkIndex];
  25230. var value = chunkStore[chunkOffset]; // FIXME ordinal data type is not stackable
  25231. // if (stack) {
  25232. // var dimensionInfo = this._dimensionInfos[dim];
  25233. // if (dimensionInfo && dimensionInfo.stackable) {
  25234. // var stackedOn = this.stackedOn;
  25235. // while (stackedOn) {
  25236. // // Get no stacked data of stacked on
  25237. // var stackedValue = stackedOn.get(dim, idx);
  25238. // // Considering positive stack, negative stack and empty data
  25239. // if ((value >= 0 && stackedValue > 0) // Positive stack
  25240. // || (value <= 0 && stackedValue < 0) // Negative stack
  25241. // ) {
  25242. // value += stackedValue;
  25243. // }
  25244. // stackedOn = stackedOn.stackedOn;
  25245. // }
  25246. // }
  25247. // }
  25248. return value;
  25249. };
  25250. /**
  25251. * @param {string} dim concrete dim
  25252. * @param {number} rawIndex
  25253. * @return {number|string}
  25254. */
  25255. listProto.getByRawIndex = function (dim, rawIdx) {
  25256. if (!(rawIdx >= 0 && rawIdx < this._rawCount)) {
  25257. return NaN;
  25258. }
  25259. var dimStore = this._storage[dim];
  25260. if (!dimStore) {
  25261. // TODO Warn ?
  25262. return NaN;
  25263. }
  25264. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25265. var chunkOffset = rawIdx % this._chunkSize;
  25266. var chunkStore = dimStore[chunkIndex];
  25267. return chunkStore[chunkOffset];
  25268. };
  25269. /**
  25270. * FIXME Use `get` on chrome maybe slow(in filterSelf and selectRange).
  25271. * Hack a much simpler _getFast
  25272. * @private
  25273. */
  25274. listProto._getFast = function (dim, rawIdx) {
  25275. var chunkIndex = Math.floor(rawIdx / this._chunkSize);
  25276. var chunkOffset = rawIdx % this._chunkSize;
  25277. var chunkStore = this._storage[dim][chunkIndex];
  25278. return chunkStore[chunkOffset];
  25279. };
  25280. /**
  25281. * Get value for multi dimensions.
  25282. * @param {Array.<string>} [dimensions] If ignored, using all dimensions.
  25283. * @param {number} idx
  25284. * @return {number}
  25285. */
  25286. listProto.getValues = function (dimensions, idx
  25287. /*, stack */
  25288. ) {
  25289. var values = [];
  25290. if (!isArray(dimensions)) {
  25291. // stack = idx;
  25292. idx = dimensions;
  25293. dimensions = this.dimensions;
  25294. }
  25295. for (var i = 0, len = dimensions.length; i < len; i++) {
  25296. values.push(this.get(dimensions[i], idx
  25297. /*, stack */
  25298. ));
  25299. }
  25300. return values;
  25301. };
  25302. /**
  25303. * If value is NaN. Inlcuding '-'
  25304. * Only check the coord dimensions.
  25305. * @param {string} dim
  25306. * @param {number} idx
  25307. * @return {number}
  25308. */
  25309. listProto.hasValue = function (idx) {
  25310. var dataDimsOnCoord = this._dimensionsSummary.dataDimsOnCoord;
  25311. for (var i = 0, len = dataDimsOnCoord.length; i < len; i++) {
  25312. // Ordinal type originally can be string or number.
  25313. // But when an ordinal type is used on coord, it can
  25314. // not be string but only number. So we can also use isNaN.
  25315. if (isNaN(this.get(dataDimsOnCoord[i], idx))) {
  25316. return false;
  25317. }
  25318. }
  25319. return true;
  25320. };
  25321. /**
  25322. * Get extent of data in one dimension
  25323. * @param {string} dim
  25324. * @param {boolean} stack
  25325. */
  25326. listProto.getDataExtent = function (dim
  25327. /*, stack */
  25328. ) {
  25329. // Make sure use concrete dim as cache name.
  25330. dim = this.getDimension(dim);
  25331. var dimData = this._storage[dim];
  25332. var initialExtent = getInitialExtent(); // stack = !!((stack || false) && this.getCalculationInfo(dim));
  25333. if (!dimData) {
  25334. return initialExtent;
  25335. } // Make more strict checkings to ensure hitting cache.
  25336. var currEnd = this.count(); // var cacheName = [dim, !!stack].join('_');
  25337. // var cacheName = dim;
  25338. // Consider the most cases when using data zoom, `getDataExtent`
  25339. // happened before filtering. We cache raw extent, which is not
  25340. // necessary to be cleared and recalculated when restore data.
  25341. var useRaw = !this._indices; // && !stack;
  25342. var dimExtent;
  25343. if (useRaw) {
  25344. return this._rawExtent[dim].slice();
  25345. }
  25346. dimExtent = this._extent[dim];
  25347. if (dimExtent) {
  25348. return dimExtent.slice();
  25349. }
  25350. dimExtent = initialExtent;
  25351. var min = dimExtent[0];
  25352. var max = dimExtent[1];
  25353. for (var i = 0; i < currEnd; i++) {
  25354. // var value = stack ? this.get(dim, i, true) : this._getFast(dim, this.getRawIndex(i));
  25355. var value = this._getFast(dim, this.getRawIndex(i));
  25356. value < min && (min = value);
  25357. value > max && (max = value);
  25358. }
  25359. dimExtent = [min, max];
  25360. this._extent[dim] = dimExtent;
  25361. return dimExtent;
  25362. };
  25363. /**
  25364. * Optimize for the scenario that data is filtered by a given extent.
  25365. * Consider that if data amount is more than hundreds of thousand,
  25366. * extent calculation will cost more than 10ms and the cache will
  25367. * be erased because of the filtering.
  25368. */
  25369. listProto.getApproximateExtent = function (dim
  25370. /*, stack */
  25371. ) {
  25372. dim = this.getDimension(dim);
  25373. return this._approximateExtent[dim] || this.getDataExtent(dim
  25374. /*, stack */
  25375. );
  25376. };
  25377. listProto.setApproximateExtent = function (extent, dim
  25378. /*, stack */
  25379. ) {
  25380. dim = this.getDimension(dim);
  25381. this._approximateExtent[dim] = extent.slice();
  25382. };
  25383. /**
  25384. * @param {string} key
  25385. * @return {*}
  25386. */
  25387. listProto.getCalculationInfo = function (key) {
  25388. return this._calculationInfo[key];
  25389. };
  25390. /**
  25391. * @param {string|Object} key or k-v object
  25392. * @param {*} [value]
  25393. */
  25394. listProto.setCalculationInfo = function (key, value) {
  25395. isObject$4(key) ? extend(this._calculationInfo, key) : this._calculationInfo[key] = value;
  25396. };
  25397. /**
  25398. * Get sum of data in one dimension
  25399. * @param {string} dim
  25400. */
  25401. listProto.getSum = function (dim
  25402. /*, stack */
  25403. ) {
  25404. var dimData = this._storage[dim];
  25405. var sum = 0;
  25406. if (dimData) {
  25407. for (var i = 0, len = this.count(); i < len; i++) {
  25408. var value = this.get(dim, i
  25409. /*, stack */
  25410. );
  25411. if (!isNaN(value)) {
  25412. sum += value;
  25413. }
  25414. }
  25415. }
  25416. return sum;
  25417. };
  25418. /**
  25419. * Get median of data in one dimension
  25420. * @param {string} dim
  25421. */
  25422. listProto.getMedian = function (dim
  25423. /*, stack */
  25424. ) {
  25425. var dimDataArray = []; // map all data of one dimension
  25426. this.each(dim, function (val, idx) {
  25427. if (!isNaN(val)) {
  25428. dimDataArray.push(val);
  25429. }
  25430. }); // TODO
  25431. // Use quick select?
  25432. // immutability & sort
  25433. var sortedDimDataArray = [].concat(dimDataArray).sort(function (a, b) {
  25434. return a - b;
  25435. });
  25436. var len = this.count(); // calculate median
  25437. return len === 0 ? 0 : len % 2 === 1 ? sortedDimDataArray[(len - 1) / 2] : (sortedDimDataArray[len / 2] + sortedDimDataArray[len / 2 - 1]) / 2;
  25438. }; // /**
  25439. // * Retreive the index with given value
  25440. // * @param {string} dim Concrete dimension.
  25441. // * @param {number} value
  25442. // * @return {number}
  25443. // */
  25444. // Currently incorrect: should return dataIndex but not rawIndex.
  25445. // Do not fix it until this method is to be used somewhere.
  25446. // FIXME Precision of float value
  25447. // listProto.indexOf = function (dim, value) {
  25448. // var storage = this._storage;
  25449. // var dimData = storage[dim];
  25450. // var chunkSize = this._chunkSize;
  25451. // if (dimData) {
  25452. // for (var i = 0, len = this.count(); i < len; i++) {
  25453. // var chunkIndex = Math.floor(i / chunkSize);
  25454. // var chunkOffset = i % chunkSize;
  25455. // if (dimData[chunkIndex][chunkOffset] === value) {
  25456. // return i;
  25457. // }
  25458. // }
  25459. // }
  25460. // return -1;
  25461. // };
  25462. /**
  25463. * Only support the dimension which inverted index created.
  25464. * Do not support other cases until required.
  25465. * @param {string} concrete dim
  25466. * @param {number|string} value
  25467. * @return {number} rawIndex
  25468. */
  25469. listProto.rawIndexOf = function (dim, value) {
  25470. var invertedIndices = dim && this._invertedIndicesMap[dim];
  25471. var rawIndex = invertedIndices[value];
  25472. if (rawIndex == null || isNaN(rawIndex)) {
  25473. return INDEX_NOT_FOUND;
  25474. }
  25475. return rawIndex;
  25476. };
  25477. /**
  25478. * Retreive the index with given name
  25479. * @param {number} idx
  25480. * @param {number} name
  25481. * @return {number}
  25482. */
  25483. listProto.indexOfName = function (name) {
  25484. for (var i = 0, len = this.count(); i < len; i++) {
  25485. if (this.getName(i) === name) {
  25486. return i;
  25487. }
  25488. }
  25489. return -1;
  25490. };
  25491. /**
  25492. * Retreive the index with given raw data index
  25493. * @param {number} idx
  25494. * @param {number} name
  25495. * @return {number}
  25496. */
  25497. listProto.indexOfRawIndex = function (rawIndex) {
  25498. if (rawIndex >= this._rawCount || rawIndex < 0) {
  25499. return -1;
  25500. }
  25501. if (!this._indices) {
  25502. return rawIndex;
  25503. } // Indices are ascending
  25504. var indices = this._indices; // If rawIndex === dataIndex
  25505. var rawDataIndex = indices[rawIndex];
  25506. if (rawDataIndex != null && rawDataIndex < this._count && rawDataIndex === rawIndex) {
  25507. return rawIndex;
  25508. }
  25509. var left = 0;
  25510. var right = this._count - 1;
  25511. while (left <= right) {
  25512. var mid = (left + right) / 2 | 0;
  25513. if (indices[mid] < rawIndex) {
  25514. left = mid + 1;
  25515. } else if (indices[mid] > rawIndex) {
  25516. right = mid - 1;
  25517. } else {
  25518. return mid;
  25519. }
  25520. }
  25521. return -1;
  25522. };
  25523. /**
  25524. * Retreive the index of nearest value
  25525. * @param {string} dim
  25526. * @param {number} value
  25527. * @param {number} [maxDistance=Infinity]
  25528. * @return {Array.<number>} If and only if multiple indices has
  25529. * the same value, they are put to the result.
  25530. */
  25531. listProto.indicesOfNearest = function (dim, value, maxDistance) {
  25532. var storage = this._storage;
  25533. var dimData = storage[dim];
  25534. var nearestIndices = [];
  25535. if (!dimData) {
  25536. return nearestIndices;
  25537. }
  25538. if (maxDistance == null) {
  25539. maxDistance = Infinity;
  25540. }
  25541. var minDist = Infinity;
  25542. var minDiff = -1;
  25543. var nearestIndicesLen = 0; // Check the test case of `test/ut/spec/data/List.js`.
  25544. for (var i = 0, len = this.count(); i < len; i++) {
  25545. var diff = value - this.get(dim, i);
  25546. var dist = Math.abs(diff);
  25547. if (dist <= maxDistance) {
  25548. // When the `value` is at the middle of `this.get(dim, i)` and `this.get(dim, i+1)`,
  25549. // we'd better not push both of them to `nearestIndices`, otherwise it is easy to
  25550. // get more than one item in `nearestIndices` (more specifically, in `tooltip`).
  25551. // So we chose the one that `diff >= 0` in this csae.
  25552. // But if `this.get(dim, i)` and `this.get(dim, j)` get the same value, both of them
  25553. // should be push to `nearestIndices`.
  25554. if (dist < minDist || dist === minDist && diff >= 0 && minDiff < 0) {
  25555. minDist = dist;
  25556. minDiff = diff;
  25557. nearestIndicesLen = 0;
  25558. }
  25559. if (diff === minDiff) {
  25560. nearestIndices[nearestIndicesLen++] = i;
  25561. }
  25562. }
  25563. }
  25564. nearestIndices.length = nearestIndicesLen;
  25565. return nearestIndices;
  25566. };
  25567. /**
  25568. * Get raw data index
  25569. * @param {number} idx
  25570. * @return {number}
  25571. */
  25572. listProto.getRawIndex = getRawIndexWithoutIndices;
  25573. function getRawIndexWithoutIndices(idx) {
  25574. return idx;
  25575. }
  25576. function getRawIndexWithIndices(idx) {
  25577. if (idx < this._count && idx >= 0) {
  25578. return this._indices[idx];
  25579. }
  25580. return -1;
  25581. }
  25582. /**
  25583. * Get raw data item
  25584. * @param {number} idx
  25585. * @return {number}
  25586. */
  25587. listProto.getRawDataItem = function (idx) {
  25588. if (!this._rawData.persistent) {
  25589. var val = [];
  25590. for (var i = 0; i < this.dimensions.length; i++) {
  25591. var dim = this.dimensions[i];
  25592. val.push(this.get(dim, idx));
  25593. }
  25594. return val;
  25595. } else {
  25596. return this._rawData.getItem(this.getRawIndex(idx));
  25597. }
  25598. };
  25599. /**
  25600. * @param {number} idx
  25601. * @param {boolean} [notDefaultIdx=false]
  25602. * @return {string}
  25603. */
  25604. listProto.getName = function (idx) {
  25605. var rawIndex = this.getRawIndex(idx);
  25606. return this._nameList[rawIndex] || getRawValueFromStore(this, this._nameDimIdx, rawIndex) || '';
  25607. };
  25608. /**
  25609. * @param {number} idx
  25610. * @param {boolean} [notDefaultIdx=false]
  25611. * @return {string}
  25612. */
  25613. listProto.getId = function (idx) {
  25614. return getId(this, this.getRawIndex(idx));
  25615. };
  25616. function getId(list, rawIndex) {
  25617. var id = list._idList[rawIndex];
  25618. if (id == null) {
  25619. id = getRawValueFromStore(list, list._idDimIdx, rawIndex);
  25620. }
  25621. if (id == null) {
  25622. // FIXME Check the usage in graph, should not use prefix.
  25623. id = ID_PREFIX + rawIndex;
  25624. }
  25625. return id;
  25626. }
  25627. function normalizeDimensions(dimensions) {
  25628. if (!isArray(dimensions)) {
  25629. dimensions = [dimensions];
  25630. }
  25631. return dimensions;
  25632. }
  25633. /**
  25634. * Data iteration
  25635. * @param {string|Array.<string>}
  25636. * @param {Function} cb
  25637. * @param {*} [context=this]
  25638. *
  25639. * @example
  25640. * list.each('x', function (x, idx) {});
  25641. * list.each(['x', 'y'], function (x, y, idx) {});
  25642. * list.each(function (idx) {})
  25643. */
  25644. listProto.each = function (dims, cb, context, contextCompat) {
  25645. 'use strict';
  25646. if (!this._count) {
  25647. return;
  25648. }
  25649. if (typeof dims === 'function') {
  25650. contextCompat = context;
  25651. context = cb;
  25652. cb = dims;
  25653. dims = [];
  25654. } // contextCompat just for compat echarts3
  25655. context = context || contextCompat || this;
  25656. dims = map(normalizeDimensions(dims), this.getDimension, this);
  25657. var dimSize = dims.length;
  25658. for (var i = 0; i < this.count(); i++) {
  25659. // Simple optimization
  25660. switch (dimSize) {
  25661. case 0:
  25662. cb.call(context, i);
  25663. break;
  25664. case 1:
  25665. cb.call(context, this.get(dims[0], i), i);
  25666. break;
  25667. case 2:
  25668. cb.call(context, this.get(dims[0], i), this.get(dims[1], i), i);
  25669. break;
  25670. default:
  25671. var k = 0;
  25672. var value = [];
  25673. for (; k < dimSize; k++) {
  25674. value[k] = this.get(dims[k], i);
  25675. } // Index
  25676. value[k] = i;
  25677. cb.apply(context, value);
  25678. }
  25679. }
  25680. };
  25681. /**
  25682. * Data filter
  25683. * @param {string|Array.<string>}
  25684. * @param {Function} cb
  25685. * @param {*} [context=this]
  25686. */
  25687. listProto.filterSelf = function (dimensions, cb, context, contextCompat) {
  25688. 'use strict';
  25689. if (!this._count) {
  25690. return;
  25691. }
  25692. if (typeof dimensions === 'function') {
  25693. contextCompat = context;
  25694. context = cb;
  25695. cb = dimensions;
  25696. dimensions = [];
  25697. } // contextCompat just for compat echarts3
  25698. context = context || contextCompat || this;
  25699. dimensions = map(normalizeDimensions(dimensions), this.getDimension, this);
  25700. var count = this.count();
  25701. var Ctor = getIndicesCtor(this);
  25702. var newIndices = new Ctor(count);
  25703. var value = [];
  25704. var dimSize = dimensions.length;
  25705. var offset = 0;
  25706. var dim0 = dimensions[0];
  25707. for (var i = 0; i < count; i++) {
  25708. var keep;
  25709. var rawIdx = this.getRawIndex(i); // Simple optimization
  25710. if (dimSize === 0) {
  25711. keep = cb.call(context, i);
  25712. } else if (dimSize === 1) {
  25713. var val = this._getFast(dim0, rawIdx);
  25714. keep = cb.call(context, val, i);
  25715. } else {
  25716. for (var k = 0; k < dimSize; k++) {
  25717. value[k] = this._getFast(dim0, rawIdx);
  25718. }
  25719. value[k] = i;
  25720. keep = cb.apply(context, value);
  25721. }
  25722. if (keep) {
  25723. newIndices[offset++] = rawIdx;
  25724. }
  25725. } // Set indices after filtered.
  25726. if (offset < count) {
  25727. this._indices = newIndices;
  25728. }
  25729. this._count = offset; // Reset data extent
  25730. this._extent = {};
  25731. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25732. return this;
  25733. };
  25734. /**
  25735. * Select data in range. (For optimization of filter)
  25736. * (Manually inline code, support 5 million data filtering in data zoom.)
  25737. */
  25738. listProto.selectRange = function (range) {
  25739. 'use strict';
  25740. if (!this._count) {
  25741. return;
  25742. }
  25743. var dimensions = [];
  25744. for (var dim in range) {
  25745. if (range.hasOwnProperty(dim)) {
  25746. dimensions.push(dim);
  25747. }
  25748. }
  25749. var dimSize = dimensions.length;
  25750. if (!dimSize) {
  25751. return;
  25752. }
  25753. var originalCount = this.count();
  25754. var Ctor = getIndicesCtor(this);
  25755. var newIndices = new Ctor(originalCount);
  25756. var offset = 0;
  25757. var dim0 = dimensions[0];
  25758. var min = range[dim0][0];
  25759. var max = range[dim0][1];
  25760. var quickFinished = false;
  25761. if (!this._indices) {
  25762. // Extreme optimization for common case. About 2x faster in chrome.
  25763. var idx = 0;
  25764. if (dimSize === 1) {
  25765. var dimStorage = this._storage[dimensions[0]];
  25766. for (var k = 0; k < this._chunkCount; k++) {
  25767. var chunkStorage = dimStorage[k];
  25768. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25769. for (var i = 0; i < len; i++) {
  25770. var val = chunkStorage[i]; // NaN will not be filtered. Consider the case, in line chart, empty
  25771. // value indicates the line should be broken. But for the case like
  25772. // scatter plot, a data item with empty value will not be rendered,
  25773. // but the axis extent may be effected if some other dim of the data
  25774. // item has value. Fortunately it is not a significant negative effect.
  25775. if (val >= min && val <= max || isNaN(val)) {
  25776. newIndices[offset++] = idx;
  25777. }
  25778. idx++;
  25779. }
  25780. }
  25781. quickFinished = true;
  25782. } else if (dimSize === 2) {
  25783. var dimStorage = this._storage[dim0];
  25784. var dimStorage2 = this._storage[dimensions[1]];
  25785. var min2 = range[dimensions[1]][0];
  25786. var max2 = range[dimensions[1]][1];
  25787. for (var k = 0; k < this._chunkCount; k++) {
  25788. var chunkStorage = dimStorage[k];
  25789. var chunkStorage2 = dimStorage2[k];
  25790. var len = Math.min(this._count - k * this._chunkSize, this._chunkSize);
  25791. for (var i = 0; i < len; i++) {
  25792. var val = chunkStorage[i];
  25793. var val2 = chunkStorage2[i]; // Do not filter NaN, see comment above.
  25794. if ((val >= min && val <= max || isNaN(val)) && (val2 >= min2 && val2 <= max2 || isNaN(val2))) {
  25795. newIndices[offset++] = idx;
  25796. }
  25797. idx++;
  25798. }
  25799. }
  25800. quickFinished = true;
  25801. }
  25802. }
  25803. if (!quickFinished) {
  25804. if (dimSize === 1) {
  25805. for (var i = 0; i < originalCount; i++) {
  25806. var rawIndex = this.getRawIndex(i);
  25807. var val = this._getFast(dim0, rawIndex); // Do not filter NaN, see comment above.
  25808. if (val >= min && val <= max || isNaN(val)) {
  25809. newIndices[offset++] = rawIndex;
  25810. }
  25811. }
  25812. } else {
  25813. for (var i = 0; i < originalCount; i++) {
  25814. var keep = true;
  25815. var rawIndex = this.getRawIndex(i);
  25816. for (var k = 0; k < dimSize; k++) {
  25817. var dimk = dimensions[k];
  25818. var val = this._getFast(dim, rawIndex); // Do not filter NaN, see comment above.
  25819. if (val < range[dimk][0] || val > range[dimk][1]) {
  25820. keep = false;
  25821. }
  25822. }
  25823. if (keep) {
  25824. newIndices[offset++] = this.getRawIndex(i);
  25825. }
  25826. }
  25827. }
  25828. } // Set indices after filtered.
  25829. if (offset < originalCount) {
  25830. this._indices = newIndices;
  25831. }
  25832. this._count = offset; // Reset data extent
  25833. this._extent = {};
  25834. this.getRawIndex = this._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25835. return this;
  25836. };
  25837. /**
  25838. * Data mapping to a plain array
  25839. * @param {string|Array.<string>} [dimensions]
  25840. * @param {Function} cb
  25841. * @param {*} [context=this]
  25842. * @return {Array}
  25843. */
  25844. listProto.mapArray = function (dimensions, cb, context, contextCompat) {
  25845. 'use strict';
  25846. if (typeof dimensions === 'function') {
  25847. contextCompat = context;
  25848. context = cb;
  25849. cb = dimensions;
  25850. dimensions = [];
  25851. } // contextCompat just for compat echarts3
  25852. context = context || contextCompat || this;
  25853. var result = [];
  25854. this.each(dimensions, function () {
  25855. result.push(cb && cb.apply(this, arguments));
  25856. }, context);
  25857. return result;
  25858. }; // Data in excludeDimensions is copied, otherwise transfered.
  25859. function cloneListForMapAndSample(original, excludeDimensions) {
  25860. var allDimensions = original.dimensions;
  25861. var list = new List(map(allDimensions, original.getDimensionInfo, original), original.hostModel); // FIXME If needs stackedOn, value may already been stacked
  25862. transferProperties(list, original);
  25863. var storage = list._storage = {};
  25864. var originalStorage = original._storage; // Init storage
  25865. for (var i = 0; i < allDimensions.length; i++) {
  25866. var dim = allDimensions[i];
  25867. if (originalStorage[dim]) {
  25868. // Notice that we do not reset invertedIndicesMap here, becuase
  25869. // there is no scenario of mapping or sampling ordinal dimension.
  25870. if (indexOf(excludeDimensions, dim) >= 0) {
  25871. storage[dim] = cloneDimStore(originalStorage[dim]);
  25872. list._rawExtent[dim] = getInitialExtent();
  25873. list._extent[dim] = null;
  25874. } else {
  25875. // Direct reference for other dimensions
  25876. storage[dim] = originalStorage[dim];
  25877. }
  25878. }
  25879. }
  25880. return list;
  25881. }
  25882. function cloneDimStore(originalDimStore) {
  25883. var newDimStore = new Array(originalDimStore.length);
  25884. for (var j = 0; j < originalDimStore.length; j++) {
  25885. newDimStore[j] = cloneChunk(originalDimStore[j]);
  25886. }
  25887. return newDimStore;
  25888. }
  25889. function getInitialExtent() {
  25890. return [Infinity, -Infinity];
  25891. }
  25892. /**
  25893. * Data mapping to a new List with given dimensions
  25894. * @param {string|Array.<string>} dimensions
  25895. * @param {Function} cb
  25896. * @param {*} [context=this]
  25897. * @return {Array}
  25898. */
  25899. listProto.map = function (dimensions, cb, context, contextCompat) {
  25900. 'use strict'; // contextCompat just for compat echarts3
  25901. context = context || contextCompat || this;
  25902. dimensions = map(normalizeDimensions(dimensions), this.getDimension, this);
  25903. var list = cloneListForMapAndSample(this, dimensions); // Following properties are all immutable.
  25904. // So we can reference to the same value
  25905. list._indices = this._indices;
  25906. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  25907. var storage = list._storage;
  25908. var tmpRetValue = [];
  25909. var chunkSize = this._chunkSize;
  25910. var dimSize = dimensions.length;
  25911. var dataCount = this.count();
  25912. var values = [];
  25913. var rawExtent = list._rawExtent;
  25914. for (var dataIndex = 0; dataIndex < dataCount; dataIndex++) {
  25915. for (var dimIndex = 0; dimIndex < dimSize; dimIndex++) {
  25916. values[dimIndex] = this.get(dimensions[dimIndex], dataIndex
  25917. /*, stack */
  25918. );
  25919. }
  25920. values[dimSize] = dataIndex;
  25921. var retValue = cb && cb.apply(context, values);
  25922. if (retValue != null) {
  25923. // a number or string (in oridinal dimension)?
  25924. if (typeof retValue !== 'object') {
  25925. tmpRetValue[0] = retValue;
  25926. retValue = tmpRetValue;
  25927. }
  25928. var rawIndex = this.getRawIndex(dataIndex);
  25929. var chunkIndex = Math.floor(rawIndex / chunkSize);
  25930. var chunkOffset = rawIndex % chunkSize;
  25931. for (var i = 0; i < retValue.length; i++) {
  25932. var dim = dimensions[i];
  25933. var val = retValue[i];
  25934. var rawExtentOnDim = rawExtent[dim];
  25935. var dimStore = storage[dim];
  25936. if (dimStore) {
  25937. dimStore[chunkIndex][chunkOffset] = val;
  25938. }
  25939. if (val < rawExtentOnDim[0]) {
  25940. rawExtentOnDim[0] = val;
  25941. }
  25942. if (val > rawExtentOnDim[1]) {
  25943. rawExtentOnDim[1] = val;
  25944. }
  25945. }
  25946. }
  25947. }
  25948. return list;
  25949. };
  25950. /**
  25951. * Large data down sampling on given dimension
  25952. * @param {string} dimension
  25953. * @param {number} rate
  25954. * @param {Function} sampleValue
  25955. * @param {Function} sampleIndex Sample index for name and id
  25956. */
  25957. listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) {
  25958. var list = cloneListForMapAndSample(this, [dimension]);
  25959. var targetStorage = list._storage;
  25960. var frameValues = [];
  25961. var frameSize = Math.floor(1 / rate);
  25962. var dimStore = targetStorage[dimension];
  25963. var len = this.count();
  25964. var chunkSize = this._chunkSize;
  25965. var rawExtentOnDim = list._rawExtent[dimension];
  25966. var newIndices = new (getIndicesCtor(this))(len);
  25967. var offset = 0;
  25968. for (var i = 0; i < len; i += frameSize) {
  25969. // Last frame
  25970. if (frameSize > len - i) {
  25971. frameSize = len - i;
  25972. frameValues.length = frameSize;
  25973. }
  25974. for (var k = 0; k < frameSize; k++) {
  25975. var dataIdx = this.getRawIndex(i + k);
  25976. var originalChunkIndex = Math.floor(dataIdx / chunkSize);
  25977. var originalChunkOffset = dataIdx % chunkSize;
  25978. frameValues[k] = dimStore[originalChunkIndex][originalChunkOffset];
  25979. }
  25980. var value = sampleValue(frameValues);
  25981. var sampleFrameIdx = this.getRawIndex(Math.min(i + sampleIndex(frameValues, value) || 0, len - 1));
  25982. var sampleChunkIndex = Math.floor(sampleFrameIdx / chunkSize);
  25983. var sampleChunkOffset = sampleFrameIdx % chunkSize; // Only write value on the filtered data
  25984. dimStore[sampleChunkIndex][sampleChunkOffset] = value;
  25985. if (value < rawExtentOnDim[0]) {
  25986. rawExtentOnDim[0] = value;
  25987. }
  25988. if (value > rawExtentOnDim[1]) {
  25989. rawExtentOnDim[1] = value;
  25990. }
  25991. newIndices[offset++] = sampleFrameIdx;
  25992. }
  25993. list._count = offset;
  25994. list._indices = newIndices;
  25995. list.getRawIndex = getRawIndexWithIndices;
  25996. return list;
  25997. };
  25998. /**
  25999. * Get model of one data item.
  26000. *
  26001. * @param {number} idx
  26002. */
  26003. // FIXME Model proxy ?
  26004. listProto.getItemModel = function (idx) {
  26005. var hostModel = this.hostModel;
  26006. return new Model(this.getRawDataItem(idx), hostModel, hostModel && hostModel.ecModel);
  26007. };
  26008. /**
  26009. * Create a data differ
  26010. * @param {module:echarts/data/List} otherList
  26011. * @return {module:echarts/data/DataDiffer}
  26012. */
  26013. listProto.diff = function (otherList) {
  26014. var thisList = this;
  26015. return new DataDiffer(otherList ? otherList.getIndices() : [], this.getIndices(), function (idx) {
  26016. return getId(otherList, idx);
  26017. }, function (idx) {
  26018. return getId(thisList, idx);
  26019. });
  26020. };
  26021. /**
  26022. * Get visual property.
  26023. * @param {string} key
  26024. */
  26025. listProto.getVisual = function (key) {
  26026. var visual = this._visual;
  26027. return visual && visual[key];
  26028. };
  26029. /**
  26030. * Set visual property
  26031. * @param {string|Object} key
  26032. * @param {*} [value]
  26033. *
  26034. * @example
  26035. * setVisual('color', color);
  26036. * setVisual({
  26037. * 'color': color
  26038. * });
  26039. */
  26040. listProto.setVisual = function (key, val) {
  26041. if (isObject$4(key)) {
  26042. for (var name in key) {
  26043. if (key.hasOwnProperty(name)) {
  26044. this.setVisual(name, key[name]);
  26045. }
  26046. }
  26047. return;
  26048. }
  26049. this._visual = this._visual || {};
  26050. this._visual[key] = val;
  26051. };
  26052. /**
  26053. * Set layout property.
  26054. * @param {string|Object} key
  26055. * @param {*} [val]
  26056. */
  26057. listProto.setLayout = function (key, val) {
  26058. if (isObject$4(key)) {
  26059. for (var name in key) {
  26060. if (key.hasOwnProperty(name)) {
  26061. this.setLayout(name, key[name]);
  26062. }
  26063. }
  26064. return;
  26065. }
  26066. this._layout[key] = val;
  26067. };
  26068. /**
  26069. * Get layout property.
  26070. * @param {string} key.
  26071. * @return {*}
  26072. */
  26073. listProto.getLayout = function (key) {
  26074. return this._layout[key];
  26075. };
  26076. /**
  26077. * Get layout of single data item
  26078. * @param {number} idx
  26079. */
  26080. listProto.getItemLayout = function (idx) {
  26081. return this._itemLayouts[idx];
  26082. };
  26083. /**
  26084. * Set layout of single data item
  26085. * @param {number} idx
  26086. * @param {Object} layout
  26087. * @param {boolean=} [merge=false]
  26088. */
  26089. listProto.setItemLayout = function (idx, layout, merge$$1) {
  26090. this._itemLayouts[idx] = merge$$1 ? extend(this._itemLayouts[idx] || {}, layout) : layout;
  26091. };
  26092. /**
  26093. * Clear all layout of single data item
  26094. */
  26095. listProto.clearItemLayouts = function () {
  26096. this._itemLayouts.length = 0;
  26097. };
  26098. /**
  26099. * Get visual property of single data item
  26100. * @param {number} idx
  26101. * @param {string} key
  26102. * @param {boolean} [ignoreParent=false]
  26103. */
  26104. listProto.getItemVisual = function (idx, key, ignoreParent) {
  26105. var itemVisual = this._itemVisuals[idx];
  26106. var val = itemVisual && itemVisual[key];
  26107. if (val == null && !ignoreParent) {
  26108. // Use global visual property
  26109. return this.getVisual(key);
  26110. }
  26111. return val;
  26112. };
  26113. /**
  26114. * Set visual property of single data item
  26115. *
  26116. * @param {number} idx
  26117. * @param {string|Object} key
  26118. * @param {*} [value]
  26119. *
  26120. * @example
  26121. * setItemVisual(0, 'color', color);
  26122. * setItemVisual(0, {
  26123. * 'color': color
  26124. * });
  26125. */
  26126. listProto.setItemVisual = function (idx, key, value) {
  26127. var itemVisual = this._itemVisuals[idx] || {};
  26128. var hasItemVisual = this.hasItemVisual;
  26129. this._itemVisuals[idx] = itemVisual;
  26130. if (isObject$4(key)) {
  26131. for (var name in key) {
  26132. if (key.hasOwnProperty(name)) {
  26133. itemVisual[name] = key[name];
  26134. hasItemVisual[name] = true;
  26135. }
  26136. }
  26137. return;
  26138. }
  26139. itemVisual[key] = value;
  26140. hasItemVisual[key] = true;
  26141. };
  26142. /**
  26143. * Clear itemVisuals and list visual.
  26144. */
  26145. listProto.clearAllVisual = function () {
  26146. this._visual = {};
  26147. this._itemVisuals = [];
  26148. this.hasItemVisual = {};
  26149. };
  26150. var setItemDataAndSeriesIndex = function (child) {
  26151. child.seriesIndex = this.seriesIndex;
  26152. child.dataIndex = this.dataIndex;
  26153. child.dataType = this.dataType;
  26154. };
  26155. /**
  26156. * Set graphic element relative to data. It can be set as null
  26157. * @param {number} idx
  26158. * @param {module:zrender/Element} [el]
  26159. */
  26160. listProto.setItemGraphicEl = function (idx, el) {
  26161. var hostModel = this.hostModel;
  26162. if (el) {
  26163. // Add data index and series index for indexing the data by element
  26164. // Useful in tooltip
  26165. el.dataIndex = idx;
  26166. el.dataType = this.dataType;
  26167. el.seriesIndex = hostModel && hostModel.seriesIndex;
  26168. if (el.type === 'group') {
  26169. el.traverse(setItemDataAndSeriesIndex, el);
  26170. }
  26171. }
  26172. this._graphicEls[idx] = el;
  26173. };
  26174. /**
  26175. * @param {number} idx
  26176. * @return {module:zrender/Element}
  26177. */
  26178. listProto.getItemGraphicEl = function (idx) {
  26179. return this._graphicEls[idx];
  26180. };
  26181. /**
  26182. * @param {Function} cb
  26183. * @param {*} context
  26184. */
  26185. listProto.eachItemGraphicEl = function (cb, context) {
  26186. each$1(this._graphicEls, function (el, idx) {
  26187. if (el) {
  26188. cb && cb.call(context, el, idx);
  26189. }
  26190. });
  26191. };
  26192. /**
  26193. * Shallow clone a new list except visual and layout properties, and graph elements.
  26194. * New list only change the indices.
  26195. */
  26196. listProto.cloneShallow = function (list) {
  26197. if (!list) {
  26198. var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this);
  26199. list = new List(dimensionInfoList, this.hostModel);
  26200. } // FIXME
  26201. list._storage = this._storage;
  26202. transferProperties(list, this); // Clone will not change the data extent and indices
  26203. if (this._indices) {
  26204. var Ctor = this._indices.constructor;
  26205. list._indices = new Ctor(this._indices);
  26206. } else {
  26207. list._indices = null;
  26208. }
  26209. list.getRawIndex = list._indices ? getRawIndexWithIndices : getRawIndexWithoutIndices;
  26210. return list;
  26211. };
  26212. /**
  26213. * Wrap some method to add more feature
  26214. * @param {string} methodName
  26215. * @param {Function} injectFunction
  26216. */
  26217. listProto.wrapMethod = function (methodName, injectFunction) {
  26218. var originalMethod = this[methodName];
  26219. if (typeof originalMethod !== 'function') {
  26220. return;
  26221. }
  26222. this.__wrappedMethods = this.__wrappedMethods || [];
  26223. this.__wrappedMethods.push(methodName);
  26224. this[methodName] = function () {
  26225. var res = originalMethod.apply(this, arguments);
  26226. return injectFunction.apply(this, [res].concat(slice(arguments)));
  26227. };
  26228. }; // Methods that create a new list based on this list should be listed here.
  26229. // Notice that those method should `RETURN` the new list.
  26230. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map']; // Methods that change indices of this list should be listed here.
  26231. listProto.CHANGABLE_METHODS = ['filterSelf', 'selectRange'];
  26232. /*
  26233. * Licensed to the Apache Software Foundation (ASF) under one
  26234. * or more contributor license agreements. See the NOTICE file
  26235. * distributed with this work for additional information
  26236. * regarding copyright ownership. The ASF licenses this file
  26237. * to you under the Apache License, Version 2.0 (the
  26238. * "License"); you may not use this file except in compliance
  26239. * with the License. You may obtain a copy of the License at
  26240. *
  26241. * http://www.apache.org/licenses/LICENSE-2.0
  26242. *
  26243. * Unless required by applicable law or agreed to in writing,
  26244. * software distributed under the License is distributed on an
  26245. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26246. * KIND, either express or implied. See the License for the
  26247. * specific language governing permissions and limitations
  26248. * under the License.
  26249. */
  26250. /**
  26251. * @deprecated
  26252. * Use `echarts/data/helper/createDimensions` instead.
  26253. */
  26254. /**
  26255. * @see {module:echarts/test/ut/spec/data/completeDimensions}
  26256. *
  26257. * This method builds the relationship between:
  26258. * + "what the coord sys or series requires (see `sysDims`)",
  26259. * + "what the user defines (in `encode` and `dimensions`, see `opt.dimsDef` and `opt.encodeDef`)"
  26260. * + "what the data source provids (see `source`)".
  26261. *
  26262. * Some guess strategy will be adapted if user does not define something.
  26263. * If no 'value' dimension specified, the first no-named dimension will be
  26264. * named as 'value'.
  26265. *
  26266. * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which
  26267. * provides not only dim template, but also default order.
  26268. * properties: 'name', 'type', 'displayName'.
  26269. * `name` of each item provides default coord name.
  26270. * [{dimsDef: [string|Object, ...]}, ...] dimsDef of sysDim item provides default dim name, and
  26271. * provide dims count that the sysDim required.
  26272. * [{ordinalMeta}] can be specified.
  26273. * @param {module:echarts/data/Source|Array|Object} source or data (for compatibal with pervious)
  26274. * @param {Object} [opt]
  26275. * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions
  26276. * For example: ['asdf', {name, type}, ...].
  26277. * @param {Object|HashMap} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3}
  26278. * @param {Function} [opt.encodeDefaulter] Called if no `opt.encodeDef` exists.
  26279. * If not specified, auto find the next available data dim.
  26280. * param source {module:data/Source}
  26281. * param dimCount {number}
  26282. * return {Object} encode Never be `null/undefined`.
  26283. * @param {string} [opt.generateCoord] Generate coord dim with the given name.
  26284. * If not specified, extra dim names will be:
  26285. * 'value', 'value0', 'value1', ...
  26286. * @param {number} [opt.generateCoordCount] By default, the generated dim name is `generateCoord`.
  26287. * If `generateCoordCount` specified, the generated dim names will be:
  26288. * `generateCoord` + 0, `generateCoord` + 1, ...
  26289. * can be Infinity, indicate that use all of the remain columns.
  26290. * @param {number} [opt.dimCount] If not specified, guess by the first data item.
  26291. * @return {Array.<module:data/DataDimensionInfo>}
  26292. */
  26293. function completeDimensions(sysDims, source, opt) {
  26294. if (!Source.isInstance(source)) {
  26295. source = Source.seriesDataToSource(source);
  26296. }
  26297. opt = opt || {};
  26298. sysDims = (sysDims || []).slice();
  26299. var dimsDef = (opt.dimsDef || []).slice();
  26300. var dataDimNameMap = createHashMap();
  26301. var coordDimNameMap = createHashMap(); // var valueCandidate;
  26302. var result = [];
  26303. var dimCount = getDimCount(source, sysDims, dimsDef, opt.dimCount); // Apply user defined dims (`name` and `type`) and init result.
  26304. for (var i = 0; i < dimCount; i++) {
  26305. var dimDefItem = dimsDef[i] = extend({}, isObject$1(dimsDef[i]) ? dimsDef[i] : {
  26306. name: dimsDef[i]
  26307. });
  26308. var userDimName = dimDefItem.name;
  26309. var resultItem = result[i] = new DataDimensionInfo(); // Name will be applied later for avoiding duplication.
  26310. if (userDimName != null && dataDimNameMap.get(userDimName) == null) {
  26311. // Only if `series.dimensions` is defined in option
  26312. // displayName, will be set, and dimension will be diplayed vertically in
  26313. // tooltip by default.
  26314. resultItem.name = resultItem.displayName = userDimName;
  26315. dataDimNameMap.set(userDimName, i);
  26316. }
  26317. dimDefItem.type != null && (resultItem.type = dimDefItem.type);
  26318. dimDefItem.displayName != null && (resultItem.displayName = dimDefItem.displayName);
  26319. }
  26320. var encodeDef = opt.encodeDef;
  26321. if (!encodeDef && opt.encodeDefaulter) {
  26322. encodeDef = opt.encodeDefaulter(source, dimCount);
  26323. }
  26324. encodeDef = createHashMap(encodeDef); // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`.
  26325. encodeDef.each(function (dataDims, coordDim) {
  26326. dataDims = normalizeToArray(dataDims).slice(); // Note: It is allowed that `dataDims.length` is `0`, e.g., options is
  26327. // `{encode: {x: -1, y: 1}}`. Should not filter anything in
  26328. // this case.
  26329. if (dataDims.length === 1 && !isString(dataDims[0]) && dataDims[0] < 0) {
  26330. encodeDef.set(coordDim, false);
  26331. return;
  26332. }
  26333. var validDataDims = encodeDef.set(coordDim, []);
  26334. each$1(dataDims, function (resultDimIdx, idx) {
  26335. // The input resultDimIdx can be dim name or index.
  26336. isString(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx));
  26337. if (resultDimIdx != null && resultDimIdx < dimCount) {
  26338. validDataDims[idx] = resultDimIdx;
  26339. applyDim(result[resultDimIdx], coordDim, idx);
  26340. }
  26341. });
  26342. }); // Apply templetes and default order from `sysDims`.
  26343. var availDimIdx = 0;
  26344. each$1(sysDims, function (sysDimItem, sysDimIndex) {
  26345. var coordDim;
  26346. var sysDimItem;
  26347. var sysDimItemDimsDef;
  26348. var sysDimItemOtherDims;
  26349. if (isString(sysDimItem)) {
  26350. coordDim = sysDimItem;
  26351. sysDimItem = {};
  26352. } else {
  26353. coordDim = sysDimItem.name;
  26354. var ordinalMeta = sysDimItem.ordinalMeta;
  26355. sysDimItem.ordinalMeta = null;
  26356. sysDimItem = clone(sysDimItem);
  26357. sysDimItem.ordinalMeta = ordinalMeta; // `coordDimIndex` should not be set directly.
  26358. sysDimItemDimsDef = sysDimItem.dimsDef;
  26359. sysDimItemOtherDims = sysDimItem.otherDims;
  26360. sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null;
  26361. }
  26362. var dataDims = encodeDef.get(coordDim); // negative resultDimIdx means no need to mapping.
  26363. if (dataDims === false) {
  26364. return;
  26365. }
  26366. var dataDims = normalizeToArray(dataDims); // dimensions provides default dim sequences.
  26367. if (!dataDims.length) {
  26368. for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) {
  26369. while (availDimIdx < result.length && result[availDimIdx].coordDim != null) {
  26370. availDimIdx++;
  26371. }
  26372. availDimIdx < result.length && dataDims.push(availDimIdx++);
  26373. }
  26374. } // Apply templates.
  26375. each$1(dataDims, function (resultDimIdx, coordDimIndex) {
  26376. var resultItem = result[resultDimIdx];
  26377. applyDim(defaults(resultItem, sysDimItem), coordDim, coordDimIndex);
  26378. if (resultItem.name == null && sysDimItemDimsDef) {
  26379. var sysDimItemDimsDefItem = sysDimItemDimsDef[coordDimIndex];
  26380. !isObject$1(sysDimItemDimsDefItem) && (sysDimItemDimsDefItem = {
  26381. name: sysDimItemDimsDefItem
  26382. });
  26383. resultItem.name = resultItem.displayName = sysDimItemDimsDefItem.name;
  26384. resultItem.defaultTooltip = sysDimItemDimsDefItem.defaultTooltip;
  26385. } // FIXME refactor, currently only used in case: {otherDims: {tooltip: false}}
  26386. sysDimItemOtherDims && defaults(resultItem.otherDims, sysDimItemOtherDims);
  26387. });
  26388. });
  26389. function applyDim(resultItem, coordDim, coordDimIndex) {
  26390. if (OTHER_DIMENSIONS.get(coordDim) != null) {
  26391. resultItem.otherDims[coordDim] = coordDimIndex;
  26392. } else {
  26393. resultItem.coordDim = coordDim;
  26394. resultItem.coordDimIndex = coordDimIndex;
  26395. coordDimNameMap.set(coordDim, true);
  26396. }
  26397. } // Make sure the first extra dim is 'value'.
  26398. var generateCoord = opt.generateCoord;
  26399. var generateCoordCount = opt.generateCoordCount;
  26400. var fromZero = generateCoordCount != null;
  26401. generateCoordCount = generateCoord ? generateCoordCount || 1 : 0;
  26402. var extra = generateCoord || 'value'; // Set dim `name` and other `coordDim` and other props.
  26403. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) {
  26404. var resultItem = result[resultDimIdx] = result[resultDimIdx] || new DataDimensionInfo();
  26405. var coordDim = resultItem.coordDim;
  26406. if (coordDim == null) {
  26407. resultItem.coordDim = genName(extra, coordDimNameMap, fromZero);
  26408. resultItem.coordDimIndex = 0;
  26409. if (!generateCoord || generateCoordCount <= 0) {
  26410. resultItem.isExtraCoord = true;
  26411. }
  26412. generateCoordCount--;
  26413. }
  26414. resultItem.name == null && (resultItem.name = genName(resultItem.coordDim, dataDimNameMap));
  26415. if (resultItem.type == null && (guessOrdinal(source, resultDimIdx, resultItem.name) === BE_ORDINAL.Must // Consider the case:
  26416. // {
  26417. // dataset: {source: [
  26418. // ['2001', 123],
  26419. // ['2002', 456],
  26420. // ...
  26421. // ['The others', 987],
  26422. // ]},
  26423. // series: {type: 'pie'}
  26424. // }
  26425. // The first colum should better be treated as a "ordinal" although it
  26426. // might not able to be detected as an "ordinal" by `guessOrdinal`.
  26427. || resultItem.isExtraCoord && (resultItem.otherDims.itemName != null || resultItem.otherDims.seriesName != null))) {
  26428. resultItem.type = 'ordinal';
  26429. }
  26430. }
  26431. return result;
  26432. } // ??? TODO
  26433. // Originally detect dimCount by data[0]. Should we
  26434. // optimize it to only by sysDims and dimensions and encode.
  26435. // So only necessary dims will be initialized.
  26436. // But
  26437. // (1) custom series should be considered. where other dims
  26438. // may be visited.
  26439. // (2) sometimes user need to calcualte bubble size or use visualMap
  26440. // on other dimensions besides coordSys needed.
  26441. // So, dims that is not used by system, should be shared in storage?
  26442. function getDimCount(source, sysDims, dimsDef, optDimCount) {
  26443. // Note that the result dimCount should not small than columns count
  26444. // of data, otherwise `dataDimNameMap` checking will be incorrect.
  26445. var dimCount = Math.max(source.dimensionsDetectCount || 1, sysDims.length, dimsDef.length, optDimCount || 0);
  26446. each$1(sysDims, function (sysDimItem) {
  26447. var sysDimItemDimsDef = sysDimItem.dimsDef;
  26448. sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length));
  26449. });
  26450. return dimCount;
  26451. }
  26452. function genName(name, map$$1, fromZero) {
  26453. if (fromZero || map$$1.get(name) != null) {
  26454. var i = 0;
  26455. while (map$$1.get(name + i) != null) {
  26456. i++;
  26457. }
  26458. name += i;
  26459. }
  26460. map$$1.set(name, true);
  26461. return name;
  26462. }
  26463. /*
  26464. * Licensed to the Apache Software Foundation (ASF) under one
  26465. * or more contributor license agreements. See the NOTICE file
  26466. * distributed with this work for additional information
  26467. * regarding copyright ownership. The ASF licenses this file
  26468. * to you under the Apache License, Version 2.0 (the
  26469. * "License"); you may not use this file except in compliance
  26470. * with the License. You may obtain a copy of the License at
  26471. *
  26472. * http://www.apache.org/licenses/LICENSE-2.0
  26473. *
  26474. * Unless required by applicable law or agreed to in writing,
  26475. * software distributed under the License is distributed on an
  26476. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26477. * KIND, either express or implied. See the License for the
  26478. * specific language governing permissions and limitations
  26479. * under the License.
  26480. */
  26481. /**
  26482. * Substitute `completeDimensions`.
  26483. * `completeDimensions` is to be deprecated.
  26484. */
  26485. /**
  26486. * @param {module:echarts/data/Source|module:echarts/data/List} source or data.
  26487. * @param {Object|Array} [opt]
  26488. * @param {Array.<string|Object>} [opt.coordDimensions=[]]
  26489. * @param {number} [opt.dimensionsCount]
  26490. * @param {string} [opt.generateCoord]
  26491. * @param {string} [opt.generateCoordCount]
  26492. * @param {Array.<string|Object>} [opt.dimensionsDefine=source.dimensionsDefine] Overwrite source define.
  26493. * @param {Object|HashMap} [opt.encodeDefine=source.encodeDefine] Overwrite source define.
  26494. * @param {Function} [opt.encodeDefaulter] Make default encode if user not specified.
  26495. * @return {Array.<Object>} dimensionsInfo
  26496. */
  26497. var createDimensions = function (source, opt) {
  26498. opt = opt || {};
  26499. return completeDimensions(opt.coordDimensions || [], source, {
  26500. dimsDef: opt.dimensionsDefine || source.dimensionsDefine,
  26501. encodeDef: opt.encodeDefine || source.encodeDefine,
  26502. dimCount: opt.dimensionsCount,
  26503. encodeDefaulter: opt.encodeDefaulter,
  26504. generateCoord: opt.generateCoord,
  26505. generateCoordCount: opt.generateCoordCount
  26506. });
  26507. };
  26508. /*
  26509. * Licensed to the Apache Software Foundation (ASF) under one
  26510. * or more contributor license agreements. See the NOTICE file
  26511. * distributed with this work for additional information
  26512. * regarding copyright ownership. The ASF licenses this file
  26513. * to you under the Apache License, Version 2.0 (the
  26514. * "License"); you may not use this file except in compliance
  26515. * with the License. You may obtain a copy of the License at
  26516. *
  26517. * http://www.apache.org/licenses/LICENSE-2.0
  26518. *
  26519. * Unless required by applicable law or agreed to in writing,
  26520. * software distributed under the License is distributed on an
  26521. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26522. * KIND, either express or implied. See the License for the
  26523. * specific language governing permissions and limitations
  26524. * under the License.
  26525. */
  26526. /**
  26527. * Helper for model references.
  26528. * There are many manners to refer axis/coordSys.
  26529. */
  26530. // TODO
  26531. // merge relevant logic to this file?
  26532. // check: "modelHelper" of tooltip and "BrushTargetManager".
  26533. /**
  26534. * @class
  26535. * For example:
  26536. * {
  26537. * coordSysName: 'cartesian2d',
  26538. * coordSysDims: ['x', 'y', ...],
  26539. * axisMap: HashMap({
  26540. * x: xAxisModel,
  26541. * y: yAxisModel
  26542. * }),
  26543. * categoryAxisMap: HashMap({
  26544. * x: xAxisModel,
  26545. * y: undefined
  26546. * }),
  26547. * // The index of the first category axis in `coordSysDims`.
  26548. * // `null/undefined` means no category axis exists.
  26549. * firstCategoryDimIndex: 1,
  26550. * // To replace user specified encode.
  26551. * }
  26552. */
  26553. function CoordSysInfo(coordSysName) {
  26554. /**
  26555. * @type {string}
  26556. */
  26557. this.coordSysName = coordSysName;
  26558. /**
  26559. * @type {Array.<string>}
  26560. */
  26561. this.coordSysDims = [];
  26562. /**
  26563. * @type {module:zrender/core/util#HashMap}
  26564. */
  26565. this.axisMap = createHashMap();
  26566. /**
  26567. * @type {module:zrender/core/util#HashMap}
  26568. */
  26569. this.categoryAxisMap = createHashMap();
  26570. /**
  26571. * @type {number}
  26572. */
  26573. this.firstCategoryDimIndex = null;
  26574. }
  26575. /**
  26576. * @return {module:model/referHelper#CoordSysInfo}
  26577. */
  26578. function getCoordSysInfoBySeries(seriesModel) {
  26579. var coordSysName = seriesModel.get('coordinateSystem');
  26580. var result = new CoordSysInfo(coordSysName);
  26581. var fetch = fetchers[coordSysName];
  26582. if (fetch) {
  26583. fetch(seriesModel, result, result.axisMap, result.categoryAxisMap);
  26584. return result;
  26585. }
  26586. }
  26587. var fetchers = {
  26588. cartesian2d: function (seriesModel, result, axisMap, categoryAxisMap) {
  26589. var xAxisModel = seriesModel.getReferringComponents('xAxis')[0];
  26590. var yAxisModel = seriesModel.getReferringComponents('yAxis')[0];
  26591. result.coordSysDims = ['x', 'y'];
  26592. axisMap.set('x', xAxisModel);
  26593. axisMap.set('y', yAxisModel);
  26594. if (isCategory(xAxisModel)) {
  26595. categoryAxisMap.set('x', xAxisModel);
  26596. result.firstCategoryDimIndex = 0;
  26597. }
  26598. if (isCategory(yAxisModel)) {
  26599. categoryAxisMap.set('y', yAxisModel);
  26600. result.firstCategoryDimIndex == null & (result.firstCategoryDimIndex = 1);
  26601. }
  26602. },
  26603. singleAxis: function (seriesModel, result, axisMap, categoryAxisMap) {
  26604. var singleAxisModel = seriesModel.getReferringComponents('singleAxis')[0];
  26605. result.coordSysDims = ['single'];
  26606. axisMap.set('single', singleAxisModel);
  26607. if (isCategory(singleAxisModel)) {
  26608. categoryAxisMap.set('single', singleAxisModel);
  26609. result.firstCategoryDimIndex = 0;
  26610. }
  26611. },
  26612. polar: function (seriesModel, result, axisMap, categoryAxisMap) {
  26613. var polarModel = seriesModel.getReferringComponents('polar')[0];
  26614. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  26615. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  26616. result.coordSysDims = ['radius', 'angle'];
  26617. axisMap.set('radius', radiusAxisModel);
  26618. axisMap.set('angle', angleAxisModel);
  26619. if (isCategory(radiusAxisModel)) {
  26620. categoryAxisMap.set('radius', radiusAxisModel);
  26621. result.firstCategoryDimIndex = 0;
  26622. }
  26623. if (isCategory(angleAxisModel)) {
  26624. categoryAxisMap.set('angle', angleAxisModel);
  26625. result.firstCategoryDimIndex == null && (result.firstCategoryDimIndex = 1);
  26626. }
  26627. },
  26628. geo: function (seriesModel, result, axisMap, categoryAxisMap) {
  26629. result.coordSysDims = ['lng', 'lat'];
  26630. },
  26631. parallel: function (seriesModel, result, axisMap, categoryAxisMap) {
  26632. var ecModel = seriesModel.ecModel;
  26633. var parallelModel = ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  26634. var coordSysDims = result.coordSysDims = parallelModel.dimensions.slice();
  26635. each$1(parallelModel.parallelAxisIndex, function (axisIndex, index) {
  26636. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  26637. var axisDim = coordSysDims[index];
  26638. axisMap.set(axisDim, axisModel);
  26639. if (isCategory(axisModel) && result.firstCategoryDimIndex == null) {
  26640. categoryAxisMap.set(axisDim, axisModel);
  26641. result.firstCategoryDimIndex = index;
  26642. }
  26643. });
  26644. }
  26645. };
  26646. function isCategory(axisModel) {
  26647. return axisModel.get('type') === 'category';
  26648. }
  26649. /*
  26650. * Licensed to the Apache Software Foundation (ASF) under one
  26651. * or more contributor license agreements. See the NOTICE file
  26652. * distributed with this work for additional information
  26653. * regarding copyright ownership. The ASF licenses this file
  26654. * to you under the Apache License, Version 2.0 (the
  26655. * "License"); you may not use this file except in compliance
  26656. * with the License. You may obtain a copy of the License at
  26657. *
  26658. * http://www.apache.org/licenses/LICENSE-2.0
  26659. *
  26660. * Unless required by applicable law or agreed to in writing,
  26661. * software distributed under the License is distributed on an
  26662. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26663. * KIND, either express or implied. See the License for the
  26664. * specific language governing permissions and limitations
  26665. * under the License.
  26666. */
  26667. /**
  26668. * Note that it is too complicated to support 3d stack by value
  26669. * (have to create two-dimension inverted index), so in 3d case
  26670. * we just support that stacked by index.
  26671. *
  26672. * @param {module:echarts/model/Series} seriesModel
  26673. * @param {Array.<string|Object>} dimensionInfoList The same as the input of <module:echarts/data/List>.
  26674. * The input dimensionInfoList will be modified.
  26675. * @param {Object} [opt]
  26676. * @param {boolean} [opt.stackedCoordDimension=''] Specify a coord dimension if needed.
  26677. * @param {boolean} [opt.byIndex=false]
  26678. * @return {Object} calculationInfo
  26679. * {
  26680. * stackedDimension: string
  26681. * stackedByDimension: string
  26682. * isStackedByIndex: boolean
  26683. * stackedOverDimension: string
  26684. * stackResultDimension: string
  26685. * }
  26686. */
  26687. function enableDataStack(seriesModel, dimensionInfoList, opt) {
  26688. opt = opt || {};
  26689. var byIndex = opt.byIndex;
  26690. var stackedCoordDimension = opt.stackedCoordDimension; // Compatibal: when `stack` is set as '', do not stack.
  26691. var mayStack = !!(seriesModel && seriesModel.get('stack'));
  26692. var stackedByDimInfo;
  26693. var stackedDimInfo;
  26694. var stackResultDimension;
  26695. var stackedOverDimension;
  26696. each$1(dimensionInfoList, function (dimensionInfo, index) {
  26697. if (isString(dimensionInfo)) {
  26698. dimensionInfoList[index] = dimensionInfo = {
  26699. name: dimensionInfo
  26700. };
  26701. }
  26702. if (mayStack && !dimensionInfo.isExtraCoord) {
  26703. // Find the first ordinal dimension as the stackedByDimInfo.
  26704. if (!byIndex && !stackedByDimInfo && dimensionInfo.ordinalMeta) {
  26705. stackedByDimInfo = dimensionInfo;
  26706. } // Find the first stackable dimension as the stackedDimInfo.
  26707. if (!stackedDimInfo && dimensionInfo.type !== 'ordinal' && dimensionInfo.type !== 'time' && (!stackedCoordDimension || stackedCoordDimension === dimensionInfo.coordDim)) {
  26708. stackedDimInfo = dimensionInfo;
  26709. }
  26710. }
  26711. });
  26712. if (stackedDimInfo && !byIndex && !stackedByDimInfo) {
  26713. // Compatible with previous design, value axis (time axis) only stack by index.
  26714. // It may make sense if the user provides elaborately constructed data.
  26715. byIndex = true;
  26716. } // Add stack dimension, they can be both calculated by coordinate system in `unionExtent`.
  26717. // That put stack logic in List is for using conveniently in echarts extensions, but it
  26718. // might not be a good way.
  26719. if (stackedDimInfo) {
  26720. // Use a weird name that not duplicated with other names.
  26721. stackResultDimension = '__\0ecstackresult';
  26722. stackedOverDimension = '__\0ecstackedover'; // Create inverted index to fast query index by value.
  26723. if (stackedByDimInfo) {
  26724. stackedByDimInfo.createInvertedIndices = true;
  26725. }
  26726. var stackedDimCoordDim = stackedDimInfo.coordDim;
  26727. var stackedDimType = stackedDimInfo.type;
  26728. var stackedDimCoordIndex = 0;
  26729. each$1(dimensionInfoList, function (dimensionInfo) {
  26730. if (dimensionInfo.coordDim === stackedDimCoordDim) {
  26731. stackedDimCoordIndex++;
  26732. }
  26733. });
  26734. dimensionInfoList.push({
  26735. name: stackResultDimension,
  26736. coordDim: stackedDimCoordDim,
  26737. coordDimIndex: stackedDimCoordIndex,
  26738. type: stackedDimType,
  26739. isExtraCoord: true,
  26740. isCalculationCoord: true
  26741. });
  26742. stackedDimCoordIndex++;
  26743. dimensionInfoList.push({
  26744. name: stackedOverDimension,
  26745. // This dimension contains stack base (generally, 0), so do not set it as
  26746. // `stackedDimCoordDim` to avoid extent calculation, consider log scale.
  26747. coordDim: stackedOverDimension,
  26748. coordDimIndex: stackedDimCoordIndex,
  26749. type: stackedDimType,
  26750. isExtraCoord: true,
  26751. isCalculationCoord: true
  26752. });
  26753. }
  26754. return {
  26755. stackedDimension: stackedDimInfo && stackedDimInfo.name,
  26756. stackedByDimension: stackedByDimInfo && stackedByDimInfo.name,
  26757. isStackedByIndex: byIndex,
  26758. stackedOverDimension: stackedOverDimension,
  26759. stackResultDimension: stackResultDimension
  26760. };
  26761. }
  26762. /**
  26763. * @param {module:echarts/data/List} data
  26764. * @param {string} stackedDim
  26765. */
  26766. function isDimensionStacked(data, stackedDim
  26767. /*, stackedByDim*/
  26768. ) {
  26769. // Each single series only maps to one pair of axis. So we do not need to
  26770. // check stackByDim, whatever stacked by a dimension or stacked by index.
  26771. return !!stackedDim && stackedDim === data.getCalculationInfo('stackedDimension'); // && (
  26772. // stackedByDim != null
  26773. // ? stackedByDim === data.getCalculationInfo('stackedByDimension')
  26774. // : data.getCalculationInfo('isStackedByIndex')
  26775. // );
  26776. }
  26777. /**
  26778. * @param {module:echarts/data/List} data
  26779. * @param {string} targetDim
  26780. * @param {string} [stackedByDim] If not input this parameter, check whether
  26781. * stacked by index.
  26782. * @return {string} dimension
  26783. */
  26784. function getStackedDimension(data, targetDim) {
  26785. return isDimensionStacked(data, targetDim) ? data.getCalculationInfo('stackResultDimension') : targetDim;
  26786. }
  26787. /*
  26788. * Licensed to the Apache Software Foundation (ASF) under one
  26789. * or more contributor license agreements. See the NOTICE file
  26790. * distributed with this work for additional information
  26791. * regarding copyright ownership. The ASF licenses this file
  26792. * to you under the Apache License, Version 2.0 (the
  26793. * "License"); you may not use this file except in compliance
  26794. * with the License. You may obtain a copy of the License at
  26795. *
  26796. * http://www.apache.org/licenses/LICENSE-2.0
  26797. *
  26798. * Unless required by applicable law or agreed to in writing,
  26799. * software distributed under the License is distributed on an
  26800. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26801. * KIND, either express or implied. See the License for the
  26802. * specific language governing permissions and limitations
  26803. * under the License.
  26804. */
  26805. /**
  26806. * @param {module:echarts/data/Source|Array} source Or raw data.
  26807. * @param {module:echarts/model/Series} seriesModel
  26808. * @param {Object} [opt]
  26809. * @param {string} [opt.generateCoord]
  26810. * @param {boolean} [opt.useEncodeDefaulter]
  26811. */
  26812. function createListFromArray(source, seriesModel, opt) {
  26813. opt = opt || {};
  26814. if (!Source.isInstance(source)) {
  26815. source = Source.seriesDataToSource(source);
  26816. }
  26817. var coordSysName = seriesModel.get('coordinateSystem');
  26818. var registeredCoordSys = CoordinateSystemManager.get(coordSysName);
  26819. var coordSysInfo = getCoordSysInfoBySeries(seriesModel);
  26820. var coordSysDimDefs;
  26821. if (coordSysInfo) {
  26822. coordSysDimDefs = map(coordSysInfo.coordSysDims, function (dim) {
  26823. var dimInfo = {
  26824. name: dim
  26825. };
  26826. var axisModel = coordSysInfo.axisMap.get(dim);
  26827. if (axisModel) {
  26828. var axisType = axisModel.get('type');
  26829. dimInfo.type = getDimensionTypeByAxis(axisType); // dimInfo.stackable = isStackable(axisType);
  26830. }
  26831. return dimInfo;
  26832. });
  26833. }
  26834. if (!coordSysDimDefs) {
  26835. // Get dimensions from registered coordinate system
  26836. coordSysDimDefs = registeredCoordSys && (registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice()) || ['x', 'y'];
  26837. }
  26838. var dimInfoList = createDimensions(source, {
  26839. coordDimensions: coordSysDimDefs,
  26840. generateCoord: opt.generateCoord,
  26841. encodeDefaulter: opt.useEncodeDefaulter ? curry(makeSeriesEncodeForAxisCoordSys, coordSysDimDefs, seriesModel) : null
  26842. });
  26843. var firstCategoryDimIndex;
  26844. var hasNameEncode;
  26845. coordSysInfo && each$1(dimInfoList, function (dimInfo, dimIndex) {
  26846. var coordDim = dimInfo.coordDim;
  26847. var categoryAxisModel = coordSysInfo.categoryAxisMap.get(coordDim);
  26848. if (categoryAxisModel) {
  26849. if (firstCategoryDimIndex == null) {
  26850. firstCategoryDimIndex = dimIndex;
  26851. }
  26852. dimInfo.ordinalMeta = categoryAxisModel.getOrdinalMeta();
  26853. }
  26854. if (dimInfo.otherDims.itemName != null) {
  26855. hasNameEncode = true;
  26856. }
  26857. });
  26858. if (!hasNameEncode && firstCategoryDimIndex != null) {
  26859. dimInfoList[firstCategoryDimIndex].otherDims.itemName = 0;
  26860. }
  26861. var stackCalculationInfo = enableDataStack(seriesModel, dimInfoList);
  26862. var list = new List(dimInfoList, seriesModel);
  26863. list.setCalculationInfo(stackCalculationInfo);
  26864. var dimValueGetter = firstCategoryDimIndex != null && isNeedCompleteOrdinalData(source) ? function (itemOpt, dimName, dataIndex, dimIndex) {
  26865. // Use dataIndex as ordinal value in categoryAxis
  26866. return dimIndex === firstCategoryDimIndex ? dataIndex : this.defaultDimValueGetter(itemOpt, dimName, dataIndex, dimIndex);
  26867. } : null;
  26868. list.hasItemOption = false;
  26869. list.initData(source, null, dimValueGetter);
  26870. return list;
  26871. }
  26872. function isNeedCompleteOrdinalData(source) {
  26873. if (source.sourceFormat === SOURCE_FORMAT_ORIGINAL) {
  26874. var sampleItem = firstDataNotNull(source.data || []);
  26875. return sampleItem != null && !isArray(getDataItemValue(sampleItem));
  26876. }
  26877. }
  26878. function firstDataNotNull(data) {
  26879. var i = 0;
  26880. while (i < data.length && data[i] == null) {
  26881. i++;
  26882. }
  26883. return data[i];
  26884. }
  26885. /*
  26886. * Licensed to the Apache Software Foundation (ASF) under one
  26887. * or more contributor license agreements. See the NOTICE file
  26888. * distributed with this work for additional information
  26889. * regarding copyright ownership. The ASF licenses this file
  26890. * to you under the Apache License, Version 2.0 (the
  26891. * "License"); you may not use this file except in compliance
  26892. * with the License. You may obtain a copy of the License at
  26893. *
  26894. * http://www.apache.org/licenses/LICENSE-2.0
  26895. *
  26896. * Unless required by applicable law or agreed to in writing,
  26897. * software distributed under the License is distributed on an
  26898. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  26899. * KIND, either express or implied. See the License for the
  26900. * specific language governing permissions and limitations
  26901. * under the License.
  26902. */
  26903. /**
  26904. * // Scale class management
  26905. * @module echarts/scale/Scale
  26906. */
  26907. /**
  26908. * @param {Object} [setting]
  26909. */
  26910. function Scale(setting) {
  26911. this._setting = setting || {};
  26912. /**
  26913. * Extent
  26914. * @type {Array.<number>}
  26915. * @protected
  26916. */
  26917. this._extent = [Infinity, -Infinity];
  26918. /**
  26919. * Step is calculated in adjustExtent
  26920. * @type {Array.<number>}
  26921. * @protected
  26922. */
  26923. this._interval = 0;
  26924. this.init && this.init.apply(this, arguments);
  26925. }
  26926. /**
  26927. * Parse input val to valid inner number.
  26928. * @param {*} val
  26929. * @return {number}
  26930. */
  26931. Scale.prototype.parse = function (val) {
  26932. // Notice: This would be a trap here, If the implementation
  26933. // of this method depends on extent, and this method is used
  26934. // before extent set (like in dataZoom), it would be wrong.
  26935. // Nevertheless, parse does not depend on extent generally.
  26936. return val;
  26937. };
  26938. Scale.prototype.getSetting = function (name) {
  26939. return this._setting[name];
  26940. };
  26941. Scale.prototype.contain = function (val) {
  26942. var extent = this._extent;
  26943. return val >= extent[0] && val <= extent[1];
  26944. };
  26945. /**
  26946. * Normalize value to linear [0, 1], return 0.5 if extent span is 0
  26947. * @param {number} val
  26948. * @return {number}
  26949. */
  26950. Scale.prototype.normalize = function (val) {
  26951. var extent = this._extent;
  26952. if (extent[1] === extent[0]) {
  26953. return 0.5;
  26954. }
  26955. return (val - extent[0]) / (extent[1] - extent[0]);
  26956. };
  26957. /**
  26958. * Scale normalized value
  26959. * @param {number} val
  26960. * @return {number}
  26961. */
  26962. Scale.prototype.scale = function (val) {
  26963. var extent = this._extent;
  26964. return val * (extent[1] - extent[0]) + extent[0];
  26965. };
  26966. /**
  26967. * Set extent from data
  26968. * @param {Array.<number>} other
  26969. */
  26970. Scale.prototype.unionExtent = function (other) {
  26971. var extent = this._extent;
  26972. other[0] < extent[0] && (extent[0] = other[0]);
  26973. other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power
  26974. // this.setExtent(extent[0], extent[1]);
  26975. };
  26976. /**
  26977. * Set extent from data
  26978. * @param {module:echarts/data/List} data
  26979. * @param {string} dim
  26980. */
  26981. Scale.prototype.unionExtentFromData = function (data, dim) {
  26982. this.unionExtent(data.getApproximateExtent(dim));
  26983. };
  26984. /**
  26985. * Get extent
  26986. * @return {Array.<number>}
  26987. */
  26988. Scale.prototype.getExtent = function () {
  26989. return this._extent.slice();
  26990. };
  26991. /**
  26992. * Set extent
  26993. * @param {number} start
  26994. * @param {number} end
  26995. */
  26996. Scale.prototype.setExtent = function (start, end) {
  26997. var thisExtent = this._extent;
  26998. if (!isNaN(start)) {
  26999. thisExtent[0] = start;
  27000. }
  27001. if (!isNaN(end)) {
  27002. thisExtent[1] = end;
  27003. }
  27004. };
  27005. /**
  27006. * When axis extent depends on data and no data exists,
  27007. * axis ticks should not be drawn, which is named 'blank'.
  27008. */
  27009. Scale.prototype.isBlank = function () {
  27010. return this._isBlank;
  27011. },
  27012. /**
  27013. * When axis extent depends on data and no data exists,
  27014. * axis ticks should not be drawn, which is named 'blank'.
  27015. */
  27016. Scale.prototype.setBlank = function (isBlank) {
  27017. this._isBlank = isBlank;
  27018. };
  27019. /**
  27020. * @abstract
  27021. * @param {*} tick
  27022. * @return {string} label of the tick.
  27023. */
  27024. Scale.prototype.getLabel = null;
  27025. enableClassExtend(Scale);
  27026. enableClassManagement(Scale, {
  27027. registerWhenExtend: true
  27028. });
  27029. /*
  27030. * Licensed to the Apache Software Foundation (ASF) under one
  27031. * or more contributor license agreements. See the NOTICE file
  27032. * distributed with this work for additional information
  27033. * regarding copyright ownership. The ASF licenses this file
  27034. * to you under the Apache License, Version 2.0 (the
  27035. * "License"); you may not use this file except in compliance
  27036. * with the License. You may obtain a copy of the License at
  27037. *
  27038. * http://www.apache.org/licenses/LICENSE-2.0
  27039. *
  27040. * Unless required by applicable law or agreed to in writing,
  27041. * software distributed under the License is distributed on an
  27042. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27043. * KIND, either express or implied. See the License for the
  27044. * specific language governing permissions and limitations
  27045. * under the License.
  27046. */
  27047. /**
  27048. * @constructor
  27049. * @param {Object} [opt]
  27050. * @param {Object} [opt.categories=[]]
  27051. * @param {Object} [opt.needCollect=false]
  27052. * @param {Object} [opt.deduplication=false]
  27053. */
  27054. function OrdinalMeta(opt) {
  27055. /**
  27056. * @readOnly
  27057. * @type {Array.<string>}
  27058. */
  27059. this.categories = opt.categories || [];
  27060. /**
  27061. * @private
  27062. * @type {boolean}
  27063. */
  27064. this._needCollect = opt.needCollect;
  27065. /**
  27066. * @private
  27067. * @type {boolean}
  27068. */
  27069. this._deduplication = opt.deduplication;
  27070. /**
  27071. * @private
  27072. * @type {boolean}
  27073. */
  27074. this._map;
  27075. }
  27076. /**
  27077. * @param {module:echarts/model/Model} axisModel
  27078. * @return {module:echarts/data/OrdinalMeta}
  27079. */
  27080. OrdinalMeta.createByAxisModel = function (axisModel) {
  27081. var option = axisModel.option;
  27082. var data = option.data;
  27083. var categories = data && map(data, getName);
  27084. return new OrdinalMeta({
  27085. categories: categories,
  27086. needCollect: !categories,
  27087. // deduplication is default in axis.
  27088. deduplication: option.dedplication !== false
  27089. });
  27090. };
  27091. var proto$1 = OrdinalMeta.prototype;
  27092. /**
  27093. * @param {string} category
  27094. * @return {number} ordinal
  27095. */
  27096. proto$1.getOrdinal = function (category) {
  27097. return getOrCreateMap(this).get(category);
  27098. };
  27099. /**
  27100. * @param {*} category
  27101. * @return {number} The ordinal. If not found, return NaN.
  27102. */
  27103. proto$1.parseAndCollect = function (category) {
  27104. var index;
  27105. var needCollect = this._needCollect; // The value of category dim can be the index of the given category set.
  27106. // This feature is only supported when !needCollect, because we should
  27107. // consider a common case: a value is 2017, which is a number but is
  27108. // expected to be tread as a category. This case usually happen in dataset,
  27109. // where it happent to be no need of the index feature.
  27110. if (typeof category !== 'string' && !needCollect) {
  27111. return category;
  27112. } // Optimize for the scenario:
  27113. // category is ['2012-01-01', '2012-01-02', ...], where the input
  27114. // data has been ensured not duplicate and is large data.
  27115. // Notice, if a dataset dimension provide categroies, usually echarts
  27116. // should remove duplication except user tell echarts dont do that
  27117. // (set axis.deduplication = false), because echarts do not know whether
  27118. // the values in the category dimension has duplication (consider the
  27119. // parallel-aqi example)
  27120. if (needCollect && !this._deduplication) {
  27121. index = this.categories.length;
  27122. this.categories[index] = category;
  27123. return index;
  27124. }
  27125. var map$$1 = getOrCreateMap(this);
  27126. index = map$$1.get(category);
  27127. if (index == null) {
  27128. if (needCollect) {
  27129. index = this.categories.length;
  27130. this.categories[index] = category;
  27131. map$$1.set(category, index);
  27132. } else {
  27133. index = NaN;
  27134. }
  27135. }
  27136. return index;
  27137. }; // Consider big data, do not create map until needed.
  27138. function getOrCreateMap(ordinalMeta) {
  27139. return ordinalMeta._map || (ordinalMeta._map = createHashMap(ordinalMeta.categories));
  27140. }
  27141. function getName(obj) {
  27142. if (isObject$1(obj) && obj.value != null) {
  27143. return obj.value;
  27144. } else {
  27145. return obj + '';
  27146. }
  27147. }
  27148. /*
  27149. * Licensed to the Apache Software Foundation (ASF) under one
  27150. * or more contributor license agreements. See the NOTICE file
  27151. * distributed with this work for additional information
  27152. * regarding copyright ownership. The ASF licenses this file
  27153. * to you under the Apache License, Version 2.0 (the
  27154. * "License"); you may not use this file except in compliance
  27155. * with the License. You may obtain a copy of the License at
  27156. *
  27157. * http://www.apache.org/licenses/LICENSE-2.0
  27158. *
  27159. * Unless required by applicable law or agreed to in writing,
  27160. * software distributed under the License is distributed on an
  27161. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27162. * KIND, either express or implied. See the License for the
  27163. * specific language governing permissions and limitations
  27164. * under the License.
  27165. */
  27166. /**
  27167. * Linear continuous scale
  27168. * @module echarts/coord/scale/Ordinal
  27169. *
  27170. * http://en.wikipedia.org/wiki/Level_of_measurement
  27171. */
  27172. // FIXME only one data
  27173. var scaleProto = Scale.prototype;
  27174. var OrdinalScale = Scale.extend({
  27175. type: 'ordinal',
  27176. /**
  27177. * @param {module:echarts/data/OrdianlMeta|Array.<string>} ordinalMeta
  27178. */
  27179. init: function (ordinalMeta, extent) {
  27180. // Caution: Should not use instanceof, consider ec-extensions using
  27181. // import approach to get OrdinalMeta class.
  27182. if (!ordinalMeta || isArray(ordinalMeta)) {
  27183. ordinalMeta = new OrdinalMeta({
  27184. categories: ordinalMeta
  27185. });
  27186. }
  27187. this._ordinalMeta = ordinalMeta;
  27188. this._extent = extent || [0, ordinalMeta.categories.length - 1];
  27189. },
  27190. parse: function (val) {
  27191. return typeof val === 'string' ? this._ordinalMeta.getOrdinal(val) // val might be float.
  27192. : Math.round(val);
  27193. },
  27194. contain: function (rank) {
  27195. rank = this.parse(rank);
  27196. return scaleProto.contain.call(this, rank) && this._ordinalMeta.categories[rank] != null;
  27197. },
  27198. /**
  27199. * Normalize given rank or name to linear [0, 1]
  27200. * @param {number|string} [val]
  27201. * @return {number}
  27202. */
  27203. normalize: function (val) {
  27204. return scaleProto.normalize.call(this, this.parse(val));
  27205. },
  27206. scale: function (val) {
  27207. return Math.round(scaleProto.scale.call(this, val));
  27208. },
  27209. /**
  27210. * @return {Array}
  27211. */
  27212. getTicks: function () {
  27213. var ticks = [];
  27214. var extent = this._extent;
  27215. var rank = extent[0];
  27216. while (rank <= extent[1]) {
  27217. ticks.push(rank);
  27218. rank++;
  27219. }
  27220. return ticks;
  27221. },
  27222. /**
  27223. * Get item on rank n
  27224. * @param {number} n
  27225. * @return {string}
  27226. */
  27227. getLabel: function (n) {
  27228. if (!this.isBlank()) {
  27229. // Note that if no data, ordinalMeta.categories is an empty array.
  27230. return this._ordinalMeta.categories[n];
  27231. }
  27232. },
  27233. /**
  27234. * @return {number}
  27235. */
  27236. count: function () {
  27237. return this._extent[1] - this._extent[0] + 1;
  27238. },
  27239. /**
  27240. * @override
  27241. */
  27242. unionExtentFromData: function (data, dim) {
  27243. this.unionExtent(data.getApproximateExtent(dim));
  27244. },
  27245. getOrdinalMeta: function () {
  27246. return this._ordinalMeta;
  27247. },
  27248. niceTicks: noop,
  27249. niceExtent: noop
  27250. });
  27251. /**
  27252. * @return {module:echarts/scale/Time}
  27253. */
  27254. OrdinalScale.create = function () {
  27255. return new OrdinalScale();
  27256. };
  27257. /*
  27258. * Licensed to the Apache Software Foundation (ASF) under one
  27259. * or more contributor license agreements. See the NOTICE file
  27260. * distributed with this work for additional information
  27261. * regarding copyright ownership. The ASF licenses this file
  27262. * to you under the Apache License, Version 2.0 (the
  27263. * "License"); you may not use this file except in compliance
  27264. * with the License. You may obtain a copy of the License at
  27265. *
  27266. * http://www.apache.org/licenses/LICENSE-2.0
  27267. *
  27268. * Unless required by applicable law or agreed to in writing,
  27269. * software distributed under the License is distributed on an
  27270. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27271. * KIND, either express or implied. See the License for the
  27272. * specific language governing permissions and limitations
  27273. * under the License.
  27274. */
  27275. /**
  27276. * For testable.
  27277. */
  27278. var roundNumber$1 = round$1;
  27279. /**
  27280. * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number.
  27281. * Should be extent[0] < extent[1].
  27282. * @param {number} splitNumber splitNumber should be >= 1.
  27283. * @param {number} [minInterval]
  27284. * @param {number} [maxInterval]
  27285. * @return {Object} {interval, intervalPrecision, niceTickExtent}
  27286. */
  27287. function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) {
  27288. var result = {};
  27289. var span = extent[1] - extent[0];
  27290. var interval = result.interval = nice(span / splitNumber, true);
  27291. if (minInterval != null && interval < minInterval) {
  27292. interval = result.interval = minInterval;
  27293. }
  27294. if (maxInterval != null && interval > maxInterval) {
  27295. interval = result.interval = maxInterval;
  27296. } // Tow more digital for tick.
  27297. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent
  27298. var niceTickExtent = result.niceTickExtent = [roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision), roundNumber$1(Math.floor(extent[1] / interval) * interval, precision)];
  27299. fixExtent(niceTickExtent, extent);
  27300. return result;
  27301. }
  27302. /**
  27303. * @param {number} interval
  27304. * @return {number} interval precision
  27305. */
  27306. function getIntervalPrecision(interval) {
  27307. // Tow more digital for tick.
  27308. return getPrecisionSafe(interval) + 2;
  27309. }
  27310. function clamp(niceTickExtent, idx, extent) {
  27311. niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]);
  27312. } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent.
  27313. function fixExtent(niceTickExtent, extent) {
  27314. !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]);
  27315. !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]);
  27316. clamp(niceTickExtent, 0, extent);
  27317. clamp(niceTickExtent, 1, extent);
  27318. if (niceTickExtent[0] > niceTickExtent[1]) {
  27319. niceTickExtent[0] = niceTickExtent[1];
  27320. }
  27321. }
  27322. /*
  27323. * Licensed to the Apache Software Foundation (ASF) under one
  27324. * or more contributor license agreements. See the NOTICE file
  27325. * distributed with this work for additional information
  27326. * regarding copyright ownership. The ASF licenses this file
  27327. * to you under the Apache License, Version 2.0 (the
  27328. * "License"); you may not use this file except in compliance
  27329. * with the License. You may obtain a copy of the License at
  27330. *
  27331. * http://www.apache.org/licenses/LICENSE-2.0
  27332. *
  27333. * Unless required by applicable law or agreed to in writing,
  27334. * software distributed under the License is distributed on an
  27335. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27336. * KIND, either express or implied. See the License for the
  27337. * specific language governing permissions and limitations
  27338. * under the License.
  27339. */
  27340. /**
  27341. * Interval scale
  27342. * @module echarts/scale/Interval
  27343. */
  27344. var roundNumber = round$1;
  27345. /**
  27346. * @alias module:echarts/coord/scale/Interval
  27347. * @constructor
  27348. */
  27349. var IntervalScale = Scale.extend({
  27350. type: 'interval',
  27351. _interval: 0,
  27352. _intervalPrecision: 2,
  27353. setExtent: function (start, end) {
  27354. var thisExtent = this._extent; //start,end may be a Number like '25',so...
  27355. if (!isNaN(start)) {
  27356. thisExtent[0] = parseFloat(start);
  27357. }
  27358. if (!isNaN(end)) {
  27359. thisExtent[1] = parseFloat(end);
  27360. }
  27361. },
  27362. unionExtent: function (other) {
  27363. var extent = this._extent;
  27364. other[0] < extent[0] && (extent[0] = other[0]);
  27365. other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes
  27366. IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]);
  27367. },
  27368. /**
  27369. * Get interval
  27370. */
  27371. getInterval: function () {
  27372. return this._interval;
  27373. },
  27374. /**
  27375. * Set interval
  27376. */
  27377. setInterval: function (interval) {
  27378. this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent
  27379. // We assume user wan't to set both interval, min, max to get a better result
  27380. this._niceExtent = this._extent.slice();
  27381. this._intervalPrecision = getIntervalPrecision(interval);
  27382. },
  27383. /**
  27384. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  27385. * @return {Array.<number>}
  27386. */
  27387. getTicks: function (expandToNicedExtent) {
  27388. var interval = this._interval;
  27389. var extent = this._extent;
  27390. var niceTickExtent = this._niceExtent;
  27391. var intervalPrecision = this._intervalPrecision;
  27392. var ticks = []; // If interval is 0, return [];
  27393. if (!interval) {
  27394. return ticks;
  27395. } // Consider this case: using dataZoom toolbox, zoom and zoom.
  27396. var safeLimit = 10000;
  27397. if (extent[0] < niceTickExtent[0]) {
  27398. if (expandToNicedExtent) {
  27399. ticks.push(roundNumber(niceTickExtent[0] - interval, intervalPrecision));
  27400. } else {
  27401. ticks.push(extent[0]);
  27402. }
  27403. }
  27404. var tick = niceTickExtent[0];
  27405. while (tick <= niceTickExtent[1]) {
  27406. ticks.push(tick); // Avoid rounding error
  27407. tick = roundNumber(tick + interval, intervalPrecision);
  27408. if (tick === ticks[ticks.length - 1]) {
  27409. // Consider out of safe float point, e.g.,
  27410. // -3711126.9907707 + 2e-10 === -3711126.9907707
  27411. break;
  27412. }
  27413. if (ticks.length > safeLimit) {
  27414. return [];
  27415. }
  27416. } // Consider this case: the last item of ticks is smaller
  27417. // than niceTickExtent[1] and niceTickExtent[1] === extent[1].
  27418. var lastNiceTick = ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1];
  27419. if (extent[1] > lastNiceTick) {
  27420. if (expandToNicedExtent) {
  27421. ticks.push(roundNumber(lastNiceTick + interval, intervalPrecision));
  27422. } else {
  27423. ticks.push(extent[1]);
  27424. }
  27425. }
  27426. return ticks;
  27427. },
  27428. /**
  27429. * @param {number} [splitNumber=5]
  27430. * @return {Array.<Array.<number>>}
  27431. */
  27432. getMinorTicks: function (splitNumber) {
  27433. var ticks = this.getTicks(true);
  27434. var minorTicks = [];
  27435. var extent = this.getExtent();
  27436. for (var i = 1; i < ticks.length; i++) {
  27437. var nextTick = ticks[i];
  27438. var prevTick = ticks[i - 1];
  27439. var count = 0;
  27440. var minorTicksGroup = [];
  27441. var interval = nextTick - prevTick;
  27442. var minorInterval = interval / splitNumber;
  27443. while (count < splitNumber - 1) {
  27444. var minorTick = round$1(prevTick + (count + 1) * minorInterval); // For the first and last interval. The count may be less than splitNumber.
  27445. if (minorTick > extent[0] && minorTick < extent[1]) {
  27446. minorTicksGroup.push(minorTick);
  27447. }
  27448. count++;
  27449. }
  27450. minorTicks.push(minorTicksGroup);
  27451. }
  27452. return minorTicks;
  27453. },
  27454. /**
  27455. * @param {number} data
  27456. * @param {Object} [opt]
  27457. * @param {number|string} [opt.precision] If 'auto', use nice presision.
  27458. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2.
  27459. * @return {string}
  27460. */
  27461. getLabel: function (data, opt) {
  27462. if (data == null) {
  27463. return '';
  27464. }
  27465. var precision = opt && opt.precision;
  27466. if (precision == null) {
  27467. precision = getPrecisionSafe(data) || 0;
  27468. } else if (precision === 'auto') {
  27469. // Should be more precise then tick.
  27470. precision = this._intervalPrecision;
  27471. } // (1) If `precision` is set, 12.005 should be display as '12.00500'.
  27472. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'.
  27473. data = roundNumber(data, precision, true);
  27474. return addCommas(data);
  27475. },
  27476. /**
  27477. * Update interval and extent of intervals for nice ticks
  27478. *
  27479. * @param {number} [splitNumber = 5] Desired number of ticks
  27480. * @param {number} [minInterval]
  27481. * @param {number} [maxInterval]
  27482. */
  27483. niceTicks: function (splitNumber, minInterval, maxInterval) {
  27484. splitNumber = splitNumber || 5;
  27485. var extent = this._extent;
  27486. var span = extent[1] - extent[0];
  27487. if (!isFinite(span)) {
  27488. return;
  27489. } // User may set axis min 0 and data are all negative
  27490. // FIXME If it needs to reverse ?
  27491. if (span < 0) {
  27492. span = -span;
  27493. extent.reverse();
  27494. }
  27495. var result = intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval);
  27496. this._intervalPrecision = result.intervalPrecision;
  27497. this._interval = result.interval;
  27498. this._niceExtent = result.niceTickExtent;
  27499. },
  27500. /**
  27501. * Nice extent.
  27502. * @param {Object} opt
  27503. * @param {number} [opt.splitNumber = 5] Given approx tick number
  27504. * @param {boolean} [opt.fixMin=false]
  27505. * @param {boolean} [opt.fixMax=false]
  27506. * @param {boolean} [opt.minInterval]
  27507. * @param {boolean} [opt.maxInterval]
  27508. */
  27509. niceExtent: function (opt) {
  27510. var extent = this._extent; // If extent start and end are same, expand them
  27511. if (extent[0] === extent[1]) {
  27512. if (extent[0] !== 0) {
  27513. // Expand extent
  27514. var expandSize = extent[0]; // In the fowllowing case
  27515. // Axis has been fixed max 100
  27516. // Plus data are all 100 and axis extent are [100, 100].
  27517. // Extend to the both side will cause expanded max is larger than fixed max.
  27518. // So only expand to the smaller side.
  27519. if (!opt.fixMax) {
  27520. extent[1] += expandSize / 2;
  27521. extent[0] -= expandSize / 2;
  27522. } else {
  27523. extent[0] -= expandSize / 2;
  27524. }
  27525. } else {
  27526. extent[1] = 1;
  27527. }
  27528. }
  27529. var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity]
  27530. if (!isFinite(span)) {
  27531. extent[0] = 0;
  27532. extent[1] = 1;
  27533. }
  27534. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent;
  27535. var interval = this._interval;
  27536. if (!opt.fixMin) {
  27537. extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval);
  27538. }
  27539. if (!opt.fixMax) {
  27540. extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval);
  27541. }
  27542. }
  27543. });
  27544. /**
  27545. * @return {module:echarts/scale/Time}
  27546. */
  27547. IntervalScale.create = function () {
  27548. return new IntervalScale();
  27549. };
  27550. /*
  27551. * Licensed to the Apache Software Foundation (ASF) under one
  27552. * or more contributor license agreements. See the NOTICE file
  27553. * distributed with this work for additional information
  27554. * regarding copyright ownership. The ASF licenses this file
  27555. * to you under the Apache License, Version 2.0 (the
  27556. * "License"); you may not use this file except in compliance
  27557. * with the License. You may obtain a copy of the License at
  27558. *
  27559. * http://www.apache.org/licenses/LICENSE-2.0
  27560. *
  27561. * Unless required by applicable law or agreed to in writing,
  27562. * software distributed under the License is distributed on an
  27563. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  27564. * KIND, either express or implied. See the License for the
  27565. * specific language governing permissions and limitations
  27566. * under the License.
  27567. */
  27568. /* global Float32Array */
  27569. var STACK_PREFIX = '__ec_stack_';
  27570. var LARGE_BAR_MIN_WIDTH = 0.5;
  27571. var LargeArr = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  27572. function getSeriesStackId(seriesModel) {
  27573. return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex;
  27574. }
  27575. function getAxisKey(axis) {
  27576. return axis.dim + axis.index;
  27577. }
  27578. /**
  27579. * @param {Object} opt
  27580. * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently.
  27581. * @param {number} opt.count Positive interger.
  27582. * @param {number} [opt.barWidth]
  27583. * @param {number} [opt.barMaxWidth]
  27584. * @param {number} [opt.barMinWidth]
  27585. * @param {number} [opt.barGap]
  27586. * @param {number} [opt.barCategoryGap]
  27587. * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined.
  27588. */
  27589. function getLayoutOnAxis(opt) {
  27590. var params = [];
  27591. var baseAxis = opt.axis;
  27592. var axisKey = 'axis0';
  27593. if (baseAxis.type !== 'category') {
  27594. return;
  27595. }
  27596. var bandWidth = baseAxis.getBandWidth();
  27597. for (var i = 0; i < opt.count || 0; i++) {
  27598. params.push(defaults({
  27599. bandWidth: bandWidth,
  27600. axisKey: axisKey,
  27601. stackId: STACK_PREFIX + i
  27602. }, opt));
  27603. }
  27604. var widthAndOffsets = doCalBarWidthAndOffset(params);
  27605. var result = [];
  27606. for (var i = 0; i < opt.count; i++) {
  27607. var item = widthAndOffsets[axisKey][STACK_PREFIX + i];
  27608. item.offsetCenter = item.offset + item.width / 2;
  27609. result.push(item);
  27610. }
  27611. return result;
  27612. }
  27613. function prepareLayoutBarSeries(seriesType, ecModel) {
  27614. var seriesModels = [];
  27615. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  27616. // Check series coordinate, do layout for cartesian2d only
  27617. if (isOnCartesian(seriesModel) && !isInLargeMode(seriesModel)) {
  27618. seriesModels.push(seriesModel);
  27619. }
  27620. });
  27621. return seriesModels;
  27622. }
  27623. /**
  27624. * Map from (baseAxis.dim + '_' + baseAxis.index) to min gap of two adjacent
  27625. * values.
  27626. * This works for time axes, value axes, and log axes.
  27627. * For a single time axis, return value is in the form like
  27628. * {'x_0': [1000000]}.
  27629. * The value of 1000000 is in milliseconds.
  27630. */
  27631. function getValueAxesMinGaps(barSeries) {
  27632. /**
  27633. * Map from axis.index to values.
  27634. * For a single time axis, axisValues is in the form like
  27635. * {'x_0': [1495555200000, 1495641600000, 1495728000000]}.
  27636. * Items in axisValues[x], e.g. 1495555200000, are time values of all
  27637. * series.
  27638. */
  27639. var axisValues = {};
  27640. each$1(barSeries, function (seriesModel) {
  27641. var cartesian = seriesModel.coordinateSystem;
  27642. var baseAxis = cartesian.getBaseAxis();
  27643. if (baseAxis.type !== 'time' && baseAxis.type !== 'value') {
  27644. return;
  27645. }
  27646. var data = seriesModel.getData();
  27647. var key = baseAxis.dim + '_' + baseAxis.index;
  27648. var dim = data.mapDimension(baseAxis.dim);
  27649. for (var i = 0, cnt = data.count(); i < cnt; ++i) {
  27650. var value = data.get(dim, i);
  27651. if (!axisValues[key]) {
  27652. // No previous data for the axis
  27653. axisValues[key] = [value];
  27654. } else {
  27655. // No value in previous series
  27656. axisValues[key].push(value);
  27657. } // Ignore duplicated time values in the same axis
  27658. }
  27659. });
  27660. var axisMinGaps = [];
  27661. for (var key in axisValues) {
  27662. if (axisValues.hasOwnProperty(key)) {
  27663. var valuesInAxis = axisValues[key];
  27664. if (valuesInAxis) {
  27665. // Sort axis values into ascending order to calculate gaps
  27666. valuesInAxis.sort(function (a, b) {
  27667. return a - b;
  27668. });
  27669. var min = null;
  27670. for (var j = 1; j < valuesInAxis.length; ++j) {
  27671. var delta = valuesInAxis[j] - valuesInAxis[j - 1];
  27672. if (delta > 0) {
  27673. // Ignore 0 delta because they are of the same axis value
  27674. min = min === null ? delta : Math.min(min, delta);
  27675. }
  27676. } // Set to null if only have one data
  27677. axisMinGaps[key] = min;
  27678. }
  27679. }
  27680. }
  27681. return axisMinGaps;
  27682. }
  27683. function makeColumnLayout(barSeries) {
  27684. var axisMinGaps = getValueAxesMinGaps(barSeries);
  27685. var seriesInfoList = [];
  27686. each$1(barSeries, function (seriesModel) {
  27687. var cartesian = seriesModel.coordinateSystem;
  27688. var baseAxis = cartesian.getBaseAxis();
  27689. var axisExtent = baseAxis.getExtent();
  27690. var bandWidth;
  27691. if (baseAxis.type === 'category') {
  27692. bandWidth = baseAxis.getBandWidth();
  27693. } else if (baseAxis.type === 'value' || baseAxis.type === 'time') {
  27694. var key = baseAxis.dim + '_' + baseAxis.index;
  27695. var minGap = axisMinGaps[key];
  27696. var extentSpan = Math.abs(axisExtent[1] - axisExtent[0]);
  27697. var scale = baseAxis.scale.getExtent();
  27698. var scaleSpan = Math.abs(scale[1] - scale[0]);
  27699. bandWidth = minGap ? extentSpan / scaleSpan * minGap : extentSpan; // When there is only one data value
  27700. } else {
  27701. var data = seriesModel.getData();
  27702. bandWidth = Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  27703. }
  27704. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  27705. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  27706. var barMinWidth = parsePercent$1( // barMinWidth by default is 1 in cartesian. Because in value axis,
  27707. // the auto-calculated bar width might be less than 1.
  27708. seriesModel.get('barMinWidth') || 1, bandWidth);
  27709. var barGap = seriesModel.get('barGap');
  27710. var barCategoryGap = seriesModel.get('barCategoryGap');
  27711. seriesInfoList.push({
  27712. bandWidth: bandWidth,
  27713. barWidth: barWidth,
  27714. barMaxWidth: barMaxWidth,
  27715. barMinWidth: barMinWidth,
  27716. barGap: barGap,
  27717. barCategoryGap: barCategoryGap,
  27718. axisKey: getAxisKey(baseAxis),
  27719. stackId: getSeriesStackId(seriesModel)
  27720. });
  27721. });
  27722. return doCalBarWidthAndOffset(seriesInfoList);
  27723. }
  27724. function doCalBarWidthAndOffset(seriesInfoList) {
  27725. // Columns info on each category axis. Key is cartesian name
  27726. var columnsMap = {};
  27727. each$1(seriesInfoList, function (seriesInfo, idx) {
  27728. var axisKey = seriesInfo.axisKey;
  27729. var bandWidth = seriesInfo.bandWidth;
  27730. var columnsOnAxis = columnsMap[axisKey] || {
  27731. bandWidth: bandWidth,
  27732. remainedWidth: bandWidth,
  27733. autoWidthCount: 0,
  27734. categoryGap: '20%',
  27735. gap: '30%',
  27736. stacks: {}
  27737. };
  27738. var stacks = columnsOnAxis.stacks;
  27739. columnsMap[axisKey] = columnsOnAxis;
  27740. var stackId = seriesInfo.stackId;
  27741. if (!stacks[stackId]) {
  27742. columnsOnAxis.autoWidthCount++;
  27743. }
  27744. stacks[stackId] = stacks[stackId] || {
  27745. width: 0,
  27746. maxWidth: 0
  27747. }; // Caution: In a single coordinate system, these barGrid attributes
  27748. // will be shared by series. Consider that they have default values,
  27749. // only the attributes set on the last series will work.
  27750. // Do not change this fact unless there will be a break change.
  27751. var barWidth = seriesInfo.barWidth;
  27752. if (barWidth && !stacks[stackId].width) {
  27753. // See #6312, do not restrict width.
  27754. stacks[stackId].width = barWidth;
  27755. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  27756. columnsOnAxis.remainedWidth -= barWidth;
  27757. }
  27758. var barMaxWidth = seriesInfo.barMaxWidth;
  27759. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  27760. var barMinWidth = seriesInfo.barMinWidth;
  27761. barMinWidth && (stacks[stackId].minWidth = barMinWidth);
  27762. var barGap = seriesInfo.barGap;
  27763. barGap != null && (columnsOnAxis.gap = barGap);
  27764. var barCategoryGap = seriesInfo.barCategoryGap;
  27765. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  27766. });
  27767. var result = {};
  27768. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  27769. result[coordSysName] = {};
  27770. var stacks = columnsOnAxis.stacks;
  27771. var bandWidth = columnsOnAxis.bandWidth;
  27772. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  27773. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  27774. var remainedWidth = columnsOnAxis.remainedWidth;
  27775. var autoWidthCount = columnsOnAxis.autoWidthCount;
  27776. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27777. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  27778. each$1(stacks, function (column) {
  27779. var maxWidth = column.maxWidth;
  27780. var minWidth = column.minWidth;
  27781. if (!column.width) {
  27782. var finalWidth = autoWidth;
  27783. if (maxWidth && maxWidth < finalWidth) {
  27784. finalWidth = Math.min(maxWidth, remainedWidth);
  27785. } // `minWidth` has higher priority. `minWidth` decide that wheter the
  27786. // bar is able to be visible. So `minWidth` should not be restricted
  27787. // by `maxWidth` or `remainedWidth` (which is from `bandWidth`). In
  27788. // the extreme cases for `value` axis, bars are allowed to overlap
  27789. // with each other if `minWidth` specified.
  27790. if (minWidth && minWidth > finalWidth) {
  27791. finalWidth = minWidth;
  27792. }
  27793. if (finalWidth !== autoWidth) {
  27794. column.width = finalWidth;
  27795. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  27796. autoWidthCount--;
  27797. }
  27798. } else {
  27799. // `barMinWidth/barMaxWidth` has higher priority than `barWidth`, as
  27800. // CSS does. Becuase barWidth can be a percent value, where
  27801. // `barMaxWidth` can be used to restrict the final width.
  27802. var finalWidth = column.width;
  27803. if (maxWidth) {
  27804. finalWidth = Math.min(finalWidth, maxWidth);
  27805. } // `minWidth` has higher priority, as described above
  27806. if (minWidth) {
  27807. finalWidth = Math.max(finalWidth, minWidth);
  27808. }
  27809. column.width = finalWidth;
  27810. remainedWidth -= finalWidth + barGapPercent * finalWidth;
  27811. autoWidthCount--;
  27812. }
  27813. }); // Recalculate width again
  27814. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  27815. autoWidth = Math.max(autoWidth, 0);
  27816. var widthSum = 0;
  27817. var lastColumn;
  27818. each$1(stacks, function (column, idx) {
  27819. if (!column.width) {
  27820. column.width = autoWidth;
  27821. }
  27822. lastColumn = column;
  27823. widthSum += column.width * (1 + barGapPercent);
  27824. });
  27825. if (lastColumn) {
  27826. widthSum -= lastColumn.width * barGapPercent;
  27827. }
  27828. var offset = -widthSum / 2;
  27829. each$1(stacks, function (column, stackId) {
  27830. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  27831. bandWidth: bandWidth,
  27832. offset: offset,
  27833. width: column.width
  27834. };
  27835. offset += column.width * (1 + barGapPercent);
  27836. });
  27837. });
  27838. return result;
  27839. }
  27840. /**
  27841. * @param {Object} barWidthAndOffset The result of makeColumnLayout
  27842. * @param {module:echarts/coord/Axis} axis
  27843. * @param {module:echarts/model/Series} [seriesModel] If not provided, return all.
  27844. * @return {Object} {stackId: {offset, width}} or {offset, width} if seriesModel provided.
  27845. */
  27846. function retrieveColumnLayout(barWidthAndOffset, axis, seriesModel) {
  27847. if (barWidthAndOffset && axis) {
  27848. var result = barWidthAndOffset[getAxisKey(axis)];
  27849. if (result != null && seriesModel != null) {
  27850. result = result[getSeriesStackId(seriesModel)];
  27851. }
  27852. return result;
  27853. }
  27854. }
  27855. /**
  27856. * @param {string} seriesType
  27857. * @param {module:echarts/model/Global} ecModel
  27858. */
  27859. function layout(seriesType, ecModel) {
  27860. var seriesModels = prepareLayoutBarSeries(seriesType, ecModel);
  27861. var barWidthAndOffset = makeColumnLayout(seriesModels);
  27862. var lastStackCoords = {};
  27863. each$1(seriesModels, function (seriesModel) {
  27864. var data = seriesModel.getData();
  27865. var cartesian = seriesModel.coordinateSystem;
  27866. var baseAxis = cartesian.getBaseAxis();
  27867. var stackId = getSeriesStackId(seriesModel);
  27868. var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId];
  27869. var columnOffset = columnLayoutInfo.offset;
  27870. var columnWidth = columnLayoutInfo.width;
  27871. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27872. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  27873. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  27874. data.setLayout({
  27875. bandWidth: columnLayoutInfo.bandWidth,
  27876. offset: columnOffset,
  27877. size: columnWidth
  27878. });
  27879. var valueDim = data.mapDimension(valueAxis.dim);
  27880. var baseDim = data.mapDimension(baseAxis.dim);
  27881. var stacked = isDimensionStacked(data, valueDim
  27882. /*, baseDim*/
  27883. );
  27884. var isValueAxisH = valueAxis.isHorizontal();
  27885. var valueAxisStart = getValueAxisStart(baseAxis, valueAxis, stacked);
  27886. for (var idx = 0, len = data.count(); idx < len; idx++) {
  27887. var value = data.get(valueDim, idx);
  27888. var baseValue = data.get(baseDim, idx);
  27889. var sign = value >= 0 ? 'p' : 'n';
  27890. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  27891. // stackResultDimension directly.
  27892. if (stacked) {
  27893. // Only ordinal axis can be stacked.
  27894. if (!lastStackCoords[stackId][baseValue]) {
  27895. lastStackCoords[stackId][baseValue] = {
  27896. p: valueAxisStart,
  27897. // Positive stack
  27898. n: valueAxisStart // Negative stack
  27899. };
  27900. } // Should also consider #4243
  27901. baseCoord = lastStackCoords[stackId][baseValue][sign];
  27902. }
  27903. var x;
  27904. var y;
  27905. var width;
  27906. var height;
  27907. if (isValueAxisH) {
  27908. var coord = cartesian.dataToPoint([value, baseValue]);
  27909. x = baseCoord;
  27910. y = coord[1] + columnOffset;
  27911. width = coord[0] - valueAxisStart;
  27912. height = columnWidth;
  27913. if (Math.abs(width) < barMinHeight) {
  27914. width = (width < 0 ? -1 : 1) * barMinHeight;
  27915. } // Ignore stack from NaN value
  27916. if (!isNaN(width)) {
  27917. stacked && (lastStackCoords[stackId][baseValue][sign] += width);
  27918. }
  27919. } else {
  27920. var coord = cartesian.dataToPoint([baseValue, value]);
  27921. x = coord[0] + columnOffset;
  27922. y = baseCoord;
  27923. width = columnWidth;
  27924. height = coord[1] - valueAxisStart;
  27925. if (Math.abs(height) < barMinHeight) {
  27926. // Include zero to has a positive bar
  27927. height = (height <= 0 ? -1 : 1) * barMinHeight;
  27928. } // Ignore stack from NaN value
  27929. if (!isNaN(height)) {
  27930. stacked && (lastStackCoords[stackId][baseValue][sign] += height);
  27931. }
  27932. }
  27933. data.setItemLayout(idx, {
  27934. x: x,
  27935. y: y,
  27936. width: width,
  27937. height: height
  27938. });
  27939. }
  27940. }, this);
  27941. } // TODO: Do not support stack in large mode yet.
  27942. var largeLayout = {
  27943. seriesType: 'bar',
  27944. plan: createRenderPlanner(),
  27945. reset: function (seriesModel) {
  27946. if (!isOnCartesian(seriesModel) || !isInLargeMode(seriesModel)) {
  27947. return;
  27948. }
  27949. var data = seriesModel.getData();
  27950. var cartesian = seriesModel.coordinateSystem;
  27951. var coordLayout = cartesian.grid.getRect();
  27952. var baseAxis = cartesian.getBaseAxis();
  27953. var valueAxis = cartesian.getOtherAxis(baseAxis);
  27954. var valueDim = data.mapDimension(valueAxis.dim);
  27955. var baseDim = data.mapDimension(baseAxis.dim);
  27956. var valueAxisHorizontal = valueAxis.isHorizontal();
  27957. var valueDimIdx = valueAxisHorizontal ? 0 : 1;
  27958. var barWidth = retrieveColumnLayout(makeColumnLayout([seriesModel]), baseAxis, seriesModel).width;
  27959. if (!(barWidth > LARGE_BAR_MIN_WIDTH)) {
  27960. // jshint ignore:line
  27961. barWidth = LARGE_BAR_MIN_WIDTH;
  27962. }
  27963. return {
  27964. progress: progress
  27965. };
  27966. function progress(params, data) {
  27967. var count = params.count;
  27968. var largePoints = new LargeArr(count * 2);
  27969. var largeBackgroundPoints = new LargeArr(count * 2);
  27970. var largeDataIndices = new LargeArr(count);
  27971. var dataIndex;
  27972. var coord = [];
  27973. var valuePair = [];
  27974. var pointsOffset = 0;
  27975. var idxOffset = 0;
  27976. while ((dataIndex = params.next()) != null) {
  27977. valuePair[valueDimIdx] = data.get(valueDim, dataIndex);
  27978. valuePair[1 - valueDimIdx] = data.get(baseDim, dataIndex);
  27979. coord = cartesian.dataToPoint(valuePair, null, coord); // Data index might not be in order, depends on `progressiveChunkMode`.
  27980. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coordLayout.x + coordLayout.width : coord[0];
  27981. largePoints[pointsOffset++] = coord[0];
  27982. largeBackgroundPoints[pointsOffset] = valueAxisHorizontal ? coord[1] : coordLayout.y + coordLayout.height;
  27983. largePoints[pointsOffset++] = coord[1];
  27984. largeDataIndices[idxOffset++] = dataIndex;
  27985. }
  27986. data.setLayout({
  27987. largePoints: largePoints,
  27988. largeDataIndices: largeDataIndices,
  27989. largeBackgroundPoints: largeBackgroundPoints,
  27990. barWidth: barWidth,
  27991. valueAxisStart: getValueAxisStart(baseAxis, valueAxis, false),
  27992. backgroundStart: valueAxisHorizontal ? coordLayout.x : coordLayout.y,
  27993. valueAxisHorizontal: valueAxisHorizontal
  27994. });
  27995. }
  27996. }
  27997. };
  27998. function isOnCartesian(seriesModel) {
  27999. return seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d';
  28000. }
  28001. function isInLargeMode(seriesModel) {
  28002. return seriesModel.pipelineContext && seriesModel.pipelineContext.large;
  28003. } // See cases in `test/bar-start.html` and `#7412`, `#8747`.
  28004. function getValueAxisStart(baseAxis, valueAxis, stacked) {
  28005. return valueAxis.toGlobalCoord(valueAxis.dataToCoord(valueAxis.type === 'log' ? 1 : 0));
  28006. }
  28007. /*
  28008. * Licensed to the Apache Software Foundation (ASF) under one
  28009. * or more contributor license agreements. See the NOTICE file
  28010. * distributed with this work for additional information
  28011. * regarding copyright ownership. The ASF licenses this file
  28012. * to you under the Apache License, Version 2.0 (the
  28013. * "License"); you may not use this file except in compliance
  28014. * with the License. You may obtain a copy of the License at
  28015. *
  28016. * http://www.apache.org/licenses/LICENSE-2.0
  28017. *
  28018. * Unless required by applicable law or agreed to in writing,
  28019. * software distributed under the License is distributed on an
  28020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28021. * KIND, either express or implied. See the License for the
  28022. * specific language governing permissions and limitations
  28023. * under the License.
  28024. */
  28025. /*
  28026. * A third-party license is embeded for some of the code in this file:
  28027. * The "scaleLevels" was originally copied from "d3.js" with some
  28028. * modifications made for this project.
  28029. * (See more details in the comment on the definition of "scaleLevels" below.)
  28030. * The use of the source code of this file is also subject to the terms
  28031. * and consitions of the license of "d3.js" (BSD-3Clause, see
  28032. * </licenses/LICENSE-d3>).
  28033. */
  28034. // [About UTC and local time zone]:
  28035. // In most cases, `number.parseDate` will treat input data string as local time
  28036. // (except time zone is specified in time string). And `format.formateTime` returns
  28037. // local time by default. option.useUTC is false by default. This design have
  28038. // concidered these common case:
  28039. // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed
  28040. // in local time by default.
  28041. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed
  28042. // as its original time, without any time difference.
  28043. var intervalScaleProto = IntervalScale.prototype;
  28044. var mathCeil = Math.ceil;
  28045. var mathFloor = Math.floor;
  28046. var ONE_SECOND = 1000;
  28047. var ONE_MINUTE = ONE_SECOND * 60;
  28048. var ONE_HOUR = ONE_MINUTE * 60;
  28049. var ONE_DAY = ONE_HOUR * 24; // FIXME 公用?
  28050. var bisect = function (a, x, lo, hi) {
  28051. while (lo < hi) {
  28052. var mid = lo + hi >>> 1;
  28053. if (a[mid][1] < x) {
  28054. lo = mid + 1;
  28055. } else {
  28056. hi = mid;
  28057. }
  28058. }
  28059. return lo;
  28060. };
  28061. /**
  28062. * @alias module:echarts/coord/scale/Time
  28063. * @constructor
  28064. */
  28065. var TimeScale = IntervalScale.extend({
  28066. type: 'time',
  28067. /**
  28068. * @override
  28069. */
  28070. getLabel: function (val) {
  28071. var stepLvl = this._stepLvl;
  28072. var date = new Date(val);
  28073. return formatTime(stepLvl[0], date, this.getSetting('useUTC'));
  28074. },
  28075. /**
  28076. * @override
  28077. */
  28078. niceExtent: function (opt) {
  28079. var extent = this._extent; // If extent start and end are same, expand them
  28080. if (extent[0] === extent[1]) {
  28081. // Expand extent
  28082. extent[0] -= ONE_DAY;
  28083. extent[1] += ONE_DAY;
  28084. } // If there are no data and extent are [Infinity, -Infinity]
  28085. if (extent[1] === -Infinity && extent[0] === Infinity) {
  28086. var d = new Date();
  28087. extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate());
  28088. extent[0] = extent[1] - ONE_DAY;
  28089. }
  28090. this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent;
  28091. var interval = this._interval;
  28092. if (!opt.fixMin) {
  28093. extent[0] = round$1(mathFloor(extent[0] / interval) * interval);
  28094. }
  28095. if (!opt.fixMax) {
  28096. extent[1] = round$1(mathCeil(extent[1] / interval) * interval);
  28097. }
  28098. },
  28099. /**
  28100. * @override
  28101. */
  28102. niceTicks: function (approxTickNum, minInterval, maxInterval) {
  28103. approxTickNum = approxTickNum || 10;
  28104. var extent = this._extent;
  28105. var span = extent[1] - extent[0];
  28106. var approxInterval = span / approxTickNum;
  28107. if (minInterval != null && approxInterval < minInterval) {
  28108. approxInterval = minInterval;
  28109. }
  28110. if (maxInterval != null && approxInterval > maxInterval) {
  28111. approxInterval = maxInterval;
  28112. }
  28113. var scaleLevelsLen = scaleLevels.length;
  28114. var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen);
  28115. var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)];
  28116. var interval = level[1]; // Same with interval scale if span is much larger than 1 year
  28117. if (level[0] === 'year') {
  28118. var yearSpan = span / interval; // From "Nice Numbers for Graph Labels" of Graphic Gems
  28119. // var niceYearSpan = numberUtil.nice(yearSpan, false);
  28120. var yearStep = nice(yearSpan / approxTickNum, true);
  28121. interval *= yearStep;
  28122. }
  28123. var timezoneOffset = this.getSetting('useUTC') ? 0 : new Date(+extent[0] || +extent[1]).getTimezoneOffset() * 60 * 1000;
  28124. var niceExtent = [Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset), Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset)];
  28125. fixExtent(niceExtent, extent);
  28126. this._stepLvl = level; // Interval will be used in getTicks
  28127. this._interval = interval;
  28128. this._niceExtent = niceExtent;
  28129. },
  28130. parse: function (val) {
  28131. // val might be float.
  28132. return +parseDate(val);
  28133. }
  28134. });
  28135. each$1(['contain', 'normalize'], function (methodName) {
  28136. TimeScale.prototype[methodName] = function (val) {
  28137. return intervalScaleProto[methodName].call(this, this.parse(val));
  28138. };
  28139. });
  28140. /**
  28141. * This implementation was originally copied from "d3.js"
  28142. * <https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/time/scale.js>
  28143. * with some modifications made for this program.
  28144. * See the license statement at the head of this file.
  28145. */
  28146. var scaleLevels = [// Format interval
  28147. ['hh:mm:ss', ONE_SECOND], // 1s
  28148. ['hh:mm:ss', ONE_SECOND * 5], // 5s
  28149. ['hh:mm:ss', ONE_SECOND * 10], // 10s
  28150. ['hh:mm:ss', ONE_SECOND * 15], // 15s
  28151. ['hh:mm:ss', ONE_SECOND * 30], // 30s
  28152. ['hh:mm\nMM-dd', ONE_MINUTE], // 1m
  28153. ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m
  28154. ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m
  28155. ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m
  28156. ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m
  28157. ['hh:mm\nMM-dd', ONE_HOUR], // 1h
  28158. ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h
  28159. ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h
  28160. ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h
  28161. ['MM-dd\nyyyy', ONE_DAY], // 1d
  28162. ['MM-dd\nyyyy', ONE_DAY * 2], // 2d
  28163. ['MM-dd\nyyyy', ONE_DAY * 3], // 3d
  28164. ['MM-dd\nyyyy', ONE_DAY * 4], // 4d
  28165. ['MM-dd\nyyyy', ONE_DAY * 5], // 5d
  28166. ['MM-dd\nyyyy', ONE_DAY * 6], // 6d
  28167. ['week', ONE_DAY * 7], // 7d
  28168. ['MM-dd\nyyyy', ONE_DAY * 10], // 10d
  28169. ['week', ONE_DAY * 14], // 2w
  28170. ['week', ONE_DAY * 21], // 3w
  28171. ['month', ONE_DAY * 31], // 1M
  28172. ['week', ONE_DAY * 42], // 6w
  28173. ['month', ONE_DAY * 62], // 2M
  28174. ['week', ONE_DAY * 70], // 10w
  28175. ['quarter', ONE_DAY * 95], // 3M
  28176. ['month', ONE_DAY * 31 * 4], // 4M
  28177. ['month', ONE_DAY * 31 * 5], // 5M
  28178. ['half-year', ONE_DAY * 380 / 2], // 6M
  28179. ['month', ONE_DAY * 31 * 8], // 8M
  28180. ['month', ONE_DAY * 31 * 10], // 10M
  28181. ['year', ONE_DAY * 380] // 1Y
  28182. ];
  28183. /**
  28184. * @param {module:echarts/model/Model}
  28185. * @return {module:echarts/scale/Time}
  28186. */
  28187. TimeScale.create = function (model) {
  28188. return new TimeScale({
  28189. useUTC: model.ecModel.get('useUTC')
  28190. });
  28191. };
  28192. /*
  28193. * Licensed to the Apache Software Foundation (ASF) under one
  28194. * or more contributor license agreements. See the NOTICE file
  28195. * distributed with this work for additional information
  28196. * regarding copyright ownership. The ASF licenses this file
  28197. * to you under the Apache License, Version 2.0 (the
  28198. * "License"); you may not use this file except in compliance
  28199. * with the License. You may obtain a copy of the License at
  28200. *
  28201. * http://www.apache.org/licenses/LICENSE-2.0
  28202. *
  28203. * Unless required by applicable law or agreed to in writing,
  28204. * software distributed under the License is distributed on an
  28205. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28206. * KIND, either express or implied. See the License for the
  28207. * specific language governing permissions and limitations
  28208. * under the License.
  28209. */
  28210. /**
  28211. * Log scale
  28212. * @module echarts/scale/Log
  28213. */
  28214. var scaleProto$1 = Scale.prototype;
  28215. var intervalScaleProto$1 = IntervalScale.prototype;
  28216. var getPrecisionSafe$1 = getPrecisionSafe;
  28217. var roundingErrorFix = round$1;
  28218. var mathFloor$1 = Math.floor;
  28219. var mathCeil$1 = Math.ceil;
  28220. var mathPow$1 = Math.pow;
  28221. var mathLog = Math.log;
  28222. var LogScale = Scale.extend({
  28223. type: 'log',
  28224. base: 10,
  28225. $constructor: function () {
  28226. Scale.apply(this, arguments);
  28227. this._originalScale = new IntervalScale();
  28228. },
  28229. /**
  28230. * @param {boolean} [expandToNicedExtent=false] If expand the ticks to niced extent.
  28231. * @return {Array.<number>}
  28232. */
  28233. getTicks: function (expandToNicedExtent) {
  28234. var originalScale = this._originalScale;
  28235. var extent = this._extent;
  28236. var originalExtent = originalScale.getExtent();
  28237. return map(intervalScaleProto$1.getTicks.call(this, expandToNicedExtent), function (val) {
  28238. var powVal = round$1(mathPow$1(this.base, val)); // Fix #4158
  28239. powVal = val === extent[0] && originalScale.__fixMin ? fixRoundingError(powVal, originalExtent[0]) : powVal;
  28240. powVal = val === extent[1] && originalScale.__fixMax ? fixRoundingError(powVal, originalExtent[1]) : powVal;
  28241. return powVal;
  28242. }, this);
  28243. },
  28244. /**
  28245. * @param {number} splitNumber
  28246. * @return {Array.<Array.<number>>}
  28247. */
  28248. getMinorTicks: intervalScaleProto$1.getMinorTicks,
  28249. /**
  28250. * @param {number} val
  28251. * @return {string}
  28252. */
  28253. getLabel: intervalScaleProto$1.getLabel,
  28254. /**
  28255. * @param {number} val
  28256. * @return {number}
  28257. */
  28258. scale: function (val) {
  28259. val = scaleProto$1.scale.call(this, val);
  28260. return mathPow$1(this.base, val);
  28261. },
  28262. /**
  28263. * @param {number} start
  28264. * @param {number} end
  28265. */
  28266. setExtent: function (start, end) {
  28267. var base = this.base;
  28268. start = mathLog(start) / mathLog(base);
  28269. end = mathLog(end) / mathLog(base);
  28270. intervalScaleProto$1.setExtent.call(this, start, end);
  28271. },
  28272. /**
  28273. * @return {number} end
  28274. */
  28275. getExtent: function () {
  28276. var base = this.base;
  28277. var extent = scaleProto$1.getExtent.call(this);
  28278. extent[0] = mathPow$1(base, extent[0]);
  28279. extent[1] = mathPow$1(base, extent[1]); // Fix #4158
  28280. var originalScale = this._originalScale;
  28281. var originalExtent = originalScale.getExtent();
  28282. originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0]));
  28283. originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1]));
  28284. return extent;
  28285. },
  28286. /**
  28287. * @param {Array.<number>} extent
  28288. */
  28289. unionExtent: function (extent) {
  28290. this._originalScale.unionExtent(extent);
  28291. var base = this.base;
  28292. extent[0] = mathLog(extent[0]) / mathLog(base);
  28293. extent[1] = mathLog(extent[1]) / mathLog(base);
  28294. scaleProto$1.unionExtent.call(this, extent);
  28295. },
  28296. /**
  28297. * @override
  28298. */
  28299. unionExtentFromData: function (data, dim) {
  28300. // TODO
  28301. // filter value that <= 0
  28302. this.unionExtent(data.getApproximateExtent(dim));
  28303. },
  28304. /**
  28305. * Update interval and extent of intervals for nice ticks
  28306. * @param {number} [approxTickNum = 10] Given approx tick number
  28307. */
  28308. niceTicks: function (approxTickNum) {
  28309. approxTickNum = approxTickNum || 10;
  28310. var extent = this._extent;
  28311. var span = extent[1] - extent[0];
  28312. if (span === Infinity || span <= 0) {
  28313. return;
  28314. }
  28315. var interval = quantity(span);
  28316. var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count.
  28317. if (err <= 0.5) {
  28318. interval *= 10;
  28319. } // Interval should be integer
  28320. while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) {
  28321. interval *= 10;
  28322. }
  28323. var niceExtent = [round$1(mathCeil$1(extent[0] / interval) * interval), round$1(mathFloor$1(extent[1] / interval) * interval)];
  28324. this._interval = interval;
  28325. this._niceExtent = niceExtent;
  28326. },
  28327. /**
  28328. * Nice extent.
  28329. * @override
  28330. */
  28331. niceExtent: function (opt) {
  28332. intervalScaleProto$1.niceExtent.call(this, opt);
  28333. var originalScale = this._originalScale;
  28334. originalScale.__fixMin = opt.fixMin;
  28335. originalScale.__fixMax = opt.fixMax;
  28336. }
  28337. });
  28338. each$1(['contain', 'normalize'], function (methodName) {
  28339. LogScale.prototype[methodName] = function (val) {
  28340. val = mathLog(val) / mathLog(this.base);
  28341. return scaleProto$1[methodName].call(this, val);
  28342. };
  28343. });
  28344. LogScale.create = function () {
  28345. return new LogScale();
  28346. };
  28347. function fixRoundingError(val, originalVal) {
  28348. return roundingErrorFix(val, getPrecisionSafe$1(originalVal));
  28349. }
  28350. /*
  28351. * Licensed to the Apache Software Foundation (ASF) under one
  28352. * or more contributor license agreements. See the NOTICE file
  28353. * distributed with this work for additional information
  28354. * regarding copyright ownership. The ASF licenses this file
  28355. * to you under the Apache License, Version 2.0 (the
  28356. * "License"); you may not use this file except in compliance
  28357. * with the License. You may obtain a copy of the License at
  28358. *
  28359. * http://www.apache.org/licenses/LICENSE-2.0
  28360. *
  28361. * Unless required by applicable law or agreed to in writing,
  28362. * software distributed under the License is distributed on an
  28363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28364. * KIND, either express or implied. See the License for the
  28365. * specific language governing permissions and limitations
  28366. * under the License.
  28367. */
  28368. /**
  28369. * Get axis scale extent before niced.
  28370. * Item of returned array can only be number (including Infinity and NaN).
  28371. */
  28372. function getScaleExtent(scale, model) {
  28373. var scaleType = scale.type;
  28374. var min = model.getMin();
  28375. var max = model.getMax();
  28376. var originalExtent = scale.getExtent();
  28377. var axisDataLen;
  28378. var boundaryGap;
  28379. var span;
  28380. if (scaleType === 'ordinal') {
  28381. axisDataLen = model.getCategories().length;
  28382. } else {
  28383. boundaryGap = model.get('boundaryGap');
  28384. if (!isArray(boundaryGap)) {
  28385. boundaryGap = [boundaryGap || 0, boundaryGap || 0];
  28386. }
  28387. if (typeof boundaryGap[0] === 'boolean') {
  28388. boundaryGap = [0, 0];
  28389. }
  28390. boundaryGap[0] = parsePercent$1(boundaryGap[0], 1);
  28391. boundaryGap[1] = parsePercent$1(boundaryGap[1], 1);
  28392. span = originalExtent[1] - originalExtent[0] || Math.abs(originalExtent[0]);
  28393. } // Notice: When min/max is not set (that is, when there are null/undefined,
  28394. // which is the most common case), these cases should be ensured:
  28395. // (1) For 'ordinal', show all axis.data.
  28396. // (2) For others:
  28397. // + `boundaryGap` is applied (if min/max set, boundaryGap is
  28398. // disabled).
  28399. // + If `needCrossZero`, min/max should be zero, otherwise, min/max should
  28400. // be the result that originalExtent enlarged by boundaryGap.
  28401. // (3) If no data, it should be ensured that `scale.setBlank` is set.
  28402. // FIXME
  28403. // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used?
  28404. // (2) When `needCrossZero` and all data is positive/negative, should it be ensured
  28405. // that the results processed by boundaryGap are positive/negative?
  28406. if (min === 'dataMin') {
  28407. min = originalExtent[0];
  28408. } else if (typeof min === 'function') {
  28409. min = min({
  28410. min: originalExtent[0],
  28411. max: originalExtent[1]
  28412. });
  28413. }
  28414. if (max === 'dataMax') {
  28415. max = originalExtent[1];
  28416. } else if (typeof max === 'function') {
  28417. max = max({
  28418. min: originalExtent[0],
  28419. max: originalExtent[1]
  28420. });
  28421. }
  28422. var fixMin = min != null;
  28423. var fixMax = max != null;
  28424. if (min == null) {
  28425. min = scaleType === 'ordinal' ? axisDataLen ? 0 : NaN : originalExtent[0] - boundaryGap[0] * span;
  28426. }
  28427. if (max == null) {
  28428. max = scaleType === 'ordinal' ? axisDataLen ? axisDataLen - 1 : NaN : originalExtent[1] + boundaryGap[1] * span;
  28429. }
  28430. (min == null || !isFinite(min)) && (min = NaN);
  28431. (max == null || !isFinite(max)) && (max = NaN);
  28432. scale.setBlank(eqNaN(min) || eqNaN(max) || scaleType === 'ordinal' && !scale.getOrdinalMeta().categories.length); // Evaluate if axis needs cross zero
  28433. if (model.getNeedCrossZero()) {
  28434. // Axis is over zero and min is not set
  28435. if (min > 0 && max > 0 && !fixMin) {
  28436. min = 0;
  28437. } // Axis is under zero and max is not set
  28438. if (min < 0 && max < 0 && !fixMax) {
  28439. max = 0;
  28440. }
  28441. } // If bars are placed on a base axis of type time or interval account for axis boundary overflow and current axis
  28442. // is base axis
  28443. // FIXME
  28444. // (1) Consider support value axis, where below zero and axis `onZero` should be handled properly.
  28445. // (2) Refactor the logic with `barGrid`. Is it not need to `makeBarWidthAndOffsetInfo` twice with different extent?
  28446. // Should not depend on series type `bar`?
  28447. // (3) Fix that might overlap when using dataZoom.
  28448. // (4) Consider other chart types using `barGrid`?
  28449. // See #6728, #4862, `test/bar-overflow-time-plot.html`
  28450. var ecModel = model.ecModel;
  28451. if (ecModel && scaleType === 'time'
  28452. /*|| scaleType === 'interval' */
  28453. ) {
  28454. var barSeriesModels = prepareLayoutBarSeries('bar', ecModel);
  28455. var isBaseAxisAndHasBarSeries;
  28456. each$1(barSeriesModels, function (seriesModel) {
  28457. isBaseAxisAndHasBarSeries |= seriesModel.getBaseAxis() === model.axis;
  28458. });
  28459. if (isBaseAxisAndHasBarSeries) {
  28460. // Calculate placement of bars on axis
  28461. var barWidthAndOffset = makeColumnLayout(barSeriesModels); // Adjust axis min and max to account for overflow
  28462. var adjustedScale = adjustScaleForOverflow(min, max, model, barWidthAndOffset);
  28463. min = adjustedScale.min;
  28464. max = adjustedScale.max;
  28465. }
  28466. }
  28467. return {
  28468. extent: [min, max],
  28469. // "fix" means "fixed", the value should not be
  28470. // changed in the subsequent steps.
  28471. fixMin: fixMin,
  28472. fixMax: fixMax
  28473. };
  28474. }
  28475. function adjustScaleForOverflow(min, max, model, barWidthAndOffset) {
  28476. // Get Axis Length
  28477. var axisExtent = model.axis.getExtent();
  28478. var axisLength = axisExtent[1] - axisExtent[0]; // Get bars on current base axis and calculate min and max overflow
  28479. var barsOnCurrentAxis = retrieveColumnLayout(barWidthAndOffset, model.axis);
  28480. if (barsOnCurrentAxis === undefined) {
  28481. return {
  28482. min: min,
  28483. max: max
  28484. };
  28485. }
  28486. var minOverflow = Infinity;
  28487. each$1(barsOnCurrentAxis, function (item) {
  28488. minOverflow = Math.min(item.offset, minOverflow);
  28489. });
  28490. var maxOverflow = -Infinity;
  28491. each$1(barsOnCurrentAxis, function (item) {
  28492. maxOverflow = Math.max(item.offset + item.width, maxOverflow);
  28493. });
  28494. minOverflow = Math.abs(minOverflow);
  28495. maxOverflow = Math.abs(maxOverflow);
  28496. var totalOverFlow = minOverflow + maxOverflow; // Calulate required buffer based on old range and overflow
  28497. var oldRange = max - min;
  28498. var oldRangePercentOfNew = 1 - (minOverflow + maxOverflow) / axisLength;
  28499. var overflowBuffer = oldRange / oldRangePercentOfNew - oldRange;
  28500. max += overflowBuffer * (maxOverflow / totalOverFlow);
  28501. min -= overflowBuffer * (minOverflow / totalOverFlow);
  28502. return {
  28503. min: min,
  28504. max: max
  28505. };
  28506. }
  28507. function niceScaleExtent(scale, model) {
  28508. var extentInfo = getScaleExtent(scale, model);
  28509. var extent = extentInfo.extent;
  28510. var splitNumber = model.get('splitNumber');
  28511. if (scale.type === 'log') {
  28512. scale.base = model.get('logBase');
  28513. }
  28514. var scaleType = scale.type;
  28515. scale.setExtent(extent[0], extent[1]);
  28516. scale.niceExtent({
  28517. splitNumber: splitNumber,
  28518. fixMin: extentInfo.fixMin,
  28519. fixMax: extentInfo.fixMax,
  28520. minInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('minInterval') : null,
  28521. maxInterval: scaleType === 'interval' || scaleType === 'time' ? model.get('maxInterval') : null
  28522. }); // If some one specified the min, max. And the default calculated interval
  28523. // is not good enough. He can specify the interval. It is often appeared
  28524. // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard
  28525. // to be 60.
  28526. // FIXME
  28527. var interval = model.get('interval');
  28528. if (interval != null) {
  28529. scale.setInterval && scale.setInterval(interval);
  28530. }
  28531. }
  28532. /**
  28533. * @param {module:echarts/model/Model} model
  28534. * @param {string} [axisType] Default retrieve from model.type
  28535. * @return {module:echarts/scale/*}
  28536. */
  28537. function createScaleByModel(model, axisType) {
  28538. axisType = axisType || model.get('type');
  28539. if (axisType) {
  28540. switch (axisType) {
  28541. // Buildin scale
  28542. case 'category':
  28543. return new OrdinalScale(model.getOrdinalMeta ? model.getOrdinalMeta() : model.getCategories(), [Infinity, -Infinity]);
  28544. case 'value':
  28545. return new IntervalScale();
  28546. // Extended scale, like time and log
  28547. default:
  28548. return (Scale.getClass(axisType) || IntervalScale).create(model);
  28549. }
  28550. }
  28551. }
  28552. /**
  28553. * Check if the axis corss 0
  28554. */
  28555. function ifAxisCrossZero(axis) {
  28556. var dataExtent = axis.scale.getExtent();
  28557. var min = dataExtent[0];
  28558. var max = dataExtent[1];
  28559. return !(min > 0 && max > 0 || min < 0 && max < 0);
  28560. }
  28561. /**
  28562. * @param {module:echarts/coord/Axis} axis
  28563. * @return {Function} Label formatter function.
  28564. * param: {number} tickValue,
  28565. * param: {number} idx, the index in all ticks.
  28566. * If category axis, this param is not requied.
  28567. * return: {string} label string.
  28568. */
  28569. function makeLabelFormatter(axis) {
  28570. var labelFormatter = axis.getLabelModel().get('formatter');
  28571. var categoryTickStart = axis.type === 'category' ? axis.scale.getExtent()[0] : null;
  28572. if (typeof labelFormatter === 'string') {
  28573. labelFormatter = function (tpl) {
  28574. return function (val) {
  28575. // For category axis, get raw value; for numeric axis,
  28576. // get foramtted label like '1,333,444'.
  28577. val = axis.scale.getLabel(val);
  28578. return tpl.replace('{value}', val != null ? val : '');
  28579. };
  28580. }(labelFormatter); // Consider empty array
  28581. return labelFormatter;
  28582. } else if (typeof labelFormatter === 'function') {
  28583. return function (tickValue, idx) {
  28584. // The original intention of `idx` is "the index of the tick in all ticks".
  28585. // But the previous implementation of category axis do not consider the
  28586. // `axisLabel.interval`, which cause that, for example, the `interval` is
  28587. // `1`, then the ticks "name5", "name7", "name9" are displayed, where the
  28588. // corresponding `idx` are `0`, `2`, `4`, but not `0`, `1`, `2`. So we keep
  28589. // the definition here for back compatibility.
  28590. if (categoryTickStart != null) {
  28591. idx = tickValue - categoryTickStart;
  28592. }
  28593. return labelFormatter(getAxisRawValue(axis, tickValue), idx);
  28594. };
  28595. } else {
  28596. return function (tick) {
  28597. return axis.scale.getLabel(tick);
  28598. };
  28599. }
  28600. }
  28601. function getAxisRawValue(axis, value) {
  28602. // In category axis with data zoom, tick is not the original
  28603. // index of axis.data. So tick should not be exposed to user
  28604. // in category axis.
  28605. return axis.type === 'category' ? axis.scale.getLabel(value) : value;
  28606. }
  28607. /**
  28608. * @param {module:echarts/coord/Axis} axis
  28609. * @return {module:zrender/core/BoundingRect} Be null/undefined if no labels.
  28610. */
  28611. function estimateLabelUnionRect(axis) {
  28612. var axisModel = axis.model;
  28613. var scale = axis.scale;
  28614. if (!axisModel.get('axisLabel.show') || scale.isBlank()) {
  28615. return;
  28616. }
  28617. var isCategory = axis.type === 'category';
  28618. var realNumberScaleTicks;
  28619. var tickCount;
  28620. var categoryScaleExtent = scale.getExtent(); // Optimize for large category data, avoid call `getTicks()`.
  28621. if (isCategory) {
  28622. tickCount = scale.count();
  28623. } else {
  28624. realNumberScaleTicks = scale.getTicks();
  28625. tickCount = realNumberScaleTicks.length;
  28626. }
  28627. var axisLabelModel = axis.getLabelModel();
  28628. var labelFormatter = makeLabelFormatter(axis);
  28629. var rect;
  28630. var step = 1; // Simple optimization for large amount of labels
  28631. if (tickCount > 40) {
  28632. step = Math.ceil(tickCount / 40);
  28633. }
  28634. for (var i = 0; i < tickCount; i += step) {
  28635. var tickValue = realNumberScaleTicks ? realNumberScaleTicks[i] : categoryScaleExtent[0] + i;
  28636. var label = labelFormatter(tickValue);
  28637. var unrotatedSingleRect = axisLabelModel.getTextRect(label);
  28638. var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0);
  28639. rect ? rect.union(singleRect) : rect = singleRect;
  28640. }
  28641. return rect;
  28642. }
  28643. function rotateTextRect(textRect, rotate) {
  28644. var rotateRadians = rotate * Math.PI / 180;
  28645. var boundingBox = textRect.plain();
  28646. var beforeWidth = boundingBox.width;
  28647. var beforeHeight = boundingBox.height;
  28648. var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians);
  28649. var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians);
  28650. var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight);
  28651. return rotatedRect;
  28652. }
  28653. /**
  28654. * @param {module:echarts/src/model/Model} model axisLabelModel or axisTickModel
  28655. * @return {number|String} Can be null|'auto'|number|function
  28656. */
  28657. function getOptionCategoryInterval(model) {
  28658. var interval = model.get('interval');
  28659. return interval == null ? 'auto' : interval;
  28660. }
  28661. /**
  28662. * Set `categoryInterval` as 0 implicitly indicates that
  28663. * show all labels reguardless of overlap.
  28664. * @param {Object} axis axisModel.axis
  28665. * @return {boolean}
  28666. */
  28667. function shouldShowAllLabels(axis) {
  28668. return axis.type === 'category' && getOptionCategoryInterval(axis.getLabelModel()) === 0;
  28669. }
  28670. /*
  28671. * Licensed to the Apache Software Foundation (ASF) under one
  28672. * or more contributor license agreements. See the NOTICE file
  28673. * distributed with this work for additional information
  28674. * regarding copyright ownership. The ASF licenses this file
  28675. * to you under the Apache License, Version 2.0 (the
  28676. * "License"); you may not use this file except in compliance
  28677. * with the License. You may obtain a copy of the License at
  28678. *
  28679. * http://www.apache.org/licenses/LICENSE-2.0
  28680. *
  28681. * Unless required by applicable law or agreed to in writing,
  28682. * software distributed under the License is distributed on an
  28683. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28684. * KIND, either express or implied. See the License for the
  28685. * specific language governing permissions and limitations
  28686. * under the License.
  28687. */
  28688. var axisModelCommonMixin = {
  28689. /**
  28690. * @param {boolean} origin
  28691. * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN
  28692. */
  28693. getMin: function (origin) {
  28694. var option = this.option;
  28695. var min = !origin && option.rangeStart != null ? option.rangeStart : option.min;
  28696. if (this.axis && min != null && min !== 'dataMin' && typeof min !== 'function' && !eqNaN(min)) {
  28697. min = this.axis.scale.parse(min);
  28698. }
  28699. return min;
  28700. },
  28701. /**
  28702. * @param {boolean} origin
  28703. * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN
  28704. */
  28705. getMax: function (origin) {
  28706. var option = this.option;
  28707. var max = !origin && option.rangeEnd != null ? option.rangeEnd : option.max;
  28708. if (this.axis && max != null && max !== 'dataMax' && typeof max !== 'function' && !eqNaN(max)) {
  28709. max = this.axis.scale.parse(max);
  28710. }
  28711. return max;
  28712. },
  28713. /**
  28714. * @return {boolean}
  28715. */
  28716. getNeedCrossZero: function () {
  28717. var option = this.option;
  28718. return option.rangeStart != null || option.rangeEnd != null ? false : !option.scale;
  28719. },
  28720. /**
  28721. * Should be implemented by each axis model if necessary.
  28722. * @return {module:echarts/model/Component} coordinate system model
  28723. */
  28724. getCoordSysModel: noop,
  28725. /**
  28726. * @param {number} rangeStart Can only be finite number or null/undefined or NaN.
  28727. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN.
  28728. */
  28729. setRange: function (rangeStart, rangeEnd) {
  28730. this.option.rangeStart = rangeStart;
  28731. this.option.rangeEnd = rangeEnd;
  28732. },
  28733. /**
  28734. * Reset range
  28735. */
  28736. resetRange: function () {
  28737. // rangeStart and rangeEnd is readonly.
  28738. this.option.rangeStart = this.option.rangeEnd = null;
  28739. }
  28740. };
  28741. /*
  28742. * Licensed to the Apache Software Foundation (ASF) under one
  28743. * or more contributor license agreements. See the NOTICE file
  28744. * distributed with this work for additional information
  28745. * regarding copyright ownership. The ASF licenses this file
  28746. * to you under the Apache License, Version 2.0 (the
  28747. * "License"); you may not use this file except in compliance
  28748. * with the License. You may obtain a copy of the License at
  28749. *
  28750. * http://www.apache.org/licenses/LICENSE-2.0
  28751. *
  28752. * Unless required by applicable law or agreed to in writing,
  28753. * software distributed under the License is distributed on an
  28754. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  28755. * KIND, either express or implied. See the License for the
  28756. * specific language governing permissions and limitations
  28757. * under the License.
  28758. */
  28759. // Symbol factory
  28760. /**
  28761. * Triangle shape
  28762. * @inner
  28763. */
  28764. var Triangle = extendShape({
  28765. type: 'triangle',
  28766. shape: {
  28767. cx: 0,
  28768. cy: 0,
  28769. width: 0,
  28770. height: 0
  28771. },
  28772. buildPath: function (path, shape) {
  28773. var cx = shape.cx;
  28774. var cy = shape.cy;
  28775. var width = shape.width / 2;
  28776. var height = shape.height / 2;
  28777. path.moveTo(cx, cy - height);
  28778. path.lineTo(cx + width, cy + height);
  28779. path.lineTo(cx - width, cy + height);
  28780. path.closePath();
  28781. }
  28782. });
  28783. /**
  28784. * Diamond shape
  28785. * @inner
  28786. */
  28787. var Diamond = extendShape({
  28788. type: 'diamond',
  28789. shape: {
  28790. cx: 0,
  28791. cy: 0,
  28792. width: 0,
  28793. height: 0
  28794. },
  28795. buildPath: function (path, shape) {
  28796. var cx = shape.cx;
  28797. var cy = shape.cy;
  28798. var width = shape.width / 2;
  28799. var height = shape.height / 2;
  28800. path.moveTo(cx, cy - height);
  28801. path.lineTo(cx + width, cy);
  28802. path.lineTo(cx, cy + height);
  28803. path.lineTo(cx - width, cy);
  28804. path.closePath();
  28805. }
  28806. });
  28807. /**
  28808. * Pin shape
  28809. * @inner
  28810. */
  28811. var Pin = extendShape({
  28812. type: 'pin',
  28813. shape: {
  28814. // x, y on the cusp
  28815. x: 0,
  28816. y: 0,
  28817. width: 0,
  28818. height: 0
  28819. },
  28820. buildPath: function (path, shape) {
  28821. var x = shape.x;
  28822. var y = shape.y;
  28823. var w = shape.width / 5 * 3; // Height must be larger than width
  28824. var h = Math.max(w, shape.height);
  28825. var r = w / 2; // Dist on y with tangent point and circle center
  28826. var dy = r * r / (h - r);
  28827. var cy = y - h + r + dy;
  28828. var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center
  28829. var dx = Math.cos(angle) * r;
  28830. var tanX = Math.sin(angle);
  28831. var tanY = Math.cos(angle);
  28832. var cpLen = r * 0.6;
  28833. var cpLen2 = r * 0.7;
  28834. path.moveTo(x - dx, cy + dy);
  28835. path.arc(x, cy, r, Math.PI - angle, Math.PI * 2 + angle);
  28836. path.bezierCurveTo(x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y);
  28837. path.bezierCurveTo(x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy);
  28838. path.closePath();
  28839. }
  28840. });
  28841. /**
  28842. * Arrow shape
  28843. * @inner
  28844. */
  28845. var Arrow = extendShape({
  28846. type: 'arrow',
  28847. shape: {
  28848. x: 0,
  28849. y: 0,
  28850. width: 0,
  28851. height: 0
  28852. },
  28853. buildPath: function (ctx, shape) {
  28854. var height = shape.height;
  28855. var width = shape.width;
  28856. var x = shape.x;
  28857. var y = shape.y;
  28858. var dx = width / 3 * 2;
  28859. ctx.moveTo(x, y);
  28860. ctx.lineTo(x + dx, y + height);
  28861. ctx.lineTo(x, y + height / 4 * 3);
  28862. ctx.lineTo(x - dx, y + height);
  28863. ctx.lineTo(x, y);
  28864. ctx.closePath();
  28865. }
  28866. });
  28867. /**
  28868. * Map of path contructors
  28869. * @type {Object.<string, module:zrender/graphic/Path>}
  28870. */
  28871. var symbolCtors = {
  28872. line: Line,
  28873. rect: Rect,
  28874. roundRect: Rect,
  28875. square: Rect,
  28876. circle: Circle,
  28877. diamond: Diamond,
  28878. pin: Pin,
  28879. arrow: Arrow,
  28880. triangle: Triangle
  28881. };
  28882. var symbolShapeMakers = {
  28883. line: function (x, y, w, h, shape) {
  28884. // FIXME
  28885. shape.x1 = x;
  28886. shape.y1 = y + h / 2;
  28887. shape.x2 = x + w;
  28888. shape.y2 = y + h / 2;
  28889. },
  28890. rect: function (x, y, w, h, shape) {
  28891. shape.x = x;
  28892. shape.y = y;
  28893. shape.width = w;
  28894. shape.height = h;
  28895. },
  28896. roundRect: function (x, y, w, h, shape) {
  28897. shape.x = x;
  28898. shape.y = y;
  28899. shape.width = w;
  28900. shape.height = h;
  28901. shape.r = Math.min(w, h) / 4;
  28902. },
  28903. square: function (x, y, w, h, shape) {
  28904. var size = Math.min(w, h);
  28905. shape.x = x;
  28906. shape.y = y;
  28907. shape.width = size;
  28908. shape.height = size;
  28909. },
  28910. circle: function (x, y, w, h, shape) {
  28911. // Put circle in the center of square
  28912. shape.cx = x + w / 2;
  28913. shape.cy = y + h / 2;
  28914. shape.r = Math.min(w, h) / 2;
  28915. },
  28916. diamond: function (x, y, w, h, shape) {
  28917. shape.cx = x + w / 2;
  28918. shape.cy = y + h / 2;
  28919. shape.width = w;
  28920. shape.height = h;
  28921. },
  28922. pin: function (x, y, w, h, shape) {
  28923. shape.x = x + w / 2;
  28924. shape.y = y + h / 2;
  28925. shape.width = w;
  28926. shape.height = h;
  28927. },
  28928. arrow: function (x, y, w, h, shape) {
  28929. shape.x = x + w / 2;
  28930. shape.y = y + h / 2;
  28931. shape.width = w;
  28932. shape.height = h;
  28933. },
  28934. triangle: function (x, y, w, h, shape) {
  28935. shape.cx = x + w / 2;
  28936. shape.cy = y + h / 2;
  28937. shape.width = w;
  28938. shape.height = h;
  28939. }
  28940. };
  28941. var symbolBuildProxies = {};
  28942. each$1(symbolCtors, function (Ctor, name) {
  28943. symbolBuildProxies[name] = new Ctor();
  28944. });
  28945. var SymbolClz = extendShape({
  28946. type: 'symbol',
  28947. shape: {
  28948. symbolType: '',
  28949. x: 0,
  28950. y: 0,
  28951. width: 0,
  28952. height: 0
  28953. },
  28954. calculateTextPosition: function (out, style, rect) {
  28955. var res = calculateTextPosition(out, style, rect);
  28956. var shape = this.shape;
  28957. if (shape && shape.symbolType === 'pin' && style.textPosition === 'inside') {
  28958. res.y = rect.y + rect.height * 0.4;
  28959. }
  28960. return res;
  28961. },
  28962. buildPath: function (ctx, shape, inBundle) {
  28963. var symbolType = shape.symbolType;
  28964. if (symbolType !== 'none') {
  28965. var proxySymbol = symbolBuildProxies[symbolType];
  28966. if (!proxySymbol) {
  28967. // Default rect
  28968. symbolType = 'rect';
  28969. proxySymbol = symbolBuildProxies[symbolType];
  28970. }
  28971. symbolShapeMakers[symbolType](shape.x, shape.y, shape.width, shape.height, proxySymbol.shape);
  28972. proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle);
  28973. }
  28974. }
  28975. }); // Provide setColor helper method to avoid determine if set the fill or stroke outside
  28976. function symbolPathSetColor(color, innerColor) {
  28977. if (this.type !== 'image') {
  28978. var symbolStyle = this.style;
  28979. var symbolShape = this.shape;
  28980. if (symbolShape && symbolShape.symbolType === 'line') {
  28981. symbolStyle.stroke = color;
  28982. } else if (this.__isEmptyBrush) {
  28983. symbolStyle.stroke = color;
  28984. symbolStyle.fill = innerColor || '#fff';
  28985. } else {
  28986. // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ?
  28987. symbolStyle.fill && (symbolStyle.fill = color);
  28988. symbolStyle.stroke && (symbolStyle.stroke = color);
  28989. }
  28990. this.dirty(false);
  28991. }
  28992. }
  28993. /**
  28994. * Create a symbol element with given symbol configuration: shape, x, y, width, height, color
  28995. * @param {string} symbolType
  28996. * @param {number} x
  28997. * @param {number} y
  28998. * @param {number} w
  28999. * @param {number} h
  29000. * @param {string} color
  29001. * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h,
  29002. * for path and image only.
  29003. */
  29004. function createSymbol(symbolType, x, y, w, h, color, keepAspect) {
  29005. // TODO Support image object, DynamicImage.
  29006. var isEmpty = symbolType.indexOf('empty') === 0;
  29007. if (isEmpty) {
  29008. symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6);
  29009. }
  29010. var symbolPath;
  29011. if (symbolType.indexOf('image://') === 0) {
  29012. symbolPath = makeImage(symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  29013. } else if (symbolType.indexOf('path://') === 0) {
  29014. symbolPath = makePath(symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover');
  29015. } else {
  29016. symbolPath = new SymbolClz({
  29017. shape: {
  29018. symbolType: symbolType,
  29019. x: x,
  29020. y: y,
  29021. width: w,
  29022. height: h
  29023. }
  29024. });
  29025. }
  29026. symbolPath.__isEmptyBrush = isEmpty;
  29027. symbolPath.setColor = symbolPathSetColor;
  29028. symbolPath.setColor(color);
  29029. return symbolPath;
  29030. }
  29031. /*
  29032. * Licensed to the Apache Software Foundation (ASF) under one
  29033. * or more contributor license agreements. See the NOTICE file
  29034. * distributed with this work for additional information
  29035. * regarding copyright ownership. The ASF licenses this file
  29036. * to you under the Apache License, Version 2.0 (the
  29037. * "License"); you may not use this file except in compliance
  29038. * with the License. You may obtain a copy of the License at
  29039. *
  29040. * http://www.apache.org/licenses/LICENSE-2.0
  29041. *
  29042. * Unless required by applicable law or agreed to in writing,
  29043. * software distributed under the License is distributed on an
  29044. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29045. * KIND, either express or implied. See the License for the
  29046. * specific language governing permissions and limitations
  29047. * under the License.
  29048. */
  29049. /**
  29050. * Create a muti dimension List structure from seriesModel.
  29051. * @param {module:echarts/model/Model} seriesModel
  29052. * @return {module:echarts/data/List} list
  29053. */
  29054. function createList(seriesModel) {
  29055. return createListFromArray(seriesModel.getSource(), seriesModel);
  29056. } // export function createGraph(seriesModel) {
  29057. var dataStack$1 = {
  29058. isDimensionStacked: isDimensionStacked,
  29059. enableDataStack: enableDataStack,
  29060. getStackedDimension: getStackedDimension
  29061. };
  29062. /**
  29063. * Create scale
  29064. * @param {Array.<number>} dataExtent
  29065. * @param {Object|module:echarts/Model} option
  29066. */
  29067. function createScale(dataExtent, option) {
  29068. var axisModel = option;
  29069. if (!Model.isInstance(option)) {
  29070. axisModel = new Model(option);
  29071. mixin(axisModel, axisModelCommonMixin);
  29072. }
  29073. var scale = createScaleByModel(axisModel);
  29074. scale.setExtent(dataExtent[0], dataExtent[1]);
  29075. niceScaleExtent(scale, axisModel);
  29076. return scale;
  29077. }
  29078. /**
  29079. * Mixin common methods to axis model,
  29080. *
  29081. * Inlcude methods
  29082. * `getFormattedLabels() => Array.<string>`
  29083. * `getCategories() => Array.<string>`
  29084. * `getMin(origin: boolean) => number`
  29085. * `getMax(origin: boolean) => number`
  29086. * `getNeedCrossZero() => boolean`
  29087. * `setRange(start: number, end: number)`
  29088. * `resetRange()`
  29089. */
  29090. function mixinAxisModelCommonMethods(Model$$1) {
  29091. mixin(Model$$1, axisModelCommonMixin);
  29092. }
  29093. var helper = (Object.freeze || Object)({
  29094. createList: createList,
  29095. getLayoutRect: getLayoutRect,
  29096. dataStack: dataStack$1,
  29097. createScale: createScale,
  29098. mixinAxisModelCommonMethods: mixinAxisModelCommonMethods,
  29099. completeDimensions: completeDimensions,
  29100. createDimensions: createDimensions,
  29101. createSymbol: createSymbol
  29102. });
  29103. var EPSILON$3 = 1e-8;
  29104. function isAroundEqual$1(a, b) {
  29105. return Math.abs(a - b) < EPSILON$3;
  29106. }
  29107. function contain$1(points, x, y) {
  29108. var w = 0;
  29109. var p = points[0];
  29110. if (!p) {
  29111. return false;
  29112. }
  29113. for (var i = 1; i < points.length; i++) {
  29114. var p2 = points[i];
  29115. w += windingLine(p[0], p[1], p2[0], p2[1], x, y);
  29116. p = p2;
  29117. } // Close polygon
  29118. var p0 = points[0];
  29119. if (!isAroundEqual$1(p[0], p0[0]) || !isAroundEqual$1(p[1], p0[1])) {
  29120. w += windingLine(p[0], p[1], p0[0], p0[1], x, y);
  29121. }
  29122. return w !== 0;
  29123. }
  29124. /*
  29125. * Licensed to the Apache Software Foundation (ASF) under one
  29126. * or more contributor license agreements. See the NOTICE file
  29127. * distributed with this work for additional information
  29128. * regarding copyright ownership. The ASF licenses this file
  29129. * to you under the Apache License, Version 2.0 (the
  29130. * "License"); you may not use this file except in compliance
  29131. * with the License. You may obtain a copy of the License at
  29132. *
  29133. * http://www.apache.org/licenses/LICENSE-2.0
  29134. *
  29135. * Unless required by applicable law or agreed to in writing,
  29136. * software distributed under the License is distributed on an
  29137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29138. * KIND, either express or implied. See the License for the
  29139. * specific language governing permissions and limitations
  29140. * under the License.
  29141. */
  29142. /**
  29143. * @module echarts/coord/geo/Region
  29144. */
  29145. /**
  29146. * @param {string|Region} name
  29147. * @param {Array} geometries
  29148. * @param {Array.<number>} cp
  29149. */
  29150. function Region(name, geometries, cp) {
  29151. /**
  29152. * @type {string}
  29153. * @readOnly
  29154. */
  29155. this.name = name;
  29156. /**
  29157. * @type {Array.<Array>}
  29158. * @readOnly
  29159. */
  29160. this.geometries = geometries;
  29161. if (!cp) {
  29162. var rect = this.getBoundingRect();
  29163. cp = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  29164. } else {
  29165. cp = [cp[0], cp[1]];
  29166. }
  29167. /**
  29168. * @type {Array.<number>}
  29169. */
  29170. this.center = cp;
  29171. }
  29172. Region.prototype = {
  29173. constructor: Region,
  29174. properties: null,
  29175. /**
  29176. * @return {module:zrender/core/BoundingRect}
  29177. */
  29178. getBoundingRect: function () {
  29179. var rect = this._rect;
  29180. if (rect) {
  29181. return rect;
  29182. }
  29183. var MAX_NUMBER = Number.MAX_VALUE;
  29184. var min$$1 = [MAX_NUMBER, MAX_NUMBER];
  29185. var max$$1 = [-MAX_NUMBER, -MAX_NUMBER];
  29186. var min2 = [];
  29187. var max2 = [];
  29188. var geometries = this.geometries;
  29189. for (var i = 0; i < geometries.length; i++) {
  29190. // Only support polygon
  29191. if (geometries[i].type !== 'polygon') {
  29192. continue;
  29193. } // Doesn't consider hole
  29194. var exterior = geometries[i].exterior;
  29195. fromPoints(exterior, min2, max2);
  29196. min(min$$1, min$$1, min2);
  29197. max(max$$1, max$$1, max2);
  29198. } // No data
  29199. if (i === 0) {
  29200. min$$1[0] = min$$1[1] = max$$1[0] = max$$1[1] = 0;
  29201. }
  29202. return this._rect = new BoundingRect(min$$1[0], min$$1[1], max$$1[0] - min$$1[0], max$$1[1] - min$$1[1]);
  29203. },
  29204. /**
  29205. * @param {<Array.<number>} coord
  29206. * @return {boolean}
  29207. */
  29208. contain: function (coord) {
  29209. var rect = this.getBoundingRect();
  29210. var geometries = this.geometries;
  29211. if (!rect.contain(coord[0], coord[1])) {
  29212. return false;
  29213. }
  29214. loopGeo: for (var i = 0, len$$1 = geometries.length; i < len$$1; i++) {
  29215. // Only support polygon.
  29216. if (geometries[i].type !== 'polygon') {
  29217. continue;
  29218. }
  29219. var exterior = geometries[i].exterior;
  29220. var interiors = geometries[i].interiors;
  29221. if (contain$1(exterior, coord[0], coord[1])) {
  29222. // Not in the region if point is in the hole.
  29223. for (var k = 0; k < (interiors ? interiors.length : 0); k++) {
  29224. if (contain$1(interiors[k])) {
  29225. continue loopGeo;
  29226. }
  29227. }
  29228. return true;
  29229. }
  29230. }
  29231. return false;
  29232. },
  29233. transformTo: function (x, y, width, height) {
  29234. var rect = this.getBoundingRect();
  29235. var aspect = rect.width / rect.height;
  29236. if (!width) {
  29237. width = aspect * height;
  29238. } else if (!height) {
  29239. height = width / aspect;
  29240. }
  29241. var target = new BoundingRect(x, y, width, height);
  29242. var transform = rect.calculateTransform(target);
  29243. var geometries = this.geometries;
  29244. for (var i = 0; i < geometries.length; i++) {
  29245. // Only support polygon.
  29246. if (geometries[i].type !== 'polygon') {
  29247. continue;
  29248. }
  29249. var exterior = geometries[i].exterior;
  29250. var interiors = geometries[i].interiors;
  29251. for (var p = 0; p < exterior.length; p++) {
  29252. applyTransform(exterior[p], exterior[p], transform);
  29253. }
  29254. for (var h = 0; h < (interiors ? interiors.length : 0); h++) {
  29255. for (var p = 0; p < interiors[h].length; p++) {
  29256. applyTransform(interiors[h][p], interiors[h][p], transform);
  29257. }
  29258. }
  29259. }
  29260. rect = this._rect;
  29261. rect.copy(target); // Update center
  29262. this.center = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  29263. },
  29264. cloneShallow: function (name) {
  29265. name == null && (name = this.name);
  29266. var newRegion = new Region(name, this.geometries, this.center);
  29267. newRegion._rect = this._rect;
  29268. newRegion.transformTo = null; // Simply avoid to be called.
  29269. return newRegion;
  29270. }
  29271. };
  29272. /*
  29273. * Licensed to the Apache Software Foundation (ASF) under one
  29274. * or more contributor license agreements. See the NOTICE file
  29275. * distributed with this work for additional information
  29276. * regarding copyright ownership. The ASF licenses this file
  29277. * to you under the Apache License, Version 2.0 (the
  29278. * "License"); you may not use this file except in compliance
  29279. * with the License. You may obtain a copy of the License at
  29280. *
  29281. * http://www.apache.org/licenses/LICENSE-2.0
  29282. *
  29283. * Unless required by applicable law or agreed to in writing,
  29284. * software distributed under the License is distributed on an
  29285. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29286. * KIND, either express or implied. See the License for the
  29287. * specific language governing permissions and limitations
  29288. * under the License.
  29289. */
  29290. /**
  29291. * Parse and decode geo json
  29292. * @module echarts/coord/geo/parseGeoJson
  29293. */
  29294. function decode(json) {
  29295. if (!json.UTF8Encoding) {
  29296. return json;
  29297. }
  29298. var encodeScale = json.UTF8Scale;
  29299. if (encodeScale == null) {
  29300. encodeScale = 1024;
  29301. }
  29302. var features = json.features;
  29303. for (var f = 0; f < features.length; f++) {
  29304. var feature = features[f];
  29305. var geometry = feature.geometry;
  29306. var coordinates = geometry.coordinates;
  29307. var encodeOffsets = geometry.encodeOffsets;
  29308. for (var c = 0; c < coordinates.length; c++) {
  29309. var coordinate = coordinates[c];
  29310. if (geometry.type === 'Polygon') {
  29311. coordinates[c] = decodePolygon(coordinate, encodeOffsets[c], encodeScale);
  29312. } else if (geometry.type === 'MultiPolygon') {
  29313. for (var c2 = 0; c2 < coordinate.length; c2++) {
  29314. var polygon = coordinate[c2];
  29315. coordinate[c2] = decodePolygon(polygon, encodeOffsets[c][c2], encodeScale);
  29316. }
  29317. }
  29318. }
  29319. } // Has been decoded
  29320. json.UTF8Encoding = false;
  29321. return json;
  29322. }
  29323. function decodePolygon(coordinate, encodeOffsets, encodeScale) {
  29324. var result = [];
  29325. var prevX = encodeOffsets[0];
  29326. var prevY = encodeOffsets[1];
  29327. for (var i = 0; i < coordinate.length; i += 2) {
  29328. var x = coordinate.charCodeAt(i) - 64;
  29329. var y = coordinate.charCodeAt(i + 1) - 64; // ZigZag decoding
  29330. x = x >> 1 ^ -(x & 1);
  29331. y = y >> 1 ^ -(y & 1); // Delta deocding
  29332. x += prevX;
  29333. y += prevY;
  29334. prevX = x;
  29335. prevY = y; // Dequantize
  29336. result.push([x / encodeScale, y / encodeScale]);
  29337. }
  29338. return result;
  29339. }
  29340. /**
  29341. * @alias module:echarts/coord/geo/parseGeoJson
  29342. * @param {Object} geoJson
  29343. * @param {string} nameProperty
  29344. * @return {module:zrender/container/Group}
  29345. */
  29346. var parseGeoJson$1 = function (geoJson, nameProperty) {
  29347. decode(geoJson);
  29348. return map(filter(geoJson.features, function (featureObj) {
  29349. // Output of mapshaper may have geometry null
  29350. return featureObj.geometry && featureObj.properties && featureObj.geometry.coordinates.length > 0;
  29351. }), function (featureObj) {
  29352. var properties = featureObj.properties;
  29353. var geo = featureObj.geometry;
  29354. var coordinates = geo.coordinates;
  29355. var geometries = [];
  29356. if (geo.type === 'Polygon') {
  29357. geometries.push({
  29358. type: 'polygon',
  29359. // According to the GeoJSON specification.
  29360. // First must be exterior, and the rest are all interior(holes).
  29361. exterior: coordinates[0],
  29362. interiors: coordinates.slice(1)
  29363. });
  29364. }
  29365. if (geo.type === 'MultiPolygon') {
  29366. each$1(coordinates, function (item) {
  29367. if (item[0]) {
  29368. geometries.push({
  29369. type: 'polygon',
  29370. exterior: item[0],
  29371. interiors: item.slice(1)
  29372. });
  29373. }
  29374. });
  29375. }
  29376. var region = new Region(properties[nameProperty || 'name'], geometries, properties.cp);
  29377. region.properties = properties;
  29378. return region;
  29379. });
  29380. };
  29381. /*
  29382. * Licensed to the Apache Software Foundation (ASF) under one
  29383. * or more contributor license agreements. See the NOTICE file
  29384. * distributed with this work for additional information
  29385. * regarding copyright ownership. The ASF licenses this file
  29386. * to you under the Apache License, Version 2.0 (the
  29387. * "License"); you may not use this file except in compliance
  29388. * with the License. You may obtain a copy of the License at
  29389. *
  29390. * http://www.apache.org/licenses/LICENSE-2.0
  29391. *
  29392. * Unless required by applicable law or agreed to in writing,
  29393. * software distributed under the License is distributed on an
  29394. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29395. * KIND, either express or implied. See the License for the
  29396. * specific language governing permissions and limitations
  29397. * under the License.
  29398. */
  29399. var inner$6 = makeInner();
  29400. /**
  29401. * @param {module:echats/coord/Axis} axis
  29402. * @return {Object} {
  29403. * labels: [{
  29404. * formattedLabel: string,
  29405. * rawLabel: string,
  29406. * tickValue: number
  29407. * }, ...],
  29408. * labelCategoryInterval: number
  29409. * }
  29410. */
  29411. function createAxisLabels(axis) {
  29412. // Only ordinal scale support tick interval
  29413. return axis.type === 'category' ? makeCategoryLabels(axis) : makeRealNumberLabels(axis);
  29414. }
  29415. /**
  29416. * @param {module:echats/coord/Axis} axis
  29417. * @param {module:echarts/model/Model} tickModel For example, can be axisTick, splitLine, splitArea.
  29418. * @return {Object} {
  29419. * ticks: Array.<number>
  29420. * tickCategoryInterval: number
  29421. * }
  29422. */
  29423. function createAxisTicks(axis, tickModel) {
  29424. // Only ordinal scale support tick interval
  29425. return axis.type === 'category' ? makeCategoryTicks(axis, tickModel) : {
  29426. ticks: axis.scale.getTicks()
  29427. };
  29428. }
  29429. function makeCategoryLabels(axis) {
  29430. var labelModel = axis.getLabelModel();
  29431. var result = makeCategoryLabelsActually(axis, labelModel);
  29432. return !labelModel.get('show') || axis.scale.isBlank() ? {
  29433. labels: [],
  29434. labelCategoryInterval: result.labelCategoryInterval
  29435. } : result;
  29436. }
  29437. function makeCategoryLabelsActually(axis, labelModel) {
  29438. var labelsCache = getListCache(axis, 'labels');
  29439. var optionLabelInterval = getOptionCategoryInterval(labelModel);
  29440. var result = listCacheGet(labelsCache, optionLabelInterval);
  29441. if (result) {
  29442. return result;
  29443. }
  29444. var labels;
  29445. var numericLabelInterval;
  29446. if (isFunction$1(optionLabelInterval)) {
  29447. labels = makeLabelsByCustomizedCategoryInterval(axis, optionLabelInterval);
  29448. } else {
  29449. numericLabelInterval = optionLabelInterval === 'auto' ? makeAutoCategoryInterval(axis) : optionLabelInterval;
  29450. labels = makeLabelsByNumericCategoryInterval(axis, numericLabelInterval);
  29451. } // Cache to avoid calling interval function repeatly.
  29452. return listCacheSet(labelsCache, optionLabelInterval, {
  29453. labels: labels,
  29454. labelCategoryInterval: numericLabelInterval
  29455. });
  29456. }
  29457. function makeCategoryTicks(axis, tickModel) {
  29458. var ticksCache = getListCache(axis, 'ticks');
  29459. var optionTickInterval = getOptionCategoryInterval(tickModel);
  29460. var result = listCacheGet(ticksCache, optionTickInterval);
  29461. if (result) {
  29462. return result;
  29463. }
  29464. var ticks;
  29465. var tickCategoryInterval; // Optimize for the case that large category data and no label displayed,
  29466. // we should not return all ticks.
  29467. if (!tickModel.get('show') || axis.scale.isBlank()) {
  29468. ticks = [];
  29469. }
  29470. if (isFunction$1(optionTickInterval)) {
  29471. ticks = makeLabelsByCustomizedCategoryInterval(axis, optionTickInterval, true);
  29472. } // Always use label interval by default despite label show. Consider this
  29473. // scenario, Use multiple grid with the xAxis sync, and only one xAxis shows
  29474. // labels. `splitLine` and `axisTick` should be consistent in this case.
  29475. else if (optionTickInterval === 'auto') {
  29476. var labelsResult = makeCategoryLabelsActually(axis, axis.getLabelModel());
  29477. tickCategoryInterval = labelsResult.labelCategoryInterval;
  29478. ticks = map(labelsResult.labels, function (labelItem) {
  29479. return labelItem.tickValue;
  29480. });
  29481. } else {
  29482. tickCategoryInterval = optionTickInterval;
  29483. ticks = makeLabelsByNumericCategoryInterval(axis, tickCategoryInterval, true);
  29484. } // Cache to avoid calling interval function repeatly.
  29485. return listCacheSet(ticksCache, optionTickInterval, {
  29486. ticks: ticks,
  29487. tickCategoryInterval: tickCategoryInterval
  29488. });
  29489. }
  29490. function makeRealNumberLabels(axis) {
  29491. var ticks = axis.scale.getTicks();
  29492. var labelFormatter = makeLabelFormatter(axis);
  29493. return {
  29494. labels: map(ticks, function (tickValue, idx) {
  29495. return {
  29496. formattedLabel: labelFormatter(tickValue, idx),
  29497. rawLabel: axis.scale.getLabel(tickValue),
  29498. tickValue: tickValue
  29499. };
  29500. })
  29501. };
  29502. } // Large category data calculation is performence sensitive, and ticks and label
  29503. // probably be fetched by multiple times. So we cache the result.
  29504. // axis is created each time during a ec process, so we do not need to clear cache.
  29505. function getListCache(axis, prop) {
  29506. // Because key can be funciton, and cache size always be small, we use array cache.
  29507. return inner$6(axis)[prop] || (inner$6(axis)[prop] = []);
  29508. }
  29509. function listCacheGet(cache, key) {
  29510. for (var i = 0; i < cache.length; i++) {
  29511. if (cache[i].key === key) {
  29512. return cache[i].value;
  29513. }
  29514. }
  29515. }
  29516. function listCacheSet(cache, key, value) {
  29517. cache.push({
  29518. key: key,
  29519. value: value
  29520. });
  29521. return value;
  29522. }
  29523. function makeAutoCategoryInterval(axis) {
  29524. var result = inner$6(axis).autoInterval;
  29525. return result != null ? result : inner$6(axis).autoInterval = axis.calculateCategoryInterval();
  29526. }
  29527. /**
  29528. * Calculate interval for category axis ticks and labels.
  29529. * To get precise result, at least one of `getRotate` and `isHorizontal`
  29530. * should be implemented in axis.
  29531. */
  29532. function calculateCategoryInterval(axis) {
  29533. var params = fetchAutoCategoryIntervalCalculationParams(axis);
  29534. var labelFormatter = makeLabelFormatter(axis);
  29535. var rotation = (params.axisRotate - params.labelRotate) / 180 * Math.PI;
  29536. var ordinalScale = axis.scale;
  29537. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  29538. // avoid generating a long array by `getTicks`
  29539. // in large category data case.
  29540. var tickCount = ordinalScale.count();
  29541. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  29542. return 0;
  29543. }
  29544. var step = 1; // Simple optimization. Empirical value: tick count should less than 40.
  29545. if (tickCount > 40) {
  29546. step = Math.max(1, Math.floor(tickCount / 40));
  29547. }
  29548. var tickValue = ordinalExtent[0];
  29549. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  29550. var unitW = Math.abs(unitSpan * Math.cos(rotation));
  29551. var unitH = Math.abs(unitSpan * Math.sin(rotation));
  29552. var maxW = 0;
  29553. var maxH = 0; // Caution: Performance sensitive for large category data.
  29554. // Consider dataZoom, we should make appropriate step to avoid O(n) loop.
  29555. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  29556. var width = 0;
  29557. var height = 0; // Not precise, do not consider align and vertical align
  29558. // and each distance from axis line yet.
  29559. var rect = getBoundingRect(labelFormatter(tickValue), params.font, 'center', 'top'); // Magic number
  29560. width = rect.width * 1.3;
  29561. height = rect.height * 1.3; // Min size, void long loop.
  29562. maxW = Math.max(maxW, width, 7);
  29563. maxH = Math.max(maxH, height, 7);
  29564. }
  29565. var dw = maxW / unitW;
  29566. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  29567. isNaN(dw) && (dw = Infinity);
  29568. isNaN(dh) && (dh = Infinity);
  29569. var interval = Math.max(0, Math.floor(Math.min(dw, dh)));
  29570. var cache = inner$6(axis.model);
  29571. var axisExtent = axis.getExtent();
  29572. var lastAutoInterval = cache.lastAutoInterval;
  29573. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  29574. // otherwise the calculated interval might jitter when the zoom
  29575. // window size is close to the interval-changing size.
  29576. // For example, if all of the axis labels are `a, b, c, d, e, f, g`.
  29577. // The jitter will cause that sometimes the displayed labels are
  29578. // `a, d, g` (interval: 2) sometimes `a, c, e`(interval: 1).
  29579. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  29580. // point is not the same when zooming in or zooming out.
  29581. && lastAutoInterval > interval // If the axis change is caused by chart resize, the cache should not
  29582. // be used. Otherwise some hiden labels might not be shown again.
  29583. && cache.axisExtend0 === axisExtent[0] && cache.axisExtend1 === axisExtent[1]) {
  29584. interval = lastAutoInterval;
  29585. } // Only update cache if cache not used, otherwise the
  29586. // changing of interval is too insensitive.
  29587. else {
  29588. cache.lastTickCount = tickCount;
  29589. cache.lastAutoInterval = interval;
  29590. cache.axisExtend0 = axisExtent[0];
  29591. cache.axisExtend1 = axisExtent[1];
  29592. }
  29593. return interval;
  29594. }
  29595. function fetchAutoCategoryIntervalCalculationParams(axis) {
  29596. var labelModel = axis.getLabelModel();
  29597. return {
  29598. axisRotate: axis.getRotate ? axis.getRotate() : axis.isHorizontal && !axis.isHorizontal() ? 90 : 0,
  29599. labelRotate: labelModel.get('rotate') || 0,
  29600. font: labelModel.getFont()
  29601. };
  29602. }
  29603. function makeLabelsByNumericCategoryInterval(axis, categoryInterval, onlyTick) {
  29604. var labelFormatter = makeLabelFormatter(axis);
  29605. var ordinalScale = axis.scale;
  29606. var ordinalExtent = ordinalScale.getExtent();
  29607. var labelModel = axis.getLabelModel();
  29608. var result = []; // TODO: axisType: ordinalTime, pick the tick from each month/day/year/...
  29609. var step = Math.max((categoryInterval || 0) + 1, 1);
  29610. var startTick = ordinalExtent[0];
  29611. var tickCount = ordinalScale.count(); // Calculate start tick based on zero if possible to keep label consistent
  29612. // while zooming and moving while interval > 0. Otherwise the selection
  29613. // of displayable ticks and symbols probably keep changing.
  29614. // 3 is empirical value.
  29615. if (startTick !== 0 && step > 1 && tickCount / step > 2) {
  29616. startTick = Math.round(Math.ceil(startTick / step) * step);
  29617. } // (1) Only add min max label here but leave overlap checking
  29618. // to render stage, which also ensure the returned list
  29619. // suitable for splitLine and splitArea rendering.
  29620. // (2) Scales except category always contain min max label so
  29621. // do not need to perform this process.
  29622. var showAllLabel = shouldShowAllLabels(axis);
  29623. var includeMinLabel = labelModel.get('showMinLabel') || showAllLabel;
  29624. var includeMaxLabel = labelModel.get('showMaxLabel') || showAllLabel;
  29625. if (includeMinLabel && startTick !== ordinalExtent[0]) {
  29626. addItem(ordinalExtent[0]);
  29627. } // Optimize: avoid generating large array by `ordinalScale.getTicks()`.
  29628. var tickValue = startTick;
  29629. for (; tickValue <= ordinalExtent[1]; tickValue += step) {
  29630. addItem(tickValue);
  29631. }
  29632. if (includeMaxLabel && tickValue - step !== ordinalExtent[1]) {
  29633. addItem(ordinalExtent[1]);
  29634. }
  29635. function addItem(tVal) {
  29636. result.push(onlyTick ? tVal : {
  29637. formattedLabel: labelFormatter(tVal),
  29638. rawLabel: ordinalScale.getLabel(tVal),
  29639. tickValue: tVal
  29640. });
  29641. }
  29642. return result;
  29643. } // When interval is function, the result `false` means ignore the tick.
  29644. // It is time consuming for large category data.
  29645. function makeLabelsByCustomizedCategoryInterval(axis, categoryInterval, onlyTick) {
  29646. var ordinalScale = axis.scale;
  29647. var labelFormatter = makeLabelFormatter(axis);
  29648. var result = [];
  29649. each$1(ordinalScale.getTicks(), function (tickValue) {
  29650. var rawLabel = ordinalScale.getLabel(tickValue);
  29651. if (categoryInterval(tickValue, rawLabel)) {
  29652. result.push(onlyTick ? tickValue : {
  29653. formattedLabel: labelFormatter(tickValue),
  29654. rawLabel: rawLabel,
  29655. tickValue: tickValue
  29656. });
  29657. }
  29658. });
  29659. return result;
  29660. }
  29661. /*
  29662. * Licensed to the Apache Software Foundation (ASF) under one
  29663. * or more contributor license agreements. See the NOTICE file
  29664. * distributed with this work for additional information
  29665. * regarding copyright ownership. The ASF licenses this file
  29666. * to you under the Apache License, Version 2.0 (the
  29667. * "License"); you may not use this file except in compliance
  29668. * with the License. You may obtain a copy of the License at
  29669. *
  29670. * http://www.apache.org/licenses/LICENSE-2.0
  29671. *
  29672. * Unless required by applicable law or agreed to in writing,
  29673. * software distributed under the License is distributed on an
  29674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29675. * KIND, either express or implied. See the License for the
  29676. * specific language governing permissions and limitations
  29677. * under the License.
  29678. */
  29679. var NORMALIZED_EXTENT = [0, 1];
  29680. /**
  29681. * Base class of Axis.
  29682. * @constructor
  29683. */
  29684. var Axis = function (dim, scale, extent) {
  29685. /**
  29686. * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius'.
  29687. * @type {string}
  29688. */
  29689. this.dim = dim;
  29690. /**
  29691. * Axis scale
  29692. * @type {module:echarts/coord/scale/*}
  29693. */
  29694. this.scale = scale;
  29695. /**
  29696. * @type {Array.<number>}
  29697. * @private
  29698. */
  29699. this._extent = extent || [0, 0];
  29700. /**
  29701. * @type {boolean}
  29702. */
  29703. this.inverse = false;
  29704. /**
  29705. * Usually true when axis has a ordinal scale
  29706. * @type {boolean}
  29707. */
  29708. this.onBand = false;
  29709. };
  29710. Axis.prototype = {
  29711. constructor: Axis,
  29712. /**
  29713. * If axis extent contain given coord
  29714. * @param {number} coord
  29715. * @return {boolean}
  29716. */
  29717. contain: function (coord) {
  29718. var extent = this._extent;
  29719. var min = Math.min(extent[0], extent[1]);
  29720. var max = Math.max(extent[0], extent[1]);
  29721. return coord >= min && coord <= max;
  29722. },
  29723. /**
  29724. * If axis extent contain given data
  29725. * @param {number} data
  29726. * @return {boolean}
  29727. */
  29728. containData: function (data) {
  29729. return this.scale.contain(data);
  29730. },
  29731. /**
  29732. * Get coord extent.
  29733. * @return {Array.<number>}
  29734. */
  29735. getExtent: function () {
  29736. return this._extent.slice();
  29737. },
  29738. /**
  29739. * Get precision used for formatting
  29740. * @param {Array.<number>} [dataExtent]
  29741. * @return {number}
  29742. */
  29743. getPixelPrecision: function (dataExtent) {
  29744. return getPixelPrecision(dataExtent || this.scale.getExtent(), this._extent);
  29745. },
  29746. /**
  29747. * Set coord extent
  29748. * @param {number} start
  29749. * @param {number} end
  29750. */
  29751. setExtent: function (start, end) {
  29752. var extent = this._extent;
  29753. extent[0] = start;
  29754. extent[1] = end;
  29755. },
  29756. /**
  29757. * Convert data to coord. Data is the rank if it has an ordinal scale
  29758. * @param {number} data
  29759. * @param {boolean} clamp
  29760. * @return {number}
  29761. */
  29762. dataToCoord: function (data, clamp) {
  29763. var extent = this._extent;
  29764. var scale = this.scale;
  29765. data = scale.normalize(data);
  29766. if (this.onBand && scale.type === 'ordinal') {
  29767. extent = extent.slice();
  29768. fixExtentWithBands(extent, scale.count());
  29769. }
  29770. return linearMap(data, NORMALIZED_EXTENT, extent, clamp);
  29771. },
  29772. /**
  29773. * Convert coord to data. Data is the rank if it has an ordinal scale
  29774. * @param {number} coord
  29775. * @param {boolean} clamp
  29776. * @return {number}
  29777. */
  29778. coordToData: function (coord, clamp) {
  29779. var extent = this._extent;
  29780. var scale = this.scale;
  29781. if (this.onBand && scale.type === 'ordinal') {
  29782. extent = extent.slice();
  29783. fixExtentWithBands(extent, scale.count());
  29784. }
  29785. var t = linearMap(coord, extent, NORMALIZED_EXTENT, clamp);
  29786. return this.scale.scale(t);
  29787. },
  29788. /**
  29789. * Convert pixel point to data in axis
  29790. * @param {Array.<number>} point
  29791. * @param {boolean} clamp
  29792. * @return {number} data
  29793. */
  29794. pointToData: function (point, clamp) {// Should be implemented in derived class if necessary.
  29795. },
  29796. /**
  29797. * Different from `zrUtil.map(axis.getTicks(), axis.dataToCoord, axis)`,
  29798. * `axis.getTicksCoords` considers `onBand`, which is used by
  29799. * `boundaryGap:true` of category axis and splitLine and splitArea.
  29800. * @param {Object} [opt]
  29801. * @param {Model} [opt.tickModel=axis.model.getModel('axisTick')]
  29802. * @param {boolean} [opt.clamp] If `true`, the first and the last
  29803. * tick must be at the axis end points. Otherwise, clip ticks
  29804. * that outside the axis extent.
  29805. * @return {Array.<Object>} [{
  29806. * coord: ...,
  29807. * tickValue: ...
  29808. * }, ...]
  29809. */
  29810. getTicksCoords: function (opt) {
  29811. opt = opt || {};
  29812. var tickModel = opt.tickModel || this.getTickModel();
  29813. var result = createAxisTicks(this, tickModel);
  29814. var ticks = result.ticks;
  29815. var ticksCoords = map(ticks, function (tickValue) {
  29816. return {
  29817. coord: this.dataToCoord(tickValue),
  29818. tickValue: tickValue
  29819. };
  29820. }, this);
  29821. var alignWithLabel = tickModel.get('alignWithLabel');
  29822. fixOnBandTicksCoords(this, ticksCoords, alignWithLabel, opt.clamp);
  29823. return ticksCoords;
  29824. },
  29825. /**
  29826. * @return {Array.<Array.<Object>>} [{ coord: ..., tickValue: ...}]
  29827. */
  29828. getMinorTicksCoords: function () {
  29829. if (this.scale.type === 'ordinal') {
  29830. // Category axis doesn't support minor ticks
  29831. return [];
  29832. }
  29833. var minorTickModel = this.model.getModel('minorTick');
  29834. var splitNumber = minorTickModel.get('splitNumber'); // Protection.
  29835. if (!(splitNumber > 0 && splitNumber < 100)) {
  29836. splitNumber = 5;
  29837. }
  29838. var minorTicks = this.scale.getMinorTicks(splitNumber);
  29839. var minorTicksCoords = map(minorTicks, function (minorTicksGroup) {
  29840. return map(minorTicksGroup, function (minorTick) {
  29841. return {
  29842. coord: this.dataToCoord(minorTick),
  29843. tickValue: minorTick
  29844. };
  29845. }, this);
  29846. }, this);
  29847. return minorTicksCoords;
  29848. },
  29849. /**
  29850. * @return {Array.<Object>} [{
  29851. * formattedLabel: string,
  29852. * rawLabel: axis.scale.getLabel(tickValue)
  29853. * tickValue: number
  29854. * }, ...]
  29855. */
  29856. getViewLabels: function () {
  29857. return createAxisLabels(this).labels;
  29858. },
  29859. /**
  29860. * @return {module:echarts/coord/model/Model}
  29861. */
  29862. getLabelModel: function () {
  29863. return this.model.getModel('axisLabel');
  29864. },
  29865. /**
  29866. * Notice here we only get the default tick model. For splitLine
  29867. * or splitArea, we should pass the splitLineModel or splitAreaModel
  29868. * manually when calling `getTicksCoords`.
  29869. * In GL, this method may be overrided to:
  29870. * `axisModel.getModel('axisTick', grid3DModel.getModel('axisTick'));`
  29871. * @return {module:echarts/coord/model/Model}
  29872. */
  29873. getTickModel: function () {
  29874. return this.model.getModel('axisTick');
  29875. },
  29876. /**
  29877. * Get width of band
  29878. * @return {number}
  29879. */
  29880. getBandWidth: function () {
  29881. var axisExtent = this._extent;
  29882. var dataExtent = this.scale.getExtent();
  29883. var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data.
  29884. len === 0 && (len = 1);
  29885. var size = Math.abs(axisExtent[1] - axisExtent[0]);
  29886. return Math.abs(size) / len;
  29887. },
  29888. /**
  29889. * @abstract
  29890. * @return {boolean} Is horizontal
  29891. */
  29892. isHorizontal: null,
  29893. /**
  29894. * @abstract
  29895. * @return {number} Get axis rotate, by degree.
  29896. */
  29897. getRotate: null,
  29898. /**
  29899. * Only be called in category axis.
  29900. * Can be overrided, consider other axes like in 3D.
  29901. * @return {number} Auto interval for cateogry axis tick and label
  29902. */
  29903. calculateCategoryInterval: function () {
  29904. return calculateCategoryInterval(this);
  29905. }
  29906. };
  29907. function fixExtentWithBands(extent, nTick) {
  29908. var size = extent[1] - extent[0];
  29909. var len = nTick;
  29910. var margin = size / len / 2;
  29911. extent[0] += margin;
  29912. extent[1] -= margin;
  29913. } // If axis has labels [1, 2, 3, 4]. Bands on the axis are
  29914. // |---1---|---2---|---3---|---4---|.
  29915. // So the displayed ticks and splitLine/splitArea should between
  29916. // each data item, otherwise cause misleading (e.g., split tow bars
  29917. // of a single data item when there are two bar series).
  29918. // Also consider if tickCategoryInterval > 0 and onBand, ticks and
  29919. // splitLine/spliteArea should layout appropriately corresponding
  29920. // to displayed labels. (So we should not use `getBandWidth` in this
  29921. // case).
  29922. function fixOnBandTicksCoords(axis, ticksCoords, alignWithLabel, clamp) {
  29923. var ticksLen = ticksCoords.length;
  29924. if (!axis.onBand || alignWithLabel || !ticksLen) {
  29925. return;
  29926. }
  29927. var axisExtent = axis.getExtent();
  29928. var last;
  29929. var diffSize;
  29930. if (ticksLen === 1) {
  29931. ticksCoords[0].coord = axisExtent[0];
  29932. last = ticksCoords[1] = {
  29933. coord: axisExtent[0]
  29934. };
  29935. } else {
  29936. var crossLen = ticksCoords[ticksLen - 1].tickValue - ticksCoords[0].tickValue;
  29937. var shift = (ticksCoords[ticksLen - 1].coord - ticksCoords[0].coord) / crossLen;
  29938. each$1(ticksCoords, function (ticksItem) {
  29939. ticksItem.coord -= shift / 2;
  29940. });
  29941. var dataExtent = axis.scale.getExtent();
  29942. diffSize = 1 + dataExtent[1] - ticksCoords[ticksLen - 1].tickValue;
  29943. last = {
  29944. coord: ticksCoords[ticksLen - 1].coord + shift * diffSize
  29945. };
  29946. ticksCoords.push(last);
  29947. }
  29948. var inverse = axisExtent[0] > axisExtent[1]; // Handling clamp.
  29949. if (littleThan(ticksCoords[0].coord, axisExtent[0])) {
  29950. clamp ? ticksCoords[0].coord = axisExtent[0] : ticksCoords.shift();
  29951. }
  29952. if (clamp && littleThan(axisExtent[0], ticksCoords[0].coord)) {
  29953. ticksCoords.unshift({
  29954. coord: axisExtent[0]
  29955. });
  29956. }
  29957. if (littleThan(axisExtent[1], last.coord)) {
  29958. clamp ? last.coord = axisExtent[1] : ticksCoords.pop();
  29959. }
  29960. if (clamp && littleThan(last.coord, axisExtent[1])) {
  29961. ticksCoords.push({
  29962. coord: axisExtent[1]
  29963. });
  29964. }
  29965. function littleThan(a, b) {
  29966. // Avoid rounding error cause calculated tick coord different with extent.
  29967. // It may cause an extra unecessary tick added.
  29968. a = round$1(a);
  29969. b = round$1(b);
  29970. return inverse ? a > b : a < b;
  29971. }
  29972. }
  29973. /*
  29974. * Licensed to the Apache Software Foundation (ASF) under one
  29975. * or more contributor license agreements. See the NOTICE file
  29976. * distributed with this work for additional information
  29977. * regarding copyright ownership. The ASF licenses this file
  29978. * to you under the Apache License, Version 2.0 (the
  29979. * "License"); you may not use this file except in compliance
  29980. * with the License. You may obtain a copy of the License at
  29981. *
  29982. * http://www.apache.org/licenses/LICENSE-2.0
  29983. *
  29984. * Unless required by applicable law or agreed to in writing,
  29985. * software distributed under the License is distributed on an
  29986. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  29987. * KIND, either express or implied. See the License for the
  29988. * specific language governing permissions and limitations
  29989. * under the License.
  29990. */
  29991. /**
  29992. * Do not mount those modules on 'src/echarts' for better tree shaking.
  29993. */
  29994. var parseGeoJson = parseGeoJson$1;
  29995. var ecUtil = {};
  29996. each$1(['map', 'each', 'filter', 'indexOf', 'inherits', 'reduce', 'filter', 'bind', 'curry', 'isArray', 'isString', 'isObject', 'isFunction', 'extend', 'defaults', 'clone', 'merge'], function (name) {
  29997. ecUtil[name] = zrUtil[name];
  29998. });
  29999. var graphic$1 = {};
  30000. each$1(['extendShape', 'extendPath', 'makePath', 'makeImage', 'mergePath', 'resizePath', 'createIcon', 'setHoverStyle', 'setLabelStyle', 'setTextStyle', 'setText', 'getFont', 'updateProps', 'initProps', 'getTransform', 'clipPointsByRect', 'clipRectByRect', 'registerShape', 'getShapeClass', 'Group', 'Image', 'Text', 'Circle', 'Sector', 'Ring', 'Polygon', 'Polyline', 'Rect', 'Line', 'BezierCurve', 'Arc', 'IncrementalDisplayable', 'CompoundPath', 'LinearGradient', 'RadialGradient', 'BoundingRect'], function (name) {
  30001. graphic$1[name] = graphic[name];
  30002. });
  30003. /*
  30004. * Licensed to the Apache Software Foundation (ASF) under one
  30005. * or more contributor license agreements. See the NOTICE file
  30006. * distributed with this work for additional information
  30007. * regarding copyright ownership. The ASF licenses this file
  30008. * to you under the Apache License, Version 2.0 (the
  30009. * "License"); you may not use this file except in compliance
  30010. * with the License. You may obtain a copy of the License at
  30011. *
  30012. * http://www.apache.org/licenses/LICENSE-2.0
  30013. *
  30014. * Unless required by applicable law or agreed to in writing,
  30015. * software distributed under the License is distributed on an
  30016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30017. * KIND, either express or implied. See the License for the
  30018. * specific language governing permissions and limitations
  30019. * under the License.
  30020. */
  30021. /**
  30022. * Cartesian coordinate system
  30023. * @module echarts/coord/Cartesian
  30024. *
  30025. */
  30026. function dimAxisMapper(dim) {
  30027. return this._axes[dim];
  30028. }
  30029. /**
  30030. * @alias module:echarts/coord/Cartesian
  30031. * @constructor
  30032. */
  30033. var Cartesian = function (name) {
  30034. this._axes = {};
  30035. this._dimList = [];
  30036. /**
  30037. * @type {string}
  30038. */
  30039. this.name = name || '';
  30040. };
  30041. Cartesian.prototype = {
  30042. constructor: Cartesian,
  30043. type: 'cartesian',
  30044. /**
  30045. * Get axis
  30046. * @param {number|string} dim
  30047. * @return {module:echarts/coord/Cartesian~Axis}
  30048. */
  30049. getAxis: function (dim) {
  30050. return this._axes[dim];
  30051. },
  30052. /**
  30053. * Get axes list
  30054. * @return {Array.<module:echarts/coord/Cartesian~Axis>}
  30055. */
  30056. getAxes: function () {
  30057. return map(this._dimList, dimAxisMapper, this);
  30058. },
  30059. /**
  30060. * Get axes list by given scale type
  30061. */
  30062. getAxesByScale: function (scaleType) {
  30063. scaleType = scaleType.toLowerCase();
  30064. return filter(this.getAxes(), function (axis) {
  30065. return axis.scale.type === scaleType;
  30066. });
  30067. },
  30068. /**
  30069. * Add axis
  30070. * @param {module:echarts/coord/Cartesian.Axis}
  30071. */
  30072. addAxis: function (axis) {
  30073. var dim = axis.dim;
  30074. this._axes[dim] = axis;
  30075. this._dimList.push(dim);
  30076. },
  30077. /**
  30078. * Convert data to coord in nd space
  30079. * @param {Array.<number>|Object.<string, number>} val
  30080. * @return {Array.<number>|Object.<string, number>}
  30081. */
  30082. dataToCoord: function (val) {
  30083. return this._dataCoordConvert(val, 'dataToCoord');
  30084. },
  30085. /**
  30086. * Convert coord in nd space to data
  30087. * @param {Array.<number>|Object.<string, number>} val
  30088. * @return {Array.<number>|Object.<string, number>}
  30089. */
  30090. coordToData: function (val) {
  30091. return this._dataCoordConvert(val, 'coordToData');
  30092. },
  30093. _dataCoordConvert: function (input, method) {
  30094. var dimList = this._dimList;
  30095. var output = input instanceof Array ? [] : {};
  30096. for (var i = 0; i < dimList.length; i++) {
  30097. var dim = dimList[i];
  30098. var axis = this._axes[dim];
  30099. output[dim] = axis[method](input[dim]);
  30100. }
  30101. return output;
  30102. }
  30103. };
  30104. /*
  30105. * Licensed to the Apache Software Foundation (ASF) under one
  30106. * or more contributor license agreements. See the NOTICE file
  30107. * distributed with this work for additional information
  30108. * regarding copyright ownership. The ASF licenses this file
  30109. * to you under the Apache License, Version 2.0 (the
  30110. * "License"); you may not use this file except in compliance
  30111. * with the License. You may obtain a copy of the License at
  30112. *
  30113. * http://www.apache.org/licenses/LICENSE-2.0
  30114. *
  30115. * Unless required by applicable law or agreed to in writing,
  30116. * software distributed under the License is distributed on an
  30117. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30118. * KIND, either express or implied. See the License for the
  30119. * specific language governing permissions and limitations
  30120. * under the License.
  30121. */
  30122. function Cartesian2D(name) {
  30123. Cartesian.call(this, name);
  30124. }
  30125. Cartesian2D.prototype = {
  30126. constructor: Cartesian2D,
  30127. type: 'cartesian2d',
  30128. /**
  30129. * @type {Array.<string>}
  30130. * @readOnly
  30131. */
  30132. dimensions: ['x', 'y'],
  30133. /**
  30134. * Base axis will be used on stacking.
  30135. *
  30136. * @return {module:echarts/coord/cartesian/Axis2D}
  30137. */
  30138. getBaseAxis: function () {
  30139. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x');
  30140. },
  30141. /**
  30142. * If contain point
  30143. * @param {Array.<number>} point
  30144. * @return {boolean}
  30145. */
  30146. containPoint: function (point) {
  30147. var axisX = this.getAxis('x');
  30148. var axisY = this.getAxis('y');
  30149. return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1]));
  30150. },
  30151. /**
  30152. * If contain data
  30153. * @param {Array.<number>} data
  30154. * @return {boolean}
  30155. */
  30156. containData: function (data) {
  30157. return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]);
  30158. },
  30159. /**
  30160. * @param {Array.<number>} data
  30161. * @param {Array.<number>} out
  30162. * @return {Array.<number>}
  30163. */
  30164. dataToPoint: function (data, reserved, out) {
  30165. var xAxis = this.getAxis('x');
  30166. var yAxis = this.getAxis('y');
  30167. out = out || [];
  30168. out[0] = xAxis.toGlobalCoord(xAxis.dataToCoord(data[0]));
  30169. out[1] = yAxis.toGlobalCoord(yAxis.dataToCoord(data[1]));
  30170. return out;
  30171. },
  30172. /**
  30173. * @param {Array.<number>} data
  30174. * @param {Array.<number>} out
  30175. * @return {Array.<number>}
  30176. */
  30177. clampData: function (data, out) {
  30178. var xScale = this.getAxis('x').scale;
  30179. var yScale = this.getAxis('y').scale;
  30180. var xAxisExtent = xScale.getExtent();
  30181. var yAxisExtent = yScale.getExtent();
  30182. var x = xScale.parse(data[0]);
  30183. var y = yScale.parse(data[1]);
  30184. out = out || [];
  30185. out[0] = Math.min(Math.max(Math.min(xAxisExtent[0], xAxisExtent[1]), x), Math.max(xAxisExtent[0], xAxisExtent[1]));
  30186. out[1] = Math.min(Math.max(Math.min(yAxisExtent[0], yAxisExtent[1]), y), Math.max(yAxisExtent[0], yAxisExtent[1]));
  30187. return out;
  30188. },
  30189. /**
  30190. * @param {Array.<number>} point
  30191. * @param {Array.<number>} out
  30192. * @return {Array.<number>}
  30193. */
  30194. pointToData: function (point, out) {
  30195. var xAxis = this.getAxis('x');
  30196. var yAxis = this.getAxis('y');
  30197. out = out || [];
  30198. out[0] = xAxis.coordToData(xAxis.toLocalCoord(point[0]));
  30199. out[1] = yAxis.coordToData(yAxis.toLocalCoord(point[1]));
  30200. return out;
  30201. },
  30202. /**
  30203. * Get other axis
  30204. * @param {module:echarts/coord/cartesian/Axis2D} axis
  30205. */
  30206. getOtherAxis: function (axis) {
  30207. return this.getAxis(axis.dim === 'x' ? 'y' : 'x');
  30208. },
  30209. /**
  30210. * Get rect area of cartesian.
  30211. * Area will have a contain function to determine if a point is in the coordinate system.
  30212. * @return {BoundingRect}
  30213. */
  30214. getArea: function () {
  30215. var xExtent = this.getAxis('x').getGlobalExtent();
  30216. var yExtent = this.getAxis('y').getGlobalExtent();
  30217. var x = Math.min(xExtent[0], xExtent[1]);
  30218. var y = Math.min(yExtent[0], yExtent[1]);
  30219. var width = Math.max(xExtent[0], xExtent[1]) - x;
  30220. var height = Math.max(yExtent[0], yExtent[1]) - y;
  30221. var rect = new BoundingRect(x, y, width, height);
  30222. return rect;
  30223. }
  30224. };
  30225. inherits(Cartesian2D, Cartesian);
  30226. /*
  30227. * Licensed to the Apache Software Foundation (ASF) under one
  30228. * or more contributor license agreements. See the NOTICE file
  30229. * distributed with this work for additional information
  30230. * regarding copyright ownership. The ASF licenses this file
  30231. * to you under the Apache License, Version 2.0 (the
  30232. * "License"); you may not use this file except in compliance
  30233. * with the License. You may obtain a copy of the License at
  30234. *
  30235. * http://www.apache.org/licenses/LICENSE-2.0
  30236. *
  30237. * Unless required by applicable law or agreed to in writing,
  30238. * software distributed under the License is distributed on an
  30239. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30240. * KIND, either express or implied. See the License for the
  30241. * specific language governing permissions and limitations
  30242. * under the License.
  30243. */
  30244. /**
  30245. * Extend axis 2d
  30246. * @constructor module:echarts/coord/cartesian/Axis2D
  30247. * @extends {module:echarts/coord/cartesian/Axis}
  30248. * @param {string} dim
  30249. * @param {*} scale
  30250. * @param {Array.<number>} coordExtent
  30251. * @param {string} axisType
  30252. * @param {string} position
  30253. */
  30254. var Axis2D = function (dim, scale, coordExtent, axisType, position) {
  30255. Axis.call(this, dim, scale, coordExtent);
  30256. /**
  30257. * Axis type
  30258. * - 'category'
  30259. * - 'value'
  30260. * - 'time'
  30261. * - 'log'
  30262. * @type {string}
  30263. */
  30264. this.type = axisType || 'value';
  30265. /**
  30266. * Axis position
  30267. * - 'top'
  30268. * - 'bottom'
  30269. * - 'left'
  30270. * - 'right'
  30271. */
  30272. this.position = position || 'bottom';
  30273. };
  30274. Axis2D.prototype = {
  30275. constructor: Axis2D,
  30276. /**
  30277. * Index of axis, can be used as key
  30278. */
  30279. index: 0,
  30280. /**
  30281. * Implemented in <module:echarts/coord/cartesian/Grid>.
  30282. * @return {Array.<module:echarts/coord/cartesian/Axis2D>}
  30283. * If not on zero of other axis, return null/undefined.
  30284. * If no axes, return an empty array.
  30285. */
  30286. getAxesOnZeroOf: null,
  30287. /**
  30288. * Axis model
  30289. * @param {module:echarts/coord/cartesian/AxisModel}
  30290. */
  30291. model: null,
  30292. isHorizontal: function () {
  30293. var position = this.position;
  30294. return position === 'top' || position === 'bottom';
  30295. },
  30296. /**
  30297. * Each item cooresponds to this.getExtent(), which
  30298. * means globalExtent[0] may greater than globalExtent[1],
  30299. * unless `asc` is input.
  30300. *
  30301. * @param {boolean} [asc]
  30302. * @return {Array.<number>}
  30303. */
  30304. getGlobalExtent: function (asc) {
  30305. var ret = this.getExtent();
  30306. ret[0] = this.toGlobalCoord(ret[0]);
  30307. ret[1] = this.toGlobalCoord(ret[1]);
  30308. asc && ret[0] > ret[1] && ret.reverse();
  30309. return ret;
  30310. },
  30311. getOtherAxis: function () {
  30312. this.grid.getOtherAxis();
  30313. },
  30314. /**
  30315. * @override
  30316. */
  30317. pointToData: function (point, clamp) {
  30318. return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp);
  30319. },
  30320. /**
  30321. * Transform global coord to local coord,
  30322. * i.e. var localCoord = axis.toLocalCoord(80);
  30323. * designate by module:echarts/coord/cartesian/Grid.
  30324. * @type {Function}
  30325. */
  30326. toLocalCoord: null,
  30327. /**
  30328. * Transform global coord to local coord,
  30329. * i.e. var globalCoord = axis.toLocalCoord(40);
  30330. * designate by module:echarts/coord/cartesian/Grid.
  30331. * @type {Function}
  30332. */
  30333. toGlobalCoord: null
  30334. };
  30335. inherits(Axis2D, Axis);
  30336. /*
  30337. * Licensed to the Apache Software Foundation (ASF) under one
  30338. * or more contributor license agreements. See the NOTICE file
  30339. * distributed with this work for additional information
  30340. * regarding copyright ownership. The ASF licenses this file
  30341. * to you under the Apache License, Version 2.0 (the
  30342. * "License"); you may not use this file except in compliance
  30343. * with the License. You may obtain a copy of the License at
  30344. *
  30345. * http://www.apache.org/licenses/LICENSE-2.0
  30346. *
  30347. * Unless required by applicable law or agreed to in writing,
  30348. * software distributed under the License is distributed on an
  30349. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30350. * KIND, either express or implied. See the License for the
  30351. * specific language governing permissions and limitations
  30352. * under the License.
  30353. */
  30354. var defaultOption = {
  30355. show: true,
  30356. zlevel: 0,
  30357. z: 0,
  30358. // Inverse the axis.
  30359. inverse: false,
  30360. // Axis name displayed.
  30361. name: '',
  30362. // 'start' | 'middle' | 'end'
  30363. nameLocation: 'end',
  30364. // By degree. By defualt auto rotate by nameLocation.
  30365. nameRotate: null,
  30366. nameTruncate: {
  30367. maxWidth: null,
  30368. ellipsis: '...',
  30369. placeholder: '.'
  30370. },
  30371. // Use global text style by default.
  30372. nameTextStyle: {},
  30373. // The gap between axisName and axisLine.
  30374. nameGap: 15,
  30375. // Default `false` to support tooltip.
  30376. silent: false,
  30377. // Default `false` to avoid legacy user event listener fail.
  30378. triggerEvent: false,
  30379. tooltip: {
  30380. show: false
  30381. },
  30382. axisPointer: {},
  30383. axisLine: {
  30384. show: true,
  30385. onZero: true,
  30386. onZeroAxisIndex: null,
  30387. lineStyle: {
  30388. color: '#333',
  30389. width: 1,
  30390. type: 'solid'
  30391. },
  30392. // The arrow at both ends the the axis.
  30393. symbol: ['none', 'none'],
  30394. symbolSize: [10, 15]
  30395. },
  30396. axisTick: {
  30397. show: true,
  30398. // Whether axisTick is inside the grid or outside the grid.
  30399. inside: false,
  30400. // The length of axisTick.
  30401. length: 5,
  30402. lineStyle: {
  30403. width: 1
  30404. }
  30405. },
  30406. axisLabel: {
  30407. show: true,
  30408. // Whether axisLabel is inside the grid or outside the grid.
  30409. inside: false,
  30410. rotate: 0,
  30411. // true | false | null/undefined (auto)
  30412. showMinLabel: null,
  30413. // true | false | null/undefined (auto)
  30414. showMaxLabel: null,
  30415. margin: 8,
  30416. // formatter: null,
  30417. fontSize: 12
  30418. },
  30419. splitLine: {
  30420. show: true,
  30421. lineStyle: {
  30422. color: ['#ccc'],
  30423. width: 1,
  30424. type: 'solid'
  30425. }
  30426. },
  30427. splitArea: {
  30428. show: false,
  30429. areaStyle: {
  30430. color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
  30431. }
  30432. }
  30433. };
  30434. var axisDefault = {};
  30435. axisDefault.categoryAxis = merge({
  30436. // The gap at both ends of the axis. For categoryAxis, boolean.
  30437. boundaryGap: true,
  30438. // Set false to faster category collection.
  30439. // Only usefull in the case like: category is
  30440. // ['2012-01-01', '2012-01-02', ...], where the input
  30441. // data has been ensured not duplicate and is large data.
  30442. // null means "auto":
  30443. // if axis.data provided, do not deduplication,
  30444. // else do deduplication.
  30445. deduplication: null,
  30446. // splitArea: {
  30447. // show: false
  30448. // },
  30449. splitLine: {
  30450. show: false
  30451. },
  30452. axisTick: {
  30453. // If tick is align with label when boundaryGap is true
  30454. alignWithLabel: false,
  30455. interval: 'auto'
  30456. },
  30457. axisLabel: {
  30458. interval: 'auto'
  30459. }
  30460. }, defaultOption);
  30461. axisDefault.valueAxis = merge({
  30462. // The gap at both ends of the axis. For value axis, [GAP, GAP], where
  30463. // `GAP` can be an absolute pixel number (like `35`), or percent (like `'30%'`)
  30464. boundaryGap: [0, 0],
  30465. // TODO
  30466. // min/max: [30, datamin, 60] or [20, datamin] or [datamin, 60]
  30467. // Min value of the axis. can be:
  30468. // + a number
  30469. // + 'dataMin': use the min value in data.
  30470. // + null/undefined: auto decide min value (consider pretty look and boundaryGap).
  30471. // min: null,
  30472. // Max value of the axis. can be:
  30473. // + a number
  30474. // + 'dataMax': use the max value in data.
  30475. // + null/undefined: auto decide max value (consider pretty look and boundaryGap).
  30476. // max: null,
  30477. // Readonly prop, specifies start value of the range when using data zoom.
  30478. // rangeStart: null
  30479. // Readonly prop, specifies end value of the range when using data zoom.
  30480. // rangeEnd: null
  30481. // Optional value can be:
  30482. // + `false`: always include value 0.
  30483. // + `true`: the extent do not consider value 0.
  30484. // scale: false,
  30485. // AxisTick and axisLabel and splitLine are caculated based on splitNumber.
  30486. splitNumber: 5,
  30487. // Interval specifies the span of the ticks is mandatorily.
  30488. // interval: null
  30489. // Specify min interval when auto calculate tick interval.
  30490. // minInterval: null
  30491. // Specify max interval when auto calculate tick interval.
  30492. // maxInterval: null
  30493. minorTick: {
  30494. // Minor tick, not available for cateogry axis.
  30495. show: false,
  30496. // Split number of minor ticks. The value should be in range of (0, 100)
  30497. splitNumber: 5,
  30498. // Lenght of minor tick
  30499. length: 3,
  30500. // Same inside with axisTick
  30501. // Line style
  30502. lineStyle: {// Default to be same with axisTick
  30503. }
  30504. },
  30505. minorSplitLine: {
  30506. show: false,
  30507. lineStyle: {
  30508. color: '#eee',
  30509. width: 1
  30510. }
  30511. }
  30512. }, defaultOption);
  30513. axisDefault.timeAxis = defaults({
  30514. scale: true,
  30515. min: 'dataMin',
  30516. max: 'dataMax'
  30517. }, axisDefault.valueAxis);
  30518. axisDefault.logAxis = defaults({
  30519. scale: true,
  30520. logBase: 10
  30521. }, axisDefault.valueAxis);
  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. var AXIS_TYPES = ['value', 'category', 'time', 'log'];
  30541. /**
  30542. * Generate sub axis model class
  30543. * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel'
  30544. * @param {module:echarts/model/Component} BaseAxisModelClass
  30545. * @param {Function} axisTypeDefaulter
  30546. * @param {Object} [extraDefaultOption]
  30547. */
  30548. var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) {
  30549. each$1(AXIS_TYPES, function (axisType) {
  30550. BaseAxisModelClass.extend({
  30551. /**
  30552. * @readOnly
  30553. */
  30554. type: axisName + 'Axis.' + axisType,
  30555. mergeDefaultAndTheme: function (option, ecModel) {
  30556. var layoutMode = this.layoutMode;
  30557. var inputPositionParams = layoutMode ? getLayoutParams(option) : {};
  30558. var themeModel = ecModel.getTheme();
  30559. merge(option, themeModel.get(axisType + 'Axis'));
  30560. merge(option, this.getDefaultOption());
  30561. option.type = axisTypeDefaulter(axisName, option);
  30562. if (layoutMode) {
  30563. mergeLayoutParam(option, inputPositionParams, layoutMode);
  30564. }
  30565. },
  30566. /**
  30567. * @override
  30568. */
  30569. optionUpdated: function () {
  30570. var thisOption = this.option;
  30571. if (thisOption.type === 'category') {
  30572. this.__ordinalMeta = OrdinalMeta.createByAxisModel(this);
  30573. }
  30574. },
  30575. /**
  30576. * Should not be called before all of 'getInitailData' finished.
  30577. * Because categories are collected during initializing data.
  30578. */
  30579. getCategories: function (rawData) {
  30580. var option = this.option; // FIXME
  30581. // warning if called before all of 'getInitailData' finished.
  30582. if (option.type === 'category') {
  30583. if (rawData) {
  30584. return option.data;
  30585. }
  30586. return this.__ordinalMeta.categories;
  30587. }
  30588. },
  30589. getOrdinalMeta: function () {
  30590. return this.__ordinalMeta;
  30591. },
  30592. defaultOption: mergeAll([{}, axisDefault[axisType + 'Axis'], extraDefaultOption], true)
  30593. });
  30594. });
  30595. ComponentModel.registerSubTypeDefaulter(axisName + 'Axis', curry(axisTypeDefaulter, axisName));
  30596. };
  30597. /*
  30598. * Licensed to the Apache Software Foundation (ASF) under one
  30599. * or more contributor license agreements. See the NOTICE file
  30600. * distributed with this work for additional information
  30601. * regarding copyright ownership. The ASF licenses this file
  30602. * to you under the Apache License, Version 2.0 (the
  30603. * "License"); you may not use this file except in compliance
  30604. * with the License. You may obtain a copy of the License at
  30605. *
  30606. * http://www.apache.org/licenses/LICENSE-2.0
  30607. *
  30608. * Unless required by applicable law or agreed to in writing,
  30609. * software distributed under the License is distributed on an
  30610. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30611. * KIND, either express or implied. See the License for the
  30612. * specific language governing permissions and limitations
  30613. * under the License.
  30614. */
  30615. var AxisModel = ComponentModel.extend({
  30616. type: 'cartesian2dAxis',
  30617. /**
  30618. * @type {module:echarts/coord/cartesian/Axis2D}
  30619. */
  30620. axis: null,
  30621. /**
  30622. * @override
  30623. */
  30624. init: function () {
  30625. AxisModel.superApply(this, 'init', arguments);
  30626. this.resetRange();
  30627. },
  30628. /**
  30629. * @override
  30630. */
  30631. mergeOption: function () {
  30632. AxisModel.superApply(this, 'mergeOption', arguments);
  30633. this.resetRange();
  30634. },
  30635. /**
  30636. * @override
  30637. */
  30638. restoreData: function () {
  30639. AxisModel.superApply(this, 'restoreData', arguments);
  30640. this.resetRange();
  30641. },
  30642. /**
  30643. * @override
  30644. * @return {module:echarts/model/Component}
  30645. */
  30646. getCoordSysModel: function () {
  30647. return this.ecModel.queryComponents({
  30648. mainType: 'grid',
  30649. index: this.option.gridIndex,
  30650. id: this.option.gridId
  30651. })[0];
  30652. }
  30653. });
  30654. function getAxisType(axisDim, option) {
  30655. // Default axis with data is category axis
  30656. return option.type || (option.data ? 'category' : 'value');
  30657. }
  30658. merge(AxisModel.prototype, axisModelCommonMixin);
  30659. var extraOption = {
  30660. // gridIndex: 0,
  30661. // gridId: '',
  30662. // Offset is for multiple axis on the same position
  30663. offset: 0
  30664. };
  30665. axisModelCreator('x', AxisModel, getAxisType, extraOption);
  30666. axisModelCreator('y', AxisModel, getAxisType, extraOption);
  30667. /*
  30668. * Licensed to the Apache Software Foundation (ASF) under one
  30669. * or more contributor license agreements. See the NOTICE file
  30670. * distributed with this work for additional information
  30671. * regarding copyright ownership. The ASF licenses this file
  30672. * to you under the Apache License, Version 2.0 (the
  30673. * "License"); you may not use this file except in compliance
  30674. * with the License. You may obtain a copy of the License at
  30675. *
  30676. * http://www.apache.org/licenses/LICENSE-2.0
  30677. *
  30678. * Unless required by applicable law or agreed to in writing,
  30679. * software distributed under the License is distributed on an
  30680. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30681. * KIND, either express or implied. See the License for the
  30682. * specific language governing permissions and limitations
  30683. * under the License.
  30684. */
  30685. // Grid 是在有直角坐标系的时候必须要存在的
  30686. // 所以这里也要被 Cartesian2D 依赖
  30687. ComponentModel.extend({
  30688. type: 'grid',
  30689. dependencies: ['xAxis', 'yAxis'],
  30690. layoutMode: 'box',
  30691. /**
  30692. * @type {module:echarts/coord/cartesian/Grid}
  30693. */
  30694. coordinateSystem: null,
  30695. defaultOption: {
  30696. show: false,
  30697. zlevel: 0,
  30698. z: 0,
  30699. left: '10%',
  30700. top: 60,
  30701. right: '10%',
  30702. bottom: 60,
  30703. // If grid size contain label
  30704. containLabel: false,
  30705. // width: {totalWidth} - left - right,
  30706. // height: {totalHeight} - top - bottom,
  30707. backgroundColor: 'rgba(0,0,0,0)',
  30708. borderWidth: 1,
  30709. borderColor: '#ccc'
  30710. }
  30711. });
  30712. /*
  30713. * Licensed to the Apache Software Foundation (ASF) under one
  30714. * or more contributor license agreements. See the NOTICE file
  30715. * distributed with this work for additional information
  30716. * regarding copyright ownership. The ASF licenses this file
  30717. * to you under the Apache License, Version 2.0 (the
  30718. * "License"); you may not use this file except in compliance
  30719. * with the License. You may obtain a copy of the License at
  30720. *
  30721. * http://www.apache.org/licenses/LICENSE-2.0
  30722. *
  30723. * Unless required by applicable law or agreed to in writing,
  30724. * software distributed under the License is distributed on an
  30725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  30726. * KIND, either express or implied. See the License for the
  30727. * specific language governing permissions and limitations
  30728. * under the License.
  30729. */
  30730. /**
  30731. * Grid is a region which contains at most 4 cartesian systems
  30732. *
  30733. * TODO Default cartesian
  30734. */
  30735. /**
  30736. * Check if the axis is used in the specified grid
  30737. * @inner
  30738. */
  30739. function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) {
  30740. return axisModel.getCoordSysModel() === gridModel;
  30741. }
  30742. function Grid(gridModel, ecModel, api) {
  30743. /**
  30744. * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>}
  30745. * @private
  30746. */
  30747. this._coordsMap = {};
  30748. /**
  30749. * @type {Array.<module:echarts/coord/cartesian/Cartesian>}
  30750. * @private
  30751. */
  30752. this._coordsList = [];
  30753. /**
  30754. * @type {Object.<string, Array.<module:echarts/coord/cartesian/Axis2D>>}
  30755. * @private
  30756. */
  30757. this._axesMap = {};
  30758. /**
  30759. * @type {Array.<module:echarts/coord/cartesian/Axis2D>}
  30760. * @private
  30761. */
  30762. this._axesList = [];
  30763. this._initCartesian(gridModel, ecModel, api);
  30764. this.model = gridModel;
  30765. }
  30766. var gridProto = Grid.prototype;
  30767. gridProto.type = 'grid';
  30768. gridProto.axisPointerEnabled = true;
  30769. gridProto.getRect = function () {
  30770. return this._rect;
  30771. };
  30772. gridProto.update = function (ecModel, api) {
  30773. var axesMap = this._axesMap;
  30774. this._updateScale(ecModel, this.model);
  30775. each$1(axesMap.x, function (xAxis) {
  30776. niceScaleExtent(xAxis.scale, xAxis.model);
  30777. });
  30778. each$1(axesMap.y, function (yAxis) {
  30779. niceScaleExtent(yAxis.scale, yAxis.model);
  30780. }); // Key: axisDim_axisIndex, value: boolean, whether onZero target.
  30781. var onZeroRecords = {};
  30782. each$1(axesMap.x, function (xAxis) {
  30783. fixAxisOnZero(axesMap, 'y', xAxis, onZeroRecords);
  30784. });
  30785. each$1(axesMap.y, function (yAxis) {
  30786. fixAxisOnZero(axesMap, 'x', yAxis, onZeroRecords);
  30787. }); // Resize again if containLabel is enabled
  30788. // FIXME It may cause getting wrong grid size in data processing stage
  30789. this.resize(this.model, api);
  30790. };
  30791. function fixAxisOnZero(axesMap, otherAxisDim, axis, onZeroRecords) {
  30792. axis.getAxesOnZeroOf = function () {
  30793. // TODO: onZero of multiple axes.
  30794. return otherAxisOnZeroOf ? [otherAxisOnZeroOf] : [];
  30795. }; // onZero can not be enabled in these two situations:
  30796. // 1. When any other axis is a category axis.
  30797. // 2. When no axis is cross 0 point.
  30798. var otherAxes = axesMap[otherAxisDim];
  30799. var otherAxisOnZeroOf;
  30800. var axisModel = axis.model;
  30801. var onZero = axisModel.get('axisLine.onZero');
  30802. var onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex');
  30803. if (!onZero) {
  30804. return;
  30805. } // If target axis is specified.
  30806. if (onZeroAxisIndex != null) {
  30807. if (canOnZeroToAxis(otherAxes[onZeroAxisIndex])) {
  30808. otherAxisOnZeroOf = otherAxes[onZeroAxisIndex];
  30809. }
  30810. } else {
  30811. // Find the first available other axis.
  30812. for (var idx in otherAxes) {
  30813. if (otherAxes.hasOwnProperty(idx) && canOnZeroToAxis(otherAxes[idx]) // Consider that two Y axes on one value axis,
  30814. // if both onZero, the two Y axes overlap.
  30815. && !onZeroRecords[getOnZeroRecordKey(otherAxes[idx])]) {
  30816. otherAxisOnZeroOf = otherAxes[idx];
  30817. break;
  30818. }
  30819. }
  30820. }
  30821. if (otherAxisOnZeroOf) {
  30822. onZeroRecords[getOnZeroRecordKey(otherAxisOnZeroOf)] = true;
  30823. }
  30824. function getOnZeroRecordKey(axis) {
  30825. return axis.dim + '_' + axis.index;
  30826. }
  30827. }
  30828. function canOnZeroToAxis(axis) {
  30829. return axis && axis.type !== 'category' && axis.type !== 'time' && ifAxisCrossZero(axis);
  30830. }
  30831. /**
  30832. * Resize the grid
  30833. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  30834. * @param {module:echarts/ExtensionAPI} api
  30835. */
  30836. gridProto.resize = function (gridModel, api, ignoreContainLabel) {
  30837. var gridRect = getLayoutRect(gridModel.getBoxLayoutParams(), {
  30838. width: api.getWidth(),
  30839. height: api.getHeight()
  30840. });
  30841. this._rect = gridRect;
  30842. var axesList = this._axesList;
  30843. adjustAxes(); // Minus label size
  30844. if (!ignoreContainLabel && gridModel.get('containLabel')) {
  30845. each$1(axesList, function (axis) {
  30846. if (!axis.model.get('axisLabel.inside')) {
  30847. var labelUnionRect = estimateLabelUnionRect(axis);
  30848. if (labelUnionRect) {
  30849. var dim = axis.isHorizontal() ? 'height' : 'width';
  30850. var margin = axis.model.get('axisLabel.margin');
  30851. gridRect[dim] -= labelUnionRect[dim] + margin;
  30852. if (axis.position === 'top') {
  30853. gridRect.y += labelUnionRect.height + margin;
  30854. } else if (axis.position === 'left') {
  30855. gridRect.x += labelUnionRect.width + margin;
  30856. }
  30857. }
  30858. }
  30859. });
  30860. adjustAxes();
  30861. }
  30862. function adjustAxes() {
  30863. each$1(axesList, function (axis) {
  30864. var isHorizontal = axis.isHorizontal();
  30865. var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height];
  30866. var idx = axis.inverse ? 1 : 0;
  30867. axis.setExtent(extent[idx], extent[1 - idx]);
  30868. updateAxisTransform(axis, isHorizontal ? gridRect.x : gridRect.y);
  30869. });
  30870. }
  30871. };
  30872. /**
  30873. * @param {string} axisType
  30874. * @param {number} [axisIndex]
  30875. */
  30876. gridProto.getAxis = function (axisType, axisIndex) {
  30877. var axesMapOnDim = this._axesMap[axisType];
  30878. if (axesMapOnDim != null) {
  30879. if (axisIndex == null) {
  30880. // Find first axis
  30881. for (var name in axesMapOnDim) {
  30882. if (axesMapOnDim.hasOwnProperty(name)) {
  30883. return axesMapOnDim[name];
  30884. }
  30885. }
  30886. }
  30887. return axesMapOnDim[axisIndex];
  30888. }
  30889. };
  30890. /**
  30891. * @return {Array.<module:echarts/coord/Axis>}
  30892. */
  30893. gridProto.getAxes = function () {
  30894. return this._axesList.slice();
  30895. };
  30896. /**
  30897. * Usage:
  30898. * grid.getCartesian(xAxisIndex, yAxisIndex);
  30899. * grid.getCartesian(xAxisIndex);
  30900. * grid.getCartesian(null, yAxisIndex);
  30901. * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...});
  30902. *
  30903. * @param {number|Object} [xAxisIndex]
  30904. * @param {number} [yAxisIndex]
  30905. */
  30906. gridProto.getCartesian = function (xAxisIndex, yAxisIndex) {
  30907. if (xAxisIndex != null && yAxisIndex != null) {
  30908. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  30909. return this._coordsMap[key];
  30910. }
  30911. if (isObject$1(xAxisIndex)) {
  30912. yAxisIndex = xAxisIndex.yAxisIndex;
  30913. xAxisIndex = xAxisIndex.xAxisIndex;
  30914. } // When only xAxisIndex or yAxisIndex given, find its first cartesian.
  30915. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) {
  30916. if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex) {
  30917. return coordList[i];
  30918. }
  30919. }
  30920. };
  30921. gridProto.getCartesians = function () {
  30922. return this._coordsList.slice();
  30923. };
  30924. /**
  30925. * @implements
  30926. * see {module:echarts/CoodinateSystem}
  30927. */
  30928. gridProto.convertToPixel = function (ecModel, finder, value) {
  30929. var target = this._findConvertTarget(ecModel, finder);
  30930. return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null;
  30931. };
  30932. /**
  30933. * @implements
  30934. * see {module:echarts/CoodinateSystem}
  30935. */
  30936. gridProto.convertFromPixel = function (ecModel, finder, value) {
  30937. var target = this._findConvertTarget(ecModel, finder);
  30938. return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null;
  30939. };
  30940. /**
  30941. * @inner
  30942. */
  30943. gridProto._findConvertTarget = function (ecModel, finder) {
  30944. var seriesModel = finder.seriesModel;
  30945. var xAxisModel = finder.xAxisModel || seriesModel && seriesModel.getReferringComponents('xAxis')[0];
  30946. var yAxisModel = finder.yAxisModel || seriesModel && seriesModel.getReferringComponents('yAxis')[0];
  30947. var gridModel = finder.gridModel;
  30948. var coordsList = this._coordsList;
  30949. var cartesian;
  30950. var axis;
  30951. if (seriesModel) {
  30952. cartesian = seriesModel.coordinateSystem;
  30953. indexOf(coordsList, cartesian) < 0 && (cartesian = null);
  30954. } else if (xAxisModel && yAxisModel) {
  30955. cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  30956. } else if (xAxisModel) {
  30957. axis = this.getAxis('x', xAxisModel.componentIndex);
  30958. } else if (yAxisModel) {
  30959. axis = this.getAxis('y', yAxisModel.componentIndex);
  30960. } // Lowest priority.
  30961. else if (gridModel) {
  30962. var grid = gridModel.coordinateSystem;
  30963. if (grid === this) {
  30964. cartesian = this._coordsList[0];
  30965. }
  30966. }
  30967. return {
  30968. cartesian: cartesian,
  30969. axis: axis
  30970. };
  30971. };
  30972. /**
  30973. * @implements
  30974. * see {module:echarts/CoodinateSystem}
  30975. */
  30976. gridProto.containPoint = function (point) {
  30977. var coord = this._coordsList[0];
  30978. if (coord) {
  30979. return coord.containPoint(point);
  30980. }
  30981. };
  30982. /**
  30983. * Initialize cartesian coordinate systems
  30984. * @private
  30985. */
  30986. gridProto._initCartesian = function (gridModel, ecModel, api) {
  30987. var axisPositionUsed = {
  30988. left: false,
  30989. right: false,
  30990. top: false,
  30991. bottom: false
  30992. };
  30993. var axesMap = {
  30994. x: {},
  30995. y: {}
  30996. };
  30997. var axesCount = {
  30998. x: 0,
  30999. y: 0
  31000. }; /// Create axis
  31001. ecModel.eachComponent('xAxis', createAxisCreator('x'), this);
  31002. ecModel.eachComponent('yAxis', createAxisCreator('y'), this);
  31003. if (!axesCount.x || !axesCount.y) {
  31004. // Roll back when there no either x or y axis
  31005. this._axesMap = {};
  31006. this._axesList = [];
  31007. return;
  31008. }
  31009. this._axesMap = axesMap; /// Create cartesian2d
  31010. each$1(axesMap.x, function (xAxis, xAxisIndex) {
  31011. each$1(axesMap.y, function (yAxis, yAxisIndex) {
  31012. var key = 'x' + xAxisIndex + 'y' + yAxisIndex;
  31013. var cartesian = new Cartesian2D(key);
  31014. cartesian.grid = this;
  31015. cartesian.model = gridModel;
  31016. this._coordsMap[key] = cartesian;
  31017. this._coordsList.push(cartesian);
  31018. cartesian.addAxis(xAxis);
  31019. cartesian.addAxis(yAxis);
  31020. }, this);
  31021. }, this);
  31022. function createAxisCreator(axisType) {
  31023. return function (axisModel, idx) {
  31024. if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) {
  31025. return;
  31026. }
  31027. var axisPosition = axisModel.get('position');
  31028. if (axisType === 'x') {
  31029. // Fix position
  31030. if (axisPosition !== 'top' && axisPosition !== 'bottom') {
  31031. // Default bottom of X
  31032. axisPosition = axisPositionUsed.bottom ? 'top' : 'bottom';
  31033. }
  31034. } else {
  31035. // Fix position
  31036. if (axisPosition !== 'left' && axisPosition !== 'right') {
  31037. // Default left of Y
  31038. axisPosition = axisPositionUsed.left ? 'right' : 'left';
  31039. }
  31040. }
  31041. axisPositionUsed[axisPosition] = true;
  31042. var axis = new Axis2D(axisType, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition);
  31043. var isCategory = axis.type === 'category';
  31044. axis.onBand = isCategory && axisModel.get('boundaryGap');
  31045. axis.inverse = axisModel.get('inverse'); // Inject axis into axisModel
  31046. axisModel.axis = axis; // Inject axisModel into axis
  31047. axis.model = axisModel; // Inject grid info axis
  31048. axis.grid = this; // Index of axis, can be used as key
  31049. axis.index = idx;
  31050. this._axesList.push(axis);
  31051. axesMap[axisType][idx] = axis;
  31052. axesCount[axisType]++;
  31053. };
  31054. }
  31055. };
  31056. /**
  31057. * Update cartesian properties from series
  31058. * @param {module:echarts/model/Option} option
  31059. * @private
  31060. */
  31061. gridProto._updateScale = function (ecModel, gridModel) {
  31062. // Reset scale
  31063. each$1(this._axesList, function (axis) {
  31064. axis.scale.setExtent(Infinity, -Infinity);
  31065. });
  31066. ecModel.eachSeries(function (seriesModel) {
  31067. if (isCartesian2D(seriesModel)) {
  31068. var axesModels = findAxesModels(seriesModel, ecModel);
  31069. var xAxisModel = axesModels[0];
  31070. var yAxisModel = axesModels[1];
  31071. if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel)) {
  31072. return;
  31073. }
  31074. var cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  31075. var data = seriesModel.getData();
  31076. var xAxis = cartesian.getAxis('x');
  31077. var yAxis = cartesian.getAxis('y');
  31078. if (data.type === 'list') {
  31079. unionExtent(data, xAxis, seriesModel);
  31080. unionExtent(data, yAxis, seriesModel);
  31081. }
  31082. }
  31083. }, this);
  31084. function unionExtent(data, axis, seriesModel) {
  31085. each$1(data.mapDimension(axis.dim, true), function (dim) {
  31086. axis.scale.unionExtentFromData( // For example, the extent of the orginal dimension
  31087. // is [0.1, 0.5], the extent of the `stackResultDimension`
  31088. // is [7, 9], the final extent should not include [0.1, 0.5].
  31089. data, getStackedDimension(data, dim));
  31090. });
  31091. }
  31092. };
  31093. /**
  31094. * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined
  31095. * @return {Object} {baseAxes: [], otherAxes: []}
  31096. */
  31097. gridProto.getTooltipAxes = function (dim) {
  31098. var baseAxes = [];
  31099. var otherAxes = [];
  31100. each$1(this.getCartesians(), function (cartesian) {
  31101. var baseAxis = dim != null && dim !== 'auto' ? cartesian.getAxis(dim) : cartesian.getBaseAxis();
  31102. var otherAxis = cartesian.getOtherAxis(baseAxis);
  31103. indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis);
  31104. indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis);
  31105. });
  31106. return {
  31107. baseAxes: baseAxes,
  31108. otherAxes: otherAxes
  31109. };
  31110. };
  31111. /**
  31112. * @inner
  31113. */
  31114. function updateAxisTransform(axis, coordBase) {
  31115. var axisExtent = axis.getExtent();
  31116. var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform
  31117. axis.toGlobalCoord = axis.dim === 'x' ? function (coord) {
  31118. return coord + coordBase;
  31119. } : function (coord) {
  31120. return axisExtentSum - coord + coordBase;
  31121. };
  31122. axis.toLocalCoord = axis.dim === 'x' ? function (coord) {
  31123. return coord - coordBase;
  31124. } : function (coord) {
  31125. return axisExtentSum - coord + coordBase;
  31126. };
  31127. }
  31128. var axesTypes = ['xAxis', 'yAxis'];
  31129. /**
  31130. * @inner
  31131. */
  31132. function findAxesModels(seriesModel, ecModel) {
  31133. return map(axesTypes, function (axisType) {
  31134. var axisModel = seriesModel.getReferringComponents(axisType)[0];
  31135. return axisModel;
  31136. });
  31137. }
  31138. /**
  31139. * @inner
  31140. */
  31141. function isCartesian2D(seriesModel) {
  31142. return seriesModel.get('coordinateSystem') === 'cartesian2d';
  31143. }
  31144. Grid.create = function (ecModel, api) {
  31145. var grids = [];
  31146. ecModel.eachComponent('grid', function (gridModel, idx) {
  31147. var grid = new Grid(gridModel, ecModel, api);
  31148. grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize
  31149. // should be performed in create stage.
  31150. grid.resize(gridModel, api, true);
  31151. gridModel.coordinateSystem = grid;
  31152. grids.push(grid);
  31153. }); // Inject the coordinateSystems into seriesModel
  31154. ecModel.eachSeries(function (seriesModel) {
  31155. if (!isCartesian2D(seriesModel)) {
  31156. return;
  31157. }
  31158. var axesModels = findAxesModels(seriesModel, ecModel);
  31159. var xAxisModel = axesModels[0];
  31160. var yAxisModel = axesModels[1];
  31161. var gridModel = xAxisModel.getCoordSysModel();
  31162. var grid = gridModel.coordinateSystem;
  31163. seriesModel.coordinateSystem = grid.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex);
  31164. });
  31165. return grids;
  31166. }; // For deciding which dimensions to use when creating list data
  31167. Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions;
  31168. CoordinateSystemManager.register('cartesian2d', Grid);
  31169. /*
  31170. * Licensed to the Apache Software Foundation (ASF) under one
  31171. * or more contributor license agreements. See the NOTICE file
  31172. * distributed with this work for additional information
  31173. * regarding copyright ownership. The ASF licenses this file
  31174. * to you under the Apache License, Version 2.0 (the
  31175. * "License"); you may not use this file except in compliance
  31176. * with the License. You may obtain a copy of the License at
  31177. *
  31178. * http://www.apache.org/licenses/LICENSE-2.0
  31179. *
  31180. * Unless required by applicable law or agreed to in writing,
  31181. * software distributed under the License is distributed on an
  31182. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31183. * KIND, either express or implied. See the License for the
  31184. * specific language governing permissions and limitations
  31185. * under the License.
  31186. */
  31187. var BaseBarSeries = SeriesModel.extend({
  31188. type: 'series.__base_bar__',
  31189. getInitialData: function (option, ecModel) {
  31190. return createListFromArray(this.getSource(), this, {
  31191. useEncodeDefaulter: true
  31192. });
  31193. },
  31194. getMarkerPosition: function (value) {
  31195. var coordSys = this.coordinateSystem;
  31196. if (coordSys) {
  31197. // PENDING if clamp ?
  31198. var pt = coordSys.dataToPoint(coordSys.clampData(value));
  31199. var data = this.getData();
  31200. var offset = data.getLayout('offset');
  31201. var size = data.getLayout('size');
  31202. var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1;
  31203. pt[offsetIndex] += offset + size / 2;
  31204. return pt;
  31205. }
  31206. return [NaN, NaN];
  31207. },
  31208. defaultOption: {
  31209. zlevel: 0,
  31210. // 一级层叠
  31211. z: 2,
  31212. // 二级层叠
  31213. coordinateSystem: 'cartesian2d',
  31214. legendHoverLink: true,
  31215. // stack: null
  31216. // Cartesian coordinate system
  31217. // xAxisIndex: 0,
  31218. // yAxisIndex: 0,
  31219. // 最小高度改为0
  31220. barMinHeight: 0,
  31221. // 最小角度为0,仅对极坐标系下的柱状图有效
  31222. barMinAngle: 0,
  31223. // cursor: null,
  31224. large: false,
  31225. largeThreshold: 400,
  31226. progressive: 3e3,
  31227. progressiveChunkMode: 'mod',
  31228. // barMaxWidth: null,
  31229. // In cartesian, the default value is 1. Otherwise null.
  31230. // barMinWidth: null,
  31231. // 默认自适应
  31232. // barWidth: null,
  31233. // 柱间距离,默认为柱形宽度的30%,可设固定值
  31234. // barGap: '30%',
  31235. // 类目间柱形距离,默认为类目间距的20%,可设固定值
  31236. // barCategoryGap: '20%',
  31237. // label: {
  31238. // show: false
  31239. // },
  31240. itemStyle: {},
  31241. emphasis: {}
  31242. }
  31243. });
  31244. /*
  31245. * Licensed to the Apache Software Foundation (ASF) under one
  31246. * or more contributor license agreements. See the NOTICE file
  31247. * distributed with this work for additional information
  31248. * regarding copyright ownership. The ASF licenses this file
  31249. * to you under the Apache License, Version 2.0 (the
  31250. * "License"); you may not use this file except in compliance
  31251. * with the License. You may obtain a copy of the License at
  31252. *
  31253. * http://www.apache.org/licenses/LICENSE-2.0
  31254. *
  31255. * Unless required by applicable law or agreed to in writing,
  31256. * software distributed under the License is distributed on an
  31257. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31258. * KIND, either express or implied. See the License for the
  31259. * specific language governing permissions and limitations
  31260. * under the License.
  31261. */
  31262. BaseBarSeries.extend({
  31263. type: 'series.bar',
  31264. dependencies: ['grid', 'polar'],
  31265. brushSelector: 'rect',
  31266. /**
  31267. * @override
  31268. */
  31269. getProgressive: function () {
  31270. // Do not support progressive in normal mode.
  31271. return this.get('large') ? this.get('progressive') : false;
  31272. },
  31273. /**
  31274. * @override
  31275. */
  31276. getProgressiveThreshold: function () {
  31277. // Do not support progressive in normal mode.
  31278. var progressiveThreshold = this.get('progressiveThreshold');
  31279. var largeThreshold = this.get('largeThreshold');
  31280. if (largeThreshold > progressiveThreshold) {
  31281. progressiveThreshold = largeThreshold;
  31282. }
  31283. return progressiveThreshold;
  31284. },
  31285. defaultOption: {
  31286. // If clipped
  31287. // Only available on cartesian2d
  31288. clip: true,
  31289. // If use caps on two sides of bars
  31290. // Only available on tangential polar bar
  31291. roundCap: false,
  31292. showBackground: false,
  31293. backgroundStyle: {
  31294. color: 'rgba(180, 180, 180, 0.2)',
  31295. borderColor: null,
  31296. borderWidth: 0,
  31297. borderType: 'solid',
  31298. borderRadius: 0,
  31299. shadowBlur: 0,
  31300. shadowColor: null,
  31301. shadowOffsetX: 0,
  31302. shadowOffsetY: 0,
  31303. opacity: 1
  31304. }
  31305. }
  31306. });
  31307. /*
  31308. * Licensed to the Apache Software Foundation (ASF) under one
  31309. * or more contributor license agreements. See the NOTICE file
  31310. * distributed with this work for additional information
  31311. * regarding copyright ownership. The ASF licenses this file
  31312. * to you under the Apache License, Version 2.0 (the
  31313. * "License"); you may not use this file except in compliance
  31314. * with the License. You may obtain a copy of the License at
  31315. *
  31316. * http://www.apache.org/licenses/LICENSE-2.0
  31317. *
  31318. * Unless required by applicable law or agreed to in writing,
  31319. * software distributed under the License is distributed on an
  31320. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31321. * KIND, either express or implied. See the License for the
  31322. * specific language governing permissions and limitations
  31323. * under the License.
  31324. */
  31325. /**
  31326. * @param {module:echarts/data/List} data
  31327. * @param {number} dataIndex
  31328. * @return {string} label string. Not null/undefined
  31329. */
  31330. function getDefaultLabel(data, dataIndex) {
  31331. var labelDims = data.mapDimension('defaultedLabel', true);
  31332. var len = labelDims.length; // Simple optimization (in lots of cases, label dims length is 1)
  31333. if (len === 1) {
  31334. return retrieveRawValue(data, dataIndex, labelDims[0]);
  31335. } else if (len) {
  31336. var vals = [];
  31337. for (var i = 0; i < labelDims.length; i++) {
  31338. var val = retrieveRawValue(data, dataIndex, labelDims[i]);
  31339. vals.push(val);
  31340. }
  31341. return vals.join(' ');
  31342. }
  31343. }
  31344. /*
  31345. * Licensed to the Apache Software Foundation (ASF) under one
  31346. * or more contributor license agreements. See the NOTICE file
  31347. * distributed with this work for additional information
  31348. * regarding copyright ownership. The ASF licenses this file
  31349. * to you under the Apache License, Version 2.0 (the
  31350. * "License"); you may not use this file except in compliance
  31351. * with the License. You may obtain a copy of the License at
  31352. *
  31353. * http://www.apache.org/licenses/LICENSE-2.0
  31354. *
  31355. * Unless required by applicable law or agreed to in writing,
  31356. * software distributed under the License is distributed on an
  31357. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31358. * KIND, either express or implied. See the License for the
  31359. * specific language governing permissions and limitations
  31360. * under the License.
  31361. */
  31362. function setLabel(normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside) {
  31363. var labelModel = itemModel.getModel('label');
  31364. var hoverLabelModel = itemModel.getModel('emphasis.label');
  31365. setLabelStyle(normalStyle, hoverStyle, labelModel, hoverLabelModel, {
  31366. labelFetcher: seriesModel,
  31367. labelDataIndex: dataIndex,
  31368. defaultText: getDefaultLabel(seriesModel.getData(), dataIndex),
  31369. isRectText: true,
  31370. autoColor: color
  31371. });
  31372. fixPosition(normalStyle);
  31373. fixPosition(hoverStyle);
  31374. }
  31375. function fixPosition(style, labelPositionOutside) {
  31376. if (style.textPosition === 'outside') {
  31377. style.textPosition = labelPositionOutside;
  31378. }
  31379. }
  31380. /*
  31381. * Licensed to the Apache Software Foundation (ASF) under one
  31382. * or more contributor license agreements. See the NOTICE file
  31383. * distributed with this work for additional information
  31384. * regarding copyright ownership. The ASF licenses this file
  31385. * to you under the Apache License, Version 2.0 (the
  31386. * "License"); you may not use this file except in compliance
  31387. * with the License. You may obtain a copy of the License at
  31388. *
  31389. * http://www.apache.org/licenses/LICENSE-2.0
  31390. *
  31391. * Unless required by applicable law or agreed to in writing,
  31392. * software distributed under the License is distributed on an
  31393. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31394. * KIND, either express or implied. See the License for the
  31395. * specific language governing permissions and limitations
  31396. * under the License.
  31397. */
  31398. var getBarItemStyle = makeStyleMapper([['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], // Compatitable with 2
  31399. ['stroke', 'barBorderColor'], ['lineWidth', 'barBorderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor']]);
  31400. var barItemStyle = {
  31401. getBarItemStyle: function (excludes) {
  31402. var style = getBarItemStyle(this, excludes);
  31403. if (this.getBorderLineDash) {
  31404. var lineDash = this.getBorderLineDash();
  31405. lineDash && (style.lineDash = lineDash);
  31406. }
  31407. return style;
  31408. }
  31409. };
  31410. /*
  31411. * Licensed to the Apache Software Foundation (ASF) under one
  31412. * or more contributor license agreements. See the NOTICE file
  31413. * distributed with this work for additional information
  31414. * regarding copyright ownership. The ASF licenses this file
  31415. * to you under the Apache License, Version 2.0 (the
  31416. * "License"); you may not use this file except in compliance
  31417. * with the License. You may obtain a copy of the License at
  31418. *
  31419. * http://www.apache.org/licenses/LICENSE-2.0
  31420. *
  31421. * Unless required by applicable law or agreed to in writing,
  31422. * software distributed under the License is distributed on an
  31423. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31424. * KIND, either express or implied. See the License for the
  31425. * specific language governing permissions and limitations
  31426. * under the License.
  31427. */
  31428. function createGridClipPath(cartesian, hasAnimation, seriesModel) {
  31429. var rect = cartesian.getArea();
  31430. var isHorizontal = cartesian.getBaseAxis().isHorizontal();
  31431. var x = rect.x;
  31432. var y = rect.y;
  31433. var width = rect.width;
  31434. var height = rect.height;
  31435. var lineWidth = seriesModel.get('lineStyle.width') || 2; // Expand the clip path a bit to avoid the border is clipped and looks thinner
  31436. x -= lineWidth / 2;
  31437. y -= lineWidth / 2;
  31438. width += lineWidth;
  31439. height += lineWidth; // fix: https://github.com/apache/incubator-echarts/issues/11369
  31440. x = Math.floor(x);
  31441. width = Math.round(width);
  31442. var clipPath = new Rect({
  31443. shape: {
  31444. x: x,
  31445. y: y,
  31446. width: width,
  31447. height: height
  31448. }
  31449. });
  31450. if (hasAnimation) {
  31451. clipPath.shape[isHorizontal ? 'width' : 'height'] = 0;
  31452. initProps(clipPath, {
  31453. shape: {
  31454. width: width,
  31455. height: height
  31456. }
  31457. }, seriesModel);
  31458. }
  31459. return clipPath;
  31460. }
  31461. function createPolarClipPath(polar, hasAnimation, seriesModel) {
  31462. var sectorArea = polar.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  31463. var clipPath = new Sector({
  31464. shape: {
  31465. cx: round$1(polar.cx, 1),
  31466. cy: round$1(polar.cy, 1),
  31467. r0: round$1(sectorArea.r0, 1),
  31468. r: round$1(sectorArea.r, 1),
  31469. startAngle: sectorArea.startAngle,
  31470. endAngle: sectorArea.endAngle,
  31471. clockwise: sectorArea.clockwise
  31472. }
  31473. });
  31474. if (hasAnimation) {
  31475. clipPath.shape.endAngle = sectorArea.startAngle;
  31476. initProps(clipPath, {
  31477. shape: {
  31478. endAngle: sectorArea.endAngle
  31479. }
  31480. }, seriesModel);
  31481. }
  31482. return clipPath;
  31483. }
  31484. function createClipPath(coordSys, hasAnimation, seriesModel) {
  31485. if (!coordSys) {
  31486. return null;
  31487. } else if (coordSys.type === 'polar') {
  31488. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  31489. } else if (coordSys.type === 'cartesian2d') {
  31490. return createGridClipPath(coordSys, hasAnimation, seriesModel);
  31491. }
  31492. return null;
  31493. }
  31494. /*
  31495. * Licensed to the Apache Software Foundation (ASF) under one
  31496. * or more contributor license agreements. See the NOTICE file
  31497. * distributed with this work for additional information
  31498. * regarding copyright ownership. The ASF licenses this file
  31499. * to you under the Apache License, Version 2.0 (the
  31500. * "License"); you may not use this file except in compliance
  31501. * with the License. You may obtain a copy of the License at
  31502. *
  31503. * http://www.apache.org/licenses/LICENSE-2.0
  31504. *
  31505. * Unless required by applicable law or agreed to in writing,
  31506. * software distributed under the License is distributed on an
  31507. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31508. * KIND, either express or implied. See the License for the
  31509. * specific language governing permissions and limitations
  31510. * under the License.
  31511. */
  31512. /**
  31513. * Sausage: similar to sector, but have half circle on both sides
  31514. * @public
  31515. */
  31516. var Sausage = extendShape({
  31517. type: 'sausage',
  31518. shape: {
  31519. cx: 0,
  31520. cy: 0,
  31521. r0: 0,
  31522. r: 0,
  31523. startAngle: 0,
  31524. endAngle: Math.PI * 2,
  31525. clockwise: true
  31526. },
  31527. buildPath: function (ctx, shape) {
  31528. var x = shape.cx;
  31529. var y = shape.cy;
  31530. var r0 = Math.max(shape.r0 || 0, 0);
  31531. var r = Math.max(shape.r, 0);
  31532. var dr = (r - r0) * 0.5;
  31533. var rCenter = r0 + dr;
  31534. var startAngle = shape.startAngle;
  31535. var endAngle = shape.endAngle;
  31536. var clockwise = shape.clockwise;
  31537. var unitStartX = Math.cos(startAngle);
  31538. var unitStartY = Math.sin(startAngle);
  31539. var unitEndX = Math.cos(endAngle);
  31540. var unitEndY = Math.sin(endAngle);
  31541. var lessThanCircle = clockwise ? endAngle - startAngle < Math.PI * 2 : startAngle - endAngle < Math.PI * 2;
  31542. if (lessThanCircle) {
  31543. ctx.moveTo(unitStartX * r0 + x, unitStartY * r0 + y);
  31544. ctx.arc(unitStartX * rCenter + x, unitStartY * rCenter + y, dr, -Math.PI + startAngle, startAngle, !clockwise);
  31545. }
  31546. ctx.arc(x, y, r, startAngle, endAngle, !clockwise);
  31547. ctx.moveTo(unitEndX * r + x, unitEndY * r + y);
  31548. ctx.arc(unitEndX * rCenter + x, unitEndY * rCenter + y, dr, endAngle - Math.PI * 2, endAngle - Math.PI, !clockwise);
  31549. if (r0 !== 0) {
  31550. ctx.arc(x, y, r0, endAngle, startAngle, clockwise);
  31551. ctx.moveTo(unitStartX * r0 + x, unitEndY * r0 + y);
  31552. }
  31553. ctx.closePath();
  31554. }
  31555. });
  31556. /*
  31557. * Licensed to the Apache Software Foundation (ASF) under one
  31558. * or more contributor license agreements. See the NOTICE file
  31559. * distributed with this work for additional information
  31560. * regarding copyright ownership. The ASF licenses this file
  31561. * to you under the Apache License, Version 2.0 (the
  31562. * "License"); you may not use this file except in compliance
  31563. * with the License. You may obtain a copy of the License at
  31564. *
  31565. * http://www.apache.org/licenses/LICENSE-2.0
  31566. *
  31567. * Unless required by applicable law or agreed to in writing,
  31568. * software distributed under the License is distributed on an
  31569. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  31570. * KIND, either express or implied. See the License for the
  31571. * specific language governing permissions and limitations
  31572. * under the License.
  31573. */
  31574. var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'barBorderWidth'];
  31575. var _eventPos = [0, 0]; // FIXME
  31576. // Just for compatible with ec2.
  31577. extend(Model.prototype, barItemStyle);
  31578. function getClipArea(coord, data) {
  31579. var coordSysClipArea = coord.getArea && coord.getArea();
  31580. if (coord.type === 'cartesian2d') {
  31581. var baseAxis = coord.getBaseAxis(); // When boundaryGap is false or using time axis. bar may exceed the grid.
  31582. // We should not clip this part.
  31583. // See test/bar2.html
  31584. if (baseAxis.type !== 'category' || !baseAxis.onBand) {
  31585. var expandWidth = data.getLayout('bandWidth');
  31586. if (baseAxis.isHorizontal()) {
  31587. coordSysClipArea.x -= expandWidth;
  31588. coordSysClipArea.width += expandWidth * 2;
  31589. } else {
  31590. coordSysClipArea.y -= expandWidth;
  31591. coordSysClipArea.height += expandWidth * 2;
  31592. }
  31593. }
  31594. }
  31595. return coordSysClipArea;
  31596. }
  31597. extendChartView({
  31598. type: 'bar',
  31599. render: function (seriesModel, ecModel, api) {
  31600. this._updateDrawMode(seriesModel);
  31601. var coordinateSystemType = seriesModel.get('coordinateSystem');
  31602. if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar') {
  31603. this._isLargeDraw ? this._renderLarge(seriesModel, ecModel, api) : this._renderNormal(seriesModel, ecModel, api);
  31604. } else {}
  31605. return this.group;
  31606. },
  31607. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  31608. this._clear();
  31609. this._updateDrawMode(seriesModel);
  31610. },
  31611. incrementalRender: function (params, seriesModel, ecModel, api) {
  31612. // Do not support progressive in normal mode.
  31613. this._incrementalRenderLarge(params, seriesModel);
  31614. },
  31615. _updateDrawMode: function (seriesModel) {
  31616. var isLargeDraw = seriesModel.pipelineContext.large;
  31617. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  31618. this._isLargeDraw = isLargeDraw;
  31619. this._clear();
  31620. }
  31621. },
  31622. _renderNormal: function (seriesModel, ecModel, api) {
  31623. var group = this.group;
  31624. var data = seriesModel.getData();
  31625. var oldData = this._data;
  31626. var coord = seriesModel.coordinateSystem;
  31627. var baseAxis = coord.getBaseAxis();
  31628. var isHorizontalOrRadial;
  31629. if (coord.type === 'cartesian2d') {
  31630. isHorizontalOrRadial = baseAxis.isHorizontal();
  31631. } else if (coord.type === 'polar') {
  31632. isHorizontalOrRadial = baseAxis.dim === 'angle';
  31633. }
  31634. var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null;
  31635. var needsClip = seriesModel.get('clip', true);
  31636. var coordSysClipArea = getClipArea(coord, data); // If there is clipPath created in large mode. Remove it.
  31637. group.removeClipPath(); // We don't use clipPath in normal mode because we needs a perfect animation
  31638. // And don't want the label are clipped.
  31639. var roundCap = seriesModel.get('roundCap', true);
  31640. var drawBackground = seriesModel.get('showBackground', true);
  31641. var backgroundModel = seriesModel.getModel('backgroundStyle');
  31642. var barBorderRadius = backgroundModel.get('barBorderRadius') || 0;
  31643. var bgEls = [];
  31644. var oldBgEls = this._backgroundEls || [];
  31645. data.diff(oldData).add(function (dataIndex) {
  31646. var itemModel = data.getItemModel(dataIndex);
  31647. var layout = getLayout[coord.type](data, dataIndex, itemModel);
  31648. if (drawBackground) {
  31649. var bgLayout = getLayout[coord.type](data, dataIndex);
  31650. var bgEl = createBackgroundEl(coord, isHorizontalOrRadial, bgLayout);
  31651. bgEl.useStyle(backgroundModel.getBarItemStyle()); // Only cartesian2d support borderRadius.
  31652. if (coord.type === 'cartesian2d') {
  31653. bgEl.setShape('r', barBorderRadius);
  31654. }
  31655. bgEls[dataIndex] = bgEl;
  31656. } // If dataZoom in filteMode: 'empty', the baseValue can be set as NaN in "axisProxy".
  31657. if (!data.hasValue(dataIndex)) {
  31658. return;
  31659. }
  31660. if (needsClip) {
  31661. // Clip will modify the layout params.
  31662. // And return a boolean to determine if the shape are fully clipped.
  31663. var isClipped = clip[coord.type](coordSysClipArea, layout);
  31664. if (isClipped) {
  31665. group.remove(el);
  31666. return;
  31667. }
  31668. }
  31669. var el = elementCreator[coord.type](dataIndex, layout, isHorizontalOrRadial, animationModel, false, roundCap);
  31670. data.setItemGraphicEl(dataIndex, el);
  31671. group.add(el);
  31672. updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  31673. }).update(function (newIndex, oldIndex) {
  31674. var itemModel = data.getItemModel(newIndex);
  31675. var layout = getLayout[coord.type](data, newIndex, itemModel);
  31676. if (drawBackground) {
  31677. var bgEl = oldBgEls[oldIndex];
  31678. bgEl.useStyle(backgroundModel.getBarItemStyle()); // Only cartesian2d support borderRadius.
  31679. if (coord.type === 'cartesian2d') {
  31680. bgEl.setShape('r', barBorderRadius);
  31681. }
  31682. bgEls[newIndex] = bgEl;
  31683. var bgLayout = getLayout[coord.type](data, newIndex);
  31684. var shape = createBackgroundShape(isHorizontalOrRadial, bgLayout, coord);
  31685. updateProps(bgEl, {
  31686. shape: shape
  31687. }, animationModel, newIndex);
  31688. }
  31689. var el = oldData.getItemGraphicEl(oldIndex);
  31690. if (!data.hasValue(newIndex)) {
  31691. group.remove(el);
  31692. return;
  31693. }
  31694. if (needsClip) {
  31695. var isClipped = clip[coord.type](coordSysClipArea, layout);
  31696. if (isClipped) {
  31697. group.remove(el);
  31698. return;
  31699. }
  31700. }
  31701. if (el) {
  31702. updateProps(el, {
  31703. shape: layout
  31704. }, animationModel, newIndex);
  31705. } else {
  31706. el = elementCreator[coord.type](newIndex, layout, isHorizontalOrRadial, animationModel, true, roundCap);
  31707. }
  31708. data.setItemGraphicEl(newIndex, el); // Add back
  31709. group.add(el);
  31710. updateStyle(el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar');
  31711. }).remove(function (dataIndex) {
  31712. var el = oldData.getItemGraphicEl(dataIndex);
  31713. if (coord.type === 'cartesian2d') {
  31714. el && removeRect(dataIndex, animationModel, el);
  31715. } else {
  31716. el && removeSector(dataIndex, animationModel, el);
  31717. }
  31718. }).execute();
  31719. var bgGroup = this._backgroundGroup || (this._backgroundGroup = new Group());
  31720. bgGroup.removeAll();
  31721. for (var i = 0; i < bgEls.length; ++i) {
  31722. bgGroup.add(bgEls[i]);
  31723. }
  31724. group.add(bgGroup);
  31725. this._backgroundEls = bgEls;
  31726. this._data = data;
  31727. },
  31728. _renderLarge: function (seriesModel, ecModel, api) {
  31729. this._clear();
  31730. createLarge(seriesModel, this.group); // Use clipPath in large mode.
  31731. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  31732. if (clipPath) {
  31733. this.group.setClipPath(clipPath);
  31734. } else {
  31735. this.group.removeClipPath();
  31736. }
  31737. },
  31738. _incrementalRenderLarge: function (params, seriesModel) {
  31739. this._removeBackground();
  31740. createLarge(seriesModel, this.group, true);
  31741. },
  31742. dispose: noop,
  31743. remove: function (ecModel) {
  31744. this._clear(ecModel);
  31745. },
  31746. _clear: function (ecModel) {
  31747. var group = this.group;
  31748. var data = this._data;
  31749. if (ecModel && ecModel.get('animation') && data && !this._isLargeDraw) {
  31750. this._removeBackground();
  31751. this._backgroundEls = [];
  31752. data.eachItemGraphicEl(function (el) {
  31753. if (el.type === 'sector') {
  31754. removeSector(el.dataIndex, ecModel, el);
  31755. } else {
  31756. removeRect(el.dataIndex, ecModel, el);
  31757. }
  31758. });
  31759. } else {
  31760. group.removeAll();
  31761. }
  31762. this._data = null;
  31763. },
  31764. _removeBackground: function () {
  31765. this.group.remove(this._backgroundGroup);
  31766. this._backgroundGroup = null;
  31767. }
  31768. });
  31769. var mathMax$4 = Math.max;
  31770. var mathMin$4 = Math.min;
  31771. var clip = {
  31772. cartesian2d: function (coordSysBoundingRect, layout) {
  31773. var signWidth = layout.width < 0 ? -1 : 1;
  31774. var signHeight = layout.height < 0 ? -1 : 1; // Needs positive width and height
  31775. if (signWidth < 0) {
  31776. layout.x += layout.width;
  31777. layout.width = -layout.width;
  31778. }
  31779. if (signHeight < 0) {
  31780. layout.y += layout.height;
  31781. layout.height = -layout.height;
  31782. }
  31783. var x = mathMax$4(layout.x, coordSysBoundingRect.x);
  31784. var x2 = mathMin$4(layout.x + layout.width, coordSysBoundingRect.x + coordSysBoundingRect.width);
  31785. var y = mathMax$4(layout.y, coordSysBoundingRect.y);
  31786. var y2 = mathMin$4(layout.y + layout.height, coordSysBoundingRect.y + coordSysBoundingRect.height);
  31787. layout.x = x;
  31788. layout.y = y;
  31789. layout.width = x2 - x;
  31790. layout.height = y2 - y;
  31791. var clipped = layout.width < 0 || layout.height < 0; // Reverse back
  31792. if (signWidth < 0) {
  31793. layout.x += layout.width;
  31794. layout.width = -layout.width;
  31795. }
  31796. if (signHeight < 0) {
  31797. layout.y += layout.height;
  31798. layout.height = -layout.height;
  31799. }
  31800. return clipped;
  31801. },
  31802. polar: function (coordSysClipArea) {
  31803. return false;
  31804. }
  31805. };
  31806. var elementCreator = {
  31807. cartesian2d: function (dataIndex, layout, isHorizontal, animationModel, isUpdate) {
  31808. var rect = new Rect({
  31809. shape: extend({}, layout),
  31810. z2: 1
  31811. });
  31812. rect.name = 'item'; // Animation
  31813. if (animationModel) {
  31814. var rectShape = rect.shape;
  31815. var animateProperty = isHorizontal ? 'height' : 'width';
  31816. var animateTarget = {};
  31817. rectShape[animateProperty] = 0;
  31818. animateTarget[animateProperty] = layout[animateProperty];
  31819. graphic[isUpdate ? 'updateProps' : 'initProps'](rect, {
  31820. shape: animateTarget
  31821. }, animationModel, dataIndex);
  31822. }
  31823. return rect;
  31824. },
  31825. polar: function (dataIndex, layout, isRadial, animationModel, isUpdate, roundCap) {
  31826. // Keep the same logic with bar in catesion: use end value to control
  31827. // direction. Notice that if clockwise is true (by default), the sector
  31828. // will always draw clockwisely, no matter whether endAngle is greater
  31829. // or less than startAngle.
  31830. var clockwise = layout.startAngle < layout.endAngle;
  31831. var ShapeClass = !isRadial && roundCap ? Sausage : Sector;
  31832. var sector = new ShapeClass({
  31833. shape: defaults({
  31834. clockwise: clockwise
  31835. }, layout),
  31836. z2: 1
  31837. });
  31838. sector.name = 'item'; // Animation
  31839. if (animationModel) {
  31840. var sectorShape = sector.shape;
  31841. var animateProperty = isRadial ? 'r' : 'endAngle';
  31842. var animateTarget = {};
  31843. sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle;
  31844. animateTarget[animateProperty] = layout[animateProperty];
  31845. graphic[isUpdate ? 'updateProps' : 'initProps'](sector, {
  31846. shape: animateTarget
  31847. }, animationModel, dataIndex);
  31848. }
  31849. return sector;
  31850. }
  31851. };
  31852. function removeRect(dataIndex, animationModel, el) {
  31853. // Not show text when animating
  31854. el.style.text = null;
  31855. updateProps(el, {
  31856. shape: {
  31857. width: 0
  31858. }
  31859. }, animationModel, dataIndex, function () {
  31860. el.parent && el.parent.remove(el);
  31861. });
  31862. }
  31863. function removeSector(dataIndex, animationModel, el) {
  31864. // Not show text when animating
  31865. el.style.text = null;
  31866. updateProps(el, {
  31867. shape: {
  31868. r: el.shape.r0
  31869. }
  31870. }, animationModel, dataIndex, function () {
  31871. el.parent && el.parent.remove(el);
  31872. });
  31873. }
  31874. var getLayout = {
  31875. // itemModel is only used to get borderWidth, which is not needed
  31876. // when calculating bar background layout.
  31877. cartesian2d: function (data, dataIndex, itemModel) {
  31878. var layout = data.getItemLayout(dataIndex);
  31879. var fixedLineWidth = itemModel ? getLineWidth(itemModel, layout) : 0; // fix layout with lineWidth
  31880. var signX = layout.width > 0 ? 1 : -1;
  31881. var signY = layout.height > 0 ? 1 : -1;
  31882. return {
  31883. x: layout.x + signX * fixedLineWidth / 2,
  31884. y: layout.y + signY * fixedLineWidth / 2,
  31885. width: layout.width - signX * fixedLineWidth,
  31886. height: layout.height - signY * fixedLineWidth
  31887. };
  31888. },
  31889. polar: function (data, dataIndex, itemModel) {
  31890. var layout = data.getItemLayout(dataIndex);
  31891. return {
  31892. cx: layout.cx,
  31893. cy: layout.cy,
  31894. r0: layout.r0,
  31895. r: layout.r,
  31896. startAngle: layout.startAngle,
  31897. endAngle: layout.endAngle
  31898. };
  31899. }
  31900. };
  31901. function isZeroOnPolar(layout) {
  31902. return layout.startAngle != null && layout.endAngle != null && layout.startAngle === layout.endAngle;
  31903. }
  31904. function updateStyle(el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar) {
  31905. var color = data.getItemVisual(dataIndex, 'color');
  31906. var opacity = data.getItemVisual(dataIndex, 'opacity');
  31907. var stroke = data.getVisual('borderColor');
  31908. var itemStyleModel = itemModel.getModel('itemStyle');
  31909. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getBarItemStyle();
  31910. if (!isPolar) {
  31911. el.setShape('r', itemStyleModel.get('barBorderRadius') || 0);
  31912. }
  31913. el.useStyle(defaults({
  31914. stroke: isZeroOnPolar(layout) ? 'none' : stroke,
  31915. fill: isZeroOnPolar(layout) ? 'none' : color,
  31916. opacity: opacity
  31917. }, itemStyleModel.getBarItemStyle()));
  31918. var cursorStyle = itemModel.getShallow('cursor');
  31919. cursorStyle && el.attr('cursor', cursorStyle);
  31920. var labelPositionOutside = isHorizontal ? layout.height > 0 ? 'bottom' : 'top' : layout.width > 0 ? 'left' : 'right';
  31921. if (!isPolar) {
  31922. setLabel(el.style, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside);
  31923. }
  31924. if (isZeroOnPolar(layout)) {
  31925. hoverStyle.fill = hoverStyle.stroke = 'none';
  31926. }
  31927. setHoverStyle(el, hoverStyle);
  31928. } // In case width or height are too small.
  31929. function getLineWidth(itemModel, rawLayout) {
  31930. var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; // width or height may be NaN for empty data
  31931. var width = isNaN(rawLayout.width) ? Number.MAX_VALUE : Math.abs(rawLayout.width);
  31932. var height = isNaN(rawLayout.height) ? Number.MAX_VALUE : Math.abs(rawLayout.height);
  31933. return Math.min(lineWidth, width, height);
  31934. }
  31935. var LargePath = Path.extend({
  31936. type: 'largeBar',
  31937. shape: {
  31938. points: []
  31939. },
  31940. buildPath: function (ctx, shape) {
  31941. // Drawing lines is more efficient than drawing
  31942. // a whole line or drawing rects.
  31943. var points = shape.points;
  31944. var startPoint = this.__startPoint;
  31945. var baseDimIdx = this.__baseDimIdx;
  31946. for (var i = 0; i < points.length; i += 2) {
  31947. startPoint[baseDimIdx] = points[i + baseDimIdx];
  31948. ctx.moveTo(startPoint[0], startPoint[1]);
  31949. ctx.lineTo(points[i], points[i + 1]);
  31950. }
  31951. }
  31952. });
  31953. function createLarge(seriesModel, group, incremental) {
  31954. // TODO support polar
  31955. var data = seriesModel.getData();
  31956. var startPoint = [];
  31957. var baseDimIdx = data.getLayout('valueAxisHorizontal') ? 1 : 0;
  31958. startPoint[1 - baseDimIdx] = data.getLayout('valueAxisStart');
  31959. var largeDataIndices = data.getLayout('largeDataIndices');
  31960. var barWidth = data.getLayout('barWidth');
  31961. var backgroundModel = seriesModel.getModel('backgroundStyle');
  31962. var drawBackground = seriesModel.get('showBackground', true);
  31963. if (drawBackground) {
  31964. var points = data.getLayout('largeBackgroundPoints');
  31965. var backgroundStartPoint = [];
  31966. backgroundStartPoint[1 - baseDimIdx] = data.getLayout('backgroundStart');
  31967. var bgEl = new LargePath({
  31968. shape: {
  31969. points: points
  31970. },
  31971. incremental: !!incremental,
  31972. __startPoint: backgroundStartPoint,
  31973. __baseDimIdx: baseDimIdx,
  31974. __largeDataIndices: largeDataIndices,
  31975. __barWidth: barWidth,
  31976. silent: true,
  31977. z2: 0
  31978. });
  31979. setLargeBackgroundStyle(bgEl, backgroundModel, data);
  31980. group.add(bgEl);
  31981. }
  31982. var el = new LargePath({
  31983. shape: {
  31984. points: data.getLayout('largePoints')
  31985. },
  31986. incremental: !!incremental,
  31987. __startPoint: startPoint,
  31988. __baseDimIdx: baseDimIdx,
  31989. __largeDataIndices: largeDataIndices,
  31990. __barWidth: barWidth
  31991. });
  31992. group.add(el);
  31993. setLargeStyle(el, seriesModel, data); // Enable tooltip and user mouse/touch event handlers.
  31994. el.seriesIndex = seriesModel.seriesIndex;
  31995. if (!seriesModel.get('silent')) {
  31996. el.on('mousedown', largePathUpdateDataIndex);
  31997. el.on('mousemove', largePathUpdateDataIndex);
  31998. }
  31999. } // Use throttle to avoid frequently traverse to find dataIndex.
  32000. var largePathUpdateDataIndex = throttle(function (event) {
  32001. var largePath = this;
  32002. var dataIndex = largePathFindDataIndex(largePath, event.offsetX, event.offsetY);
  32003. largePath.dataIndex = dataIndex >= 0 ? dataIndex : null;
  32004. }, 30, false);
  32005. function largePathFindDataIndex(largePath, x, y) {
  32006. var baseDimIdx = largePath.__baseDimIdx;
  32007. var valueDimIdx = 1 - baseDimIdx;
  32008. var points = largePath.shape.points;
  32009. var largeDataIndices = largePath.__largeDataIndices;
  32010. var barWidthHalf = Math.abs(largePath.__barWidth / 2);
  32011. var startValueVal = largePath.__startPoint[valueDimIdx];
  32012. _eventPos[0] = x;
  32013. _eventPos[1] = y;
  32014. var pointerBaseVal = _eventPos[baseDimIdx];
  32015. var pointerValueVal = _eventPos[1 - baseDimIdx];
  32016. var baseLowerBound = pointerBaseVal - barWidthHalf;
  32017. var baseUpperBound = pointerBaseVal + barWidthHalf;
  32018. for (var i = 0, len = points.length / 2; i < len; i++) {
  32019. var ii = i * 2;
  32020. var barBaseVal = points[ii + baseDimIdx];
  32021. var barValueVal = points[ii + valueDimIdx];
  32022. if (barBaseVal >= baseLowerBound && barBaseVal <= baseUpperBound && (startValueVal <= barValueVal ? pointerValueVal >= startValueVal && pointerValueVal <= barValueVal : pointerValueVal >= barValueVal && pointerValueVal <= startValueVal)) {
  32023. return largeDataIndices[i];
  32024. }
  32025. }
  32026. return -1;
  32027. }
  32028. function setLargeStyle(el, seriesModel, data) {
  32029. var borderColor = data.getVisual('borderColor') || data.getVisual('color');
  32030. var itemStyle = seriesModel.getModel('itemStyle').getItemStyle(['color', 'borderColor']);
  32031. el.useStyle(itemStyle);
  32032. el.style.fill = null;
  32033. el.style.stroke = borderColor;
  32034. el.style.lineWidth = data.getLayout('barWidth');
  32035. }
  32036. function setLargeBackgroundStyle(el, backgroundModel, data) {
  32037. var borderColor = backgroundModel.get('borderColor') || backgroundModel.get('color');
  32038. var itemStyle = backgroundModel.getItemStyle(['color', 'borderColor']);
  32039. el.useStyle(itemStyle);
  32040. el.style.fill = null;
  32041. el.style.stroke = borderColor;
  32042. el.style.lineWidth = data.getLayout('barWidth');
  32043. }
  32044. function createBackgroundShape(isHorizontalOrRadial, layout, coord) {
  32045. var coordLayout;
  32046. var isPolar = coord.type === 'polar';
  32047. if (isPolar) {
  32048. coordLayout = coord.getArea();
  32049. } else {
  32050. coordLayout = coord.grid.getRect();
  32051. }
  32052. if (isPolar) {
  32053. return {
  32054. cx: coordLayout.cx,
  32055. cy: coordLayout.cy,
  32056. r0: isHorizontalOrRadial ? coordLayout.r0 : layout.r0,
  32057. r: isHorizontalOrRadial ? coordLayout.r : layout.r,
  32058. startAngle: isHorizontalOrRadial ? layout.startAngle : 0,
  32059. endAngle: isHorizontalOrRadial ? layout.endAngle : Math.PI * 2
  32060. };
  32061. } else {
  32062. return {
  32063. x: isHorizontalOrRadial ? layout.x : coordLayout.x,
  32064. y: isHorizontalOrRadial ? coordLayout.y : layout.y,
  32065. width: isHorizontalOrRadial ? layout.width : coordLayout.width,
  32066. height: isHorizontalOrRadial ? coordLayout.height : layout.height
  32067. };
  32068. }
  32069. }
  32070. function createBackgroundEl(coord, isHorizontalOrRadial, layout) {
  32071. var ElementClz = coord.type === 'polar' ? Sector : Rect;
  32072. return new ElementClz({
  32073. shape: createBackgroundShape(isHorizontalOrRadial, layout, coord),
  32074. silent: true,
  32075. z2: 0
  32076. });
  32077. }
  32078. /*
  32079. * Licensed to the Apache Software Foundation (ASF) under one
  32080. * or more contributor license agreements. See the NOTICE file
  32081. * distributed with this work for additional information
  32082. * regarding copyright ownership. The ASF licenses this file
  32083. * to you under the Apache License, Version 2.0 (the
  32084. * "License"); you may not use this file except in compliance
  32085. * with the License. You may obtain a copy of the License at
  32086. *
  32087. * http://www.apache.org/licenses/LICENSE-2.0
  32088. *
  32089. * Unless required by applicable law or agreed to in writing,
  32090. * software distributed under the License is distributed on an
  32091. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32092. * KIND, either express or implied. See the License for the
  32093. * specific language governing permissions and limitations
  32094. * under the License.
  32095. */
  32096. var PI$2 = Math.PI;
  32097. /**
  32098. * A final axis is translated and rotated from a "standard axis".
  32099. * So opt.position and opt.rotation is required.
  32100. *
  32101. * A standard axis is and axis from [0, 0] to [0, axisExtent[1]],
  32102. * for example: (0, 0) ------------> (0, 50)
  32103. *
  32104. * nameDirection or tickDirection or labelDirection is 1 means tick
  32105. * or label is below the standard axis, whereas is -1 means above
  32106. * the standard axis. labelOffset means offset between label and axis,
  32107. * which is useful when 'onZero', where axisLabel is in the grid and
  32108. * label in outside grid.
  32109. *
  32110. * Tips: like always,
  32111. * positive rotation represents anticlockwise, and negative rotation
  32112. * represents clockwise.
  32113. * The direction of position coordinate is the same as the direction
  32114. * of screen coordinate.
  32115. *
  32116. * Do not need to consider axis 'inverse', which is auto processed by
  32117. * axis extent.
  32118. *
  32119. * @param {module:zrender/container/Group} group
  32120. * @param {Object} axisModel
  32121. * @param {Object} opt Standard axis parameters.
  32122. * @param {Array.<number>} opt.position [x, y]
  32123. * @param {number} opt.rotation by radian
  32124. * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'.
  32125. * @param {number} [opt.tickDirection=1] 1 or -1
  32126. * @param {number} [opt.labelDirection=1] 1 or -1
  32127. * @param {number} [opt.labelOffset=0] Usefull when onZero.
  32128. * @param {string} [opt.axisLabelShow] default get from axisModel.
  32129. * @param {string} [opt.axisName] default get from axisModel.
  32130. * @param {number} [opt.axisNameAvailableWidth]
  32131. * @param {number} [opt.labelRotate] by degree, default get from axisModel.
  32132. * @param {number} [opt.strokeContainThreshold] Default label interval when label
  32133. * @param {number} [opt.nameTruncateMaxWidth]
  32134. */
  32135. var AxisBuilder = function (axisModel, opt) {
  32136. /**
  32137. * @readOnly
  32138. */
  32139. this.opt = opt;
  32140. /**
  32141. * @readOnly
  32142. */
  32143. this.axisModel = axisModel; // Default value
  32144. defaults(opt, {
  32145. labelOffset: 0,
  32146. nameDirection: 1,
  32147. tickDirection: 1,
  32148. labelDirection: 1,
  32149. silent: true
  32150. });
  32151. /**
  32152. * @readOnly
  32153. */
  32154. this.group = new Group(); // FIXME Not use a seperate text group?
  32155. var dumbGroup = new Group({
  32156. position: opt.position.slice(),
  32157. rotation: opt.rotation
  32158. }); // this.group.add(dumbGroup);
  32159. // this._dumbGroup = dumbGroup;
  32160. dumbGroup.updateTransform();
  32161. this._transform = dumbGroup.transform;
  32162. this._dumbGroup = dumbGroup;
  32163. };
  32164. AxisBuilder.prototype = {
  32165. constructor: AxisBuilder,
  32166. hasBuilder: function (name) {
  32167. return !!builders[name];
  32168. },
  32169. add: function (name) {
  32170. builders[name].call(this);
  32171. },
  32172. getGroup: function () {
  32173. return this.group;
  32174. }
  32175. };
  32176. var builders = {
  32177. /**
  32178. * @private
  32179. */
  32180. axisLine: function () {
  32181. var opt = this.opt;
  32182. var axisModel = this.axisModel;
  32183. if (!axisModel.get('axisLine.show')) {
  32184. return;
  32185. }
  32186. var extent = this.axisModel.axis.getExtent();
  32187. var matrix = this._transform;
  32188. var pt1 = [extent[0], 0];
  32189. var pt2 = [extent[1], 0];
  32190. if (matrix) {
  32191. applyTransform(pt1, pt1, matrix);
  32192. applyTransform(pt2, pt2, matrix);
  32193. }
  32194. var lineStyle = extend({
  32195. lineCap: 'round'
  32196. }, axisModel.getModel('axisLine.lineStyle').getLineStyle());
  32197. this.group.add(new Line({
  32198. // Id for animation
  32199. anid: 'line',
  32200. subPixelOptimize: true,
  32201. shape: {
  32202. x1: pt1[0],
  32203. y1: pt1[1],
  32204. x2: pt2[0],
  32205. y2: pt2[1]
  32206. },
  32207. style: lineStyle,
  32208. strokeContainThreshold: opt.strokeContainThreshold || 5,
  32209. silent: true,
  32210. z2: 1
  32211. }));
  32212. var arrows = axisModel.get('axisLine.symbol');
  32213. var arrowSize = axisModel.get('axisLine.symbolSize');
  32214. var arrowOffset = axisModel.get('axisLine.symbolOffset') || 0;
  32215. if (typeof arrowOffset === 'number') {
  32216. arrowOffset = [arrowOffset, arrowOffset];
  32217. }
  32218. if (arrows != null) {
  32219. if (typeof arrows === 'string') {
  32220. // Use the same arrow for start and end point
  32221. arrows = [arrows, arrows];
  32222. }
  32223. if (typeof arrowSize === 'string' || typeof arrowSize === 'number') {
  32224. // Use the same size for width and height
  32225. arrowSize = [arrowSize, arrowSize];
  32226. }
  32227. var symbolWidth = arrowSize[0];
  32228. var symbolHeight = arrowSize[1];
  32229. each$1([{
  32230. rotate: opt.rotation + Math.PI / 2,
  32231. offset: arrowOffset[0],
  32232. r: 0
  32233. }, {
  32234. rotate: opt.rotation - Math.PI / 2,
  32235. offset: arrowOffset[1],
  32236. r: Math.sqrt((pt1[0] - pt2[0]) * (pt1[0] - pt2[0]) + (pt1[1] - pt2[1]) * (pt1[1] - pt2[1]))
  32237. }], function (point, index) {
  32238. if (arrows[index] !== 'none' && arrows[index] != null) {
  32239. var symbol = createSymbol(arrows[index], -symbolWidth / 2, -symbolHeight / 2, symbolWidth, symbolHeight, lineStyle.stroke, true); // Calculate arrow position with offset
  32240. var r = point.r + point.offset;
  32241. var pos = [pt1[0] + r * Math.cos(opt.rotation), pt1[1] - r * Math.sin(opt.rotation)];
  32242. symbol.attr({
  32243. rotation: point.rotate,
  32244. position: pos,
  32245. silent: true,
  32246. z2: 11
  32247. });
  32248. this.group.add(symbol);
  32249. }
  32250. }, this);
  32251. }
  32252. },
  32253. /**
  32254. * @private
  32255. */
  32256. axisTickLabel: function () {
  32257. var axisModel = this.axisModel;
  32258. var opt = this.opt;
  32259. var ticksEls = buildAxisMajorTicks(this, axisModel, opt);
  32260. var labelEls = buildAxisLabel(this, axisModel, opt);
  32261. fixMinMaxLabelShow(axisModel, labelEls, ticksEls);
  32262. buildAxisMinorTicks(this, axisModel, opt);
  32263. },
  32264. /**
  32265. * @private
  32266. */
  32267. axisName: function () {
  32268. var opt = this.opt;
  32269. var axisModel = this.axisModel;
  32270. var name = retrieve(opt.axisName, axisModel.get('name'));
  32271. if (!name) {
  32272. return;
  32273. }
  32274. var nameLocation = axisModel.get('nameLocation');
  32275. var nameDirection = opt.nameDirection;
  32276. var textStyleModel = axisModel.getModel('nameTextStyle');
  32277. var gap = axisModel.get('nameGap') || 0;
  32278. var extent = this.axisModel.axis.getExtent();
  32279. var gapSignal = extent[0] > extent[1] ? -1 : 1;
  32280. var pos = [nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // 'middle'
  32281. // Reuse labelOffset.
  32282. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0];
  32283. var labelLayout;
  32284. var nameRotation = axisModel.get('nameRotate');
  32285. if (nameRotation != null) {
  32286. nameRotation = nameRotation * PI$2 / 180; // To radian.
  32287. }
  32288. var axisNameAvailableWidth;
  32289. if (isNameLocationCenter(nameLocation)) {
  32290. labelLayout = innerTextLayout(opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis.
  32291. nameDirection);
  32292. } else {
  32293. labelLayout = endTextLayout(opt, nameLocation, nameRotation || 0, extent);
  32294. axisNameAvailableWidth = opt.axisNameAvailableWidth;
  32295. if (axisNameAvailableWidth != null) {
  32296. axisNameAvailableWidth = Math.abs(axisNameAvailableWidth / Math.sin(labelLayout.rotation));
  32297. !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null);
  32298. }
  32299. }
  32300. var textFont = textStyleModel.getFont();
  32301. var truncateOpt = axisModel.get('nameTruncate', true) || {};
  32302. var ellipsis = truncateOpt.ellipsis;
  32303. var maxWidth = retrieve(opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth); // FIXME
  32304. // truncate rich text? (consider performance)
  32305. var truncatedText = ellipsis != null && maxWidth != null ? truncateText$1(name, maxWidth, textFont, ellipsis, {
  32306. minChar: 2,
  32307. placeholder: truncateOpt.placeholder
  32308. }) : name;
  32309. var tooltipOpt = axisModel.get('tooltip', true);
  32310. var mainType = axisModel.mainType;
  32311. var formatterParams = {
  32312. componentType: mainType,
  32313. name: name,
  32314. $vars: ['name']
  32315. };
  32316. formatterParams[mainType + 'Index'] = axisModel.componentIndex;
  32317. var textEl = new Text({
  32318. // Id for animation
  32319. anid: 'name',
  32320. __fullText: name,
  32321. __truncatedText: truncatedText,
  32322. position: pos,
  32323. rotation: labelLayout.rotation,
  32324. silent: isLabelSilent(axisModel),
  32325. z2: 1,
  32326. tooltip: tooltipOpt && tooltipOpt.show ? extend({
  32327. content: name,
  32328. formatter: function () {
  32329. return name;
  32330. },
  32331. formatterParams: formatterParams
  32332. }, tooltipOpt) : null
  32333. });
  32334. setTextStyle(textEl.style, textStyleModel, {
  32335. text: truncatedText,
  32336. textFont: textFont,
  32337. textFill: textStyleModel.getTextColor() || axisModel.get('axisLine.lineStyle.color'),
  32338. textAlign: textStyleModel.get('align') || labelLayout.textAlign,
  32339. textVerticalAlign: textStyleModel.get('verticalAlign') || labelLayout.textVerticalAlign
  32340. });
  32341. if (axisModel.get('triggerEvent')) {
  32342. textEl.eventData = makeAxisEventDataBase(axisModel);
  32343. textEl.eventData.targetType = 'axisName';
  32344. textEl.eventData.name = name;
  32345. } // FIXME
  32346. this._dumbGroup.add(textEl);
  32347. textEl.updateTransform();
  32348. this.group.add(textEl);
  32349. textEl.decomposeTransform();
  32350. }
  32351. };
  32352. var makeAxisEventDataBase = AxisBuilder.makeAxisEventDataBase = function (axisModel) {
  32353. var eventData = {
  32354. componentType: axisModel.mainType,
  32355. componentIndex: axisModel.componentIndex
  32356. };
  32357. eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex;
  32358. return eventData;
  32359. };
  32360. /**
  32361. * @public
  32362. * @static
  32363. * @param {Object} opt
  32364. * @param {number} axisRotation in radian
  32365. * @param {number} textRotation in radian
  32366. * @param {number} direction
  32367. * @return {Object} {
  32368. * rotation, // according to axis
  32369. * textAlign,
  32370. * textVerticalAlign
  32371. * }
  32372. */
  32373. var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) {
  32374. var rotationDiff = remRadian(textRotation - axisRotation);
  32375. var textAlign;
  32376. var textVerticalAlign;
  32377. if (isRadianAroundZero(rotationDiff)) {
  32378. // Label is parallel with axis line.
  32379. textVerticalAlign = direction > 0 ? 'top' : 'bottom';
  32380. textAlign = 'center';
  32381. } else if (isRadianAroundZero(rotationDiff - PI$2)) {
  32382. // Label is inverse parallel with axis line.
  32383. textVerticalAlign = direction > 0 ? 'bottom' : 'top';
  32384. textAlign = 'center';
  32385. } else {
  32386. textVerticalAlign = 'middle';
  32387. if (rotationDiff > 0 && rotationDiff < PI$2) {
  32388. textAlign = direction > 0 ? 'right' : 'left';
  32389. } else {
  32390. textAlign = direction > 0 ? 'left' : 'right';
  32391. }
  32392. }
  32393. return {
  32394. rotation: rotationDiff,
  32395. textAlign: textAlign,
  32396. textVerticalAlign: textVerticalAlign
  32397. };
  32398. };
  32399. function endTextLayout(opt, textPosition, textRotate, extent) {
  32400. var rotationDiff = remRadian(textRotate - opt.rotation);
  32401. var textAlign;
  32402. var textVerticalAlign;
  32403. var inverse = extent[0] > extent[1];
  32404. var onLeft = textPosition === 'start' && !inverse || textPosition !== 'start' && inverse;
  32405. if (isRadianAroundZero(rotationDiff - PI$2 / 2)) {
  32406. textVerticalAlign = onLeft ? 'bottom' : 'top';
  32407. textAlign = 'center';
  32408. } else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) {
  32409. textVerticalAlign = onLeft ? 'top' : 'bottom';
  32410. textAlign = 'center';
  32411. } else {
  32412. textVerticalAlign = 'middle';
  32413. if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) {
  32414. textAlign = onLeft ? 'left' : 'right';
  32415. } else {
  32416. textAlign = onLeft ? 'right' : 'left';
  32417. }
  32418. }
  32419. return {
  32420. rotation: rotationDiff,
  32421. textAlign: textAlign,
  32422. textVerticalAlign: textVerticalAlign
  32423. };
  32424. }
  32425. var isLabelSilent = AxisBuilder.isLabelSilent = function (axisModel) {
  32426. var tooltipOpt = axisModel.get('tooltip');
  32427. return axisModel.get('silent') // Consider mouse cursor, add these restrictions.
  32428. || !(axisModel.get('triggerEvent') || tooltipOpt && tooltipOpt.show);
  32429. };
  32430. function fixMinMaxLabelShow(axisModel, labelEls, tickEls) {
  32431. if (shouldShowAllLabels(axisModel.axis)) {
  32432. return;
  32433. } // If min or max are user set, we need to check
  32434. // If the tick on min(max) are overlap on their neighbour tick
  32435. // If they are overlapped, we need to hide the min(max) tick label
  32436. var showMinLabel = axisModel.get('axisLabel.showMinLabel');
  32437. var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); // FIXME
  32438. // Have not consider onBand yet, where tick els is more than label els.
  32439. labelEls = labelEls || [];
  32440. tickEls = tickEls || [];
  32441. var firstLabel = labelEls[0];
  32442. var nextLabel = labelEls[1];
  32443. var lastLabel = labelEls[labelEls.length - 1];
  32444. var prevLabel = labelEls[labelEls.length - 2];
  32445. var firstTick = tickEls[0];
  32446. var nextTick = tickEls[1];
  32447. var lastTick = tickEls[tickEls.length - 1];
  32448. var prevTick = tickEls[tickEls.length - 2];
  32449. if (showMinLabel === false) {
  32450. ignoreEl(firstLabel);
  32451. ignoreEl(firstTick);
  32452. } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) {
  32453. if (showMinLabel) {
  32454. ignoreEl(nextLabel);
  32455. ignoreEl(nextTick);
  32456. } else {
  32457. ignoreEl(firstLabel);
  32458. ignoreEl(firstTick);
  32459. }
  32460. }
  32461. if (showMaxLabel === false) {
  32462. ignoreEl(lastLabel);
  32463. ignoreEl(lastTick);
  32464. } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) {
  32465. if (showMaxLabel) {
  32466. ignoreEl(prevLabel);
  32467. ignoreEl(prevTick);
  32468. } else {
  32469. ignoreEl(lastLabel);
  32470. ignoreEl(lastTick);
  32471. }
  32472. }
  32473. }
  32474. function ignoreEl(el) {
  32475. el && (el.ignore = true);
  32476. }
  32477. function isTwoLabelOverlapped(current, next, labelLayout) {
  32478. // current and next has the same rotation.
  32479. var firstRect = current && current.getBoundingRect().clone();
  32480. var nextRect = next && next.getBoundingRect().clone();
  32481. if (!firstRect || !nextRect) {
  32482. return;
  32483. } // When checking intersect of two rotated labels, we use mRotationBack
  32484. // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`.
  32485. var mRotationBack = identity([]);
  32486. rotate(mRotationBack, mRotationBack, -current.rotation);
  32487. firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform()));
  32488. nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform()));
  32489. return firstRect.intersect(nextRect);
  32490. }
  32491. function isNameLocationCenter(nameLocation) {
  32492. return nameLocation === 'middle' || nameLocation === 'center';
  32493. }
  32494. function createTicks(ticksCoords, tickTransform, tickEndCoord, tickLineStyle, aniid) {
  32495. var tickEls = [];
  32496. var pt1 = [];
  32497. var pt2 = [];
  32498. for (var i = 0; i < ticksCoords.length; i++) {
  32499. var tickCoord = ticksCoords[i].coord;
  32500. pt1[0] = tickCoord;
  32501. pt1[1] = 0;
  32502. pt2[0] = tickCoord;
  32503. pt2[1] = tickEndCoord;
  32504. if (tickTransform) {
  32505. applyTransform(pt1, pt1, tickTransform);
  32506. applyTransform(pt2, pt2, tickTransform);
  32507. } // Tick line, Not use group transform to have better line draw
  32508. var tickEl = new Line({
  32509. // Id for animation
  32510. anid: aniid + '_' + ticksCoords[i].tickValue,
  32511. subPixelOptimize: true,
  32512. shape: {
  32513. x1: pt1[0],
  32514. y1: pt1[1],
  32515. x2: pt2[0],
  32516. y2: pt2[1]
  32517. },
  32518. style: tickLineStyle,
  32519. z2: 2,
  32520. silent: true
  32521. });
  32522. tickEls.push(tickEl);
  32523. }
  32524. return tickEls;
  32525. }
  32526. function buildAxisMajorTicks(axisBuilder, axisModel, opt) {
  32527. var axis = axisModel.axis;
  32528. var tickModel = axisModel.getModel('axisTick');
  32529. if (!tickModel.get('show') || axis.scale.isBlank()) {
  32530. return;
  32531. }
  32532. var lineStyleModel = tickModel.getModel('lineStyle');
  32533. var tickEndCoord = opt.tickDirection * tickModel.get('length');
  32534. var ticksCoords = axis.getTicksCoords();
  32535. var ticksEls = createTicks(ticksCoords, axisBuilder._transform, tickEndCoord, defaults(lineStyleModel.getLineStyle(), {
  32536. stroke: axisModel.get('axisLine.lineStyle.color')
  32537. }), 'ticks');
  32538. for (var i = 0; i < ticksEls.length; i++) {
  32539. axisBuilder.group.add(ticksEls[i]);
  32540. }
  32541. return ticksEls;
  32542. }
  32543. function buildAxisMinorTicks(axisBuilder, axisModel, opt) {
  32544. var axis = axisModel.axis;
  32545. var minorTickModel = axisModel.getModel('minorTick');
  32546. if (!minorTickModel.get('show') || axis.scale.isBlank()) {
  32547. return;
  32548. }
  32549. var minorTicksCoords = axis.getMinorTicksCoords();
  32550. if (!minorTicksCoords.length) {
  32551. return;
  32552. }
  32553. var lineStyleModel = minorTickModel.getModel('lineStyle');
  32554. var tickEndCoord = opt.tickDirection * minorTickModel.get('length');
  32555. var minorTickLineStyle = defaults(lineStyleModel.getLineStyle(), defaults(axisModel.getModel('axisTick').getLineStyle(), {
  32556. stroke: axisModel.get('axisLine.lineStyle.color')
  32557. }));
  32558. for (var i = 0; i < minorTicksCoords.length; i++) {
  32559. var minorTicksEls = createTicks(minorTicksCoords[i], axisBuilder._transform, tickEndCoord, minorTickLineStyle, 'minorticks_' + i);
  32560. for (var k = 0; k < minorTicksEls.length; k++) {
  32561. axisBuilder.group.add(minorTicksEls[k]);
  32562. }
  32563. }
  32564. }
  32565. function buildAxisLabel(axisBuilder, axisModel, opt) {
  32566. var axis = axisModel.axis;
  32567. var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show'));
  32568. if (!show || axis.scale.isBlank()) {
  32569. return;
  32570. }
  32571. var labelModel = axisModel.getModel('axisLabel');
  32572. var labelMargin = labelModel.get('margin');
  32573. var labels = axis.getViewLabels(); // Special label rotate.
  32574. var labelRotation = (retrieve(opt.labelRotate, labelModel.get('rotate')) || 0) * PI$2 / 180;
  32575. var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection);
  32576. var rawCategoryData = axisModel.getCategories && axisModel.getCategories(true);
  32577. var labelEls = [];
  32578. var silent = isLabelSilent(axisModel);
  32579. var triggerEvent = axisModel.get('triggerEvent');
  32580. each$1(labels, function (labelItem, index) {
  32581. var tickValue = labelItem.tickValue;
  32582. var formattedLabel = labelItem.formattedLabel;
  32583. var rawLabel = labelItem.rawLabel;
  32584. var itemLabelModel = labelModel;
  32585. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  32586. itemLabelModel = new Model(rawCategoryData[tickValue].textStyle, labelModel, axisModel.ecModel);
  32587. }
  32588. var textColor = itemLabelModel.getTextColor() || axisModel.get('axisLine.lineStyle.color');
  32589. var tickCoord = axis.dataToCoord(tickValue);
  32590. var pos = [tickCoord, opt.labelOffset + opt.labelDirection * labelMargin];
  32591. var textEl = new Text({
  32592. // Id for animation
  32593. anid: 'label_' + tickValue,
  32594. position: pos,
  32595. rotation: labelLayout.rotation,
  32596. silent: silent,
  32597. z2: 10
  32598. });
  32599. setTextStyle(textEl.style, itemLabelModel, {
  32600. text: formattedLabel,
  32601. textAlign: itemLabelModel.getShallow('align', true) || labelLayout.textAlign,
  32602. textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign,
  32603. textFill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original
  32604. // index of axis.data. So tick should not be exposed to user
  32605. // in category axis.
  32606. // (2) Compatible with previous version, which always use formatted label as
  32607. // input. But in interval scale the formatted label is like '223,445', which
  32608. // maked user repalce ','. So we modify it to return original val but remain
  32609. // it as 'string' to avoid error in replacing.
  32610. axis.type === 'category' ? rawLabel : axis.type === 'value' ? tickValue + '' : tickValue, index) : textColor
  32611. }); // Pack data for mouse event
  32612. if (triggerEvent) {
  32613. textEl.eventData = makeAxisEventDataBase(axisModel);
  32614. textEl.eventData.targetType = 'axisLabel';
  32615. textEl.eventData.value = rawLabel;
  32616. } // FIXME
  32617. axisBuilder._dumbGroup.add(textEl);
  32618. textEl.updateTransform();
  32619. labelEls.push(textEl);
  32620. axisBuilder.group.add(textEl);
  32621. textEl.decomposeTransform();
  32622. });
  32623. return labelEls;
  32624. }
  32625. /*
  32626. * Licensed to the Apache Software Foundation (ASF) under one
  32627. * or more contributor license agreements. See the NOTICE file
  32628. * distributed with this work for additional information
  32629. * regarding copyright ownership. The ASF licenses this file
  32630. * to you under the Apache License, Version 2.0 (the
  32631. * "License"); you may not use this file except in compliance
  32632. * with the License. You may obtain a copy of the License at
  32633. *
  32634. * http://www.apache.org/licenses/LICENSE-2.0
  32635. *
  32636. * Unless required by applicable law or agreed to in writing,
  32637. * software distributed under the License is distributed on an
  32638. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32639. * KIND, either express or implied. See the License for the
  32640. * specific language governing permissions and limitations
  32641. * under the License.
  32642. */
  32643. var each$6 = each$1;
  32644. var curry$1 = curry; // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  32645. // allAxesInfo should be updated when setOption performed.
  32646. function collect(ecModel, api) {
  32647. var result = {
  32648. /**
  32649. * key: makeKey(axis.model)
  32650. * value: {
  32651. * axis,
  32652. * coordSys,
  32653. * axisPointerModel,
  32654. * triggerTooltip,
  32655. * involveSeries,
  32656. * snap,
  32657. * seriesModels,
  32658. * seriesDataCount
  32659. * }
  32660. */
  32661. axesInfo: {},
  32662. seriesInvolved: false,
  32663. /**
  32664. * key: makeKey(coordSys.model)
  32665. * value: Object: key makeKey(axis.model), value: axisInfo
  32666. */
  32667. coordSysAxesInfo: {},
  32668. coordSysMap: {}
  32669. };
  32670. collectAxesInfo(result, ecModel, api); // Check seriesInvolved for performance, in case too many series in some chart.
  32671. result.seriesInvolved && collectSeriesInfo(result, ecModel);
  32672. return result;
  32673. }
  32674. function collectAxesInfo(result, ecModel, api) {
  32675. var globalTooltipModel = ecModel.getComponent('tooltip');
  32676. var globalAxisPointerModel = ecModel.getComponent('axisPointer'); // links can only be set on global.
  32677. var linksOption = globalAxisPointerModel.get('link', true) || [];
  32678. var linkGroups = []; // Collect axes info.
  32679. each$6(api.getCoordinateSystems(), function (coordSys) {
  32680. // Some coordinate system do not support axes, like geo.
  32681. if (!coordSys.axisPointerEnabled) {
  32682. return;
  32683. }
  32684. var coordSysKey = makeKey(coordSys.model);
  32685. var axesInfoInCoordSys = result.coordSysAxesInfo[coordSysKey] = {};
  32686. result.coordSysMap[coordSysKey] = coordSys; // Set tooltip (like 'cross') is a convienent way to show axisPointer
  32687. // for user. So we enable seting tooltip on coordSys model.
  32688. var coordSysModel = coordSys.model;
  32689. var baseTooltipModel = coordSysModel.getModel('tooltip', globalTooltipModel);
  32690. each$6(coordSys.getAxes(), curry$1(saveTooltipAxisInfo, false, null)); // If axis tooltip used, choose tooltip axis for each coordSys.
  32691. // Notice this case: coordSys is `grid` but not `cartesian2D` here.
  32692. if (coordSys.getTooltipAxes && globalTooltipModel // If tooltip.showContent is set as false, tooltip will not
  32693. // show but axisPointer will show as normal.
  32694. && baseTooltipModel.get('show')) {
  32695. // Compatible with previous logic. But series.tooltip.trigger: 'axis'
  32696. // or series.data[n].tooltip.trigger: 'axis' are not support any more.
  32697. var triggerAxis = baseTooltipModel.get('trigger') === 'axis';
  32698. var cross = baseTooltipModel.get('axisPointer.type') === 'cross';
  32699. var tooltipAxes = coordSys.getTooltipAxes(baseTooltipModel.get('axisPointer.axis'));
  32700. if (triggerAxis || cross) {
  32701. each$6(tooltipAxes.baseAxes, curry$1(saveTooltipAxisInfo, cross ? 'cross' : true, triggerAxis));
  32702. }
  32703. if (cross) {
  32704. each$6(tooltipAxes.otherAxes, curry$1(saveTooltipAxisInfo, 'cross', false));
  32705. }
  32706. } // fromTooltip: true | false | 'cross'
  32707. // triggerTooltip: true | false | null
  32708. function saveTooltipAxisInfo(fromTooltip, triggerTooltip, axis) {
  32709. var axisPointerModel = axis.model.getModel('axisPointer', globalAxisPointerModel);
  32710. var axisPointerShow = axisPointerModel.get('show');
  32711. if (!axisPointerShow || axisPointerShow === 'auto' && !fromTooltip && !isHandleTrigger(axisPointerModel)) {
  32712. return;
  32713. }
  32714. if (triggerTooltip == null) {
  32715. triggerTooltip = axisPointerModel.get('triggerTooltip');
  32716. }
  32717. axisPointerModel = fromTooltip ? makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) : axisPointerModel;
  32718. var snap = axisPointerModel.get('snap');
  32719. var key = makeKey(axis.model);
  32720. var involveSeries = triggerTooltip || snap || axis.type === 'category'; // If result.axesInfo[key] exist, override it (tooltip has higher priority).
  32721. var axisInfo = result.axesInfo[key] = {
  32722. key: key,
  32723. axis: axis,
  32724. coordSys: coordSys,
  32725. axisPointerModel: axisPointerModel,
  32726. triggerTooltip: triggerTooltip,
  32727. involveSeries: involveSeries,
  32728. snap: snap,
  32729. useHandle: isHandleTrigger(axisPointerModel),
  32730. seriesModels: []
  32731. };
  32732. axesInfoInCoordSys[key] = axisInfo;
  32733. result.seriesInvolved |= involveSeries;
  32734. var groupIndex = getLinkGroupIndex(linksOption, axis);
  32735. if (groupIndex != null) {
  32736. var linkGroup = linkGroups[groupIndex] || (linkGroups[groupIndex] = {
  32737. axesInfo: {}
  32738. });
  32739. linkGroup.axesInfo[key] = axisInfo;
  32740. linkGroup.mapper = linksOption[groupIndex].mapper;
  32741. axisInfo.linkGroup = linkGroup;
  32742. }
  32743. }
  32744. });
  32745. }
  32746. function makeAxisPointerModel(axis, baseTooltipModel, globalAxisPointerModel, ecModel, fromTooltip, triggerTooltip) {
  32747. var tooltipAxisPointerModel = baseTooltipModel.getModel('axisPointer');
  32748. var volatileOption = {};
  32749. each$6(['type', 'snap', 'lineStyle', 'shadowStyle', 'label', 'animation', 'animationDurationUpdate', 'animationEasingUpdate', 'z'], function (field) {
  32750. volatileOption[field] = clone(tooltipAxisPointerModel.get(field));
  32751. }); // category axis do not auto snap, otherwise some tick that do not
  32752. // has value can not be hovered. value/time/log axis default snap if
  32753. // triggered from tooltip and trigger tooltip.
  32754. volatileOption.snap = axis.type !== 'category' && !!triggerTooltip; // Compatibel with previous behavior, tooltip axis do not show label by default.
  32755. // Only these properties can be overrided from tooltip to axisPointer.
  32756. if (tooltipAxisPointerModel.get('type') === 'cross') {
  32757. volatileOption.type = 'line';
  32758. }
  32759. var labelOption = volatileOption.label || (volatileOption.label = {}); // Follow the convention, do not show label when triggered by tooltip by default.
  32760. labelOption.show == null && (labelOption.show = false);
  32761. if (fromTooltip === 'cross') {
  32762. // When 'cross', both axes show labels.
  32763. var tooltipAxisPointerLabelShow = tooltipAxisPointerModel.get('label.show');
  32764. labelOption.show = tooltipAxisPointerLabelShow != null ? tooltipAxisPointerLabelShow : true; // If triggerTooltip, this is a base axis, which should better not use cross style
  32765. // (cross style is dashed by default)
  32766. if (!triggerTooltip) {
  32767. var crossStyle = volatileOption.lineStyle = tooltipAxisPointerModel.get('crossStyle');
  32768. crossStyle && defaults(labelOption, crossStyle.textStyle);
  32769. }
  32770. }
  32771. return axis.model.getModel('axisPointer', new Model(volatileOption, globalAxisPointerModel, ecModel));
  32772. }
  32773. function collectSeriesInfo(result, ecModel) {
  32774. // Prepare data for axis trigger
  32775. ecModel.eachSeries(function (seriesModel) {
  32776. // Notice this case: this coordSys is `cartesian2D` but not `grid`.
  32777. var coordSys = seriesModel.coordinateSystem;
  32778. var seriesTooltipTrigger = seriesModel.get('tooltip.trigger', true);
  32779. var seriesTooltipShow = seriesModel.get('tooltip.show', true);
  32780. if (!coordSys || seriesTooltipTrigger === 'none' || seriesTooltipTrigger === false || seriesTooltipTrigger === 'item' || seriesTooltipShow === false || seriesModel.get('axisPointer.show', true) === false) {
  32781. return;
  32782. }
  32783. each$6(result.coordSysAxesInfo[makeKey(coordSys.model)], function (axisInfo) {
  32784. var axis = axisInfo.axis;
  32785. if (coordSys.getAxis(axis.dim) === axis) {
  32786. axisInfo.seriesModels.push(seriesModel);
  32787. axisInfo.seriesDataCount == null && (axisInfo.seriesDataCount = 0);
  32788. axisInfo.seriesDataCount += seriesModel.getData().count();
  32789. }
  32790. });
  32791. }, this);
  32792. }
  32793. /**
  32794. * For example:
  32795. * {
  32796. * axisPointer: {
  32797. * links: [{
  32798. * xAxisIndex: [2, 4],
  32799. * yAxisIndex: 'all'
  32800. * }, {
  32801. * xAxisId: ['a5', 'a7'],
  32802. * xAxisName: 'xxx'
  32803. * }]
  32804. * }
  32805. * }
  32806. */
  32807. function getLinkGroupIndex(linksOption, axis) {
  32808. var axisModel = axis.model;
  32809. var dim = axis.dim;
  32810. for (var i = 0; i < linksOption.length; i++) {
  32811. var linkOption = linksOption[i] || {};
  32812. if (checkPropInLink(linkOption[dim + 'AxisId'], axisModel.id) || checkPropInLink(linkOption[dim + 'AxisIndex'], axisModel.componentIndex) || checkPropInLink(linkOption[dim + 'AxisName'], axisModel.name)) {
  32813. return i;
  32814. }
  32815. }
  32816. }
  32817. function checkPropInLink(linkPropValue, axisPropValue) {
  32818. return linkPropValue === 'all' || isArray(linkPropValue) && indexOf(linkPropValue, axisPropValue) >= 0 || linkPropValue === axisPropValue;
  32819. }
  32820. function fixValue(axisModel) {
  32821. var axisInfo = getAxisInfo(axisModel);
  32822. if (!axisInfo) {
  32823. return;
  32824. }
  32825. var axisPointerModel = axisInfo.axisPointerModel;
  32826. var scale = axisInfo.axis.scale;
  32827. var option = axisPointerModel.option;
  32828. var status = axisPointerModel.get('status');
  32829. var value = axisPointerModel.get('value'); // Parse init value for category and time axis.
  32830. if (value != null) {
  32831. value = scale.parse(value);
  32832. }
  32833. var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value
  32834. // and status should be initialized.
  32835. if (status == null) {
  32836. option.status = useHandle ? 'show' : 'hide';
  32837. }
  32838. var extent = scale.getExtent().slice();
  32839. extent[0] > extent[1] && extent.reverse();
  32840. if ( // Pick a value on axis when initializing.
  32841. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent,
  32842. // where we should re-pick a value to keep `handle` displaying normally.
  32843. || value > extent[1]) {
  32844. // Make handle displayed on the end of the axis when init, which looks better.
  32845. value = extent[1];
  32846. }
  32847. if (value < extent[0]) {
  32848. value = extent[0];
  32849. }
  32850. option.value = value;
  32851. if (useHandle) {
  32852. option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show';
  32853. }
  32854. }
  32855. function getAxisInfo(axisModel) {
  32856. var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo;
  32857. return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)];
  32858. }
  32859. function getAxisPointerModel(axisModel) {
  32860. var axisInfo = getAxisInfo(axisModel);
  32861. return axisInfo && axisInfo.axisPointerModel;
  32862. }
  32863. function isHandleTrigger(axisPointerModel) {
  32864. return !!axisPointerModel.get('handle.show');
  32865. }
  32866. /**
  32867. * @param {module:echarts/model/Model} model
  32868. * @return {string} unique key
  32869. */
  32870. function makeKey(model) {
  32871. return model.type + '||' + model.id;
  32872. }
  32873. /*
  32874. * Licensed to the Apache Software Foundation (ASF) under one
  32875. * or more contributor license agreements. See the NOTICE file
  32876. * distributed with this work for additional information
  32877. * regarding copyright ownership. The ASF licenses this file
  32878. * to you under the Apache License, Version 2.0 (the
  32879. * "License"); you may not use this file except in compliance
  32880. * with the License. You may obtain a copy of the License at
  32881. *
  32882. * http://www.apache.org/licenses/LICENSE-2.0
  32883. *
  32884. * Unless required by applicable law or agreed to in writing,
  32885. * software distributed under the License is distributed on an
  32886. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32887. * KIND, either express or implied. See the License for the
  32888. * specific language governing permissions and limitations
  32889. * under the License.
  32890. */
  32891. /**
  32892. * Base class of AxisView.
  32893. */
  32894. var AxisView = extendComponentView({
  32895. type: 'axis',
  32896. /**
  32897. * @private
  32898. */
  32899. _axisPointer: null,
  32900. /**
  32901. * @protected
  32902. * @type {string}
  32903. */
  32904. axisPointerClass: null,
  32905. /**
  32906. * @override
  32907. */
  32908. render: function (axisModel, ecModel, api, payload) {
  32909. // FIXME
  32910. // This process should proformed after coordinate systems updated
  32911. // (axis scale updated), and should be performed each time update.
  32912. // So put it here temporarily, although it is not appropriate to
  32913. // put a model-writing procedure in `view`.
  32914. this.axisPointerClass && fixValue(axisModel);
  32915. AxisView.superApply(this, 'render', arguments);
  32916. updateAxisPointer(this, axisModel, ecModel, api, payload, true);
  32917. },
  32918. /**
  32919. * Action handler.
  32920. * @public
  32921. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  32922. * @param {module:echarts/model/Global} ecModel
  32923. * @param {module:echarts/ExtensionAPI} api
  32924. * @param {Object} payload
  32925. */
  32926. updateAxisPointer: function (axisModel, ecModel, api, payload, force) {
  32927. updateAxisPointer(this, axisModel, ecModel, api, payload, false);
  32928. },
  32929. /**
  32930. * @override
  32931. */
  32932. remove: function (ecModel, api) {
  32933. var axisPointer = this._axisPointer;
  32934. axisPointer && axisPointer.remove(api);
  32935. AxisView.superApply(this, 'remove', arguments);
  32936. },
  32937. /**
  32938. * @override
  32939. */
  32940. dispose: function (ecModel, api) {
  32941. disposeAxisPointer(this, api);
  32942. AxisView.superApply(this, 'dispose', arguments);
  32943. }
  32944. });
  32945. function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) {
  32946. var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass);
  32947. if (!Clazz) {
  32948. return;
  32949. }
  32950. var axisPointerModel = getAxisPointerModel(axisModel);
  32951. axisPointerModel ? (axisView._axisPointer || (axisView._axisPointer = new Clazz())).render(axisModel, axisPointerModel, api, forceRender) : disposeAxisPointer(axisView, api);
  32952. }
  32953. function disposeAxisPointer(axisView, ecModel, api) {
  32954. var axisPointer = axisView._axisPointer;
  32955. axisPointer && axisPointer.dispose(ecModel, api);
  32956. axisView._axisPointer = null;
  32957. }
  32958. var axisPointerClazz = [];
  32959. AxisView.registerAxisPointerClass = function (type, clazz) {
  32960. axisPointerClazz[type] = clazz;
  32961. };
  32962. AxisView.getAxisPointerClass = function (type) {
  32963. return type && axisPointerClazz[type];
  32964. };
  32965. /*
  32966. * Licensed to the Apache Software Foundation (ASF) under one
  32967. * or more contributor license agreements. See the NOTICE file
  32968. * distributed with this work for additional information
  32969. * regarding copyright ownership. The ASF licenses this file
  32970. * to you under the Apache License, Version 2.0 (the
  32971. * "License"); you may not use this file except in compliance
  32972. * with the License. You may obtain a copy of the License at
  32973. *
  32974. * http://www.apache.org/licenses/LICENSE-2.0
  32975. *
  32976. * Unless required by applicable law or agreed to in writing,
  32977. * software distributed under the License is distributed on an
  32978. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  32979. * KIND, either express or implied. See the License for the
  32980. * specific language governing permissions and limitations
  32981. * under the License.
  32982. */
  32983. /**
  32984. * Can only be called after coordinate system creation stage.
  32985. * (Can be called before coordinate system update stage).
  32986. *
  32987. * @param {Object} opt {labelInside}
  32988. * @return {Object} {
  32989. * position, rotation, labelDirection, labelOffset,
  32990. * tickDirection, labelRotate, z2
  32991. * }
  32992. */
  32993. function layout$1(gridModel, axisModel, opt) {
  32994. opt = opt || {};
  32995. var grid = gridModel.coordinateSystem;
  32996. var axis = axisModel.axis;
  32997. var layout = {};
  32998. var otherAxisOnZeroOf = axis.getAxesOnZeroOf()[0];
  32999. var rawAxisPosition = axis.position;
  33000. var axisPosition = otherAxisOnZeroOf ? 'onZero' : rawAxisPosition;
  33001. var axisDim = axis.dim;
  33002. var rect = grid.getRect();
  33003. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  33004. var idx = {
  33005. left: 0,
  33006. right: 1,
  33007. top: 0,
  33008. bottom: 1,
  33009. onZero: 2
  33010. };
  33011. var axisOffset = axisModel.get('offset') || 0;
  33012. var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset];
  33013. if (otherAxisOnZeroOf) {
  33014. var onZeroCoord = otherAxisOnZeroOf.toGlobalCoord(otherAxisOnZeroOf.dataToCoord(0));
  33015. posBound[idx.onZero] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]);
  33016. } // Axis position
  33017. layout.position = [axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3]]; // Axis rotation
  33018. layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim
  33019. var dirMap = {
  33020. top: -1,
  33021. bottom: 1,
  33022. left: -1,
  33023. right: 1
  33024. };
  33025. layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition];
  33026. layout.labelOffset = otherAxisOnZeroOf ? posBound[idx[rawAxisPosition]] - posBound[idx.onZero] : 0;
  33027. if (axisModel.get('axisTick.inside')) {
  33028. layout.tickDirection = -layout.tickDirection;
  33029. }
  33030. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  33031. layout.labelDirection = -layout.labelDirection;
  33032. } // Special label rotation
  33033. var labelRotate = axisModel.get('axisLabel.rotate');
  33034. layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // Over splitLine and splitArea
  33035. layout.z2 = 1;
  33036. return layout;
  33037. }
  33038. /*
  33039. * Licensed to the Apache Software Foundation (ASF) under one
  33040. * or more contributor license agreements. See the NOTICE file
  33041. * distributed with this work for additional information
  33042. * regarding copyright ownership. The ASF licenses this file
  33043. * to you under the Apache License, Version 2.0 (the
  33044. * "License"); you may not use this file except in compliance
  33045. * with the License. You may obtain a copy of the License at
  33046. *
  33047. * http://www.apache.org/licenses/LICENSE-2.0
  33048. *
  33049. * Unless required by applicable law or agreed to in writing,
  33050. * software distributed under the License is distributed on an
  33051. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33052. * KIND, either express or implied. See the License for the
  33053. * specific language governing permissions and limitations
  33054. * under the License.
  33055. */
  33056. function rectCoordAxisBuildSplitArea(axisView, axisGroup, axisModel, gridModel) {
  33057. var axis = axisModel.axis;
  33058. if (axis.scale.isBlank()) {
  33059. return;
  33060. }
  33061. var splitAreaModel = axisModel.getModel('splitArea');
  33062. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  33063. var areaColors = areaStyleModel.get('color');
  33064. var gridRect = gridModel.coordinateSystem.getRect();
  33065. var ticksCoords = axis.getTicksCoords({
  33066. tickModel: splitAreaModel,
  33067. clamp: true
  33068. });
  33069. if (!ticksCoords.length) {
  33070. return;
  33071. } // For Making appropriate splitArea animation, the color and anid
  33072. // should be corresponding to previous one if possible.
  33073. var areaColorsLen = areaColors.length;
  33074. var lastSplitAreaColors = axisView.__splitAreaColors;
  33075. var newSplitAreaColors = createHashMap();
  33076. var colorIndex = 0;
  33077. if (lastSplitAreaColors) {
  33078. for (var i = 0; i < ticksCoords.length; i++) {
  33079. var cIndex = lastSplitAreaColors.get(ticksCoords[i].tickValue);
  33080. if (cIndex != null) {
  33081. colorIndex = (cIndex + (areaColorsLen - 1) * i) % areaColorsLen;
  33082. break;
  33083. }
  33084. }
  33085. }
  33086. var prev = axis.toGlobalCoord(ticksCoords[0].coord);
  33087. var areaStyle = areaStyleModel.getAreaStyle();
  33088. areaColors = isArray(areaColors) ? areaColors : [areaColors];
  33089. for (var i = 1; i < ticksCoords.length; i++) {
  33090. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33091. var x;
  33092. var y;
  33093. var width;
  33094. var height;
  33095. if (axis.isHorizontal()) {
  33096. x = prev;
  33097. y = gridRect.y;
  33098. width = tickCoord - x;
  33099. height = gridRect.height;
  33100. prev = x + width;
  33101. } else {
  33102. x = gridRect.x;
  33103. y = prev;
  33104. width = gridRect.width;
  33105. height = tickCoord - y;
  33106. prev = y + height;
  33107. }
  33108. var tickValue = ticksCoords[i - 1].tickValue;
  33109. tickValue != null && newSplitAreaColors.set(tickValue, colorIndex);
  33110. axisGroup.add(new Rect({
  33111. anid: tickValue != null ? 'area_' + tickValue : null,
  33112. shape: {
  33113. x: x,
  33114. y: y,
  33115. width: width,
  33116. height: height
  33117. },
  33118. style: defaults({
  33119. fill: areaColors[colorIndex]
  33120. }, areaStyle),
  33121. silent: true
  33122. }));
  33123. colorIndex = (colorIndex + 1) % areaColorsLen;
  33124. }
  33125. axisView.__splitAreaColors = newSplitAreaColors;
  33126. }
  33127. function rectCoordAxisHandleRemove(axisView) {
  33128. axisView.__splitAreaColors = null;
  33129. }
  33130. /*
  33131. * Licensed to the Apache Software Foundation (ASF) under one
  33132. * or more contributor license agreements. See the NOTICE file
  33133. * distributed with this work for additional information
  33134. * regarding copyright ownership. The ASF licenses this file
  33135. * to you under the Apache License, Version 2.0 (the
  33136. * "License"); you may not use this file except in compliance
  33137. * with the License. You may obtain a copy of the License at
  33138. *
  33139. * http://www.apache.org/licenses/LICENSE-2.0
  33140. *
  33141. * Unless required by applicable law or agreed to in writing,
  33142. * software distributed under the License is distributed on an
  33143. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33144. * KIND, either express or implied. See the License for the
  33145. * specific language governing permissions and limitations
  33146. * under the License.
  33147. */
  33148. var axisBuilderAttrs = ['axisLine', 'axisTickLabel', 'axisName'];
  33149. var selfBuilderAttrs = ['splitArea', 'splitLine', 'minorSplitLine'];
  33150. var CartesianAxisView = AxisView.extend({
  33151. type: 'cartesianAxis',
  33152. axisPointerClass: 'CartesianAxisPointer',
  33153. /**
  33154. * @override
  33155. */
  33156. render: function (axisModel, ecModel, api, payload) {
  33157. this.group.removeAll();
  33158. var oldAxisGroup = this._axisGroup;
  33159. this._axisGroup = new Group();
  33160. this.group.add(this._axisGroup);
  33161. if (!axisModel.get('show')) {
  33162. return;
  33163. }
  33164. var gridModel = axisModel.getCoordSysModel();
  33165. var layout = layout$1(gridModel, axisModel);
  33166. var axisBuilder = new AxisBuilder(axisModel, layout);
  33167. each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder);
  33168. this._axisGroup.add(axisBuilder.getGroup());
  33169. each$1(selfBuilderAttrs, function (name) {
  33170. if (axisModel.get(name + '.show')) {
  33171. this['_' + name](axisModel, gridModel);
  33172. }
  33173. }, this);
  33174. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  33175. CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  33176. },
  33177. remove: function () {
  33178. rectCoordAxisHandleRemove(this);
  33179. },
  33180. /**
  33181. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33182. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33183. * @private
  33184. */
  33185. _splitLine: function (axisModel, gridModel) {
  33186. var axis = axisModel.axis;
  33187. if (axis.scale.isBlank()) {
  33188. return;
  33189. }
  33190. var splitLineModel = axisModel.getModel('splitLine');
  33191. var lineStyleModel = splitLineModel.getModel('lineStyle');
  33192. var lineColors = lineStyleModel.get('color');
  33193. lineColors = isArray(lineColors) ? lineColors : [lineColors];
  33194. var gridRect = gridModel.coordinateSystem.getRect();
  33195. var isHorizontal = axis.isHorizontal();
  33196. var lineCount = 0;
  33197. var ticksCoords = axis.getTicksCoords({
  33198. tickModel: splitLineModel
  33199. });
  33200. var p1 = [];
  33201. var p2 = [];
  33202. var lineStyle = lineStyleModel.getLineStyle();
  33203. for (var i = 0; i < ticksCoords.length; i++) {
  33204. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  33205. if (isHorizontal) {
  33206. p1[0] = tickCoord;
  33207. p1[1] = gridRect.y;
  33208. p2[0] = tickCoord;
  33209. p2[1] = gridRect.y + gridRect.height;
  33210. } else {
  33211. p1[0] = gridRect.x;
  33212. p1[1] = tickCoord;
  33213. p2[0] = gridRect.x + gridRect.width;
  33214. p2[1] = tickCoord;
  33215. }
  33216. var colorIndex = lineCount++ % lineColors.length;
  33217. var tickValue = ticksCoords[i].tickValue;
  33218. this._axisGroup.add(new Line({
  33219. anid: tickValue != null ? 'line_' + ticksCoords[i].tickValue : null,
  33220. subPixelOptimize: true,
  33221. shape: {
  33222. x1: p1[0],
  33223. y1: p1[1],
  33224. x2: p2[0],
  33225. y2: p2[1]
  33226. },
  33227. style: defaults({
  33228. stroke: lineColors[colorIndex]
  33229. }, lineStyle),
  33230. silent: true
  33231. }));
  33232. }
  33233. },
  33234. /**
  33235. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33236. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33237. * @private
  33238. */
  33239. _minorSplitLine: function (axisModel, gridModel) {
  33240. var axis = axisModel.axis;
  33241. var minorSplitLineModel = axisModel.getModel('minorSplitLine');
  33242. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  33243. var gridRect = gridModel.coordinateSystem.getRect();
  33244. var isHorizontal = axis.isHorizontal();
  33245. var minorTicksCoords = axis.getMinorTicksCoords();
  33246. if (!minorTicksCoords.length) {
  33247. return;
  33248. }
  33249. var p1 = [];
  33250. var p2 = [];
  33251. var lineStyle = lineStyleModel.getLineStyle();
  33252. for (var i = 0; i < minorTicksCoords.length; i++) {
  33253. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  33254. var tickCoord = axis.toGlobalCoord(minorTicksCoords[i][k].coord);
  33255. if (isHorizontal) {
  33256. p1[0] = tickCoord;
  33257. p1[1] = gridRect.y;
  33258. p2[0] = tickCoord;
  33259. p2[1] = gridRect.y + gridRect.height;
  33260. } else {
  33261. p1[0] = gridRect.x;
  33262. p1[1] = tickCoord;
  33263. p2[0] = gridRect.x + gridRect.width;
  33264. p2[1] = tickCoord;
  33265. }
  33266. this._axisGroup.add(new Line({
  33267. anid: 'minor_line_' + minorTicksCoords[i][k].tickValue,
  33268. subPixelOptimize: true,
  33269. shape: {
  33270. x1: p1[0],
  33271. y1: p1[1],
  33272. x2: p2[0],
  33273. y2: p2[1]
  33274. },
  33275. style: lineStyle,
  33276. silent: true
  33277. }));
  33278. }
  33279. }
  33280. },
  33281. /**
  33282. * @param {module:echarts/coord/cartesian/AxisModel} axisModel
  33283. * @param {module:echarts/coord/cartesian/GridModel} gridModel
  33284. * @private
  33285. */
  33286. _splitArea: function (axisModel, gridModel) {
  33287. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, gridModel);
  33288. }
  33289. });
  33290. CartesianAxisView.extend({
  33291. type: 'xAxis'
  33292. });
  33293. CartesianAxisView.extend({
  33294. type: 'yAxis'
  33295. });
  33296. /*
  33297. * Licensed to the Apache Software Foundation (ASF) under one
  33298. * or more contributor license agreements. See the NOTICE file
  33299. * distributed with this work for additional information
  33300. * regarding copyright ownership. The ASF licenses this file
  33301. * to you under the Apache License, Version 2.0 (the
  33302. * "License"); you may not use this file except in compliance
  33303. * with the License. You may obtain a copy of the License at
  33304. *
  33305. * http://www.apache.org/licenses/LICENSE-2.0
  33306. *
  33307. * Unless required by applicable law or agreed to in writing,
  33308. * software distributed under the License is distributed on an
  33309. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33310. * KIND, either express or implied. See the License for the
  33311. * specific language governing permissions and limitations
  33312. * under the License.
  33313. */
  33314. /*
  33315. * Licensed to the Apache Software Foundation (ASF) under one
  33316. * or more contributor license agreements. See the NOTICE file
  33317. * distributed with this work for additional information
  33318. * regarding copyright ownership. The ASF licenses this file
  33319. * to you under the Apache License, Version 2.0 (the
  33320. * "License"); you may not use this file except in compliance
  33321. * with the License. You may obtain a copy of the License at
  33322. *
  33323. * http://www.apache.org/licenses/LICENSE-2.0
  33324. *
  33325. * Unless required by applicable law or agreed to in writing,
  33326. * software distributed under the License is distributed on an
  33327. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33328. * KIND, either express or implied. See the License for the
  33329. * specific language governing permissions and limitations
  33330. * under the License.
  33331. */
  33332. extendComponentView({
  33333. type: 'grid',
  33334. render: function (gridModel, ecModel) {
  33335. this.group.removeAll();
  33336. if (gridModel.get('show')) {
  33337. this.group.add(new Rect({
  33338. shape: gridModel.coordinateSystem.getRect(),
  33339. style: defaults({
  33340. fill: gridModel.get('backgroundColor')
  33341. }, gridModel.getItemStyle()),
  33342. silent: true,
  33343. z2: -1
  33344. }));
  33345. }
  33346. }
  33347. });
  33348. registerPreprocessor(function (option) {
  33349. // Only create grid when need
  33350. if (option.xAxis && option.yAxis && !option.grid) {
  33351. option.grid = {};
  33352. }
  33353. });
  33354. /*
  33355. * Licensed to the Apache Software Foundation (ASF) under one
  33356. * or more contributor license agreements. See the NOTICE file
  33357. * distributed with this work for additional information
  33358. * regarding copyright ownership. The ASF licenses this file
  33359. * to you under the Apache License, Version 2.0 (the
  33360. * "License"); you may not use this file except in compliance
  33361. * with the License. You may obtain a copy of the License at
  33362. *
  33363. * http://www.apache.org/licenses/LICENSE-2.0
  33364. *
  33365. * Unless required by applicable law or agreed to in writing,
  33366. * software distributed under the License is distributed on an
  33367. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33368. * KIND, either express or implied. See the License for the
  33369. * specific language governing permissions and limitations
  33370. * under the License.
  33371. */
  33372. registerLayout(PRIORITY.VISUAL.LAYOUT, curry(layout, 'bar')); // Use higher prority to avoid to be blocked by other overall layout, which do not
  33373. // only exist in this module, but probably also exist in other modules, like `barPolar`.
  33374. registerLayout(PRIORITY.VISUAL.PROGRESSIVE_LAYOUT, largeLayout);
  33375. registerVisual({
  33376. seriesType: 'bar',
  33377. reset: function (seriesModel) {
  33378. // Visual coding for legend
  33379. seriesModel.getData().setVisual('legendSymbol', 'roundRect');
  33380. }
  33381. });
  33382. /*
  33383. * Licensed to the Apache Software Foundation (ASF) under one
  33384. * or more contributor license agreements. See the NOTICE file
  33385. * distributed with this work for additional information
  33386. * regarding copyright ownership. The ASF licenses this file
  33387. * to you under the Apache License, Version 2.0 (the
  33388. * "License"); you may not use this file except in compliance
  33389. * with the License. You may obtain a copy of the License at
  33390. *
  33391. * http://www.apache.org/licenses/LICENSE-2.0
  33392. *
  33393. * Unless required by applicable law or agreed to in writing,
  33394. * software distributed under the License is distributed on an
  33395. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33396. * KIND, either express or implied. See the License for the
  33397. * specific language governing permissions and limitations
  33398. * under the License.
  33399. */
  33400. SeriesModel.extend({
  33401. type: 'series.line',
  33402. dependencies: ['grid', 'polar'],
  33403. getInitialData: function (option, ecModel) {
  33404. return createListFromArray(this.getSource(), this, {
  33405. useEncodeDefaulter: true
  33406. });
  33407. },
  33408. defaultOption: {
  33409. zlevel: 0,
  33410. z: 2,
  33411. coordinateSystem: 'cartesian2d',
  33412. legendHoverLink: true,
  33413. hoverAnimation: true,
  33414. // stack: null
  33415. // xAxisIndex: 0,
  33416. // yAxisIndex: 0,
  33417. // polarIndex: 0,
  33418. // If clip the overflow value
  33419. clip: true,
  33420. // cursor: null,
  33421. label: {
  33422. position: 'top'
  33423. },
  33424. // itemStyle: {
  33425. // },
  33426. lineStyle: {
  33427. width: 2,
  33428. type: 'solid'
  33429. },
  33430. // areaStyle: {
  33431. // origin of areaStyle. Valid values:
  33432. // `'auto'/null/undefined`: from axisLine to data
  33433. // `'start'`: from min to data
  33434. // `'end'`: from data to max
  33435. // origin: 'auto'
  33436. // },
  33437. // false, 'start', 'end', 'middle'
  33438. step: false,
  33439. // Disabled if step is true
  33440. smooth: false,
  33441. smoothMonotone: null,
  33442. symbol: 'emptyCircle',
  33443. symbolSize: 4,
  33444. symbolRotate: null,
  33445. showSymbol: true,
  33446. // `false`: follow the label interval strategy.
  33447. // `true`: show all symbols.
  33448. // `'auto'`: If possible, show all symbols, otherwise
  33449. // follow the label interval strategy.
  33450. showAllSymbol: 'auto',
  33451. // Whether to connect break point.
  33452. connectNulls: false,
  33453. // Sampling for large data. Can be: 'average', 'max', 'min', 'sum'.
  33454. sampling: 'none',
  33455. animationEasing: 'linear',
  33456. // Disable progressive
  33457. progressive: 0,
  33458. hoverLayerThreshold: Infinity
  33459. }
  33460. });
  33461. /*
  33462. * Licensed to the Apache Software Foundation (ASF) under one
  33463. * or more contributor license agreements. See the NOTICE file
  33464. * distributed with this work for additional information
  33465. * regarding copyright ownership. The ASF licenses this file
  33466. * to you under the Apache License, Version 2.0 (the
  33467. * "License"); you may not use this file except in compliance
  33468. * with the License. You may obtain a copy of the License at
  33469. *
  33470. * http://www.apache.org/licenses/LICENSE-2.0
  33471. *
  33472. * Unless required by applicable law or agreed to in writing,
  33473. * software distributed under the License is distributed on an
  33474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33475. * KIND, either express or implied. See the License for the
  33476. * specific language governing permissions and limitations
  33477. * under the License.
  33478. */
  33479. /**
  33480. * @module echarts/chart/helper/Symbol
  33481. */
  33482. /**
  33483. * @constructor
  33484. * @alias {module:echarts/chart/helper/Symbol}
  33485. * @param {module:echarts/data/List} data
  33486. * @param {number} idx
  33487. * @extends {module:zrender/graphic/Group}
  33488. */
  33489. function SymbolClz$1(data, idx, seriesScope) {
  33490. Group.call(this);
  33491. this.updateData(data, idx, seriesScope);
  33492. }
  33493. var symbolProto = SymbolClz$1.prototype;
  33494. /**
  33495. * @public
  33496. * @static
  33497. * @param {module:echarts/data/List} data
  33498. * @param {number} dataIndex
  33499. * @return {Array.<number>} [width, height]
  33500. */
  33501. var getSymbolSize = SymbolClz$1.getSymbolSize = function (data, idx) {
  33502. var symbolSize = data.getItemVisual(idx, 'symbolSize');
  33503. return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  33504. };
  33505. function getScale(symbolSize) {
  33506. return [symbolSize[0] / 2, symbolSize[1] / 2];
  33507. }
  33508. function driftSymbol(dx, dy) {
  33509. this.parent.drift(dx, dy);
  33510. }
  33511. symbolProto._createSymbol = function (symbolType, data, idx, symbolSize, keepAspect) {
  33512. // Remove paths created before
  33513. this.removeAll();
  33514. var color = data.getItemVisual(idx, 'color'); // var symbolPath = createSymbol(
  33515. // symbolType, -0.5, -0.5, 1, 1, color
  33516. // );
  33517. // If width/height are set too small (e.g., set to 1) on ios10
  33518. // and macOS Sierra, a circle stroke become a rect, no matter what
  33519. // the scale is set. So we set width/height as 2. See #4150.
  33520. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, color, keepAspect);
  33521. symbolPath.attr({
  33522. z2: 100,
  33523. culling: true,
  33524. scale: getScale(symbolSize)
  33525. }); // Rewrite drift method
  33526. symbolPath.drift = driftSymbol;
  33527. this._symbolType = symbolType;
  33528. this.add(symbolPath);
  33529. };
  33530. /**
  33531. * Stop animation
  33532. * @param {boolean} toLastFrame
  33533. */
  33534. symbolProto.stopSymbolAnimation = function (toLastFrame) {
  33535. this.childAt(0).stopAnimation(toLastFrame);
  33536. };
  33537. /**
  33538. * FIXME:
  33539. * Caution: This method breaks the encapsulation of this module,
  33540. * but it indeed brings convenience. So do not use the method
  33541. * unless you detailedly know all the implements of `Symbol`,
  33542. * especially animation.
  33543. *
  33544. * Get symbol path element.
  33545. */
  33546. symbolProto.getSymbolPath = function () {
  33547. return this.childAt(0);
  33548. };
  33549. /**
  33550. * Get scale(aka, current symbol size).
  33551. * Including the change caused by animation
  33552. */
  33553. symbolProto.getScale = function () {
  33554. return this.childAt(0).scale;
  33555. };
  33556. /**
  33557. * Highlight symbol
  33558. */
  33559. symbolProto.highlight = function () {
  33560. this.childAt(0).trigger('emphasis');
  33561. };
  33562. /**
  33563. * Downplay symbol
  33564. */
  33565. symbolProto.downplay = function () {
  33566. this.childAt(0).trigger('normal');
  33567. };
  33568. /**
  33569. * @param {number} zlevel
  33570. * @param {number} z
  33571. */
  33572. symbolProto.setZ = function (zlevel, z) {
  33573. var symbolPath = this.childAt(0);
  33574. symbolPath.zlevel = zlevel;
  33575. symbolPath.z = z;
  33576. };
  33577. symbolProto.setDraggable = function (draggable) {
  33578. var symbolPath = this.childAt(0);
  33579. symbolPath.draggable = draggable;
  33580. symbolPath.cursor = draggable ? 'move' : symbolPath.cursor;
  33581. };
  33582. /**
  33583. * Update symbol properties
  33584. * @param {module:echarts/data/List} data
  33585. * @param {number} idx
  33586. * @param {Object} [seriesScope]
  33587. * @param {Object} [seriesScope.itemStyle]
  33588. * @param {Object} [seriesScope.hoverItemStyle]
  33589. * @param {Object} [seriesScope.symbolRotate]
  33590. * @param {Object} [seriesScope.symbolOffset]
  33591. * @param {module:echarts/model/Model} [seriesScope.labelModel]
  33592. * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel]
  33593. * @param {boolean} [seriesScope.hoverAnimation]
  33594. * @param {Object} [seriesScope.cursorStyle]
  33595. * @param {module:echarts/model/Model} [seriesScope.itemModel]
  33596. * @param {string} [seriesScope.symbolInnerColor]
  33597. * @param {Object} [seriesScope.fadeIn=false]
  33598. */
  33599. symbolProto.updateData = function (data, idx, seriesScope) {
  33600. this.silent = false;
  33601. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  33602. var seriesModel = data.hostModel;
  33603. var symbolSize = getSymbolSize(data, idx);
  33604. var isInit = symbolType !== this._symbolType;
  33605. if (isInit) {
  33606. var keepAspect = data.getItemVisual(idx, 'symbolKeepAspect');
  33607. this._createSymbol(symbolType, data, idx, symbolSize, keepAspect);
  33608. } else {
  33609. var symbolPath = this.childAt(0);
  33610. symbolPath.silent = false;
  33611. updateProps(symbolPath, {
  33612. scale: getScale(symbolSize)
  33613. }, seriesModel, idx);
  33614. }
  33615. this._updateCommon(data, idx, symbolSize, seriesScope);
  33616. if (isInit) {
  33617. var symbolPath = this.childAt(0);
  33618. var fadeIn = seriesScope && seriesScope.fadeIn;
  33619. var target = {
  33620. scale: symbolPath.scale.slice()
  33621. };
  33622. fadeIn && (target.style = {
  33623. opacity: symbolPath.style.opacity
  33624. });
  33625. symbolPath.scale = [0, 0];
  33626. fadeIn && (symbolPath.style.opacity = 0);
  33627. initProps(symbolPath, target, seriesModel, idx);
  33628. }
  33629. this._seriesModel = seriesModel;
  33630. }; // Update common properties
  33631. var normalStyleAccessPath = ['itemStyle'];
  33632. var emphasisStyleAccessPath = ['emphasis', 'itemStyle'];
  33633. var normalLabelAccessPath = ['label'];
  33634. var emphasisLabelAccessPath = ['emphasis', 'label'];
  33635. /**
  33636. * @param {module:echarts/data/List} data
  33637. * @param {number} idx
  33638. * @param {Array.<number>} symbolSize
  33639. * @param {Object} [seriesScope]
  33640. */
  33641. symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) {
  33642. var symbolPath = this.childAt(0);
  33643. var seriesModel = data.hostModel;
  33644. var color = data.getItemVisual(idx, 'color'); // Reset style
  33645. if (symbolPath.type !== 'image') {
  33646. symbolPath.useStyle({
  33647. strokeNoScale: true
  33648. });
  33649. } else {
  33650. symbolPath.setStyle({
  33651. opacity: null,
  33652. shadowBlur: null,
  33653. shadowOffsetX: null,
  33654. shadowOffsetY: null,
  33655. shadowColor: null
  33656. });
  33657. }
  33658. var itemStyle = seriesScope && seriesScope.itemStyle;
  33659. var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle;
  33660. var symbolOffset = seriesScope && seriesScope.symbolOffset;
  33661. var labelModel = seriesScope && seriesScope.labelModel;
  33662. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel;
  33663. var hoverAnimation = seriesScope && seriesScope.hoverAnimation;
  33664. var cursorStyle = seriesScope && seriesScope.cursorStyle;
  33665. if (!seriesScope || data.hasItemOption) {
  33666. var itemModel = seriesScope && seriesScope.itemModel ? seriesScope.itemModel : data.getItemModel(idx); // Color must be excluded.
  33667. // Because symbol provide setColor individually to set fill and stroke
  33668. itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']);
  33669. hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle();
  33670. symbolOffset = itemModel.getShallow('symbolOffset');
  33671. labelModel = itemModel.getModel(normalLabelAccessPath);
  33672. hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath);
  33673. hoverAnimation = itemModel.getShallow('hoverAnimation');
  33674. cursorStyle = itemModel.getShallow('cursor');
  33675. } else {
  33676. hoverItemStyle = extend({}, hoverItemStyle);
  33677. }
  33678. var elStyle = symbolPath.style;
  33679. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  33680. symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0);
  33681. if (symbolOffset) {
  33682. symbolPath.attr('position', [parsePercent$1(symbolOffset[0], symbolSize[0]), parsePercent$1(symbolOffset[1], symbolSize[1])]);
  33683. }
  33684. cursorStyle && symbolPath.attr('cursor', cursorStyle); // PENDING setColor before setStyle!!!
  33685. symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor);
  33686. symbolPath.setStyle(itemStyle);
  33687. var opacity = data.getItemVisual(idx, 'opacity');
  33688. if (opacity != null) {
  33689. elStyle.opacity = opacity;
  33690. }
  33691. var liftZ = data.getItemVisual(idx, 'liftZ');
  33692. var z2Origin = symbolPath.__z2Origin;
  33693. if (liftZ != null) {
  33694. if (z2Origin == null) {
  33695. symbolPath.__z2Origin = symbolPath.z2;
  33696. symbolPath.z2 += liftZ;
  33697. }
  33698. } else if (z2Origin != null) {
  33699. symbolPath.z2 = z2Origin;
  33700. symbolPath.__z2Origin = null;
  33701. }
  33702. var useNameLabel = seriesScope && seriesScope.useNameLabel;
  33703. setLabelStyle(elStyle, hoverItemStyle, labelModel, hoverLabelModel, {
  33704. labelFetcher: seriesModel,
  33705. labelDataIndex: idx,
  33706. defaultText: getLabelDefaultText,
  33707. isRectText: true,
  33708. autoColor: color
  33709. }); // Do not execute util needed.
  33710. function getLabelDefaultText(idx, opt) {
  33711. return useNameLabel ? data.getName(idx) : getDefaultLabel(data, idx);
  33712. }
  33713. symbolPath.__symbolOriginalScale = getScale(symbolSize);
  33714. symbolPath.hoverStyle = hoverItemStyle;
  33715. symbolPath.highDownOnUpdate = hoverAnimation && seriesModel.isAnimationEnabled() ? highDownOnUpdate : null;
  33716. setHoverStyle(symbolPath);
  33717. };
  33718. function highDownOnUpdate(fromState, toState) {
  33719. // Do not support this hover animation util some scenario required.
  33720. // Animation can only be supported in hover layer when using `el.incremetal`.
  33721. if (this.incremental || this.useHoverLayer) {
  33722. return;
  33723. }
  33724. if (toState === 'emphasis') {
  33725. var scale = this.__symbolOriginalScale;
  33726. var ratio = scale[1] / scale[0];
  33727. var emphasisOpt = {
  33728. scale: [Math.max(scale[0] * 1.1, scale[0] + 3), Math.max(scale[1] * 1.1, scale[1] + 3 * ratio)]
  33729. }; // FIXME
  33730. // modify it after support stop specified animation.
  33731. // toState === fromState
  33732. // ? (this.stopAnimation(), this.attr(emphasisOpt))
  33733. this.animateTo(emphasisOpt, 400, 'elasticOut');
  33734. } else if (toState === 'normal') {
  33735. this.animateTo({
  33736. scale: this.__symbolOriginalScale
  33737. }, 400, 'elasticOut');
  33738. }
  33739. }
  33740. /**
  33741. * @param {Function} cb
  33742. * @param {Object} [opt]
  33743. * @param {Object} [opt.keepLabel=true]
  33744. */
  33745. symbolProto.fadeOut = function (cb, opt) {
  33746. var symbolPath = this.childAt(0); // Avoid mistaken hover when fading out
  33747. this.silent = symbolPath.silent = true; // Not show text when animating
  33748. !(opt && opt.keepLabel) && (symbolPath.style.text = null);
  33749. updateProps(symbolPath, {
  33750. style: {
  33751. opacity: 0
  33752. },
  33753. scale: [0, 0]
  33754. }, this._seriesModel, this.dataIndex, cb);
  33755. };
  33756. inherits(SymbolClz$1, Group);
  33757. /*
  33758. * Licensed to the Apache Software Foundation (ASF) under one
  33759. * or more contributor license agreements. See the NOTICE file
  33760. * distributed with this work for additional information
  33761. * regarding copyright ownership. The ASF licenses this file
  33762. * to you under the Apache License, Version 2.0 (the
  33763. * "License"); you may not use this file except in compliance
  33764. * with the License. You may obtain a copy of the License at
  33765. *
  33766. * http://www.apache.org/licenses/LICENSE-2.0
  33767. *
  33768. * Unless required by applicable law or agreed to in writing,
  33769. * software distributed under the License is distributed on an
  33770. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33771. * KIND, either express or implied. See the License for the
  33772. * specific language governing permissions and limitations
  33773. * under the License.
  33774. */
  33775. /**
  33776. * @module echarts/chart/helper/SymbolDraw
  33777. */
  33778. /**
  33779. * @constructor
  33780. * @alias module:echarts/chart/helper/SymbolDraw
  33781. * @param {module:zrender/graphic/Group} [symbolCtor]
  33782. */
  33783. function SymbolDraw(symbolCtor) {
  33784. this.group = new Group();
  33785. this._symbolCtor = symbolCtor || SymbolClz$1;
  33786. }
  33787. var symbolDrawProto = SymbolDraw.prototype;
  33788. function symbolNeedsDraw(data, point, idx, opt) {
  33789. return point && !isNaN(point[0]) && !isNaN(point[1]) && !(opt.isIgnore && opt.isIgnore(idx)) // We do not set clipShape on group, because it will cut part of
  33790. // the symbol element shape. We use the same clip shape here as
  33791. // the line clip.
  33792. && !(opt.clipShape && !opt.clipShape.contain(point[0], point[1])) && data.getItemVisual(idx, 'symbol') !== 'none';
  33793. }
  33794. /**
  33795. * Update symbols draw by new data
  33796. * @param {module:echarts/data/List} data
  33797. * @param {Object} [opt] Or isIgnore
  33798. * @param {Function} [opt.isIgnore]
  33799. * @param {Object} [opt.clipShape]
  33800. */
  33801. symbolDrawProto.updateData = function (data, opt) {
  33802. opt = normalizeUpdateOpt(opt);
  33803. var group = this.group;
  33804. var seriesModel = data.hostModel;
  33805. var oldData = this._data;
  33806. var SymbolCtor = this._symbolCtor;
  33807. var seriesScope = makeSeriesScope(data); // There is no oldLineData only when first rendering or switching from
  33808. // stream mode to normal mode, where previous elements should be removed.
  33809. if (!oldData) {
  33810. group.removeAll();
  33811. }
  33812. data.diff(oldData).add(function (newIdx) {
  33813. var point = data.getItemLayout(newIdx);
  33814. if (symbolNeedsDraw(data, point, newIdx, opt)) {
  33815. var symbolEl = new SymbolCtor(data, newIdx, seriesScope);
  33816. symbolEl.attr('position', point);
  33817. data.setItemGraphicEl(newIdx, symbolEl);
  33818. group.add(symbolEl);
  33819. }
  33820. }).update(function (newIdx, oldIdx) {
  33821. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  33822. var point = data.getItemLayout(newIdx);
  33823. if (!symbolNeedsDraw(data, point, newIdx, opt)) {
  33824. group.remove(symbolEl);
  33825. return;
  33826. }
  33827. if (!symbolEl) {
  33828. symbolEl = new SymbolCtor(data, newIdx);
  33829. symbolEl.attr('position', point);
  33830. } else {
  33831. symbolEl.updateData(data, newIdx, seriesScope);
  33832. updateProps(symbolEl, {
  33833. position: point
  33834. }, seriesModel);
  33835. } // Add back
  33836. group.add(symbolEl);
  33837. data.setItemGraphicEl(newIdx, symbolEl);
  33838. }).remove(function (oldIdx) {
  33839. var el = oldData.getItemGraphicEl(oldIdx);
  33840. el && el.fadeOut(function () {
  33841. group.remove(el);
  33842. });
  33843. }).execute();
  33844. this._data = data;
  33845. };
  33846. symbolDrawProto.isPersistent = function () {
  33847. return true;
  33848. };
  33849. symbolDrawProto.updateLayout = function () {
  33850. var data = this._data;
  33851. if (data) {
  33852. // Not use animation
  33853. data.eachItemGraphicEl(function (el, idx) {
  33854. var point = data.getItemLayout(idx);
  33855. el.attr('position', point);
  33856. });
  33857. }
  33858. };
  33859. symbolDrawProto.incrementalPrepareUpdate = function (data) {
  33860. this._seriesScope = makeSeriesScope(data);
  33861. this._data = null;
  33862. this.group.removeAll();
  33863. };
  33864. /**
  33865. * Update symbols draw by new data
  33866. * @param {module:echarts/data/List} data
  33867. * @param {Object} [opt] Or isIgnore
  33868. * @param {Function} [opt.isIgnore]
  33869. * @param {Object} [opt.clipShape]
  33870. */
  33871. symbolDrawProto.incrementalUpdate = function (taskParams, data, opt) {
  33872. opt = normalizeUpdateOpt(opt);
  33873. function updateIncrementalAndHover(el) {
  33874. if (!el.isGroup) {
  33875. el.incremental = el.useHoverLayer = true;
  33876. }
  33877. }
  33878. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  33879. var point = data.getItemLayout(idx);
  33880. if (symbolNeedsDraw(data, point, idx, opt)) {
  33881. var el = new this._symbolCtor(data, idx, this._seriesScope);
  33882. el.traverse(updateIncrementalAndHover);
  33883. el.attr('position', point);
  33884. this.group.add(el);
  33885. data.setItemGraphicEl(idx, el);
  33886. }
  33887. }
  33888. };
  33889. function normalizeUpdateOpt(opt) {
  33890. if (opt != null && !isObject$1(opt)) {
  33891. opt = {
  33892. isIgnore: opt
  33893. };
  33894. }
  33895. return opt || {};
  33896. }
  33897. symbolDrawProto.remove = function (enableAnimation) {
  33898. var group = this.group;
  33899. var data = this._data; // Incremental model do not have this._data.
  33900. if (data && enableAnimation) {
  33901. data.eachItemGraphicEl(function (el) {
  33902. el.fadeOut(function () {
  33903. group.remove(el);
  33904. });
  33905. });
  33906. } else {
  33907. group.removeAll();
  33908. }
  33909. };
  33910. function makeSeriesScope(data) {
  33911. var seriesModel = data.hostModel;
  33912. return {
  33913. itemStyle: seriesModel.getModel('itemStyle').getItemStyle(['color']),
  33914. hoverItemStyle: seriesModel.getModel('emphasis.itemStyle').getItemStyle(),
  33915. symbolRotate: seriesModel.get('symbolRotate'),
  33916. symbolOffset: seriesModel.get('symbolOffset'),
  33917. hoverAnimation: seriesModel.get('hoverAnimation'),
  33918. labelModel: seriesModel.getModel('label'),
  33919. hoverLabelModel: seriesModel.getModel('emphasis.label'),
  33920. cursorStyle: seriesModel.get('cursor')
  33921. };
  33922. }
  33923. /*
  33924. * Licensed to the Apache Software Foundation (ASF) under one
  33925. * or more contributor license agreements. See the NOTICE file
  33926. * distributed with this work for additional information
  33927. * regarding copyright ownership. The ASF licenses this file
  33928. * to you under the Apache License, Version 2.0 (the
  33929. * "License"); you may not use this file except in compliance
  33930. * with the License. You may obtain a copy of the License at
  33931. *
  33932. * http://www.apache.org/licenses/LICENSE-2.0
  33933. *
  33934. * Unless required by applicable law or agreed to in writing,
  33935. * software distributed under the License is distributed on an
  33936. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  33937. * KIND, either express or implied. See the License for the
  33938. * specific language governing permissions and limitations
  33939. * under the License.
  33940. */
  33941. /**
  33942. * @param {Object} coordSys
  33943. * @param {module:echarts/data/List} data
  33944. * @param {string} valueOrigin lineSeries.option.areaStyle.origin
  33945. */
  33946. function prepareDataCoordInfo(coordSys, data, valueOrigin) {
  33947. var baseAxis = coordSys.getBaseAxis();
  33948. var valueAxis = coordSys.getOtherAxis(baseAxis);
  33949. var valueStart = getValueStart(valueAxis, valueOrigin);
  33950. var baseAxisDim = baseAxis.dim;
  33951. var valueAxisDim = valueAxis.dim;
  33952. var valueDim = data.mapDimension(valueAxisDim);
  33953. var baseDim = data.mapDimension(baseAxisDim);
  33954. var baseDataOffset = valueAxisDim === 'x' || valueAxisDim === 'radius' ? 1 : 0;
  33955. var dims = map(coordSys.dimensions, function (coordDim) {
  33956. return data.mapDimension(coordDim);
  33957. });
  33958. var stacked;
  33959. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  33960. if (stacked |= isDimensionStacked(data, dims[0]
  33961. /*, dims[1]*/
  33962. )) {
  33963. // jshint ignore:line
  33964. dims[0] = stackResultDim;
  33965. }
  33966. if (stacked |= isDimensionStacked(data, dims[1]
  33967. /*, dims[0]*/
  33968. )) {
  33969. // jshint ignore:line
  33970. dims[1] = stackResultDim;
  33971. }
  33972. return {
  33973. dataDimsForPoint: dims,
  33974. valueStart: valueStart,
  33975. valueAxisDim: valueAxisDim,
  33976. baseAxisDim: baseAxisDim,
  33977. stacked: !!stacked,
  33978. valueDim: valueDim,
  33979. baseDim: baseDim,
  33980. baseDataOffset: baseDataOffset,
  33981. stackedOverDimension: data.getCalculationInfo('stackedOverDimension')
  33982. };
  33983. }
  33984. function getValueStart(valueAxis, valueOrigin) {
  33985. var valueStart = 0;
  33986. var extent = valueAxis.scale.getExtent();
  33987. if (valueOrigin === 'start') {
  33988. valueStart = extent[0];
  33989. } else if (valueOrigin === 'end') {
  33990. valueStart = extent[1];
  33991. } // auto
  33992. else {
  33993. // Both positive
  33994. if (extent[0] > 0) {
  33995. valueStart = extent[0];
  33996. } // Both negative
  33997. else if (extent[1] < 0) {
  33998. valueStart = extent[1];
  33999. } // If is one positive, and one negative, onZero shall be true
  34000. }
  34001. return valueStart;
  34002. }
  34003. function getStackedOnPoint(dataCoordInfo, coordSys, data, idx) {
  34004. var value = NaN;
  34005. if (dataCoordInfo.stacked) {
  34006. value = data.get(data.getCalculationInfo('stackedOverDimension'), idx);
  34007. }
  34008. if (isNaN(value)) {
  34009. value = dataCoordInfo.valueStart;
  34010. }
  34011. var baseDataOffset = dataCoordInfo.baseDataOffset;
  34012. var stackedData = [];
  34013. stackedData[baseDataOffset] = data.get(dataCoordInfo.baseDim, idx);
  34014. stackedData[1 - baseDataOffset] = value;
  34015. return coordSys.dataToPoint(stackedData);
  34016. }
  34017. /*
  34018. * Licensed to the Apache Software Foundation (ASF) under one
  34019. * or more contributor license agreements. See the NOTICE file
  34020. * distributed with this work for additional information
  34021. * regarding copyright ownership. The ASF licenses this file
  34022. * to you under the Apache License, Version 2.0 (the
  34023. * "License"); you may not use this file except in compliance
  34024. * with the License. You may obtain a copy of the License at
  34025. *
  34026. * http://www.apache.org/licenses/LICENSE-2.0
  34027. *
  34028. * Unless required by applicable law or agreed to in writing,
  34029. * software distributed under the License is distributed on an
  34030. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34031. * KIND, either express or implied. See the License for the
  34032. * specific language governing permissions and limitations
  34033. * under the License.
  34034. */
  34035. // 'zrender/src/core/arrayDiff' has been used before, but it did
  34036. // not do well in performance when roam with fixed dataZoom window.
  34037. // function convertToIntId(newIdList, oldIdList) {
  34038. // // Generate int id instead of string id.
  34039. // // Compare string maybe slow in score function of arrDiff
  34040. // // Assume id in idList are all unique
  34041. // var idIndicesMap = {};
  34042. // var idx = 0;
  34043. // for (var i = 0; i < newIdList.length; i++) {
  34044. // idIndicesMap[newIdList[i]] = idx;
  34045. // newIdList[i] = idx++;
  34046. // }
  34047. // for (var i = 0; i < oldIdList.length; i++) {
  34048. // var oldId = oldIdList[i];
  34049. // // Same with newIdList
  34050. // if (idIndicesMap[oldId]) {
  34051. // oldIdList[i] = idIndicesMap[oldId];
  34052. // }
  34053. // else {
  34054. // oldIdList[i] = idx++;
  34055. // }
  34056. // }
  34057. // }
  34058. function diffData(oldData, newData) {
  34059. var diffResult = [];
  34060. newData.diff(oldData).add(function (idx) {
  34061. diffResult.push({
  34062. cmd: '+',
  34063. idx: idx
  34064. });
  34065. }).update(function (newIdx, oldIdx) {
  34066. diffResult.push({
  34067. cmd: '=',
  34068. idx: oldIdx,
  34069. idx1: newIdx
  34070. });
  34071. }).remove(function (idx) {
  34072. diffResult.push({
  34073. cmd: '-',
  34074. idx: idx
  34075. });
  34076. }).execute();
  34077. return diffResult;
  34078. }
  34079. var lineAnimationDiff = function (oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys, oldValueOrigin, newValueOrigin) {
  34080. var diff = diffData(oldData, newData); // var newIdList = newData.mapArray(newData.getId);
  34081. // var oldIdList = oldData.mapArray(oldData.getId);
  34082. // convertToIntId(newIdList, oldIdList);
  34083. // // FIXME One data ?
  34084. // diff = arrayDiff(oldIdList, newIdList);
  34085. var currPoints = [];
  34086. var nextPoints = []; // Points for stacking base line
  34087. var currStackedPoints = [];
  34088. var nextStackedPoints = [];
  34089. var status = [];
  34090. var sortedIndices = [];
  34091. var rawIndices = [];
  34092. var newDataOldCoordInfo = prepareDataCoordInfo(oldCoordSys, newData, oldValueOrigin);
  34093. var oldDataNewCoordInfo = prepareDataCoordInfo(newCoordSys, oldData, newValueOrigin);
  34094. for (var i = 0; i < diff.length; i++) {
  34095. var diffItem = diff[i];
  34096. var pointAdded = true; // FIXME, animation is not so perfect when dataZoom window moves fast
  34097. // Which is in case remvoing or add more than one data in the tail or head
  34098. switch (diffItem.cmd) {
  34099. case '=':
  34100. var currentPt = oldData.getItemLayout(diffItem.idx);
  34101. var nextPt = newData.getItemLayout(diffItem.idx1); // If previous data is NaN, use next point directly
  34102. if (isNaN(currentPt[0]) || isNaN(currentPt[1])) {
  34103. currentPt = nextPt.slice();
  34104. }
  34105. currPoints.push(currentPt);
  34106. nextPoints.push(nextPt);
  34107. currStackedPoints.push(oldStackedOnPoints[diffItem.idx]);
  34108. nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]);
  34109. rawIndices.push(newData.getRawIndex(diffItem.idx1));
  34110. break;
  34111. case '+':
  34112. var idx = diffItem.idx;
  34113. currPoints.push(oldCoordSys.dataToPoint([newData.get(newDataOldCoordInfo.dataDimsForPoint[0], idx), newData.get(newDataOldCoordInfo.dataDimsForPoint[1], idx)]));
  34114. nextPoints.push(newData.getItemLayout(idx).slice());
  34115. currStackedPoints.push(getStackedOnPoint(newDataOldCoordInfo, oldCoordSys, newData, idx));
  34116. nextStackedPoints.push(newStackedOnPoints[idx]);
  34117. rawIndices.push(newData.getRawIndex(idx));
  34118. break;
  34119. case '-':
  34120. var idx = diffItem.idx;
  34121. var rawIndex = oldData.getRawIndex(idx); // Data is replaced. In the case of dynamic data queue
  34122. // FIXME FIXME FIXME
  34123. if (rawIndex !== idx) {
  34124. currPoints.push(oldData.getItemLayout(idx));
  34125. nextPoints.push(newCoordSys.dataToPoint([oldData.get(oldDataNewCoordInfo.dataDimsForPoint[0], idx), oldData.get(oldDataNewCoordInfo.dataDimsForPoint[1], idx)]));
  34126. currStackedPoints.push(oldStackedOnPoints[idx]);
  34127. nextStackedPoints.push(getStackedOnPoint(oldDataNewCoordInfo, newCoordSys, oldData, idx));
  34128. rawIndices.push(rawIndex);
  34129. } else {
  34130. pointAdded = false;
  34131. }
  34132. } // Original indices
  34133. if (pointAdded) {
  34134. status.push(diffItem);
  34135. sortedIndices.push(sortedIndices.length);
  34136. }
  34137. } // Diff result may be crossed if all items are changed
  34138. // Sort by data index
  34139. sortedIndices.sort(function (a, b) {
  34140. return rawIndices[a] - rawIndices[b];
  34141. });
  34142. var sortedCurrPoints = [];
  34143. var sortedNextPoints = [];
  34144. var sortedCurrStackedPoints = [];
  34145. var sortedNextStackedPoints = [];
  34146. var sortedStatus = [];
  34147. for (var i = 0; i < sortedIndices.length; i++) {
  34148. var idx = sortedIndices[i];
  34149. sortedCurrPoints[i] = currPoints[idx];
  34150. sortedNextPoints[i] = nextPoints[idx];
  34151. sortedCurrStackedPoints[i] = currStackedPoints[idx];
  34152. sortedNextStackedPoints[i] = nextStackedPoints[idx];
  34153. sortedStatus[i] = status[idx];
  34154. }
  34155. return {
  34156. current: sortedCurrPoints,
  34157. next: sortedNextPoints,
  34158. stackedOnCurrent: sortedCurrStackedPoints,
  34159. stackedOnNext: sortedNextStackedPoints,
  34160. status: sortedStatus
  34161. };
  34162. };
  34163. /*
  34164. * Licensed to the Apache Software Foundation (ASF) under one
  34165. * or more contributor license agreements. See the NOTICE file
  34166. * distributed with this work for additional information
  34167. * regarding copyright ownership. The ASF licenses this file
  34168. * to you under the Apache License, Version 2.0 (the
  34169. * "License"); you may not use this file except in compliance
  34170. * with the License. You may obtain a copy of the License at
  34171. *
  34172. * http://www.apache.org/licenses/LICENSE-2.0
  34173. *
  34174. * Unless required by applicable law or agreed to in writing,
  34175. * software distributed under the License is distributed on an
  34176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34177. * KIND, either express or implied. See the License for the
  34178. * specific language governing permissions and limitations
  34179. * under the License.
  34180. */
  34181. // Poly path support NaN point
  34182. var vec2Min = min;
  34183. var vec2Max = max;
  34184. var scaleAndAdd$1 = scaleAndAdd;
  34185. var v2Copy = copy; // Temporary variable
  34186. var v = [];
  34187. var cp0 = [];
  34188. var cp1 = [];
  34189. function isPointNull(p) {
  34190. return isNaN(p[0]) || isNaN(p[1]);
  34191. }
  34192. function drawSegment(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls) {
  34193. // if (smoothMonotone == null) {
  34194. // if (isMono(points, 'x')) {
  34195. // return drawMono(ctx, points, start, segLen, allLen,
  34196. // dir, smoothMin, smoothMax, smooth, 'x', connectNulls);
  34197. // }
  34198. // else if (isMono(points, 'y')) {
  34199. // return drawMono(ctx, points, start, segLen, allLen,
  34200. // dir, smoothMin, smoothMax, smooth, 'y', connectNulls);
  34201. // }
  34202. // else {
  34203. // return drawNonMono.apply(this, arguments);
  34204. // }
  34205. // }
  34206. // else if (smoothMonotone !== 'none' && isMono(points, smoothMonotone)) {
  34207. // return drawMono.apply(this, arguments);
  34208. // }
  34209. // else {
  34210. // return drawNonMono.apply(this, arguments);
  34211. // }
  34212. if (smoothMonotone === 'none' || !smoothMonotone) {
  34213. return drawNonMono.apply(this, arguments);
  34214. } else {
  34215. return drawMono.apply(this, arguments);
  34216. }
  34217. }
  34218. /**
  34219. * Check if points is in monotone.
  34220. *
  34221. * @param {number[][]} points Array of points which is in [x, y] form
  34222. * @param {string} smoothMonotone 'x', 'y', or 'none', stating for which
  34223. * dimension that is checking.
  34224. * If is 'none', `drawNonMono` should be
  34225. * called.
  34226. * If is undefined, either being monotone
  34227. * in 'x' or 'y' will call `drawMono`.
  34228. */
  34229. // function isMono(points, smoothMonotone) {
  34230. // if (points.length <= 1) {
  34231. // return true;
  34232. // }
  34233. // var dim = smoothMonotone === 'x' ? 0 : 1;
  34234. // var last = points[0][dim];
  34235. // var lastDiff = 0;
  34236. // for (var i = 1; i < points.length; ++i) {
  34237. // var diff = points[i][dim] - last;
  34238. // if (!isNaN(diff) && !isNaN(lastDiff)
  34239. // && diff !== 0 && lastDiff !== 0
  34240. // && ((diff >= 0) !== (lastDiff >= 0))
  34241. // ) {
  34242. // return false;
  34243. // }
  34244. // if (!isNaN(diff) && diff !== 0) {
  34245. // lastDiff = diff;
  34246. // last = points[i][dim];
  34247. // }
  34248. // }
  34249. // return true;
  34250. // }
  34251. /**
  34252. * Draw smoothed line in monotone, in which only vertical or horizontal bezier
  34253. * control points will be used. This should be used when points are monotone
  34254. * either in x or y dimension.
  34255. */
  34256. function drawMono(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls) {
  34257. var prevIdx = 0;
  34258. var idx = start;
  34259. for (var k = 0; k < segLen; k++) {
  34260. var p = points[idx];
  34261. if (idx >= allLen || idx < 0) {
  34262. break;
  34263. }
  34264. if (isPointNull(p)) {
  34265. if (connectNulls) {
  34266. idx += dir;
  34267. continue;
  34268. }
  34269. break;
  34270. }
  34271. if (idx === start) {
  34272. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  34273. } else {
  34274. if (smooth > 0) {
  34275. var prevP = points[prevIdx];
  34276. var dim = smoothMonotone === 'y' ? 1 : 0; // Length of control point to p, either in x or y, but not both
  34277. var ctrlLen = (p[dim] - prevP[dim]) * smooth;
  34278. v2Copy(cp0, prevP);
  34279. cp0[dim] = prevP[dim] + ctrlLen;
  34280. v2Copy(cp1, p);
  34281. cp1[dim] = p[dim] - ctrlLen;
  34282. ctx.bezierCurveTo(cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1]);
  34283. } else {
  34284. ctx.lineTo(p[0], p[1]);
  34285. }
  34286. }
  34287. prevIdx = idx;
  34288. idx += dir;
  34289. }
  34290. return k;
  34291. }
  34292. /**
  34293. * Draw smoothed line in non-monotone, in may cause undesired curve in extreme
  34294. * situations. This should be used when points are non-monotone neither in x or
  34295. * y dimension.
  34296. */
  34297. function drawNonMono(ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls) {
  34298. var prevIdx = 0;
  34299. var idx = start;
  34300. for (var k = 0; k < segLen; k++) {
  34301. var p = points[idx];
  34302. if (idx >= allLen || idx < 0) {
  34303. break;
  34304. }
  34305. if (isPointNull(p)) {
  34306. if (connectNulls) {
  34307. idx += dir;
  34308. continue;
  34309. }
  34310. break;
  34311. }
  34312. if (idx === start) {
  34313. ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]);
  34314. v2Copy(cp0, p);
  34315. } else {
  34316. if (smooth > 0) {
  34317. var nextIdx = idx + dir;
  34318. var nextP = points[nextIdx];
  34319. if (connectNulls) {
  34320. // Find next point not null
  34321. while (nextP && isPointNull(points[nextIdx])) {
  34322. nextIdx += dir;
  34323. nextP = points[nextIdx];
  34324. }
  34325. }
  34326. var ratioNextSeg = 0.5;
  34327. var prevP = points[prevIdx];
  34328. var nextP = points[nextIdx]; // Last point
  34329. if (!nextP || isPointNull(nextP)) {
  34330. v2Copy(cp1, p);
  34331. } else {
  34332. // If next data is null in not connect case
  34333. if (isPointNull(nextP) && !connectNulls) {
  34334. nextP = p;
  34335. }
  34336. sub(v, nextP, prevP);
  34337. var lenPrevSeg;
  34338. var lenNextSeg;
  34339. if (smoothMonotone === 'x' || smoothMonotone === 'y') {
  34340. var dim = smoothMonotone === 'x' ? 0 : 1;
  34341. lenPrevSeg = Math.abs(p[dim] - prevP[dim]);
  34342. lenNextSeg = Math.abs(p[dim] - nextP[dim]);
  34343. } else {
  34344. lenPrevSeg = dist(p, prevP);
  34345. lenNextSeg = dist(p, nextP);
  34346. } // Use ratio of seg length
  34347. ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg);
  34348. scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg));
  34349. } // Smooth constraint
  34350. vec2Min(cp0, cp0, smoothMax);
  34351. vec2Max(cp0, cp0, smoothMin);
  34352. vec2Min(cp1, cp1, smoothMax);
  34353. vec2Max(cp1, cp1, smoothMin);
  34354. ctx.bezierCurveTo(cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1]); // cp0 of next segment
  34355. scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg);
  34356. } else {
  34357. ctx.lineTo(p[0], p[1]);
  34358. }
  34359. }
  34360. prevIdx = idx;
  34361. idx += dir;
  34362. }
  34363. return k;
  34364. }
  34365. function getBoundingBox(points, smoothConstraint) {
  34366. var ptMin = [Infinity, Infinity];
  34367. var ptMax = [-Infinity, -Infinity];
  34368. if (smoothConstraint) {
  34369. for (var i = 0; i < points.length; i++) {
  34370. var pt = points[i];
  34371. if (pt[0] < ptMin[0]) {
  34372. ptMin[0] = pt[0];
  34373. }
  34374. if (pt[1] < ptMin[1]) {
  34375. ptMin[1] = pt[1];
  34376. }
  34377. if (pt[0] > ptMax[0]) {
  34378. ptMax[0] = pt[0];
  34379. }
  34380. if (pt[1] > ptMax[1]) {
  34381. ptMax[1] = pt[1];
  34382. }
  34383. }
  34384. }
  34385. return {
  34386. min: smoothConstraint ? ptMin : ptMax,
  34387. max: smoothConstraint ? ptMax : ptMin
  34388. };
  34389. }
  34390. var Polyline$1 = Path.extend({
  34391. type: 'ec-polyline',
  34392. shape: {
  34393. points: [],
  34394. smooth: 0,
  34395. smoothConstraint: true,
  34396. smoothMonotone: null,
  34397. connectNulls: false
  34398. },
  34399. style: {
  34400. fill: null,
  34401. stroke: '#000'
  34402. },
  34403. brush: fixClipWithShadow(Path.prototype.brush),
  34404. buildPath: function (ctx, shape) {
  34405. var points = shape.points;
  34406. var i = 0;
  34407. var len$$1 = points.length;
  34408. var result = getBoundingBox(points, shape.smoothConstraint);
  34409. if (shape.connectNulls) {
  34410. // Must remove first and last null values avoid draw error in polygon
  34411. for (; len$$1 > 0; len$$1--) {
  34412. if (!isPointNull(points[len$$1 - 1])) {
  34413. break;
  34414. }
  34415. }
  34416. for (; i < len$$1; i++) {
  34417. if (!isPointNull(points[i])) {
  34418. break;
  34419. }
  34420. }
  34421. }
  34422. while (i < len$$1) {
  34423. i += drawSegment(ctx, points, i, len$$1, len$$1, 1, result.min, result.max, shape.smooth, shape.smoothMonotone, shape.connectNulls) + 1;
  34424. }
  34425. }
  34426. });
  34427. var Polygon$1 = Path.extend({
  34428. type: 'ec-polygon',
  34429. shape: {
  34430. points: [],
  34431. // Offset between stacked base points and points
  34432. stackedOnPoints: [],
  34433. smooth: 0,
  34434. stackedOnSmooth: 0,
  34435. smoothConstraint: true,
  34436. smoothMonotone: null,
  34437. connectNulls: false
  34438. },
  34439. brush: fixClipWithShadow(Path.prototype.brush),
  34440. buildPath: function (ctx, shape) {
  34441. var points = shape.points;
  34442. var stackedOnPoints = shape.stackedOnPoints;
  34443. var i = 0;
  34444. var len$$1 = points.length;
  34445. var smoothMonotone = shape.smoothMonotone;
  34446. var bbox = getBoundingBox(points, shape.smoothConstraint);
  34447. var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint);
  34448. if (shape.connectNulls) {
  34449. // Must remove first and last null values avoid draw error in polygon
  34450. for (; len$$1 > 0; len$$1--) {
  34451. if (!isPointNull(points[len$$1 - 1])) {
  34452. break;
  34453. }
  34454. }
  34455. for (; i < len$$1; i++) {
  34456. if (!isPointNull(points[i])) {
  34457. break;
  34458. }
  34459. }
  34460. }
  34461. while (i < len$$1) {
  34462. var k = drawSegment(ctx, points, i, len$$1, len$$1, 1, bbox.min, bbox.max, shape.smooth, smoothMonotone, shape.connectNulls);
  34463. drawSegment(ctx, stackedOnPoints, i + k - 1, k, len$$1, -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls);
  34464. i += k + 1;
  34465. ctx.closePath();
  34466. }
  34467. }
  34468. });
  34469. /*
  34470. * Licensed to the Apache Software Foundation (ASF) under one
  34471. * or more contributor license agreements. See the NOTICE file
  34472. * distributed with this work for additional information
  34473. * regarding copyright ownership. The ASF licenses this file
  34474. * to you under the Apache License, Version 2.0 (the
  34475. * "License"); you may not use this file except in compliance
  34476. * with the License. You may obtain a copy of the License at
  34477. *
  34478. * http://www.apache.org/licenses/LICENSE-2.0
  34479. *
  34480. * Unless required by applicable law or agreed to in writing,
  34481. * software distributed under the License is distributed on an
  34482. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  34483. * KIND, either express or implied. See the License for the
  34484. * specific language governing permissions and limitations
  34485. * under the License.
  34486. */
  34487. // FIXME step not support polar
  34488. function isPointsSame(points1, points2) {
  34489. if (points1.length !== points2.length) {
  34490. return;
  34491. }
  34492. for (var i = 0; i < points1.length; i++) {
  34493. var p1 = points1[i];
  34494. var p2 = points2[i];
  34495. if (p1[0] !== p2[0] || p1[1] !== p2[1]) {
  34496. return;
  34497. }
  34498. }
  34499. return true;
  34500. }
  34501. function getBoundingDiff(points1, points2) {
  34502. var min1 = [];
  34503. var max1 = [];
  34504. var min2 = [];
  34505. var max2 = [];
  34506. fromPoints(points1, min1, max1);
  34507. fromPoints(points2, min2, max2); // Get a max value from each corner of two boundings.
  34508. return Math.max(Math.abs(min1[0] - min2[0]), Math.abs(min1[1] - min2[1]), Math.abs(max1[0] - max2[0]), Math.abs(max1[1] - max2[1]));
  34509. }
  34510. function getSmooth(smooth) {
  34511. return typeof smooth === 'number' ? smooth : smooth ? 0.5 : 0;
  34512. }
  34513. /**
  34514. * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys
  34515. * @param {module:echarts/data/List} data
  34516. * @param {Object} dataCoordInfo
  34517. * @param {Array.<Array.<number>>} points
  34518. */
  34519. function getStackedOnPoints(coordSys, data, dataCoordInfo) {
  34520. if (!dataCoordInfo.valueDim) {
  34521. return [];
  34522. }
  34523. var points = [];
  34524. for (var idx = 0, len = data.count(); idx < len; idx++) {
  34525. points.push(getStackedOnPoint(dataCoordInfo, coordSys, data, idx));
  34526. }
  34527. return points;
  34528. }
  34529. function turnPointsIntoStep(points, coordSys, stepTurnAt) {
  34530. var baseAxis = coordSys.getBaseAxis();
  34531. var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1;
  34532. var stepPoints = [];
  34533. for (var i = 0; i < points.length - 1; i++) {
  34534. var nextPt = points[i + 1];
  34535. var pt = points[i];
  34536. stepPoints.push(pt);
  34537. var stepPt = [];
  34538. switch (stepTurnAt) {
  34539. case 'end':
  34540. stepPt[baseIndex] = nextPt[baseIndex];
  34541. stepPt[1 - baseIndex] = pt[1 - baseIndex]; // default is start
  34542. stepPoints.push(stepPt);
  34543. break;
  34544. case 'middle':
  34545. // default is start
  34546. var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2;
  34547. var stepPt2 = [];
  34548. stepPt[baseIndex] = stepPt2[baseIndex] = middle;
  34549. stepPt[1 - baseIndex] = pt[1 - baseIndex];
  34550. stepPt2[1 - baseIndex] = nextPt[1 - baseIndex];
  34551. stepPoints.push(stepPt);
  34552. stepPoints.push(stepPt2);
  34553. break;
  34554. default:
  34555. stepPt[baseIndex] = pt[baseIndex];
  34556. stepPt[1 - baseIndex] = nextPt[1 - baseIndex]; // default is start
  34557. stepPoints.push(stepPt);
  34558. }
  34559. } // Last points
  34560. points[i] && stepPoints.push(points[i]);
  34561. return stepPoints;
  34562. }
  34563. function getVisualGradient(data, coordSys) {
  34564. var visualMetaList = data.getVisual('visualMeta');
  34565. if (!visualMetaList || !visualMetaList.length || !data.count()) {
  34566. // When data.count() is 0, gradient range can not be calculated.
  34567. return;
  34568. }
  34569. if (coordSys.type !== 'cartesian2d') {
  34570. return;
  34571. }
  34572. var coordDim;
  34573. var visualMeta;
  34574. for (var i = visualMetaList.length - 1; i >= 0; i--) {
  34575. var dimIndex = visualMetaList[i].dimension;
  34576. var dimName = data.dimensions[dimIndex];
  34577. var dimInfo = data.getDimensionInfo(dimName);
  34578. coordDim = dimInfo && dimInfo.coordDim; // Can only be x or y
  34579. if (coordDim === 'x' || coordDim === 'y') {
  34580. visualMeta = visualMetaList[i];
  34581. break;
  34582. }
  34583. }
  34584. if (!visualMeta) {
  34585. return;
  34586. } // If the area to be rendered is bigger than area defined by LinearGradient,
  34587. // the canvas spec prescribes that the color of the first stop and the last
  34588. // stop should be used. But if two stops are added at offset 0, in effect
  34589. // browsers use the color of the second stop to render area outside
  34590. // LinearGradient. So we can only infinitesimally extend area defined in
  34591. // LinearGradient to render `outerColors`.
  34592. var axis = coordSys.getAxis(coordDim); // dataToCoor mapping may not be linear, but must be monotonic.
  34593. var colorStops = map(visualMeta.stops, function (stop) {
  34594. return {
  34595. coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)),
  34596. color: stop.color
  34597. };
  34598. });
  34599. var stopLen = colorStops.length;
  34600. var outerColors = visualMeta.outerColors.slice();
  34601. if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) {
  34602. colorStops.reverse();
  34603. outerColors.reverse();
  34604. }
  34605. var tinyExtent = 10; // Arbitrary value: 10px
  34606. var minCoord = colorStops[0].coord - tinyExtent;
  34607. var maxCoord = colorStops[stopLen - 1].coord + tinyExtent;
  34608. var coordSpan = maxCoord - minCoord;
  34609. if (coordSpan < 1e-3) {
  34610. return 'transparent';
  34611. }
  34612. each$1(colorStops, function (stop) {
  34613. stop.offset = (stop.coord - minCoord) / coordSpan;
  34614. });
  34615. colorStops.push({
  34616. offset: stopLen ? colorStops[stopLen - 1].offset : 0.5,
  34617. color: outerColors[1] || 'transparent'
  34618. });
  34619. colorStops.unshift({
  34620. // notice colorStops.length have been changed.
  34621. offset: stopLen ? colorStops[0].offset : 0.5,
  34622. color: outerColors[0] || 'transparent'
  34623. }); // zrUtil.each(colorStops, function (colorStop) {
  34624. // // Make sure each offset has rounded px to avoid not sharp edge
  34625. // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start);
  34626. // });
  34627. var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true);
  34628. gradient[coordDim] = minCoord;
  34629. gradient[coordDim + '2'] = maxCoord;
  34630. return gradient;
  34631. }
  34632. function getIsIgnoreFunc(seriesModel, data, coordSys) {
  34633. var showAllSymbol = seriesModel.get('showAllSymbol');
  34634. var isAuto = showAllSymbol === 'auto';
  34635. if (showAllSymbol && !isAuto) {
  34636. return;
  34637. }
  34638. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  34639. if (!categoryAxis) {
  34640. return;
  34641. } // Note that category label interval strategy might bring some weird effect
  34642. // in some scenario: users may wonder why some of the symbols are not
  34643. // displayed. So we show all symbols as possible as we can.
  34644. if (isAuto // Simplify the logic, do not determine label overlap here.
  34645. && canShowAllSymbolForCategory(categoryAxis, data)) {
  34646. return;
  34647. } // Otherwise follow the label interval strategy on category axis.
  34648. var categoryDataDim = data.mapDimension(categoryAxis.dim);
  34649. var labelMap = {};
  34650. each$1(categoryAxis.getViewLabels(), function (labelItem) {
  34651. labelMap[labelItem.tickValue] = 1;
  34652. });
  34653. return function (dataIndex) {
  34654. return !labelMap.hasOwnProperty(data.get(categoryDataDim, dataIndex));
  34655. };
  34656. }
  34657. function canShowAllSymbolForCategory(categoryAxis, data) {
  34658. // In mose cases, line is monotonous on category axis, and the label size
  34659. // is close with each other. So we check the symbol size and some of the
  34660. // label size alone with the category axis to estimate whether all symbol
  34661. // can be shown without overlap.
  34662. var axisExtent = categoryAxis.getExtent();
  34663. var availSize = Math.abs(axisExtent[1] - axisExtent[0]) / categoryAxis.scale.count();
  34664. isNaN(availSize) && (availSize = 0); // 0/0 is NaN.
  34665. // Sampling some points, max 5.
  34666. var dataLen = data.count();
  34667. var step = Math.max(1, Math.round(dataLen / 5));
  34668. for (var dataIndex = 0; dataIndex < dataLen; dataIndex += step) {
  34669. if (SymbolClz$1.getSymbolSize(data, dataIndex // Only for cartesian, where `isHorizontal` exists.
  34670. )[categoryAxis.isHorizontal() ? 1 : 0] // Empirical number
  34671. * 1.5 > availSize) {
  34672. return false;
  34673. }
  34674. }
  34675. return true;
  34676. }
  34677. function createLineClipPath(coordSys, hasAnimation, seriesModel) {
  34678. if (coordSys.type === 'cartesian2d') {
  34679. var isHorizontal = coordSys.getBaseAxis().isHorizontal();
  34680. var clipPath = createGridClipPath(coordSys, hasAnimation, seriesModel); // Expand clip shape to avoid clipping when line value exceeds axis
  34681. if (!seriesModel.get('clip', true)) {
  34682. var rectShape = clipPath.shape;
  34683. var expandSize = Math.max(rectShape.width, rectShape.height);
  34684. if (isHorizontal) {
  34685. rectShape.y -= expandSize;
  34686. rectShape.height += expandSize * 2;
  34687. } else {
  34688. rectShape.x -= expandSize;
  34689. rectShape.width += expandSize * 2;
  34690. }
  34691. }
  34692. return clipPath;
  34693. } else {
  34694. return createPolarClipPath(coordSys, hasAnimation, seriesModel);
  34695. }
  34696. }
  34697. Chart.extend({
  34698. type: 'line',
  34699. init: function () {
  34700. var lineGroup = new Group();
  34701. var symbolDraw = new SymbolDraw();
  34702. this.group.add(symbolDraw.group);
  34703. this._symbolDraw = symbolDraw;
  34704. this._lineGroup = lineGroup;
  34705. },
  34706. render: function (seriesModel, ecModel, api) {
  34707. var coordSys = seriesModel.coordinateSystem;
  34708. var group = this.group;
  34709. var data = seriesModel.getData();
  34710. var lineStyleModel = seriesModel.getModel('lineStyle');
  34711. var areaStyleModel = seriesModel.getModel('areaStyle');
  34712. var points = data.mapArray(data.getItemLayout);
  34713. var isCoordSysPolar = coordSys.type === 'polar';
  34714. var prevCoordSys = this._coordSys;
  34715. var symbolDraw = this._symbolDraw;
  34716. var polyline = this._polyline;
  34717. var polygon = this._polygon;
  34718. var lineGroup = this._lineGroup;
  34719. var hasAnimation = seriesModel.get('animation');
  34720. var isAreaChart = !areaStyleModel.isEmpty();
  34721. var valueOrigin = areaStyleModel.get('origin');
  34722. var dataCoordInfo = prepareDataCoordInfo(coordSys, data, valueOrigin);
  34723. var stackedOnPoints = getStackedOnPoints(coordSys, data, dataCoordInfo);
  34724. var showSymbol = seriesModel.get('showSymbol');
  34725. var isIgnoreFunc = showSymbol && !isCoordSysPolar && getIsIgnoreFunc(seriesModel, data, coordSys); // Remove temporary symbols
  34726. var oldData = this._data;
  34727. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  34728. if (el.__temp) {
  34729. group.remove(el);
  34730. oldData.setItemGraphicEl(idx, null);
  34731. }
  34732. }); // Remove previous created symbols if showSymbol changed to false
  34733. if (!showSymbol) {
  34734. symbolDraw.remove();
  34735. }
  34736. group.add(lineGroup); // FIXME step not support polar
  34737. var step = !isCoordSysPolar && seriesModel.get('step');
  34738. var clipShapeForSymbol;
  34739. if (coordSys && coordSys.getArea && seriesModel.get('clip', true)) {
  34740. clipShapeForSymbol = coordSys.getArea(); // Avoid float number rounding error for symbol on the edge of axis extent.
  34741. // See #7913 and `test/dataZoom-clip.html`.
  34742. if (clipShapeForSymbol.width != null) {
  34743. clipShapeForSymbol.x -= 0.1;
  34744. clipShapeForSymbol.y -= 0.1;
  34745. clipShapeForSymbol.width += 0.2;
  34746. clipShapeForSymbol.height += 0.2;
  34747. } else if (clipShapeForSymbol.r0) {
  34748. clipShapeForSymbol.r0 -= 0.5;
  34749. clipShapeForSymbol.r1 += 0.5;
  34750. }
  34751. }
  34752. this._clipShapeForSymbol = clipShapeForSymbol; // Initialization animation or coordinate system changed
  34753. if (!(polyline && prevCoordSys.type === coordSys.type && step === this._step)) {
  34754. showSymbol && symbolDraw.updateData(data, {
  34755. isIgnore: isIgnoreFunc,
  34756. clipShape: clipShapeForSymbol
  34757. });
  34758. if (step) {
  34759. // TODO If stacked series is not step
  34760. points = turnPointsIntoStep(points, coordSys, step);
  34761. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34762. }
  34763. polyline = this._newPolyline(points, coordSys, hasAnimation);
  34764. if (isAreaChart) {
  34765. polygon = this._newPolygon(points, stackedOnPoints, coordSys, hasAnimation);
  34766. }
  34767. lineGroup.setClipPath(createLineClipPath(coordSys, true, seriesModel));
  34768. } else {
  34769. if (isAreaChart && !polygon) {
  34770. // If areaStyle is added
  34771. polygon = this._newPolygon(points, stackedOnPoints, coordSys, hasAnimation);
  34772. } else if (polygon && !isAreaChart) {
  34773. // If areaStyle is removed
  34774. lineGroup.remove(polygon);
  34775. polygon = this._polygon = null;
  34776. } // Update clipPath
  34777. lineGroup.setClipPath(createLineClipPath(coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend
  34778. // because points are not changed
  34779. showSymbol && symbolDraw.updateData(data, {
  34780. isIgnore: isIgnoreFunc,
  34781. clipShape: clipShapeForSymbol
  34782. }); // Stop symbol animation and sync with line points
  34783. // FIXME performance?
  34784. data.eachItemGraphicEl(function (el) {
  34785. el.stopAnimation(true);
  34786. }); // In the case data zoom triggerred refreshing frequently
  34787. // Data may not change if line has a category axis. So it should animate nothing
  34788. if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points)) {
  34789. if (hasAnimation) {
  34790. this._updateAnimation(data, stackedOnPoints, coordSys, api, step, valueOrigin);
  34791. } else {
  34792. // Not do it in update with animation
  34793. if (step) {
  34794. // TODO If stacked series is not step
  34795. points = turnPointsIntoStep(points, coordSys, step);
  34796. stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step);
  34797. }
  34798. polyline.setShape({
  34799. points: points
  34800. });
  34801. polygon && polygon.setShape({
  34802. points: points,
  34803. stackedOnPoints: stackedOnPoints
  34804. });
  34805. }
  34806. }
  34807. }
  34808. var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color');
  34809. polyline.useStyle(defaults( // Use color in lineStyle first
  34810. lineStyleModel.getLineStyle(), {
  34811. fill: 'none',
  34812. stroke: visualColor,
  34813. lineJoin: 'bevel'
  34814. }));
  34815. var smooth = seriesModel.get('smooth');
  34816. smooth = getSmooth(seriesModel.get('smooth'));
  34817. polyline.setShape({
  34818. smooth: smooth,
  34819. smoothMonotone: seriesModel.get('smoothMonotone'),
  34820. connectNulls: seriesModel.get('connectNulls')
  34821. });
  34822. if (polygon) {
  34823. var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  34824. var stackedOnSmooth = 0;
  34825. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  34826. fill: visualColor,
  34827. opacity: 0.7,
  34828. lineJoin: 'bevel'
  34829. }));
  34830. if (stackedOnSeries) {
  34831. stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth'));
  34832. }
  34833. polygon.setShape({
  34834. smooth: smooth,
  34835. stackedOnSmooth: stackedOnSmooth,
  34836. smoothMonotone: seriesModel.get('smoothMonotone'),
  34837. connectNulls: seriesModel.get('connectNulls')
  34838. });
  34839. }
  34840. this._data = data; // Save the coordinate system for transition animation when data changed
  34841. this._coordSys = coordSys;
  34842. this._stackedOnPoints = stackedOnPoints;
  34843. this._points = points;
  34844. this._step = step;
  34845. this._valueOrigin = valueOrigin;
  34846. },
  34847. dispose: function () {},
  34848. highlight: function (seriesModel, ecModel, api, payload) {
  34849. var data = seriesModel.getData();
  34850. var dataIndex = queryDataIndex(data, payload);
  34851. if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) {
  34852. var symbol = data.getItemGraphicEl(dataIndex);
  34853. if (!symbol) {
  34854. // Create a temporary symbol if it is not exists
  34855. var pt = data.getItemLayout(dataIndex);
  34856. if (!pt) {
  34857. // Null data
  34858. return;
  34859. } // fix #11360: should't draw symbol outside clipShapeForSymbol
  34860. if (this._clipShapeForSymbol && !this._clipShapeForSymbol.contain(pt[0], pt[1])) {
  34861. return;
  34862. }
  34863. symbol = new SymbolClz$1(data, dataIndex);
  34864. symbol.position = pt;
  34865. symbol.setZ(seriesModel.get('zlevel'), seriesModel.get('z'));
  34866. symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]);
  34867. symbol.__temp = true;
  34868. data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation
  34869. symbol.stopSymbolAnimation(true);
  34870. this.group.add(symbol);
  34871. }
  34872. symbol.highlight();
  34873. } else {
  34874. // Highlight whole series
  34875. Chart.prototype.highlight.call(this, seriesModel, ecModel, api, payload);
  34876. }
  34877. },
  34878. downplay: function (seriesModel, ecModel, api, payload) {
  34879. var data = seriesModel.getData();
  34880. var dataIndex = queryDataIndex(data, payload);
  34881. if (dataIndex != null && dataIndex >= 0) {
  34882. var symbol = data.getItemGraphicEl(dataIndex);
  34883. if (symbol) {
  34884. if (symbol.__temp) {
  34885. data.setItemGraphicEl(dataIndex, null);
  34886. this.group.remove(symbol);
  34887. } else {
  34888. symbol.downplay();
  34889. }
  34890. }
  34891. } else {
  34892. // FIXME
  34893. // can not downplay completely.
  34894. // Downplay whole series
  34895. Chart.prototype.downplay.call(this, seriesModel, ecModel, api, payload);
  34896. }
  34897. },
  34898. /**
  34899. * @param {module:zrender/container/Group} group
  34900. * @param {Array.<Array.<number>>} points
  34901. * @private
  34902. */
  34903. _newPolyline: function (points) {
  34904. var polyline = this._polyline; // Remove previous created polyline
  34905. if (polyline) {
  34906. this._lineGroup.remove(polyline);
  34907. }
  34908. polyline = new Polyline$1({
  34909. shape: {
  34910. points: points
  34911. },
  34912. silent: true,
  34913. z2: 10
  34914. });
  34915. this._lineGroup.add(polyline);
  34916. this._polyline = polyline;
  34917. return polyline;
  34918. },
  34919. /**
  34920. * @param {module:zrender/container/Group} group
  34921. * @param {Array.<Array.<number>>} stackedOnPoints
  34922. * @param {Array.<Array.<number>>} points
  34923. * @private
  34924. */
  34925. _newPolygon: function (points, stackedOnPoints) {
  34926. var polygon = this._polygon; // Remove previous created polygon
  34927. if (polygon) {
  34928. this._lineGroup.remove(polygon);
  34929. }
  34930. polygon = new Polygon$1({
  34931. shape: {
  34932. points: points,
  34933. stackedOnPoints: stackedOnPoints
  34934. },
  34935. silent: true
  34936. });
  34937. this._lineGroup.add(polygon);
  34938. this._polygon = polygon;
  34939. return polygon;
  34940. },
  34941. /**
  34942. * @private
  34943. */
  34944. // FIXME Two value axis
  34945. _updateAnimation: function (data, stackedOnPoints, coordSys, api, step, valueOrigin) {
  34946. var polyline = this._polyline;
  34947. var polygon = this._polygon;
  34948. var seriesModel = data.hostModel;
  34949. var diff = lineAnimationDiff(this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys, this._valueOrigin, valueOrigin);
  34950. var current = diff.current;
  34951. var stackedOnCurrent = diff.stackedOnCurrent;
  34952. var next = diff.next;
  34953. var stackedOnNext = diff.stackedOnNext;
  34954. if (step) {
  34955. // TODO If stacked series is not step
  34956. current = turnPointsIntoStep(diff.current, coordSys, step);
  34957. stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step);
  34958. next = turnPointsIntoStep(diff.next, coordSys, step);
  34959. stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step);
  34960. } // Don't apply animation if diff is large.
  34961. // For better result and avoid memory explosion problems like
  34962. // https://github.com/apache/incubator-echarts/issues/12229
  34963. if (getBoundingDiff(current, next) > 3000 || polygon && getBoundingDiff(stackedOnCurrent, stackedOnNext) > 3000) {
  34964. polyline.setShape({
  34965. points: next
  34966. });
  34967. if (polygon) {
  34968. polygon.setShape({
  34969. points: next,
  34970. stackedOnPoints: stackedOnNext
  34971. });
  34972. }
  34973. return;
  34974. } // `diff.current` is subset of `current` (which should be ensured by
  34975. // turnPointsIntoStep), so points in `__points` can be updated when
  34976. // points in `current` are update during animation.
  34977. polyline.shape.__points = diff.current;
  34978. polyline.shape.points = current;
  34979. updateProps(polyline, {
  34980. shape: {
  34981. points: next
  34982. }
  34983. }, seriesModel);
  34984. if (polygon) {
  34985. polygon.setShape({
  34986. points: current,
  34987. stackedOnPoints: stackedOnCurrent
  34988. });
  34989. updateProps(polygon, {
  34990. shape: {
  34991. points: next,
  34992. stackedOnPoints: stackedOnNext
  34993. }
  34994. }, seriesModel);
  34995. }
  34996. var updatedDataInfo = [];
  34997. var diffStatus = diff.status;
  34998. for (var i = 0; i < diffStatus.length; i++) {
  34999. var cmd = diffStatus[i].cmd;
  35000. if (cmd === '=') {
  35001. var el = data.getItemGraphicEl(diffStatus[i].idx1);
  35002. if (el) {
  35003. updatedDataInfo.push({
  35004. el: el,
  35005. ptIdx: i // Index of points
  35006. });
  35007. }
  35008. }
  35009. }
  35010. if (polyline.animators && polyline.animators.length) {
  35011. polyline.animators[0].during(function () {
  35012. for (var i = 0; i < updatedDataInfo.length; i++) {
  35013. var el = updatedDataInfo[i].el;
  35014. el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]);
  35015. }
  35016. });
  35017. }
  35018. },
  35019. remove: function (ecModel) {
  35020. var group = this.group;
  35021. var oldData = this._data;
  35022. this._lineGroup.removeAll();
  35023. this._symbolDraw.remove(true); // Remove temporary created elements when highlighting
  35024. oldData && oldData.eachItemGraphicEl(function (el, idx) {
  35025. if (el.__temp) {
  35026. group.remove(el);
  35027. oldData.setItemGraphicEl(idx, null);
  35028. }
  35029. });
  35030. this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._data = null;
  35031. }
  35032. });
  35033. /*
  35034. * Licensed to the Apache Software Foundation (ASF) under one
  35035. * or more contributor license agreements. See the NOTICE file
  35036. * distributed with this work for additional information
  35037. * regarding copyright ownership. The ASF licenses this file
  35038. * to you under the Apache License, Version 2.0 (the
  35039. * "License"); you may not use this file except in compliance
  35040. * with the License. You may obtain a copy of the License at
  35041. *
  35042. * http://www.apache.org/licenses/LICENSE-2.0
  35043. *
  35044. * Unless required by applicable law or agreed to in writing,
  35045. * software distributed under the License is distributed on an
  35046. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35047. * KIND, either express or implied. See the License for the
  35048. * specific language governing permissions and limitations
  35049. * under the License.
  35050. */
  35051. var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol) {
  35052. // Encoding visual for all series include which is filtered for legend drawing
  35053. return {
  35054. seriesType: seriesType,
  35055. // For legend.
  35056. performRawSeries: true,
  35057. reset: function (seriesModel, ecModel, api) {
  35058. var data = seriesModel.getData();
  35059. var symbolType = seriesModel.get('symbol');
  35060. var symbolSize = seriesModel.get('symbolSize');
  35061. var keepAspect = seriesModel.get('symbolKeepAspect');
  35062. var symbolRotate = seriesModel.get('symbolRotate');
  35063. var hasSymbolTypeCallback = isFunction$1(symbolType);
  35064. var hasSymbolSizeCallback = isFunction$1(symbolSize);
  35065. var hasSymbolRotateCallback = isFunction$1(symbolRotate);
  35066. var hasCallback = hasSymbolTypeCallback || hasSymbolSizeCallback || hasSymbolRotateCallback;
  35067. var seriesSymbol = !hasSymbolTypeCallback && symbolType ? symbolType : defaultSymbolType;
  35068. var seriesSymbolSize = !hasSymbolSizeCallback ? symbolSize : null;
  35069. data.setVisual({
  35070. legendSymbol: legendSymbol || seriesSymbol,
  35071. // If seting callback functions on `symbol` or `symbolSize`, for simplicity and avoiding
  35072. // to bring trouble, we do not pick a reuslt from one of its calling on data item here,
  35073. // but just use the default value. Callback on `symbol` or `symbolSize` is convenient in
  35074. // some cases but generally it is not recommanded.
  35075. symbol: seriesSymbol,
  35076. symbolSize: seriesSymbolSize,
  35077. symbolKeepAspect: keepAspect,
  35078. symbolRotate: symbolRotate
  35079. }); // Only visible series has each data be visual encoded
  35080. if (ecModel.isSeriesFiltered(seriesModel)) {
  35081. return;
  35082. }
  35083. function dataEach(data, idx) {
  35084. if (hasCallback) {
  35085. var rawValue = seriesModel.getRawValue(idx);
  35086. var params = seriesModel.getDataParams(idx);
  35087. hasSymbolTypeCallback && data.setItemVisual(idx, 'symbol', symbolType(rawValue, params));
  35088. hasSymbolSizeCallback && data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params));
  35089. hasSymbolRotateCallback && data.setItemVisual(idx, 'symbolRotate', symbolRotate(rawValue, params));
  35090. }
  35091. if (data.hasItemOption) {
  35092. var itemModel = data.getItemModel(idx);
  35093. var itemSymbolType = itemModel.getShallow('symbol', true);
  35094. var itemSymbolSize = itemModel.getShallow('symbolSize', true);
  35095. var itemSymbolRotate = itemModel.getShallow('symbolRotate', true);
  35096. var itemSymbolKeepAspect = itemModel.getShallow('symbolKeepAspect', true); // If has item symbol
  35097. if (itemSymbolType != null) {
  35098. data.setItemVisual(idx, 'symbol', itemSymbolType);
  35099. }
  35100. if (itemSymbolSize != null) {
  35101. // PENDING Transform symbolSize ?
  35102. data.setItemVisual(idx, 'symbolSize', itemSymbolSize);
  35103. }
  35104. if (itemSymbolRotate != null) {
  35105. data.setItemVisual(idx, 'symbolRotate', itemSymbolRotate);
  35106. }
  35107. if (itemSymbolKeepAspect != null) {
  35108. data.setItemVisual(idx, 'symbolKeepAspect', itemSymbolKeepAspect);
  35109. }
  35110. }
  35111. }
  35112. return {
  35113. dataEach: data.hasItemOption || hasCallback ? dataEach : null
  35114. };
  35115. }
  35116. };
  35117. };
  35118. /*
  35119. * Licensed to the Apache Software Foundation (ASF) under one
  35120. * or more contributor license agreements. See the NOTICE file
  35121. * distributed with this work for additional information
  35122. * regarding copyright ownership. The ASF licenses this file
  35123. * to you under the Apache License, Version 2.0 (the
  35124. * "License"); you may not use this file except in compliance
  35125. * with the License. You may obtain a copy of the License at
  35126. *
  35127. * http://www.apache.org/licenses/LICENSE-2.0
  35128. *
  35129. * Unless required by applicable law or agreed to in writing,
  35130. * software distributed under the License is distributed on an
  35131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35132. * KIND, either express or implied. See the License for the
  35133. * specific language governing permissions and limitations
  35134. * under the License.
  35135. */
  35136. /* global Float32Array */
  35137. var pointsLayout = function (seriesType) {
  35138. return {
  35139. seriesType: seriesType,
  35140. plan: createRenderPlanner(),
  35141. reset: function (seriesModel) {
  35142. var data = seriesModel.getData();
  35143. var coordSys = seriesModel.coordinateSystem;
  35144. var pipelineContext = seriesModel.pipelineContext;
  35145. var isLargeRender = pipelineContext.large;
  35146. if (!coordSys) {
  35147. return;
  35148. }
  35149. var dims = map(coordSys.dimensions, function (dim) {
  35150. return data.mapDimension(dim);
  35151. }).slice(0, 2);
  35152. var dimLen = dims.length;
  35153. var stackResultDim = data.getCalculationInfo('stackResultDimension');
  35154. if (isDimensionStacked(data, dims[0]
  35155. /*, dims[1]*/
  35156. )) {
  35157. dims[0] = stackResultDim;
  35158. }
  35159. if (isDimensionStacked(data, dims[1]
  35160. /*, dims[0]*/
  35161. )) {
  35162. dims[1] = stackResultDim;
  35163. }
  35164. function progress(params, data) {
  35165. var segCount = params.end - params.start;
  35166. var points = isLargeRender && new Float32Array(segCount * dimLen);
  35167. for (var i = params.start, offset = 0, tmpIn = [], tmpOut = []; i < params.end; i++) {
  35168. var point;
  35169. if (dimLen === 1) {
  35170. var x = data.get(dims[0], i);
  35171. point = !isNaN(x) && coordSys.dataToPoint(x, null, tmpOut);
  35172. } else {
  35173. var x = tmpIn[0] = data.get(dims[0], i);
  35174. var y = tmpIn[1] = data.get(dims[1], i); // Also {Array.<number>}, not undefined to avoid if...else... statement
  35175. point = !isNaN(x) && !isNaN(y) && coordSys.dataToPoint(tmpIn, null, tmpOut);
  35176. }
  35177. if (isLargeRender) {
  35178. points[offset++] = point ? point[0] : NaN;
  35179. points[offset++] = point ? point[1] : NaN;
  35180. } else {
  35181. data.setItemLayout(i, point && point.slice() || [NaN, NaN]);
  35182. }
  35183. }
  35184. isLargeRender && data.setLayout('symbolPoints', points);
  35185. }
  35186. return dimLen && {
  35187. progress: progress
  35188. };
  35189. }
  35190. };
  35191. };
  35192. /*
  35193. * Licensed to the Apache Software Foundation (ASF) under one
  35194. * or more contributor license agreements. See the NOTICE file
  35195. * distributed with this work for additional information
  35196. * regarding copyright ownership. The ASF licenses this file
  35197. * to you under the Apache License, Version 2.0 (the
  35198. * "License"); you may not use this file except in compliance
  35199. * with the License. You may obtain a copy of the License at
  35200. *
  35201. * http://www.apache.org/licenses/LICENSE-2.0
  35202. *
  35203. * Unless required by applicable law or agreed to in writing,
  35204. * software distributed under the License is distributed on an
  35205. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35206. * KIND, either express or implied. See the License for the
  35207. * specific language governing permissions and limitations
  35208. * under the License.
  35209. */
  35210. var samplers = {
  35211. average: function (frame) {
  35212. var sum = 0;
  35213. var count = 0;
  35214. for (var i = 0; i < frame.length; i++) {
  35215. if (!isNaN(frame[i])) {
  35216. sum += frame[i];
  35217. count++;
  35218. }
  35219. } // Return NaN if count is 0
  35220. return count === 0 ? NaN : sum / count;
  35221. },
  35222. sum: function (frame) {
  35223. var sum = 0;
  35224. for (var i = 0; i < frame.length; i++) {
  35225. // Ignore NaN
  35226. sum += frame[i] || 0;
  35227. }
  35228. return sum;
  35229. },
  35230. max: function (frame) {
  35231. var max = -Infinity;
  35232. for (var i = 0; i < frame.length; i++) {
  35233. frame[i] > max && (max = frame[i]);
  35234. } // NaN will cause illegal axis extent.
  35235. return isFinite(max) ? max : NaN;
  35236. },
  35237. min: function (frame) {
  35238. var min = Infinity;
  35239. for (var i = 0; i < frame.length; i++) {
  35240. frame[i] < min && (min = frame[i]);
  35241. } // NaN will cause illegal axis extent.
  35242. return isFinite(min) ? min : NaN;
  35243. },
  35244. // TODO
  35245. // Median
  35246. nearest: function (frame) {
  35247. return frame[0];
  35248. }
  35249. };
  35250. var indexSampler = function (frame, value) {
  35251. return Math.round(frame.length / 2);
  35252. };
  35253. var dataSample = function (seriesType) {
  35254. return {
  35255. seriesType: seriesType,
  35256. modifyOutputEnd: true,
  35257. reset: function (seriesModel, ecModel, api) {
  35258. var data = seriesModel.getData();
  35259. var sampling = seriesModel.get('sampling');
  35260. var coordSys = seriesModel.coordinateSystem; // Only cartesian2d support down sampling
  35261. if (coordSys.type === 'cartesian2d' && sampling) {
  35262. var baseAxis = coordSys.getBaseAxis();
  35263. var valueAxis = coordSys.getOtherAxis(baseAxis);
  35264. var extent = baseAxis.getExtent(); // Coordinste system has been resized
  35265. var size = extent[1] - extent[0];
  35266. var rate = Math.round(data.count() / size);
  35267. if (rate > 1) {
  35268. var sampler;
  35269. if (typeof sampling === 'string') {
  35270. sampler = samplers[sampling];
  35271. } else if (typeof sampling === 'function') {
  35272. sampler = sampling;
  35273. }
  35274. if (sampler) {
  35275. // Only support sample the first dim mapped from value axis.
  35276. seriesModel.setData(data.downSample(data.mapDimension(valueAxis.dim), 1 / rate, sampler, indexSampler));
  35277. }
  35278. }
  35279. }
  35280. }
  35281. };
  35282. };
  35283. /*
  35284. * Licensed to the Apache Software Foundation (ASF) under one
  35285. * or more contributor license agreements. See the NOTICE file
  35286. * distributed with this work for additional information
  35287. * regarding copyright ownership. The ASF licenses this file
  35288. * to you under the Apache License, Version 2.0 (the
  35289. * "License"); you may not use this file except in compliance
  35290. * with the License. You may obtain a copy of the License at
  35291. *
  35292. * http://www.apache.org/licenses/LICENSE-2.0
  35293. *
  35294. * Unless required by applicable law or agreed to in writing,
  35295. * software distributed under the License is distributed on an
  35296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35297. * KIND, either express or implied. See the License for the
  35298. * specific language governing permissions and limitations
  35299. * under the License.
  35300. */
  35301. registerVisual(visualSymbol('line', 'circle', 'line'));
  35302. registerLayout(pointsLayout('line')); // Down sample after filter
  35303. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, dataSample('line'));
  35304. /*
  35305. * Licensed to the Apache Software Foundation (ASF) under one
  35306. * or more contributor license agreements. See the NOTICE file
  35307. * distributed with this work for additional information
  35308. * regarding copyright ownership. The ASF licenses this file
  35309. * to you under the Apache License, Version 2.0 (the
  35310. * "License"); you may not use this file except in compliance
  35311. * with the License. You may obtain a copy of the License at
  35312. *
  35313. * http://www.apache.org/licenses/LICENSE-2.0
  35314. *
  35315. * Unless required by applicable law or agreed to in writing,
  35316. * software distributed under the License is distributed on an
  35317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35318. * KIND, either express or implied. See the License for the
  35319. * specific language governing permissions and limitations
  35320. * under the License.
  35321. */
  35322. /**
  35323. * [Usage]:
  35324. * (1)
  35325. * createListSimply(seriesModel, ['value']);
  35326. * (2)
  35327. * createListSimply(seriesModel, {
  35328. * coordDimensions: ['value'],
  35329. * dimensionsCount: 5
  35330. * });
  35331. *
  35332. * @param {module:echarts/model/Series} seriesModel
  35333. * @param {Object|Array.<string|Object>} opt opt or coordDimensions
  35334. * The options in opt, see `echarts/data/helper/createDimensions`
  35335. * @param {Array.<string>} [nameList]
  35336. * @return {module:echarts/data/List}
  35337. */
  35338. var createListSimply = function (seriesModel, opt, nameList) {
  35339. opt = isArray(opt) && {
  35340. coordDimensions: opt
  35341. } || extend({}, opt);
  35342. var source = seriesModel.getSource();
  35343. var dimensionsInfo = createDimensions(source, opt);
  35344. var list = new List(dimensionsInfo, seriesModel);
  35345. list.initData(source, nameList);
  35346. return list;
  35347. };
  35348. /*
  35349. * Licensed to the Apache Software Foundation (ASF) under one
  35350. * or more contributor license agreements. See the NOTICE file
  35351. * distributed with this work for additional information
  35352. * regarding copyright ownership. The ASF licenses this file
  35353. * to you under the Apache License, Version 2.0 (the
  35354. * "License"); you may not use this file except in compliance
  35355. * with the License. You may obtain a copy of the License at
  35356. *
  35357. * http://www.apache.org/licenses/LICENSE-2.0
  35358. *
  35359. * Unless required by applicable law or agreed to in writing,
  35360. * software distributed under the License is distributed on an
  35361. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35362. * KIND, either express or implied. See the License for the
  35363. * specific language governing permissions and limitations
  35364. * under the License.
  35365. */
  35366. /**
  35367. * Data selectable mixin for chart series.
  35368. * To eanble data select, option of series must have `selectedMode`.
  35369. * And each data item will use `selected` to toggle itself selected status
  35370. */
  35371. var selectableMixin = {
  35372. /**
  35373. * @param {Array.<Object>} targetList [{name, value, selected}, ...]
  35374. * If targetList is an array, it should like [{name: ..., value: ...}, ...].
  35375. * If targetList is a "List", it must have coordDim: 'value' dimension and name.
  35376. */
  35377. updateSelectedMap: function (targetList) {
  35378. this._targetList = isArray(targetList) ? targetList.slice() : [];
  35379. this._selectTargetMap = reduce(targetList || [], function (targetMap, target) {
  35380. targetMap.set(target.name, target);
  35381. return targetMap;
  35382. }, createHashMap());
  35383. },
  35384. /**
  35385. * Either name or id should be passed as input here.
  35386. * If both of them are defined, id is used.
  35387. *
  35388. * @param {string|undefined} name name of data
  35389. * @param {number|undefined} id dataIndex of data
  35390. */
  35391. // PENGING If selectedMode is null ?
  35392. select: function (name, id) {
  35393. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name);
  35394. var selectedMode = this.get('selectedMode');
  35395. if (selectedMode === 'single') {
  35396. this._selectTargetMap.each(function (target) {
  35397. target.selected = false;
  35398. });
  35399. }
  35400. target && (target.selected = true);
  35401. },
  35402. /**
  35403. * Either name or id should be passed as input here.
  35404. * If both of them are defined, id is used.
  35405. *
  35406. * @param {string|undefined} name name of data
  35407. * @param {number|undefined} id dataIndex of data
  35408. */
  35409. unSelect: function (name, id) {
  35410. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); // var selectedMode = this.get('selectedMode');
  35411. // selectedMode !== 'single' && target && (target.selected = false);
  35412. target && (target.selected = false);
  35413. },
  35414. /**
  35415. * Either name or id should be passed as input here.
  35416. * If both of them are defined, id is used.
  35417. *
  35418. * @param {string|undefined} name name of data
  35419. * @param {number|undefined} id dataIndex of data
  35420. */
  35421. toggleSelected: function (name, id) {
  35422. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name);
  35423. if (target != null) {
  35424. this[target.selected ? 'unSelect' : 'select'](name, id);
  35425. return target.selected;
  35426. }
  35427. },
  35428. /**
  35429. * Either name or id should be passed as input here.
  35430. * If both of them are defined, id is used.
  35431. *
  35432. * @param {string|undefined} name name of data
  35433. * @param {number|undefined} id dataIndex of data
  35434. */
  35435. isSelected: function (name, id) {
  35436. var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name);
  35437. return target && target.selected;
  35438. }
  35439. };
  35440. /*
  35441. * Licensed to the Apache Software Foundation (ASF) under one
  35442. * or more contributor license agreements. See the NOTICE file
  35443. * distributed with this work for additional information
  35444. * regarding copyright ownership. The ASF licenses this file
  35445. * to you under the Apache License, Version 2.0 (the
  35446. * "License"); you may not use this file except in compliance
  35447. * with the License. You may obtain a copy of the License at
  35448. *
  35449. * http://www.apache.org/licenses/LICENSE-2.0
  35450. *
  35451. * Unless required by applicable law or agreed to in writing,
  35452. * software distributed under the License is distributed on an
  35453. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35454. * KIND, either express or implied. See the License for the
  35455. * specific language governing permissions and limitations
  35456. * under the License.
  35457. */
  35458. /**
  35459. * LegendVisualProvider is an bridge that pick encoded color from data and
  35460. * provide to the legend component.
  35461. * @param {Function} getDataWithEncodedVisual Function to get data after filtered. It stores all the encoding info
  35462. * @param {Function} getRawData Function to get raw data before filtered.
  35463. */
  35464. function LegendVisualProvider(getDataWithEncodedVisual, getRawData) {
  35465. this.getAllNames = function () {
  35466. var rawData = getRawData(); // We find the name from the raw data. In case it's filtered by the legend component.
  35467. // Normally, the name can be found in rawData, but can't be found in filtered data will display as gray.
  35468. return rawData.mapArray(rawData.getName);
  35469. };
  35470. this.containName = function (name) {
  35471. var rawData = getRawData();
  35472. return rawData.indexOfName(name) >= 0;
  35473. };
  35474. this.indexOfName = function (name) {
  35475. // Only get data when necessary.
  35476. // Because LegendVisualProvider constructor may be new in the stage that data is not prepared yet.
  35477. // Invoking Series#getData immediately will throw an error.
  35478. var dataWithEncodedVisual = getDataWithEncodedVisual();
  35479. return dataWithEncodedVisual.indexOfName(name);
  35480. };
  35481. this.getItemVisual = function (dataIndex, key) {
  35482. // Get encoded visual properties from final filtered data.
  35483. var dataWithEncodedVisual = getDataWithEncodedVisual();
  35484. return dataWithEncodedVisual.getItemVisual(dataIndex, key);
  35485. };
  35486. }
  35487. /*
  35488. * Licensed to the Apache Software Foundation (ASF) under one
  35489. * or more contributor license agreements. See the NOTICE file
  35490. * distributed with this work for additional information
  35491. * regarding copyright ownership. The ASF licenses this file
  35492. * to you under the Apache License, Version 2.0 (the
  35493. * "License"); you may not use this file except in compliance
  35494. * with the License. You may obtain a copy of the License at
  35495. *
  35496. * http://www.apache.org/licenses/LICENSE-2.0
  35497. *
  35498. * Unless required by applicable law or agreed to in writing,
  35499. * software distributed under the License is distributed on an
  35500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35501. * KIND, either express or implied. See the License for the
  35502. * specific language governing permissions and limitations
  35503. * under the License.
  35504. */
  35505. var PieSeries = extendSeriesModel({
  35506. type: 'series.pie',
  35507. // Overwrite
  35508. init: function (option) {
  35509. PieSeries.superApply(this, 'init', arguments); // Enable legend selection for each data item
  35510. // Use a function instead of direct access because data reference may changed
  35511. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  35512. this.updateSelectedMap(this._createSelectableList());
  35513. this._defaultLabelLine(option);
  35514. },
  35515. // Overwrite
  35516. mergeOption: function (newOption) {
  35517. PieSeries.superCall(this, 'mergeOption', newOption);
  35518. this.updateSelectedMap(this._createSelectableList());
  35519. },
  35520. getInitialData: function (option, ecModel) {
  35521. return createListSimply(this, {
  35522. coordDimensions: ['value'],
  35523. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  35524. });
  35525. },
  35526. _createSelectableList: function () {
  35527. var data = this.getRawData();
  35528. var valueDim = data.mapDimension('value');
  35529. var targetList = [];
  35530. for (var i = 0, len = data.count(); i < len; i++) {
  35531. targetList.push({
  35532. name: data.getName(i),
  35533. value: data.get(valueDim, i),
  35534. selected: retrieveRawAttr(data, i, 'selected')
  35535. });
  35536. }
  35537. return targetList;
  35538. },
  35539. // Overwrite
  35540. getDataParams: function (dataIndex) {
  35541. var data = this.getData();
  35542. var params = PieSeries.superCall(this, 'getDataParams', dataIndex); // FIXME toFixed?
  35543. var valueList = [];
  35544. data.each(data.mapDimension('value'), function (value) {
  35545. valueList.push(value);
  35546. });
  35547. params.percent = getPercentWithPrecision(valueList, dataIndex, data.hostModel.get('percentPrecision'));
  35548. params.$vars.push('percent');
  35549. return params;
  35550. },
  35551. _defaultLabelLine: function (option) {
  35552. // Extend labelLine emphasis
  35553. defaultEmphasis(option, 'labelLine', ['show']);
  35554. var labelLineNormalOpt = option.labelLine;
  35555. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  35556. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  35557. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  35558. },
  35559. defaultOption: {
  35560. zlevel: 0,
  35561. z: 2,
  35562. legendHoverLink: true,
  35563. hoverAnimation: true,
  35564. // 默认全局居中
  35565. center: ['50%', '50%'],
  35566. radius: [0, '75%'],
  35567. // 默认顺时针
  35568. clockwise: true,
  35569. startAngle: 90,
  35570. // 最小角度改为0
  35571. minAngle: 0,
  35572. // If the angle of a sector less than `minShowLabelAngle`,
  35573. // the label will not be displayed.
  35574. minShowLabelAngle: 0,
  35575. // 选中时扇区偏移量
  35576. selectedOffset: 10,
  35577. // 高亮扇区偏移量
  35578. hoverOffset: 10,
  35579. // If use strategy to avoid label overlapping
  35580. avoidLabelOverlap: true,
  35581. // 选择模式,默认关闭,可选single,multiple
  35582. // selectedMode: false,
  35583. // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积)
  35584. // roseType: null,
  35585. percentPrecision: 2,
  35586. // If still show when all data zero.
  35587. stillShowZeroSum: true,
  35588. // cursor: null,
  35589. left: 0,
  35590. top: 0,
  35591. right: 0,
  35592. bottom: 0,
  35593. width: null,
  35594. height: null,
  35595. label: {
  35596. // If rotate around circle
  35597. rotate: false,
  35598. show: true,
  35599. // 'outer', 'inside', 'center'
  35600. position: 'outer',
  35601. // 'none', 'labelLine', 'edge'. Works only when position is 'outer'
  35602. alignTo: 'none',
  35603. // Closest distance between label and chart edge.
  35604. // Works only position is 'outer' and alignTo is 'edge'.
  35605. margin: '25%',
  35606. // Works only position is 'outer' and alignTo is not 'edge'.
  35607. bleedMargin: 10,
  35608. // Distance between text and label line.
  35609. distanceToLabelLine: 5 // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  35610. // 默认使用全局文本样式,详见TEXTSTYLE
  35611. // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数
  35612. },
  35613. // Enabled when label.normal.position is 'outer'
  35614. labelLine: {
  35615. show: true,
  35616. // 引导线两段中的第一段长度
  35617. length: 15,
  35618. // 引导线两段中的第二段长度
  35619. length2: 15,
  35620. smooth: false,
  35621. lineStyle: {
  35622. // color: 各异,
  35623. width: 1,
  35624. type: 'solid'
  35625. }
  35626. },
  35627. itemStyle: {
  35628. borderWidth: 1
  35629. },
  35630. // Animation type. Valid values: expansion, scale
  35631. animationType: 'expansion',
  35632. // Animation type when update. Valid values: transition, expansion
  35633. animationTypeUpdate: 'transition',
  35634. animationEasing: 'cubicOut'
  35635. }
  35636. });
  35637. mixin(PieSeries, selectableMixin);
  35638. /*
  35639. * Licensed to the Apache Software Foundation (ASF) under one
  35640. * or more contributor license agreements. See the NOTICE file
  35641. * distributed with this work for additional information
  35642. * regarding copyright ownership. The ASF licenses this file
  35643. * to you under the Apache License, Version 2.0 (the
  35644. * "License"); you may not use this file except in compliance
  35645. * with the License. You may obtain a copy of the License at
  35646. *
  35647. * http://www.apache.org/licenses/LICENSE-2.0
  35648. *
  35649. * Unless required by applicable law or agreed to in writing,
  35650. * software distributed under the License is distributed on an
  35651. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35652. * KIND, either express or implied. See the License for the
  35653. * specific language governing permissions and limitations
  35654. * under the License.
  35655. */
  35656. /**
  35657. * @param {module:echarts/model/Series} seriesModel
  35658. * @param {boolean} hasAnimation
  35659. * @inner
  35660. */
  35661. function updateDataSelected(uid, seriesModel, hasAnimation, api) {
  35662. var data = seriesModel.getData();
  35663. var dataIndex = this.dataIndex;
  35664. var name = data.getName(dataIndex);
  35665. var selectedOffset = seriesModel.get('selectedOffset');
  35666. api.dispatchAction({
  35667. type: 'pieToggleSelect',
  35668. from: uid,
  35669. name: name,
  35670. seriesId: seriesModel.id
  35671. });
  35672. data.each(function (idx) {
  35673. toggleItemSelected(data.getItemGraphicEl(idx), data.getItemLayout(idx), seriesModel.isSelected(data.getName(idx)), selectedOffset, hasAnimation);
  35674. });
  35675. }
  35676. /**
  35677. * @param {module:zrender/graphic/Sector} el
  35678. * @param {Object} layout
  35679. * @param {boolean} isSelected
  35680. * @param {number} selectedOffset
  35681. * @param {boolean} hasAnimation
  35682. * @inner
  35683. */
  35684. function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) {
  35685. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  35686. var dx = Math.cos(midAngle);
  35687. var dy = Math.sin(midAngle);
  35688. var offset = isSelected ? selectedOffset : 0;
  35689. var position = [dx * offset, dy * offset];
  35690. hasAnimation // animateTo will stop revious animation like update transition
  35691. ? el.animate().when(200, {
  35692. position: position
  35693. }).start('bounceOut') : el.attr('position', position);
  35694. }
  35695. /**
  35696. * Piece of pie including Sector, Label, LabelLine
  35697. * @constructor
  35698. * @extends {module:zrender/graphic/Group}
  35699. */
  35700. function PiePiece(data, idx) {
  35701. Group.call(this);
  35702. var sector = new Sector({
  35703. z2: 2
  35704. });
  35705. var polyline = new Polyline();
  35706. var text = new Text();
  35707. this.add(sector);
  35708. this.add(polyline);
  35709. this.add(text);
  35710. this.updateData(data, idx, true);
  35711. }
  35712. var piePieceProto = PiePiece.prototype;
  35713. piePieceProto.updateData = function (data, idx, firstCreate) {
  35714. var sector = this.childAt(0);
  35715. var labelLine = this.childAt(1);
  35716. var labelText = this.childAt(2);
  35717. var seriesModel = data.hostModel;
  35718. var itemModel = data.getItemModel(idx);
  35719. var layout = data.getItemLayout(idx);
  35720. var sectorShape = extend({}, layout);
  35721. sectorShape.label = null;
  35722. var animationTypeUpdate = seriesModel.getShallow('animationTypeUpdate');
  35723. if (firstCreate) {
  35724. sector.setShape(sectorShape);
  35725. var animationType = seriesModel.getShallow('animationType');
  35726. if (animationType === 'scale') {
  35727. sector.shape.r = layout.r0;
  35728. initProps(sector, {
  35729. shape: {
  35730. r: layout.r
  35731. }
  35732. }, seriesModel, idx);
  35733. } // Expansion
  35734. else {
  35735. sector.shape.endAngle = layout.startAngle;
  35736. updateProps(sector, {
  35737. shape: {
  35738. endAngle: layout.endAngle
  35739. }
  35740. }, seriesModel, idx);
  35741. }
  35742. } else {
  35743. if (animationTypeUpdate === 'expansion') {
  35744. // Sectors are set to be target shape and an overlaying clipPath is used for animation
  35745. sector.setShape(sectorShape);
  35746. } else {
  35747. // Transition animation from the old shape
  35748. updateProps(sector, {
  35749. shape: sectorShape
  35750. }, seriesModel, idx);
  35751. }
  35752. } // Update common style
  35753. var visualColor = data.getItemVisual(idx, 'color');
  35754. sector.useStyle(defaults({
  35755. lineJoin: 'bevel',
  35756. fill: visualColor
  35757. }, itemModel.getModel('itemStyle').getItemStyle()));
  35758. sector.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  35759. var cursorStyle = itemModel.getShallow('cursor');
  35760. cursorStyle && sector.attr('cursor', cursorStyle); // Toggle selected
  35761. toggleItemSelected(this, data.getItemLayout(idx), seriesModel.isSelected(data.getName(idx)), seriesModel.get('selectedOffset'), seriesModel.get('animation')); // Label and text animation should be applied only for transition type animation when update
  35762. var withAnimation = !firstCreate && animationTypeUpdate === 'transition';
  35763. this._updateLabel(data, idx, withAnimation);
  35764. this.highDownOnUpdate = !seriesModel.get('silent') ? function (fromState, toState) {
  35765. var hasAnimation = seriesModel.isAnimationEnabled() && itemModel.get('hoverAnimation');
  35766. if (toState === 'emphasis') {
  35767. labelLine.ignore = labelLine.hoverIgnore;
  35768. labelText.ignore = labelText.hoverIgnore; // Sector may has animation of updating data. Force to move to the last frame
  35769. // Or it may stopped on the wrong shape
  35770. if (hasAnimation) {
  35771. sector.stopAnimation(true);
  35772. sector.animateTo({
  35773. shape: {
  35774. r: layout.r + seriesModel.get('hoverOffset')
  35775. }
  35776. }, 300, 'elasticOut');
  35777. }
  35778. } else {
  35779. labelLine.ignore = labelLine.normalIgnore;
  35780. labelText.ignore = labelText.normalIgnore;
  35781. if (hasAnimation) {
  35782. sector.stopAnimation(true);
  35783. sector.animateTo({
  35784. shape: {
  35785. r: layout.r
  35786. }
  35787. }, 300, 'elasticOut');
  35788. }
  35789. }
  35790. } : null;
  35791. setHoverStyle(this);
  35792. };
  35793. piePieceProto._updateLabel = function (data, idx, withAnimation) {
  35794. var labelLine = this.childAt(1);
  35795. var labelText = this.childAt(2);
  35796. var seriesModel = data.hostModel;
  35797. var itemModel = data.getItemModel(idx);
  35798. var layout = data.getItemLayout(idx);
  35799. var labelLayout = layout.label;
  35800. var visualColor = data.getItemVisual(idx, 'color');
  35801. if (!labelLayout || isNaN(labelLayout.x) || isNaN(labelLayout.y)) {
  35802. labelText.ignore = labelText.normalIgnore = labelText.hoverIgnore = labelLine.ignore = labelLine.normalIgnore = labelLine.hoverIgnore = true;
  35803. return;
  35804. }
  35805. var targetLineShape = {
  35806. points: labelLayout.linePoints || [[labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y]]
  35807. };
  35808. var targetTextStyle = {
  35809. x: labelLayout.x,
  35810. y: labelLayout.y
  35811. };
  35812. if (withAnimation) {
  35813. updateProps(labelLine, {
  35814. shape: targetLineShape
  35815. }, seriesModel, idx);
  35816. updateProps(labelText, {
  35817. style: targetTextStyle
  35818. }, seriesModel, idx);
  35819. } else {
  35820. labelLine.attr({
  35821. shape: targetLineShape
  35822. });
  35823. labelText.attr({
  35824. style: targetTextStyle
  35825. });
  35826. }
  35827. labelText.attr({
  35828. rotation: labelLayout.rotation,
  35829. origin: [labelLayout.x, labelLayout.y],
  35830. z2: 10
  35831. });
  35832. var labelModel = itemModel.getModel('label');
  35833. var labelHoverModel = itemModel.getModel('emphasis.label');
  35834. var labelLineModel = itemModel.getModel('labelLine');
  35835. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  35836. var visualColor = data.getItemVisual(idx, 'color');
  35837. setLabelStyle(labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel, {
  35838. labelFetcher: data.hostModel,
  35839. labelDataIndex: idx,
  35840. defaultText: labelLayout.text,
  35841. autoColor: visualColor,
  35842. useInsideStyle: !!labelLayout.inside
  35843. }, {
  35844. textAlign: labelLayout.textAlign,
  35845. textVerticalAlign: labelLayout.verticalAlign,
  35846. opacity: data.getItemVisual(idx, 'opacity')
  35847. });
  35848. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  35849. labelText.hoverIgnore = !labelHoverModel.get('show');
  35850. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  35851. labelLine.hoverIgnore = !labelLineHoverModel.get('show'); // Default use item visual color
  35852. labelLine.setStyle({
  35853. stroke: visualColor,
  35854. opacity: data.getItemVisual(idx, 'opacity')
  35855. });
  35856. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  35857. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  35858. var smooth = labelLineModel.get('smooth');
  35859. if (smooth && smooth === true) {
  35860. smooth = 0.4;
  35861. }
  35862. labelLine.setShape({
  35863. smooth: smooth
  35864. });
  35865. };
  35866. inherits(PiePiece, Group); // Pie view
  35867. var PieView = Chart.extend({
  35868. type: 'pie',
  35869. init: function () {
  35870. var sectorGroup = new Group();
  35871. this._sectorGroup = sectorGroup;
  35872. },
  35873. render: function (seriesModel, ecModel, api, payload) {
  35874. if (payload && payload.from === this.uid) {
  35875. return;
  35876. }
  35877. var data = seriesModel.getData();
  35878. var oldData = this._data;
  35879. var group = this.group;
  35880. var hasAnimation = ecModel.get('animation');
  35881. var isFirstRender = !oldData;
  35882. var animationType = seriesModel.get('animationType');
  35883. var animationTypeUpdate = seriesModel.get('animationTypeUpdate');
  35884. var onSectorClick = curry(updateDataSelected, this.uid, seriesModel, hasAnimation, api);
  35885. var selectedMode = seriesModel.get('selectedMode');
  35886. data.diff(oldData).add(function (idx) {
  35887. var piePiece = new PiePiece(data, idx); // Default expansion animation
  35888. if (isFirstRender && animationType !== 'scale') {
  35889. piePiece.eachChild(function (child) {
  35890. child.stopAnimation(true);
  35891. });
  35892. }
  35893. selectedMode && piePiece.on('click', onSectorClick);
  35894. data.setItemGraphicEl(idx, piePiece);
  35895. group.add(piePiece);
  35896. }).update(function (newIdx, oldIdx) {
  35897. var piePiece = oldData.getItemGraphicEl(oldIdx);
  35898. if (!isFirstRender && animationTypeUpdate !== 'transition') {
  35899. piePiece.eachChild(function (child) {
  35900. child.stopAnimation(true);
  35901. });
  35902. }
  35903. piePiece.updateData(data, newIdx);
  35904. piePiece.off('click');
  35905. selectedMode && piePiece.on('click', onSectorClick);
  35906. group.add(piePiece);
  35907. data.setItemGraphicEl(newIdx, piePiece);
  35908. }).remove(function (idx) {
  35909. var piePiece = oldData.getItemGraphicEl(idx);
  35910. group.remove(piePiece);
  35911. }).execute();
  35912. if (hasAnimation && data.count() > 0 && (isFirstRender ? animationType !== 'scale' : animationTypeUpdate !== 'transition')) {
  35913. var shape = data.getItemLayout(0);
  35914. for (var s = 1; isNaN(shape.startAngle) && s < data.count(); ++s) {
  35915. shape = data.getItemLayout(s);
  35916. }
  35917. var r = Math.max(api.getWidth(), api.getHeight()) / 2;
  35918. var removeClipPath = bind(group.removeClipPath, group);
  35919. group.setClipPath(this._createClipPath(shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel, isFirstRender));
  35920. } else {
  35921. // clipPath is used in first-time animation, so remove it when otherwise. See: #8994
  35922. group.removeClipPath();
  35923. }
  35924. this._data = data;
  35925. },
  35926. dispose: function () {},
  35927. _createClipPath: function (cx, cy, r, startAngle, clockwise, cb, seriesModel, isFirstRender) {
  35928. var clipPath = new Sector({
  35929. shape: {
  35930. cx: cx,
  35931. cy: cy,
  35932. r0: 0,
  35933. r: r,
  35934. startAngle: startAngle,
  35935. endAngle: startAngle,
  35936. clockwise: clockwise
  35937. }
  35938. });
  35939. var initOrUpdate = isFirstRender ? initProps : updateProps;
  35940. initOrUpdate(clipPath, {
  35941. shape: {
  35942. endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2
  35943. }
  35944. }, seriesModel, cb);
  35945. return clipPath;
  35946. },
  35947. /**
  35948. * @implement
  35949. */
  35950. containPoint: function (point, seriesModel) {
  35951. var data = seriesModel.getData();
  35952. var itemLayout = data.getItemLayout(0);
  35953. if (itemLayout) {
  35954. var dx = point[0] - itemLayout.cx;
  35955. var dy = point[1] - itemLayout.cy;
  35956. var radius = Math.sqrt(dx * dx + dy * dy);
  35957. return radius <= itemLayout.r && radius >= itemLayout.r0;
  35958. }
  35959. }
  35960. });
  35961. /*
  35962. * Licensed to the Apache Software Foundation (ASF) under one
  35963. * or more contributor license agreements. See the NOTICE file
  35964. * distributed with this work for additional information
  35965. * regarding copyright ownership. The ASF licenses this file
  35966. * to you under the Apache License, Version 2.0 (the
  35967. * "License"); you may not use this file except in compliance
  35968. * with the License. You may obtain a copy of the License at
  35969. *
  35970. * http://www.apache.org/licenses/LICENSE-2.0
  35971. *
  35972. * Unless required by applicable law or agreed to in writing,
  35973. * software distributed under the License is distributed on an
  35974. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  35975. * KIND, either express or implied. See the License for the
  35976. * specific language governing permissions and limitations
  35977. * under the License.
  35978. */
  35979. var createDataSelectAction = function (seriesType, actionInfos) {
  35980. each$1(actionInfos, function (actionInfo) {
  35981. actionInfo.update = 'updateView';
  35982. /**
  35983. * @payload
  35984. * @property {string} seriesName
  35985. * @property {string} name
  35986. */
  35987. registerAction(actionInfo, function (payload, ecModel) {
  35988. var selected = {};
  35989. ecModel.eachComponent({
  35990. mainType: 'series',
  35991. subType: seriesType,
  35992. query: payload
  35993. }, function (seriesModel) {
  35994. if (seriesModel[actionInfo.method]) {
  35995. seriesModel[actionInfo.method](payload.name, payload.dataIndex);
  35996. }
  35997. var data = seriesModel.getData(); // Create selected map
  35998. data.each(function (idx) {
  35999. var name = data.getName(idx);
  36000. selected[name] = seriesModel.isSelected(name) || false;
  36001. });
  36002. });
  36003. return {
  36004. name: payload.name,
  36005. selected: selected,
  36006. seriesId: payload.seriesId
  36007. };
  36008. });
  36009. });
  36010. };
  36011. /*
  36012. * Licensed to the Apache Software Foundation (ASF) under one
  36013. * or more contributor license agreements. See the NOTICE file
  36014. * distributed with this work for additional information
  36015. * regarding copyright ownership. The ASF licenses this file
  36016. * to you under the Apache License, Version 2.0 (the
  36017. * "License"); you may not use this file except in compliance
  36018. * with the License. You may obtain a copy of the License at
  36019. *
  36020. * http://www.apache.org/licenses/LICENSE-2.0
  36021. *
  36022. * Unless required by applicable law or agreed to in writing,
  36023. * software distributed under the License is distributed on an
  36024. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36025. * KIND, either express or implied. See the License for the
  36026. * specific language governing permissions and limitations
  36027. * under the License.
  36028. */
  36029. // Pick color from palette for each data item.
  36030. // Applicable for charts that require applying color palette
  36031. // in data level (like pie, funnel, chord).
  36032. var dataColor = function (seriesType) {
  36033. return {
  36034. getTargetSeries: function (ecModel) {
  36035. // Pie and funnel may use diferrent scope
  36036. var paletteScope = {};
  36037. var seiresModelMap = createHashMap();
  36038. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36039. seriesModel.__paletteScope = paletteScope;
  36040. seiresModelMap.set(seriesModel.uid, seriesModel);
  36041. });
  36042. return seiresModelMap;
  36043. },
  36044. reset: function (seriesModel, ecModel) {
  36045. var dataAll = seriesModel.getRawData();
  36046. var idxMap = {};
  36047. var data = seriesModel.getData();
  36048. data.each(function (idx) {
  36049. var rawIdx = data.getRawIndex(idx);
  36050. idxMap[rawIdx] = idx;
  36051. });
  36052. dataAll.each(function (rawIdx) {
  36053. var filteredIdx = idxMap[rawIdx]; // If series.itemStyle.normal.color is a function. itemVisual may be encoded
  36054. var singleDataColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'color', true);
  36055. var singleDataBorderColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'borderColor', true);
  36056. var itemModel;
  36057. if (!singleDataColor || !singleDataBorderColor) {
  36058. // FIXME Performance
  36059. itemModel = dataAll.getItemModel(rawIdx);
  36060. }
  36061. if (!singleDataColor) {
  36062. var color = itemModel.get('itemStyle.color') || seriesModel.getColorFromPalette(dataAll.getName(rawIdx) || rawIdx + '', seriesModel.__paletteScope, dataAll.count()); // Data is not filtered
  36063. if (filteredIdx != null) {
  36064. data.setItemVisual(filteredIdx, 'color', color);
  36065. }
  36066. }
  36067. if (!singleDataBorderColor) {
  36068. var borderColor = itemModel.get('itemStyle.borderColor'); // Data is not filtered
  36069. if (filteredIdx != null) {
  36070. data.setItemVisual(filteredIdx, 'borderColor', borderColor);
  36071. }
  36072. }
  36073. });
  36074. }
  36075. };
  36076. };
  36077. /*
  36078. * Licensed to the Apache Software Foundation (ASF) under one
  36079. * or more contributor license agreements. See the NOTICE file
  36080. * distributed with this work for additional information
  36081. * regarding copyright ownership. The ASF licenses this file
  36082. * to you under the Apache License, Version 2.0 (the
  36083. * "License"); you may not use this file except in compliance
  36084. * with the License. You may obtain a copy of the License at
  36085. *
  36086. * http://www.apache.org/licenses/LICENSE-2.0
  36087. *
  36088. * Unless required by applicable law or agreed to in writing,
  36089. * software distributed under the License is distributed on an
  36090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36091. * KIND, either express or implied. See the License for the
  36092. * specific language governing permissions and limitations
  36093. * under the License.
  36094. */
  36095. // FIXME emphasis label position is not same with normal label position
  36096. var RADIAN$1 = Math.PI / 180;
  36097. function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight, viewLeft, viewTop, farthestX) {
  36098. list.sort(function (a, b) {
  36099. return a.y - b.y;
  36100. });
  36101. function shiftDown(start, end, delta, dir) {
  36102. for (var j = start; j < end; j++) {
  36103. if (list[j].y + delta > viewTop + viewHeight) {
  36104. break;
  36105. }
  36106. list[j].y += delta;
  36107. if (j > start && j + 1 < end && list[j + 1].y > list[j].y + list[j].height) {
  36108. shiftUp(j, delta / 2);
  36109. return;
  36110. }
  36111. }
  36112. shiftUp(end - 1, delta / 2);
  36113. }
  36114. function shiftUp(end, delta) {
  36115. for (var j = end; j >= 0; j--) {
  36116. if (list[j].y - delta < viewTop) {
  36117. break;
  36118. }
  36119. list[j].y -= delta;
  36120. if (j > 0 && list[j].y > list[j - 1].y + list[j - 1].height) {
  36121. break;
  36122. }
  36123. }
  36124. }
  36125. function changeX(list, isDownList, cx, cy, r, dir) {
  36126. var lastDeltaX = dir > 0 ? isDownList // right-side
  36127. ? Number.MAX_VALUE // down
  36128. : 0 // up
  36129. : isDownList // left-side
  36130. ? Number.MAX_VALUE // down
  36131. : 0; // up
  36132. for (var i = 0, l = list.length; i < l; i++) {
  36133. if (list[i].labelAlignTo !== 'none') {
  36134. continue;
  36135. }
  36136. var deltaY = Math.abs(list[i].y - cy);
  36137. var length = list[i].len;
  36138. var length2 = list[i].len2;
  36139. var deltaX = deltaY < r + length ? Math.sqrt((r + length + length2) * (r + length + length2) - deltaY * deltaY) : Math.abs(list[i].x - cx);
  36140. if (isDownList && deltaX >= lastDeltaX) {
  36141. // right-down, left-down
  36142. deltaX = lastDeltaX - 10;
  36143. }
  36144. if (!isDownList && deltaX <= lastDeltaX) {
  36145. // right-up, left-up
  36146. deltaX = lastDeltaX + 10;
  36147. }
  36148. list[i].x = cx + deltaX * dir;
  36149. lastDeltaX = deltaX;
  36150. }
  36151. }
  36152. var lastY = 0;
  36153. var delta;
  36154. var len = list.length;
  36155. var upList = [];
  36156. var downList = [];
  36157. for (var i = 0; i < len; i++) {
  36158. if (list[i].position === 'outer' && list[i].labelAlignTo === 'labelLine') {
  36159. var dx = list[i].x - farthestX;
  36160. list[i].linePoints[1][0] += dx;
  36161. list[i].x = farthestX;
  36162. }
  36163. delta = list[i].y - lastY;
  36164. if (delta < 0) {
  36165. shiftDown(i, len, -delta, dir);
  36166. }
  36167. lastY = list[i].y + list[i].height;
  36168. }
  36169. if (viewHeight - lastY < 0) {
  36170. shiftUp(len - 1, lastY - viewHeight);
  36171. }
  36172. for (var i = 0; i < len; i++) {
  36173. if (list[i].y >= cy) {
  36174. downList.push(list[i]);
  36175. } else {
  36176. upList.push(list[i]);
  36177. }
  36178. }
  36179. changeX(upList, false, cx, cy, r, dir);
  36180. changeX(downList, true, cx, cy, r, dir);
  36181. }
  36182. function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop) {
  36183. var leftList = [];
  36184. var rightList = [];
  36185. var leftmostX = Number.MAX_VALUE;
  36186. var rightmostX = -Number.MAX_VALUE;
  36187. for (var i = 0; i < labelLayoutList.length; i++) {
  36188. if (isPositionCenter(labelLayoutList[i])) {
  36189. continue;
  36190. }
  36191. if (labelLayoutList[i].x < cx) {
  36192. leftmostX = Math.min(leftmostX, labelLayoutList[i].x);
  36193. leftList.push(labelLayoutList[i]);
  36194. } else {
  36195. rightmostX = Math.max(rightmostX, labelLayoutList[i].x);
  36196. rightList.push(labelLayoutList[i]);
  36197. }
  36198. }
  36199. adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight, viewLeft, viewTop, rightmostX);
  36200. adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight, viewLeft, viewTop, leftmostX);
  36201. for (var i = 0; i < labelLayoutList.length; i++) {
  36202. var layout = labelLayoutList[i];
  36203. if (isPositionCenter(layout)) {
  36204. continue;
  36205. }
  36206. var linePoints = layout.linePoints;
  36207. if (linePoints) {
  36208. var isAlignToEdge = layout.labelAlignTo === 'edge';
  36209. var realTextWidth = layout.textRect.width;
  36210. var targetTextWidth;
  36211. if (isAlignToEdge) {
  36212. if (layout.x < cx) {
  36213. targetTextWidth = linePoints[2][0] - layout.labelDistance - viewLeft - layout.labelMargin;
  36214. } else {
  36215. targetTextWidth = viewLeft + viewWidth - layout.labelMargin - linePoints[2][0] - layout.labelDistance;
  36216. }
  36217. } else {
  36218. if (layout.x < cx) {
  36219. targetTextWidth = layout.x - viewLeft - layout.bleedMargin;
  36220. } else {
  36221. targetTextWidth = viewLeft + viewWidth - layout.x - layout.bleedMargin;
  36222. }
  36223. }
  36224. if (targetTextWidth < layout.textRect.width) {
  36225. layout.text = truncateText(layout.text, targetTextWidth, layout.font);
  36226. if (layout.labelAlignTo === 'edge') {
  36227. realTextWidth = getWidth(layout.text, layout.font);
  36228. }
  36229. }
  36230. var dist = linePoints[1][0] - linePoints[2][0];
  36231. if (isAlignToEdge) {
  36232. if (layout.x < cx) {
  36233. linePoints[2][0] = viewLeft + layout.labelMargin + realTextWidth + layout.labelDistance;
  36234. } else {
  36235. linePoints[2][0] = viewLeft + viewWidth - layout.labelMargin - realTextWidth - layout.labelDistance;
  36236. }
  36237. } else {
  36238. if (layout.x < cx) {
  36239. linePoints[2][0] = layout.x + layout.labelDistance;
  36240. } else {
  36241. linePoints[2][0] = layout.x - layout.labelDistance;
  36242. }
  36243. linePoints[1][0] = linePoints[2][0] + dist;
  36244. }
  36245. linePoints[1][1] = linePoints[2][1] = layout.y;
  36246. }
  36247. }
  36248. }
  36249. function isPositionCenter(layout) {
  36250. // Not change x for center label
  36251. return layout.position === 'center';
  36252. }
  36253. var labelLayout = function (seriesModel, r, viewWidth, viewHeight, viewLeft, viewTop) {
  36254. var data = seriesModel.getData();
  36255. var labelLayoutList = [];
  36256. var cx;
  36257. var cy;
  36258. var hasLabelRotate = false;
  36259. var minShowLabelRadian = (seriesModel.get('minShowLabelAngle') || 0) * RADIAN$1;
  36260. data.each(function (idx) {
  36261. var layout = data.getItemLayout(idx);
  36262. var itemModel = data.getItemModel(idx);
  36263. var labelModel = itemModel.getModel('label'); // Use position in normal or emphasis
  36264. var labelPosition = labelModel.get('position') || itemModel.get('emphasis.label.position');
  36265. var labelDistance = labelModel.get('distanceToLabelLine');
  36266. var labelAlignTo = labelModel.get('alignTo');
  36267. var labelMargin = parsePercent$1(labelModel.get('margin'), viewWidth);
  36268. var bleedMargin = labelModel.get('bleedMargin');
  36269. var font = labelModel.getFont();
  36270. var labelLineModel = itemModel.getModel('labelLine');
  36271. var labelLineLen = labelLineModel.get('length');
  36272. labelLineLen = parsePercent$1(labelLineLen, viewWidth);
  36273. var labelLineLen2 = labelLineModel.get('length2');
  36274. labelLineLen2 = parsePercent$1(labelLineLen2, viewWidth);
  36275. if (layout.angle < minShowLabelRadian) {
  36276. return;
  36277. }
  36278. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  36279. var dx = Math.cos(midAngle);
  36280. var dy = Math.sin(midAngle);
  36281. var textX;
  36282. var textY;
  36283. var linePoints;
  36284. var textAlign;
  36285. cx = layout.cx;
  36286. cy = layout.cy;
  36287. var text = seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx);
  36288. var textRect = getBoundingRect(text, font, textAlign, 'top');
  36289. var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner';
  36290. if (labelPosition === 'center') {
  36291. textX = layout.cx;
  36292. textY = layout.cy;
  36293. textAlign = 'center';
  36294. } else {
  36295. var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx;
  36296. var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy;
  36297. textX = x1 + dx * 3;
  36298. textY = y1 + dy * 3;
  36299. if (!isLabelInside) {
  36300. // For roseType
  36301. var x2 = x1 + dx * (labelLineLen + r - layout.r);
  36302. var y2 = y1 + dy * (labelLineLen + r - layout.r);
  36303. var x3 = x2 + (dx < 0 ? -1 : 1) * labelLineLen2;
  36304. var y3 = y2;
  36305. if (labelAlignTo === 'edge') {
  36306. // Adjust textX because text align of edge is opposite
  36307. textX = dx < 0 ? viewLeft + labelMargin : viewLeft + viewWidth - labelMargin;
  36308. } else {
  36309. textX = x3 + (dx < 0 ? -labelDistance : labelDistance);
  36310. }
  36311. textY = y3;
  36312. linePoints = [[x1, y1], [x2, y2], [x3, y3]];
  36313. }
  36314. textAlign = isLabelInside ? 'center' : labelAlignTo === 'edge' ? dx > 0 ? 'right' : 'left' : dx > 0 ? 'left' : 'right';
  36315. }
  36316. var labelRotate;
  36317. var rotate = labelModel.get('rotate');
  36318. if (typeof rotate === 'number') {
  36319. labelRotate = rotate * (Math.PI / 180);
  36320. } else {
  36321. labelRotate = rotate ? dx < 0 ? -midAngle + Math.PI : -midAngle : 0;
  36322. }
  36323. hasLabelRotate = !!labelRotate;
  36324. layout.label = {
  36325. x: textX,
  36326. y: textY,
  36327. position: labelPosition,
  36328. height: textRect.height,
  36329. len: labelLineLen,
  36330. len2: labelLineLen2,
  36331. linePoints: linePoints,
  36332. textAlign: textAlign,
  36333. verticalAlign: 'middle',
  36334. rotation: labelRotate,
  36335. inside: isLabelInside,
  36336. labelDistance: labelDistance,
  36337. labelAlignTo: labelAlignTo,
  36338. labelMargin: labelMargin,
  36339. bleedMargin: bleedMargin,
  36340. textRect: textRect,
  36341. text: text,
  36342. font: font
  36343. }; // Not layout the inside label
  36344. if (!isLabelInside) {
  36345. labelLayoutList.push(layout.label);
  36346. }
  36347. });
  36348. if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) {
  36349. avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight, viewLeft, viewTop);
  36350. }
  36351. };
  36352. /*
  36353. * Licensed to the Apache Software Foundation (ASF) under one
  36354. * or more contributor license agreements. See the NOTICE file
  36355. * distributed with this work for additional information
  36356. * regarding copyright ownership. The ASF licenses this file
  36357. * to you under the Apache License, Version 2.0 (the
  36358. * "License"); you may not use this file except in compliance
  36359. * with the License. You may obtain a copy of the License at
  36360. *
  36361. * http://www.apache.org/licenses/LICENSE-2.0
  36362. *
  36363. * Unless required by applicable law or agreed to in writing,
  36364. * software distributed under the License is distributed on an
  36365. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36366. * KIND, either express or implied. See the License for the
  36367. * specific language governing permissions and limitations
  36368. * under the License.
  36369. */
  36370. var PI2$4 = Math.PI * 2;
  36371. var RADIAN = Math.PI / 180;
  36372. function getViewRect(seriesModel, api) {
  36373. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  36374. width: api.getWidth(),
  36375. height: api.getHeight()
  36376. });
  36377. }
  36378. var pieLayout = function (seriesType, ecModel, api, payload) {
  36379. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  36380. var data = seriesModel.getData();
  36381. var valueDim = data.mapDimension('value');
  36382. var viewRect = getViewRect(seriesModel, api);
  36383. var center = seriesModel.get('center');
  36384. var radius = seriesModel.get('radius');
  36385. if (!isArray(radius)) {
  36386. radius = [0, radius];
  36387. }
  36388. if (!isArray(center)) {
  36389. center = [center, center];
  36390. }
  36391. var width = parsePercent$1(viewRect.width, api.getWidth());
  36392. var height = parsePercent$1(viewRect.height, api.getHeight());
  36393. var size = Math.min(width, height);
  36394. var cx = parsePercent$1(center[0], width) + viewRect.x;
  36395. var cy = parsePercent$1(center[1], height) + viewRect.y;
  36396. var r0 = parsePercent$1(radius[0], size / 2);
  36397. var r = parsePercent$1(radius[1], size / 2);
  36398. var startAngle = -seriesModel.get('startAngle') * RADIAN;
  36399. var minAngle = seriesModel.get('minAngle') * RADIAN;
  36400. var validDataCount = 0;
  36401. data.each(valueDim, function (value) {
  36402. !isNaN(value) && validDataCount++;
  36403. });
  36404. var sum = data.getSum(valueDim); // Sum may be 0
  36405. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  36406. var clockwise = seriesModel.get('clockwise');
  36407. var roseType = seriesModel.get('roseType');
  36408. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max]
  36409. var extent = data.getDataExtent(valueDim);
  36410. extent[0] = 0; // In the case some sector angle is smaller than minAngle
  36411. var restAngle = PI2$4;
  36412. var valueSumLargerThanMinAngle = 0;
  36413. var currentAngle = startAngle;
  36414. var dir = clockwise ? 1 : -1;
  36415. data.each(valueDim, function (value, idx) {
  36416. var angle;
  36417. if (isNaN(value)) {
  36418. data.setItemLayout(idx, {
  36419. angle: NaN,
  36420. startAngle: NaN,
  36421. endAngle: NaN,
  36422. clockwise: clockwise,
  36423. cx: cx,
  36424. cy: cy,
  36425. r0: r0,
  36426. r: roseType ? NaN : r,
  36427. viewRect: viewRect
  36428. });
  36429. return;
  36430. } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样?
  36431. if (roseType !== 'area') {
  36432. angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  36433. } else {
  36434. angle = PI2$4 / validDataCount;
  36435. }
  36436. if (angle < minAngle) {
  36437. angle = minAngle;
  36438. restAngle -= minAngle;
  36439. } else {
  36440. valueSumLargerThanMinAngle += value;
  36441. }
  36442. var endAngle = currentAngle + dir * angle;
  36443. data.setItemLayout(idx, {
  36444. angle: angle,
  36445. startAngle: currentAngle,
  36446. endAngle: endAngle,
  36447. clockwise: clockwise,
  36448. cx: cx,
  36449. cy: cy,
  36450. r0: r0,
  36451. r: roseType ? linearMap(value, extent, [r0, r]) : r,
  36452. viewRect: viewRect
  36453. });
  36454. currentAngle = endAngle;
  36455. }); // Some sector is constrained by minAngle
  36456. // Rest sectors needs recalculate angle
  36457. if (restAngle < PI2$4 && validDataCount) {
  36458. // Average the angle if rest angle is not enough after all angles is
  36459. // Constrained by minAngle
  36460. if (restAngle <= 1e-3) {
  36461. var angle = PI2$4 / validDataCount;
  36462. data.each(valueDim, function (value, idx) {
  36463. if (!isNaN(value)) {
  36464. var layout = data.getItemLayout(idx);
  36465. layout.angle = angle;
  36466. layout.startAngle = startAngle + dir * idx * angle;
  36467. layout.endAngle = startAngle + dir * (idx + 1) * angle;
  36468. }
  36469. });
  36470. } else {
  36471. unitRadian = restAngle / valueSumLargerThanMinAngle;
  36472. currentAngle = startAngle;
  36473. data.each(valueDim, function (value, idx) {
  36474. if (!isNaN(value)) {
  36475. var layout = data.getItemLayout(idx);
  36476. var angle = layout.angle === minAngle ? minAngle : value * unitRadian;
  36477. layout.startAngle = currentAngle;
  36478. layout.endAngle = currentAngle + dir * angle;
  36479. currentAngle += dir * angle;
  36480. }
  36481. });
  36482. }
  36483. }
  36484. labelLayout(seriesModel, r, viewRect.width, viewRect.height, viewRect.x, viewRect.y);
  36485. });
  36486. };
  36487. /*
  36488. * Licensed to the Apache Software Foundation (ASF) under one
  36489. * or more contributor license agreements. See the NOTICE file
  36490. * distributed with this work for additional information
  36491. * regarding copyright ownership. The ASF licenses this file
  36492. * to you under the Apache License, Version 2.0 (the
  36493. * "License"); you may not use this file except in compliance
  36494. * with the License. You may obtain a copy of the License at
  36495. *
  36496. * http://www.apache.org/licenses/LICENSE-2.0
  36497. *
  36498. * Unless required by applicable law or agreed to in writing,
  36499. * software distributed under the License is distributed on an
  36500. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36501. * KIND, either express or implied. See the License for the
  36502. * specific language governing permissions and limitations
  36503. * under the License.
  36504. */
  36505. var dataFilter = function (seriesType) {
  36506. return {
  36507. seriesType: seriesType,
  36508. reset: function (seriesModel, ecModel) {
  36509. var legendModels = ecModel.findComponents({
  36510. mainType: 'legend'
  36511. });
  36512. if (!legendModels || !legendModels.length) {
  36513. return;
  36514. }
  36515. var data = seriesModel.getData();
  36516. data.filterSelf(function (idx) {
  36517. var name = data.getName(idx); // If in any legend component the status is not selected.
  36518. for (var i = 0; i < legendModels.length; i++) {
  36519. if (!legendModels[i].isSelected(name)) {
  36520. return false;
  36521. }
  36522. }
  36523. return true;
  36524. });
  36525. }
  36526. };
  36527. };
  36528. /*
  36529. * Licensed to the Apache Software Foundation (ASF) under one
  36530. * or more contributor license agreements. See the NOTICE file
  36531. * distributed with this work for additional information
  36532. * regarding copyright ownership. The ASF licenses this file
  36533. * to you under the Apache License, Version 2.0 (the
  36534. * "License"); you may not use this file except in compliance
  36535. * with the License. You may obtain a copy of the License at
  36536. *
  36537. * http://www.apache.org/licenses/LICENSE-2.0
  36538. *
  36539. * Unless required by applicable law or agreed to in writing,
  36540. * software distributed under the License is distributed on an
  36541. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36542. * KIND, either express or implied. See the License for the
  36543. * specific language governing permissions and limitations
  36544. * under the License.
  36545. */
  36546. createDataSelectAction('pie', [{
  36547. type: 'pieToggleSelect',
  36548. event: 'pieselectchanged',
  36549. method: 'toggleSelected'
  36550. }, {
  36551. type: 'pieSelect',
  36552. event: 'pieselected',
  36553. method: 'select'
  36554. }, {
  36555. type: 'pieUnSelect',
  36556. event: 'pieunselected',
  36557. method: 'unSelect'
  36558. }]);
  36559. registerVisual(dataColor('pie'));
  36560. registerLayout(curry(pieLayout, 'pie'));
  36561. registerProcessor(dataFilter('pie'));
  36562. /*
  36563. * Licensed to the Apache Software Foundation (ASF) under one
  36564. * or more contributor license agreements. See the NOTICE file
  36565. * distributed with this work for additional information
  36566. * regarding copyright ownership. The ASF licenses this file
  36567. * to you under the Apache License, Version 2.0 (the
  36568. * "License"); you may not use this file except in compliance
  36569. * with the License. You may obtain a copy of the License at
  36570. *
  36571. * http://www.apache.org/licenses/LICENSE-2.0
  36572. *
  36573. * Unless required by applicable law or agreed to in writing,
  36574. * software distributed under the License is distributed on an
  36575. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36576. * KIND, either express or implied. See the License for the
  36577. * specific language governing permissions and limitations
  36578. * under the License.
  36579. */
  36580. SeriesModel.extend({
  36581. type: 'series.scatter',
  36582. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  36583. getInitialData: function (option, ecModel) {
  36584. return createListFromArray(this.getSource(), this, {
  36585. useEncodeDefaulter: true
  36586. });
  36587. },
  36588. brushSelector: 'point',
  36589. getProgressive: function () {
  36590. var progressive = this.option.progressive;
  36591. if (progressive == null) {
  36592. // PENDING
  36593. return this.option.large ? 5e3 : this.get('progressive');
  36594. }
  36595. return progressive;
  36596. },
  36597. getProgressiveThreshold: function () {
  36598. var progressiveThreshold = this.option.progressiveThreshold;
  36599. if (progressiveThreshold == null) {
  36600. // PENDING
  36601. return this.option.large ? 1e4 : this.get('progressiveThreshold');
  36602. }
  36603. return progressiveThreshold;
  36604. },
  36605. defaultOption: {
  36606. coordinateSystem: 'cartesian2d',
  36607. zlevel: 0,
  36608. z: 2,
  36609. legendHoverLink: true,
  36610. hoverAnimation: true,
  36611. // Cartesian coordinate system
  36612. // xAxisIndex: 0,
  36613. // yAxisIndex: 0,
  36614. // Polar coordinate system
  36615. // polarIndex: 0,
  36616. // Geo coordinate system
  36617. // geoIndex: 0,
  36618. // symbol: null, // 图形类型
  36619. symbolSize: 10,
  36620. // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  36621. // symbolRotate: null, // 图形旋转控制
  36622. large: false,
  36623. // Available when large is true
  36624. largeThreshold: 2000,
  36625. // cursor: null,
  36626. // label: {
  36627. // show: false
  36628. // distance: 5,
  36629. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  36630. // position: 默认自适应,水平布局为'top',垂直布局为'right',可选为
  36631. // 'inside'|'left'|'right'|'top'|'bottom'
  36632. // 默认使用全局文本样式,详见TEXTSTYLE
  36633. // },
  36634. itemStyle: {
  36635. opacity: 0.8 // color: 各异
  36636. },
  36637. // If clip the overflow graphics
  36638. // Works on cartesian / polar series
  36639. clip: true // progressive: null
  36640. }
  36641. });
  36642. /*
  36643. * Licensed to the Apache Software Foundation (ASF) under one
  36644. * or more contributor license agreements. See the NOTICE file
  36645. * distributed with this work for additional information
  36646. * regarding copyright ownership. The ASF licenses this file
  36647. * to you under the Apache License, Version 2.0 (the
  36648. * "License"); you may not use this file except in compliance
  36649. * with the License. You may obtain a copy of the License at
  36650. *
  36651. * http://www.apache.org/licenses/LICENSE-2.0
  36652. *
  36653. * Unless required by applicable law or agreed to in writing,
  36654. * software distributed under the License is distributed on an
  36655. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36656. * KIND, either express or implied. See the License for the
  36657. * specific language governing permissions and limitations
  36658. * under the License.
  36659. */
  36660. /* global Float32Array */
  36661. // TODO Batch by color
  36662. var BOOST_SIZE_THRESHOLD = 4;
  36663. var LargeSymbolPath = extendShape({
  36664. shape: {
  36665. points: null
  36666. },
  36667. symbolProxy: null,
  36668. softClipShape: null,
  36669. buildPath: function (path, shape) {
  36670. var points = shape.points;
  36671. var size = shape.size;
  36672. var symbolProxy = this.symbolProxy;
  36673. var symbolProxyShape = symbolProxy.shape;
  36674. var ctx = path.getContext ? path.getContext() : path;
  36675. var canBoost = ctx && size[0] < BOOST_SIZE_THRESHOLD; // Do draw in afterBrush.
  36676. if (canBoost) {
  36677. return;
  36678. }
  36679. for (var i = 0; i < points.length;) {
  36680. var x = points[i++];
  36681. var y = points[i++];
  36682. if (isNaN(x) || isNaN(y)) {
  36683. continue;
  36684. }
  36685. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  36686. continue;
  36687. }
  36688. symbolProxyShape.x = x - size[0] / 2;
  36689. symbolProxyShape.y = y - size[1] / 2;
  36690. symbolProxyShape.width = size[0];
  36691. symbolProxyShape.height = size[1];
  36692. symbolProxy.buildPath(path, symbolProxyShape, true);
  36693. }
  36694. },
  36695. afterBrush: function (ctx) {
  36696. var shape = this.shape;
  36697. var points = shape.points;
  36698. var size = shape.size;
  36699. var canBoost = size[0] < BOOST_SIZE_THRESHOLD;
  36700. if (!canBoost) {
  36701. return;
  36702. }
  36703. this.setTransform(ctx); // PENDING If style or other canvas status changed?
  36704. for (var i = 0; i < points.length;) {
  36705. var x = points[i++];
  36706. var y = points[i++];
  36707. if (isNaN(x) || isNaN(y)) {
  36708. continue;
  36709. }
  36710. if (this.softClipShape && !this.softClipShape.contain(x, y)) {
  36711. continue;
  36712. } // fillRect is faster than building a rect path and draw.
  36713. // And it support light globalCompositeOperation.
  36714. ctx.fillRect(x - size[0] / 2, y - size[1] / 2, size[0], size[1]);
  36715. }
  36716. this.restoreTransform(ctx);
  36717. },
  36718. findDataIndex: function (x, y) {
  36719. // TODO ???
  36720. // Consider transform
  36721. var shape = this.shape;
  36722. var points = shape.points;
  36723. var size = shape.size;
  36724. var w = Math.max(size[0], 4);
  36725. var h = Math.max(size[1], 4); // Not consider transform
  36726. // Treat each element as a rect
  36727. // top down traverse
  36728. for (var idx = points.length / 2 - 1; idx >= 0; idx--) {
  36729. var i = idx * 2;
  36730. var x0 = points[i] - w / 2;
  36731. var y0 = points[i + 1] - h / 2;
  36732. if (x >= x0 && y >= y0 && x <= x0 + w && y <= y0 + h) {
  36733. return idx;
  36734. }
  36735. }
  36736. return -1;
  36737. }
  36738. });
  36739. function LargeSymbolDraw() {
  36740. this.group = new Group();
  36741. }
  36742. var largeSymbolProto = LargeSymbolDraw.prototype;
  36743. largeSymbolProto.isPersistent = function () {
  36744. return !this._incremental;
  36745. };
  36746. /**
  36747. * Update symbols draw by new data
  36748. * @param {module:echarts/data/List} data
  36749. * @param {Object} opt
  36750. * @param {Object} [opt.clipShape]
  36751. */
  36752. largeSymbolProto.updateData = function (data, opt) {
  36753. this.group.removeAll();
  36754. var symbolEl = new LargeSymbolPath({
  36755. rectHover: true,
  36756. cursor: 'default'
  36757. });
  36758. symbolEl.setShape({
  36759. points: data.getLayout('symbolPoints')
  36760. });
  36761. this._setCommon(symbolEl, data, false, opt);
  36762. this.group.add(symbolEl);
  36763. this._incremental = null;
  36764. };
  36765. largeSymbolProto.updateLayout = function (data) {
  36766. if (this._incremental) {
  36767. return;
  36768. }
  36769. var points = data.getLayout('symbolPoints');
  36770. this.group.eachChild(function (child) {
  36771. if (child.startIndex != null) {
  36772. var len = (child.endIndex - child.startIndex) * 2;
  36773. var byteOffset = child.startIndex * 4 * 2;
  36774. points = new Float32Array(points.buffer, byteOffset, len);
  36775. }
  36776. child.setShape('points', points);
  36777. });
  36778. };
  36779. largeSymbolProto.incrementalPrepareUpdate = function (data) {
  36780. this.group.removeAll();
  36781. this._clearIncremental(); // Only use incremental displayables when data amount is larger than 2 million.
  36782. // PENDING Incremental data?
  36783. if (data.count() > 2e6) {
  36784. if (!this._incremental) {
  36785. this._incremental = new IncrementalDisplayble({
  36786. silent: true
  36787. });
  36788. }
  36789. this.group.add(this._incremental);
  36790. } else {
  36791. this._incremental = null;
  36792. }
  36793. };
  36794. largeSymbolProto.incrementalUpdate = function (taskParams, data, opt) {
  36795. var symbolEl;
  36796. if (this._incremental) {
  36797. symbolEl = new LargeSymbolPath();
  36798. this._incremental.addDisplayable(symbolEl, true);
  36799. } else {
  36800. symbolEl = new LargeSymbolPath({
  36801. rectHover: true,
  36802. cursor: 'default',
  36803. startIndex: taskParams.start,
  36804. endIndex: taskParams.end
  36805. });
  36806. symbolEl.incremental = true;
  36807. this.group.add(symbolEl);
  36808. }
  36809. symbolEl.setShape({
  36810. points: data.getLayout('symbolPoints')
  36811. });
  36812. this._setCommon(symbolEl, data, !!this._incremental, opt);
  36813. };
  36814. largeSymbolProto._setCommon = function (symbolEl, data, isIncremental, opt) {
  36815. var hostModel = data.hostModel;
  36816. opt = opt || {}; // TODO
  36817. // if (data.hasItemVisual.symbolSize) {
  36818. // // TODO typed array?
  36819. // symbolEl.setShape('sizes', data.mapArray(
  36820. // function (idx) {
  36821. // var size = data.getItemVisual(idx, 'symbolSize');
  36822. // return (size instanceof Array) ? size : [size, size];
  36823. // }
  36824. // ));
  36825. // }
  36826. // else {
  36827. var size = data.getVisual('symbolSize');
  36828. symbolEl.setShape('size', size instanceof Array ? size : [size, size]); // }
  36829. symbolEl.softClipShape = opt.clipShape || null; // Create symbolProxy to build path for each data
  36830. symbolEl.symbolProxy = createSymbol(data.getVisual('symbol'), 0, 0, 0, 0); // Use symbolProxy setColor method
  36831. symbolEl.setColor = symbolEl.symbolProxy.setColor;
  36832. var extrudeShadow = symbolEl.shape.size[0] < BOOST_SIZE_THRESHOLD;
  36833. symbolEl.useStyle( // Draw shadow when doing fillRect is extremely slow.
  36834. hostModel.getModel('itemStyle').getItemStyle(extrudeShadow ? ['color', 'shadowBlur', 'shadowColor'] : ['color']));
  36835. var visualColor = data.getVisual('color');
  36836. if (visualColor) {
  36837. symbolEl.setColor(visualColor);
  36838. }
  36839. if (!isIncremental) {
  36840. // Enable tooltip
  36841. // PENDING May have performance issue when path is extremely large
  36842. symbolEl.seriesIndex = hostModel.seriesIndex;
  36843. symbolEl.on('mousemove', function (e) {
  36844. symbolEl.dataIndex = null;
  36845. var dataIndex = symbolEl.findDataIndex(e.offsetX, e.offsetY);
  36846. if (dataIndex >= 0) {
  36847. // Provide dataIndex for tooltip
  36848. symbolEl.dataIndex = dataIndex + (symbolEl.startIndex || 0);
  36849. }
  36850. });
  36851. }
  36852. };
  36853. largeSymbolProto.remove = function () {
  36854. this._clearIncremental();
  36855. this._incremental = null;
  36856. this.group.removeAll();
  36857. };
  36858. largeSymbolProto._clearIncremental = function () {
  36859. var incremental = this._incremental;
  36860. if (incremental) {
  36861. incremental.clearDisplaybles();
  36862. }
  36863. };
  36864. /*
  36865. * Licensed to the Apache Software Foundation (ASF) under one
  36866. * or more contributor license agreements. See the NOTICE file
  36867. * distributed with this work for additional information
  36868. * regarding copyright ownership. The ASF licenses this file
  36869. * to you under the Apache License, Version 2.0 (the
  36870. * "License"); you may not use this file except in compliance
  36871. * with the License. You may obtain a copy of the License at
  36872. *
  36873. * http://www.apache.org/licenses/LICENSE-2.0
  36874. *
  36875. * Unless required by applicable law or agreed to in writing,
  36876. * software distributed under the License is distributed on an
  36877. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36878. * KIND, either express or implied. See the License for the
  36879. * specific language governing permissions and limitations
  36880. * under the License.
  36881. */
  36882. extendChartView({
  36883. type: 'scatter',
  36884. render: function (seriesModel, ecModel, api) {
  36885. var data = seriesModel.getData();
  36886. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36887. symbolDraw.updateData(data, {
  36888. // TODO
  36889. // If this parameter should be a shape or a bounding volume
  36890. // shape will be more general.
  36891. // But bounding volume like bounding rect will be much faster in the contain calculation
  36892. clipShape: this._getClipShape(seriesModel)
  36893. });
  36894. this._finished = true;
  36895. },
  36896. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  36897. var data = seriesModel.getData();
  36898. var symbolDraw = this._updateSymbolDraw(data, seriesModel);
  36899. symbolDraw.incrementalPrepareUpdate(data);
  36900. this._finished = false;
  36901. },
  36902. incrementalRender: function (taskParams, seriesModel, ecModel) {
  36903. this._symbolDraw.incrementalUpdate(taskParams, seriesModel.getData(), {
  36904. clipShape: this._getClipShape(seriesModel)
  36905. });
  36906. this._finished = taskParams.end === seriesModel.getData().count();
  36907. },
  36908. updateTransform: function (seriesModel, ecModel, api) {
  36909. var data = seriesModel.getData(); // Must mark group dirty and make sure the incremental layer will be cleared
  36910. // PENDING
  36911. this.group.dirty();
  36912. if (!this._finished || data.count() > 1e4 || !this._symbolDraw.isPersistent()) {
  36913. return {
  36914. update: true
  36915. };
  36916. } else {
  36917. var res = pointsLayout().reset(seriesModel);
  36918. if (res.progress) {
  36919. res.progress({
  36920. start: 0,
  36921. end: data.count()
  36922. }, data);
  36923. }
  36924. this._symbolDraw.updateLayout(data);
  36925. }
  36926. },
  36927. _getClipShape: function (seriesModel) {
  36928. var coordSys = seriesModel.coordinateSystem;
  36929. var clipArea = coordSys && coordSys.getArea && coordSys.getArea();
  36930. return seriesModel.get('clip', true) ? clipArea : null;
  36931. },
  36932. _updateSymbolDraw: function (data, seriesModel) {
  36933. var symbolDraw = this._symbolDraw;
  36934. var pipelineContext = seriesModel.pipelineContext;
  36935. var isLargeDraw = pipelineContext.large;
  36936. if (!symbolDraw || isLargeDraw !== this._isLargeDraw) {
  36937. symbolDraw && symbolDraw.remove();
  36938. symbolDraw = this._symbolDraw = isLargeDraw ? new LargeSymbolDraw() : new SymbolDraw();
  36939. this._isLargeDraw = isLargeDraw;
  36940. this.group.removeAll();
  36941. }
  36942. this.group.add(symbolDraw.group);
  36943. return symbolDraw;
  36944. },
  36945. remove: function (ecModel, api) {
  36946. this._symbolDraw && this._symbolDraw.remove(true);
  36947. this._symbolDraw = null;
  36948. },
  36949. dispose: function () {}
  36950. });
  36951. /*
  36952. * Licensed to the Apache Software Foundation (ASF) under one
  36953. * or more contributor license agreements. See the NOTICE file
  36954. * distributed with this work for additional information
  36955. * regarding copyright ownership. The ASF licenses this file
  36956. * to you under the Apache License, Version 2.0 (the
  36957. * "License"); you may not use this file except in compliance
  36958. * with the License. You may obtain a copy of the License at
  36959. *
  36960. * http://www.apache.org/licenses/LICENSE-2.0
  36961. *
  36962. * Unless required by applicable law or agreed to in writing,
  36963. * software distributed under the License is distributed on an
  36964. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  36965. * KIND, either express or implied. See the License for the
  36966. * specific language governing permissions and limitations
  36967. * under the License.
  36968. */
  36969. registerVisual(visualSymbol('scatter', 'circle'));
  36970. registerLayout(pointsLayout('scatter')); // echarts.registerProcessor(function (ecModel, api) {
  36971. // ecModel.eachSeriesByType('scatter', function (seriesModel) {
  36972. // var data = seriesModel.getData();
  36973. // var coordSys = seriesModel.coordinateSystem;
  36974. // if (coordSys.type !== 'geo') {
  36975. // return;
  36976. // }
  36977. // var startPt = coordSys.pointToData([0, 0]);
  36978. // var endPt = coordSys.pointToData([api.getWidth(), api.getHeight()]);
  36979. // var dims = zrUtil.map(coordSys.dimensions, function (dim) {
  36980. // return data.mapDimension(dim);
  36981. // });
  36982. // var range = {};
  36983. // range[dims[0]] = [Math.min(startPt[0], endPt[0]), Math.max(startPt[0], endPt[0])];
  36984. // range[dims[1]] = [Math.min(startPt[1], endPt[1]), Math.max(startPt[1], endPt[1])];
  36985. // data.selectRange(range);
  36986. // });
  36987. // });
  36988. /*
  36989. * Licensed to the Apache Software Foundation (ASF) under one
  36990. * or more contributor license agreements. See the NOTICE file
  36991. * distributed with this work for additional information
  36992. * regarding copyright ownership. The ASF licenses this file
  36993. * to you under the Apache License, Version 2.0 (the
  36994. * "License"); you may not use this file except in compliance
  36995. * with the License. You may obtain a copy of the License at
  36996. *
  36997. * http://www.apache.org/licenses/LICENSE-2.0
  36998. *
  36999. * Unless required by applicable law or agreed to in writing,
  37000. * software distributed under the License is distributed on an
  37001. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37002. * KIND, either express or implied. See the License for the
  37003. * specific language governing permissions and limitations
  37004. * under the License.
  37005. */
  37006. SeriesModel.extend({
  37007. type: 'series.effectScatter',
  37008. dependencies: ['grid', 'polar'],
  37009. getInitialData: function (option, ecModel) {
  37010. return createListFromArray(this.getSource(), this, {
  37011. useEncodeDefaulter: true
  37012. });
  37013. },
  37014. brushSelector: 'point',
  37015. defaultOption: {
  37016. coordinateSystem: 'cartesian2d',
  37017. zlevel: 0,
  37018. z: 2,
  37019. legendHoverLink: true,
  37020. effectType: 'ripple',
  37021. progressive: 0,
  37022. // When to show the effect, option: 'render'|'emphasis'
  37023. showEffectOn: 'render',
  37024. // Ripple effect config
  37025. rippleEffect: {
  37026. period: 4,
  37027. // Scale of ripple
  37028. scale: 2.5,
  37029. // Brush type can be fill or stroke
  37030. brushType: 'fill'
  37031. },
  37032. // Cartesian coordinate system
  37033. // xAxisIndex: 0,
  37034. // yAxisIndex: 0,
  37035. // Polar coordinate system
  37036. // polarIndex: 0,
  37037. // Geo coordinate system
  37038. // geoIndex: 0,
  37039. // symbol: null, // 图形类型
  37040. symbolSize: 10 // 图形大小,半宽(半径)参数,当图形为方向或菱形则总宽度为symbolSize * 2
  37041. // symbolRotate: null, // 图形旋转控制
  37042. // large: false,
  37043. // Available when large is true
  37044. // largeThreshold: 2000,
  37045. // itemStyle: {
  37046. // opacity: 1
  37047. // }
  37048. }
  37049. });
  37050. /*
  37051. * Licensed to the Apache Software Foundation (ASF) under one
  37052. * or more contributor license agreements. See the NOTICE file
  37053. * distributed with this work for additional information
  37054. * regarding copyright ownership. The ASF licenses this file
  37055. * to you under the Apache License, Version 2.0 (the
  37056. * "License"); you may not use this file except in compliance
  37057. * with the License. You may obtain a copy of the License at
  37058. *
  37059. * http://www.apache.org/licenses/LICENSE-2.0
  37060. *
  37061. * Unless required by applicable law or agreed to in writing,
  37062. * software distributed under the License is distributed on an
  37063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37064. * KIND, either express or implied. See the License for the
  37065. * specific language governing permissions and limitations
  37066. * under the License.
  37067. */
  37068. /**
  37069. * Symbol with ripple effect
  37070. * @module echarts/chart/helper/EffectSymbol
  37071. */
  37072. var EFFECT_RIPPLE_NUMBER = 3;
  37073. function normalizeSymbolSize(symbolSize) {
  37074. if (!isArray(symbolSize)) {
  37075. symbolSize = [+symbolSize, +symbolSize];
  37076. }
  37077. return symbolSize;
  37078. }
  37079. function updateRipplePath(rippleGroup, effectCfg) {
  37080. var color = effectCfg.rippleEffectColor || effectCfg.color;
  37081. rippleGroup.eachChild(function (ripplePath) {
  37082. ripplePath.attr({
  37083. z: effectCfg.z,
  37084. zlevel: effectCfg.zlevel,
  37085. style: {
  37086. stroke: effectCfg.brushType === 'stroke' ? color : null,
  37087. fill: effectCfg.brushType === 'fill' ? color : null
  37088. }
  37089. });
  37090. });
  37091. }
  37092. /**
  37093. * @constructor
  37094. * @param {module:echarts/data/List} data
  37095. * @param {number} idx
  37096. * @extends {module:zrender/graphic/Group}
  37097. */
  37098. function EffectSymbol(data, idx) {
  37099. Group.call(this);
  37100. var symbol = new SymbolClz$1(data, idx);
  37101. var rippleGroup = new Group();
  37102. this.add(symbol);
  37103. this.add(rippleGroup);
  37104. rippleGroup.beforeUpdate = function () {
  37105. this.attr(symbol.getScale());
  37106. };
  37107. this.updateData(data, idx);
  37108. }
  37109. var effectSymbolProto = EffectSymbol.prototype;
  37110. effectSymbolProto.stopEffectAnimation = function () {
  37111. this.childAt(1).removeAll();
  37112. };
  37113. effectSymbolProto.startEffectAnimation = function (effectCfg) {
  37114. var symbolType = effectCfg.symbolType;
  37115. var color = effectCfg.color;
  37116. var rippleGroup = this.childAt(1);
  37117. for (var i = 0; i < EFFECT_RIPPLE_NUMBER; i++) {
  37118. // If width/height are set too small (e.g., set to 1) on ios10
  37119. // and macOS Sierra, a circle stroke become a rect, no matter what
  37120. // the scale is set. So we set width/height as 2. See #4136.
  37121. var ripplePath = createSymbol(symbolType, -1, -1, 2, 2, color);
  37122. ripplePath.attr({
  37123. style: {
  37124. strokeNoScale: true
  37125. },
  37126. z2: 99,
  37127. silent: true,
  37128. scale: [0.5, 0.5]
  37129. });
  37130. var delay = -i / EFFECT_RIPPLE_NUMBER * effectCfg.period + effectCfg.effectOffset; // TODO Configurable effectCfg.period
  37131. ripplePath.animate('', true).when(effectCfg.period, {
  37132. scale: [effectCfg.rippleScale / 2, effectCfg.rippleScale / 2]
  37133. }).delay(delay).start();
  37134. ripplePath.animateStyle(true).when(effectCfg.period, {
  37135. opacity: 0
  37136. }).delay(delay).start();
  37137. rippleGroup.add(ripplePath);
  37138. }
  37139. updateRipplePath(rippleGroup, effectCfg);
  37140. };
  37141. /**
  37142. * Update effect symbol
  37143. */
  37144. effectSymbolProto.updateEffectAnimation = function (effectCfg) {
  37145. var oldEffectCfg = this._effectCfg;
  37146. var rippleGroup = this.childAt(1); // Must reinitialize effect if following configuration changed
  37147. var DIFFICULT_PROPS = ['symbolType', 'period', 'rippleScale'];
  37148. for (var i = 0; i < DIFFICULT_PROPS.length; i++) {
  37149. var propName = DIFFICULT_PROPS[i];
  37150. if (oldEffectCfg[propName] !== effectCfg[propName]) {
  37151. this.stopEffectAnimation();
  37152. this.startEffectAnimation(effectCfg);
  37153. return;
  37154. }
  37155. }
  37156. updateRipplePath(rippleGroup, effectCfg);
  37157. };
  37158. /**
  37159. * Highlight symbol
  37160. */
  37161. effectSymbolProto.highlight = function () {
  37162. this.trigger('emphasis');
  37163. };
  37164. /**
  37165. * Downplay symbol
  37166. */
  37167. effectSymbolProto.downplay = function () {
  37168. this.trigger('normal');
  37169. };
  37170. /**
  37171. * Update symbol properties
  37172. * @param {module:echarts/data/List} data
  37173. * @param {number} idx
  37174. */
  37175. effectSymbolProto.updateData = function (data, idx) {
  37176. var seriesModel = data.hostModel;
  37177. this.childAt(0).updateData(data, idx);
  37178. var rippleGroup = this.childAt(1);
  37179. var itemModel = data.getItemModel(idx);
  37180. var symbolType = data.getItemVisual(idx, 'symbol');
  37181. var symbolSize = normalizeSymbolSize(data.getItemVisual(idx, 'symbolSize'));
  37182. var color = data.getItemVisual(idx, 'color');
  37183. rippleGroup.attr('scale', symbolSize);
  37184. rippleGroup.traverse(function (ripplePath) {
  37185. ripplePath.attr({
  37186. fill: color
  37187. });
  37188. });
  37189. var symbolOffset = itemModel.getShallow('symbolOffset');
  37190. if (symbolOffset) {
  37191. var pos = rippleGroup.position;
  37192. pos[0] = parsePercent$1(symbolOffset[0], symbolSize[0]);
  37193. pos[1] = parsePercent$1(symbolOffset[1], symbolSize[1]);
  37194. }
  37195. var symbolRotate = data.getItemVisual(idx, 'symbolRotate');
  37196. rippleGroup.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  37197. var effectCfg = {};
  37198. effectCfg.showEffectOn = seriesModel.get('showEffectOn');
  37199. effectCfg.rippleScale = itemModel.get('rippleEffect.scale');
  37200. effectCfg.brushType = itemModel.get('rippleEffect.brushType');
  37201. effectCfg.period = itemModel.get('rippleEffect.period') * 1000;
  37202. effectCfg.effectOffset = idx / data.count();
  37203. effectCfg.z = itemModel.getShallow('z') || 0;
  37204. effectCfg.zlevel = itemModel.getShallow('zlevel') || 0;
  37205. effectCfg.symbolType = symbolType;
  37206. effectCfg.color = color;
  37207. effectCfg.rippleEffectColor = itemModel.get('rippleEffect.color');
  37208. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  37209. if (effectCfg.showEffectOn === 'render') {
  37210. this._effectCfg ? this.updateEffectAnimation(effectCfg) : this.startEffectAnimation(effectCfg);
  37211. this._effectCfg = effectCfg;
  37212. } else {
  37213. // Not keep old effect config
  37214. this._effectCfg = null;
  37215. this.stopEffectAnimation();
  37216. var symbol = this.childAt(0);
  37217. var onEmphasis = function () {
  37218. symbol.highlight();
  37219. if (effectCfg.showEffectOn !== 'render') {
  37220. this.startEffectAnimation(effectCfg);
  37221. }
  37222. };
  37223. var onNormal = function () {
  37224. symbol.downplay();
  37225. if (effectCfg.showEffectOn !== 'render') {
  37226. this.stopEffectAnimation();
  37227. }
  37228. };
  37229. this.on('mouseover', onEmphasis, this).on('mouseout', onNormal, this).on('emphasis', onEmphasis, this).on('normal', onNormal, this);
  37230. }
  37231. this._effectCfg = effectCfg;
  37232. };
  37233. effectSymbolProto.fadeOut = function (cb) {
  37234. this.off('mouseover').off('mouseout').off('emphasis').off('normal');
  37235. cb && cb();
  37236. };
  37237. inherits(EffectSymbol, Group);
  37238. /*
  37239. * Licensed to the Apache Software Foundation (ASF) under one
  37240. * or more contributor license agreements. See the NOTICE file
  37241. * distributed with this work for additional information
  37242. * regarding copyright ownership. The ASF licenses this file
  37243. * to you under the Apache License, Version 2.0 (the
  37244. * "License"); you may not use this file except in compliance
  37245. * with the License. You may obtain a copy of the License at
  37246. *
  37247. * http://www.apache.org/licenses/LICENSE-2.0
  37248. *
  37249. * Unless required by applicable law or agreed to in writing,
  37250. * software distributed under the License is distributed on an
  37251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37252. * KIND, either express or implied. See the License for the
  37253. * specific language governing permissions and limitations
  37254. * under the License.
  37255. */
  37256. extendChartView({
  37257. type: 'effectScatter',
  37258. init: function () {
  37259. this._symbolDraw = new SymbolDraw(EffectSymbol);
  37260. },
  37261. render: function (seriesModel, ecModel, api) {
  37262. var data = seriesModel.getData();
  37263. var effectSymbolDraw = this._symbolDraw;
  37264. effectSymbolDraw.updateData(data);
  37265. this.group.add(effectSymbolDraw.group);
  37266. },
  37267. updateTransform: function (seriesModel, ecModel, api) {
  37268. var data = seriesModel.getData();
  37269. this.group.dirty();
  37270. var res = pointsLayout().reset(seriesModel);
  37271. if (res.progress) {
  37272. res.progress({
  37273. start: 0,
  37274. end: data.count()
  37275. }, data);
  37276. }
  37277. this._symbolDraw.updateLayout(data);
  37278. },
  37279. _updateGroupTransform: function (seriesModel) {
  37280. var coordSys = seriesModel.coordinateSystem;
  37281. if (coordSys && coordSys.getRoamTransform) {
  37282. this.group.transform = clone$2(coordSys.getRoamTransform());
  37283. this.group.decomposeTransform();
  37284. }
  37285. },
  37286. remove: function (ecModel, api) {
  37287. this._symbolDraw && this._symbolDraw.remove(api);
  37288. },
  37289. dispose: function () {}
  37290. });
  37291. /*
  37292. * Licensed to the Apache Software Foundation (ASF) under one
  37293. * or more contributor license agreements. See the NOTICE file
  37294. * distributed with this work for additional information
  37295. * regarding copyright ownership. The ASF licenses this file
  37296. * to you under the Apache License, Version 2.0 (the
  37297. * "License"); you may not use this file except in compliance
  37298. * with the License. You may obtain a copy of the License at
  37299. *
  37300. * http://www.apache.org/licenses/LICENSE-2.0
  37301. *
  37302. * Unless required by applicable law or agreed to in writing,
  37303. * software distributed under the License is distributed on an
  37304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37305. * KIND, either express or implied. See the License for the
  37306. * specific language governing permissions and limitations
  37307. * under the License.
  37308. */
  37309. registerVisual(visualSymbol('effectScatter', 'circle'));
  37310. registerLayout(pointsLayout('effectScatter'));
  37311. /*
  37312. * Licensed to the Apache Software Foundation (ASF) under one
  37313. * or more contributor license agreements. See the NOTICE file
  37314. * distributed with this work for additional information
  37315. * regarding copyright ownership. The ASF licenses this file
  37316. * to you under the Apache License, Version 2.0 (the
  37317. * "License"); you may not use this file except in compliance
  37318. * with the License. You may obtain a copy of the License at
  37319. *
  37320. * http://www.apache.org/licenses/LICENSE-2.0
  37321. *
  37322. * Unless required by applicable law or agreed to in writing,
  37323. * software distributed under the License is distributed on an
  37324. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37325. * KIND, either express or implied. See the License for the
  37326. * specific language governing permissions and limitations
  37327. * under the License.
  37328. */
  37329. var seriesModelMixin = {
  37330. /**
  37331. * @private
  37332. * @type {string}
  37333. */
  37334. _baseAxisDim: null,
  37335. /**
  37336. * @override
  37337. */
  37338. getInitialData: function (option, ecModel) {
  37339. // When both types of xAxis and yAxis are 'value', layout is
  37340. // needed to be specified by user. Otherwise, layout can be
  37341. // judged by which axis is category.
  37342. var ordinalMeta;
  37343. var xAxisModel = ecModel.getComponent('xAxis', this.get('xAxisIndex'));
  37344. var yAxisModel = ecModel.getComponent('yAxis', this.get('yAxisIndex'));
  37345. var xAxisType = xAxisModel.get('type');
  37346. var yAxisType = yAxisModel.get('type');
  37347. var addOrdinal; // FIXME
  37348. // Consider time axis.
  37349. if (xAxisType === 'category') {
  37350. option.layout = 'horizontal';
  37351. ordinalMeta = xAxisModel.getOrdinalMeta();
  37352. addOrdinal = true;
  37353. } else if (yAxisType === 'category') {
  37354. option.layout = 'vertical';
  37355. ordinalMeta = yAxisModel.getOrdinalMeta();
  37356. addOrdinal = true;
  37357. } else {
  37358. option.layout = option.layout || 'horizontal';
  37359. }
  37360. var coordDims = ['x', 'y'];
  37361. var baseAxisDimIndex = option.layout === 'horizontal' ? 0 : 1;
  37362. var baseAxisDim = this._baseAxisDim = coordDims[baseAxisDimIndex];
  37363. var otherAxisDim = coordDims[1 - baseAxisDimIndex];
  37364. var axisModels = [xAxisModel, yAxisModel];
  37365. var baseAxisType = axisModels[baseAxisDimIndex].get('type');
  37366. var otherAxisType = axisModels[1 - baseAxisDimIndex].get('type');
  37367. var data = option.data; // ??? FIXME make a stage to perform data transfrom.
  37368. // MUST create a new data, consider setOption({}) again.
  37369. if (data && addOrdinal) {
  37370. var newOptionData = [];
  37371. each$1(data, function (item, index) {
  37372. var newItem;
  37373. if (item.value && isArray(item.value)) {
  37374. newItem = item.value.slice();
  37375. item.value.unshift(index);
  37376. } else if (isArray(item)) {
  37377. newItem = item.slice();
  37378. item.unshift(index);
  37379. } else {
  37380. newItem = item;
  37381. }
  37382. newOptionData.push(newItem);
  37383. });
  37384. option.data = newOptionData;
  37385. }
  37386. var defaultValueDimensions = this.defaultValueDimensions;
  37387. var coordDimensions = [{
  37388. name: baseAxisDim,
  37389. type: getDimensionTypeByAxis(baseAxisType),
  37390. ordinalMeta: ordinalMeta,
  37391. otherDims: {
  37392. tooltip: false,
  37393. itemName: 0
  37394. },
  37395. dimsDef: ['base']
  37396. }, {
  37397. name: otherAxisDim,
  37398. type: getDimensionTypeByAxis(otherAxisType),
  37399. dimsDef: defaultValueDimensions.slice()
  37400. }];
  37401. return createListSimply(this, {
  37402. coordDimensions: coordDimensions,
  37403. dimensionsCount: defaultValueDimensions.length + 1,
  37404. encodeDefaulter: curry(makeSeriesEncodeForAxisCoordSys, coordDimensions, this)
  37405. });
  37406. },
  37407. /**
  37408. * If horizontal, base axis is x, otherwise y.
  37409. * @override
  37410. */
  37411. getBaseAxis: function () {
  37412. var dim = this._baseAxisDim;
  37413. return this.ecModel.getComponent(dim + 'Axis', this.get(dim + 'AxisIndex')).axis;
  37414. }
  37415. };
  37416. /*
  37417. * Licensed to the Apache Software Foundation (ASF) under one
  37418. * or more contributor license agreements. See the NOTICE file
  37419. * distributed with this work for additional information
  37420. * regarding copyright ownership. The ASF licenses this file
  37421. * to you under the Apache License, Version 2.0 (the
  37422. * "License"); you may not use this file except in compliance
  37423. * with the License. You may obtain a copy of the License at
  37424. *
  37425. * http://www.apache.org/licenses/LICENSE-2.0
  37426. *
  37427. * Unless required by applicable law or agreed to in writing,
  37428. * software distributed under the License is distributed on an
  37429. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37430. * KIND, either express or implied. See the License for the
  37431. * specific language governing permissions and limitations
  37432. * under the License.
  37433. */
  37434. var CandlestickSeries = SeriesModel.extend({
  37435. type: 'series.candlestick',
  37436. dependencies: ['xAxis', 'yAxis', 'grid'],
  37437. /**
  37438. * @readOnly
  37439. */
  37440. defaultValueDimensions: [{
  37441. name: 'open',
  37442. defaultTooltip: true
  37443. }, {
  37444. name: 'close',
  37445. defaultTooltip: true
  37446. }, {
  37447. name: 'lowest',
  37448. defaultTooltip: true
  37449. }, {
  37450. name: 'highest',
  37451. defaultTooltip: true
  37452. }],
  37453. /**
  37454. * @type {Array.<string>}
  37455. * @readOnly
  37456. */
  37457. dimensions: null,
  37458. /**
  37459. * @override
  37460. */
  37461. defaultOption: {
  37462. zlevel: 0,
  37463. z: 2,
  37464. coordinateSystem: 'cartesian2d',
  37465. legendHoverLink: true,
  37466. hoverAnimation: true,
  37467. // xAxisIndex: 0,
  37468. // yAxisIndex: 0,
  37469. layout: null,
  37470. // 'horizontal' or 'vertical'
  37471. clip: true,
  37472. itemStyle: {
  37473. color: '#c23531',
  37474. // 阳线 positive
  37475. color0: '#314656',
  37476. // 阴线 negative '#c23531', '#314656'
  37477. borderWidth: 1,
  37478. // FIXME
  37479. // ec2中使用的是lineStyle.color 和 lineStyle.color0
  37480. borderColor: '#c23531',
  37481. borderColor0: '#314656'
  37482. },
  37483. emphasis: {
  37484. itemStyle: {
  37485. borderWidth: 2
  37486. }
  37487. },
  37488. barMaxWidth: null,
  37489. barMinWidth: null,
  37490. barWidth: null,
  37491. large: true,
  37492. largeThreshold: 600,
  37493. progressive: 3e3,
  37494. progressiveThreshold: 1e4,
  37495. progressiveChunkMode: 'mod',
  37496. animationUpdate: false,
  37497. animationEasing: 'linear',
  37498. animationDuration: 300
  37499. },
  37500. /**
  37501. * Get dimension for shadow in dataZoom
  37502. * @return {string} dimension name
  37503. */
  37504. getShadowDim: function () {
  37505. return 'open';
  37506. },
  37507. brushSelector: function (dataIndex, data, selectors) {
  37508. var itemLayout = data.getItemLayout(dataIndex);
  37509. return itemLayout && selectors.rect(itemLayout.brushRect);
  37510. }
  37511. });
  37512. mixin(CandlestickSeries, seriesModelMixin, true);
  37513. /*
  37514. * Licensed to the Apache Software Foundation (ASF) under one
  37515. * or more contributor license agreements. See the NOTICE file
  37516. * distributed with this work for additional information
  37517. * regarding copyright ownership. The ASF licenses this file
  37518. * to you under the Apache License, Version 2.0 (the
  37519. * "License"); you may not use this file except in compliance
  37520. * with the License. You may obtain a copy of the License at
  37521. *
  37522. * http://www.apache.org/licenses/LICENSE-2.0
  37523. *
  37524. * Unless required by applicable law or agreed to in writing,
  37525. * software distributed under the License is distributed on an
  37526. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37527. * KIND, either express or implied. See the License for the
  37528. * specific language governing permissions and limitations
  37529. * under the License.
  37530. */
  37531. var NORMAL_ITEM_STYLE_PATH = ['itemStyle'];
  37532. var EMPHASIS_ITEM_STYLE_PATH = ['emphasis', 'itemStyle'];
  37533. var SKIP_PROPS = ['color', 'color0', 'borderColor', 'borderColor0'];
  37534. var CandlestickView = Chart.extend({
  37535. type: 'candlestick',
  37536. render: function (seriesModel, ecModel, api) {
  37537. // If there is clipPath created in large mode. Remove it.
  37538. this.group.removeClipPath();
  37539. this._updateDrawMode(seriesModel);
  37540. this._isLargeDraw ? this._renderLarge(seriesModel) : this._renderNormal(seriesModel);
  37541. },
  37542. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  37543. this._clear();
  37544. this._updateDrawMode(seriesModel);
  37545. },
  37546. incrementalRender: function (params, seriesModel, ecModel, api) {
  37547. this._isLargeDraw ? this._incrementalRenderLarge(params, seriesModel) : this._incrementalRenderNormal(params, seriesModel);
  37548. },
  37549. _updateDrawMode: function (seriesModel) {
  37550. var isLargeDraw = seriesModel.pipelineContext.large;
  37551. if (this._isLargeDraw == null || isLargeDraw ^ this._isLargeDraw) {
  37552. this._isLargeDraw = isLargeDraw;
  37553. this._clear();
  37554. }
  37555. },
  37556. _renderNormal: function (seriesModel) {
  37557. var data = seriesModel.getData();
  37558. var oldData = this._data;
  37559. var group = this.group;
  37560. var isSimpleBox = data.getLayout('isSimpleBox');
  37561. var needsClip = seriesModel.get('clip', true);
  37562. var coord = seriesModel.coordinateSystem;
  37563. var clipArea = coord.getArea && coord.getArea(); // There is no old data only when first rendering or switching from
  37564. // stream mode to normal mode, where previous elements should be removed.
  37565. if (!this._data) {
  37566. group.removeAll();
  37567. }
  37568. data.diff(oldData).add(function (newIdx) {
  37569. if (data.hasValue(newIdx)) {
  37570. var el;
  37571. var itemLayout = data.getItemLayout(newIdx);
  37572. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  37573. return;
  37574. }
  37575. el = createNormalBox(itemLayout, newIdx, true);
  37576. initProps(el, {
  37577. shape: {
  37578. points: itemLayout.ends
  37579. }
  37580. }, seriesModel, newIdx);
  37581. setBoxCommon(el, data, newIdx, isSimpleBox);
  37582. group.add(el);
  37583. data.setItemGraphicEl(newIdx, el);
  37584. }
  37585. }).update(function (newIdx, oldIdx) {
  37586. var el = oldData.getItemGraphicEl(oldIdx); // Empty data
  37587. if (!data.hasValue(newIdx)) {
  37588. group.remove(el);
  37589. return;
  37590. }
  37591. var itemLayout = data.getItemLayout(newIdx);
  37592. if (needsClip && isNormalBoxClipped(clipArea, itemLayout)) {
  37593. group.remove(el);
  37594. return;
  37595. }
  37596. if (!el) {
  37597. el = createNormalBox(itemLayout, newIdx);
  37598. } else {
  37599. updateProps(el, {
  37600. shape: {
  37601. points: itemLayout.ends
  37602. }
  37603. }, seriesModel, newIdx);
  37604. }
  37605. setBoxCommon(el, data, newIdx, isSimpleBox);
  37606. group.add(el);
  37607. data.setItemGraphicEl(newIdx, el);
  37608. }).remove(function (oldIdx) {
  37609. var el = oldData.getItemGraphicEl(oldIdx);
  37610. el && group.remove(el);
  37611. }).execute();
  37612. this._data = data;
  37613. },
  37614. _renderLarge: function (seriesModel) {
  37615. this._clear();
  37616. createLarge$1(seriesModel, this.group);
  37617. var clipPath = seriesModel.get('clip', true) ? createClipPath(seriesModel.coordinateSystem, false, seriesModel) : null;
  37618. if (clipPath) {
  37619. this.group.setClipPath(clipPath);
  37620. } else {
  37621. this.group.removeClipPath();
  37622. }
  37623. },
  37624. _incrementalRenderNormal: function (params, seriesModel) {
  37625. var data = seriesModel.getData();
  37626. var isSimpleBox = data.getLayout('isSimpleBox');
  37627. var dataIndex;
  37628. while ((dataIndex = params.next()) != null) {
  37629. var el;
  37630. var itemLayout = data.getItemLayout(dataIndex);
  37631. el = createNormalBox(itemLayout, dataIndex);
  37632. setBoxCommon(el, data, dataIndex, isSimpleBox);
  37633. el.incremental = true;
  37634. this.group.add(el);
  37635. }
  37636. },
  37637. _incrementalRenderLarge: function (params, seriesModel) {
  37638. createLarge$1(seriesModel, this.group, true);
  37639. },
  37640. remove: function (ecModel) {
  37641. this._clear();
  37642. },
  37643. _clear: function () {
  37644. this.group.removeAll();
  37645. this._data = null;
  37646. },
  37647. dispose: noop
  37648. });
  37649. var NormalBoxPath = Path.extend({
  37650. type: 'normalCandlestickBox',
  37651. shape: {},
  37652. buildPath: function (ctx, shape) {
  37653. var ends = shape.points;
  37654. if (this.__simpleBox) {
  37655. ctx.moveTo(ends[4][0], ends[4][1]);
  37656. ctx.lineTo(ends[6][0], ends[6][1]);
  37657. } else {
  37658. ctx.moveTo(ends[0][0], ends[0][1]);
  37659. ctx.lineTo(ends[1][0], ends[1][1]);
  37660. ctx.lineTo(ends[2][0], ends[2][1]);
  37661. ctx.lineTo(ends[3][0], ends[3][1]);
  37662. ctx.closePath();
  37663. ctx.moveTo(ends[4][0], ends[4][1]);
  37664. ctx.lineTo(ends[5][0], ends[5][1]);
  37665. ctx.moveTo(ends[6][0], ends[6][1]);
  37666. ctx.lineTo(ends[7][0], ends[7][1]);
  37667. }
  37668. }
  37669. });
  37670. function createNormalBox(itemLayout, dataIndex, isInit) {
  37671. var ends = itemLayout.ends;
  37672. return new NormalBoxPath({
  37673. shape: {
  37674. points: isInit ? transInit(ends, itemLayout) : ends
  37675. },
  37676. z2: 100
  37677. });
  37678. }
  37679. function isNormalBoxClipped(clipArea, itemLayout) {
  37680. var clipped = true;
  37681. for (var i = 0; i < itemLayout.ends.length; i++) {
  37682. // If any point are in the region.
  37683. if (clipArea.contain(itemLayout.ends[i][0], itemLayout.ends[i][1])) {
  37684. clipped = false;
  37685. break;
  37686. }
  37687. }
  37688. return clipped;
  37689. }
  37690. function setBoxCommon(el, data, dataIndex, isSimpleBox) {
  37691. var itemModel = data.getItemModel(dataIndex);
  37692. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH);
  37693. var color = data.getItemVisual(dataIndex, 'color');
  37694. var borderColor = data.getItemVisual(dataIndex, 'borderColor') || color; // Color must be excluded.
  37695. // Because symbol provide setColor individually to set fill and stroke
  37696. var itemStyle = normalItemStyleModel.getItemStyle(SKIP_PROPS);
  37697. el.useStyle(itemStyle);
  37698. el.style.strokeNoScale = true;
  37699. el.style.fill = color;
  37700. el.style.stroke = borderColor;
  37701. el.__simpleBox = isSimpleBox;
  37702. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH).getItemStyle();
  37703. setHoverStyle(el, hoverStyle);
  37704. }
  37705. function transInit(points, itemLayout) {
  37706. return map(points, function (point) {
  37707. point = point.slice();
  37708. point[1] = itemLayout.initBaseline;
  37709. return point;
  37710. });
  37711. }
  37712. var LargeBoxPath = Path.extend({
  37713. type: 'largeCandlestickBox',
  37714. shape: {},
  37715. buildPath: function (ctx, shape) {
  37716. // Drawing lines is more efficient than drawing
  37717. // a whole line or drawing rects.
  37718. var points = shape.points;
  37719. for (var i = 0; i < points.length;) {
  37720. if (this.__sign === points[i++]) {
  37721. var x = points[i++];
  37722. ctx.moveTo(x, points[i++]);
  37723. ctx.lineTo(x, points[i++]);
  37724. } else {
  37725. i += 3;
  37726. }
  37727. }
  37728. }
  37729. });
  37730. function createLarge$1(seriesModel, group, incremental) {
  37731. var data = seriesModel.getData();
  37732. var largePoints = data.getLayout('largePoints');
  37733. var elP = new LargeBoxPath({
  37734. shape: {
  37735. points: largePoints
  37736. },
  37737. __sign: 1
  37738. });
  37739. group.add(elP);
  37740. var elN = new LargeBoxPath({
  37741. shape: {
  37742. points: largePoints
  37743. },
  37744. __sign: -1
  37745. });
  37746. group.add(elN);
  37747. setLargeStyle$1(1, elP, seriesModel, data);
  37748. setLargeStyle$1(-1, elN, seriesModel, data);
  37749. if (incremental) {
  37750. elP.incremental = true;
  37751. elN.incremental = true;
  37752. }
  37753. }
  37754. function setLargeStyle$1(sign, el, seriesModel, data) {
  37755. var suffix = sign > 0 ? 'P' : 'N';
  37756. var borderColor = data.getVisual('borderColor' + suffix) || data.getVisual('color' + suffix); // Color must be excluded.
  37757. // Because symbol provide setColor individually to set fill and stroke
  37758. var itemStyle = seriesModel.getModel(NORMAL_ITEM_STYLE_PATH).getItemStyle(SKIP_PROPS);
  37759. el.useStyle(itemStyle);
  37760. el.style.fill = null;
  37761. el.style.stroke = borderColor; // No different
  37762. // el.style.lineWidth = .5;
  37763. }
  37764. /*
  37765. * Licensed to the Apache Software Foundation (ASF) under one
  37766. * or more contributor license agreements. See the NOTICE file
  37767. * distributed with this work for additional information
  37768. * regarding copyright ownership. The ASF licenses this file
  37769. * to you under the Apache License, Version 2.0 (the
  37770. * "License"); you may not use this file except in compliance
  37771. * with the License. You may obtain a copy of the License at
  37772. *
  37773. * http://www.apache.org/licenses/LICENSE-2.0
  37774. *
  37775. * Unless required by applicable law or agreed to in writing,
  37776. * software distributed under the License is distributed on an
  37777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37778. * KIND, either express or implied. See the License for the
  37779. * specific language governing permissions and limitations
  37780. * under the License.
  37781. */
  37782. var preprocessor = function (option) {
  37783. if (!option || !isArray(option.series)) {
  37784. return;
  37785. } // Translate 'k' to 'candlestick'.
  37786. each$1(option.series, function (seriesItem) {
  37787. if (isObject$1(seriesItem) && seriesItem.type === 'k') {
  37788. seriesItem.type = 'candlestick';
  37789. }
  37790. });
  37791. };
  37792. /*
  37793. * Licensed to the Apache Software Foundation (ASF) under one
  37794. * or more contributor license agreements. See the NOTICE file
  37795. * distributed with this work for additional information
  37796. * regarding copyright ownership. The ASF licenses this file
  37797. * to you under the Apache License, Version 2.0 (the
  37798. * "License"); you may not use this file except in compliance
  37799. * with the License. You may obtain a copy of the License at
  37800. *
  37801. * http://www.apache.org/licenses/LICENSE-2.0
  37802. *
  37803. * Unless required by applicable law or agreed to in writing,
  37804. * software distributed under the License is distributed on an
  37805. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37806. * KIND, either express or implied. See the License for the
  37807. * specific language governing permissions and limitations
  37808. * under the License.
  37809. */
  37810. var positiveBorderColorQuery = ['itemStyle', 'borderColor'];
  37811. var negativeBorderColorQuery = ['itemStyle', 'borderColor0'];
  37812. var positiveColorQuery = ['itemStyle', 'color'];
  37813. var negativeColorQuery = ['itemStyle', 'color0'];
  37814. var candlestickVisual = {
  37815. seriesType: 'candlestick',
  37816. plan: createRenderPlanner(),
  37817. // For legend.
  37818. performRawSeries: true,
  37819. reset: function (seriesModel, ecModel) {
  37820. var data = seriesModel.getData();
  37821. data.setVisual({
  37822. legendSymbol: 'roundRect',
  37823. colorP: getColor(1, seriesModel),
  37824. colorN: getColor(-1, seriesModel),
  37825. borderColorP: getBorderColor(1, seriesModel),
  37826. borderColorN: getBorderColor(-1, seriesModel)
  37827. }); // Only visible series has each data be visual encoded
  37828. if (ecModel.isSeriesFiltered(seriesModel)) {
  37829. return;
  37830. }
  37831. var isLargeRender = seriesModel.pipelineContext.large;
  37832. return !isLargeRender && {
  37833. progress: progress
  37834. };
  37835. function progress(params, data) {
  37836. var dataIndex;
  37837. while ((dataIndex = params.next()) != null) {
  37838. var itemModel = data.getItemModel(dataIndex);
  37839. var sign = data.getItemLayout(dataIndex).sign;
  37840. data.setItemVisual(dataIndex, {
  37841. color: getColor(sign, itemModel),
  37842. borderColor: getBorderColor(sign, itemModel)
  37843. });
  37844. }
  37845. }
  37846. function getColor(sign, model) {
  37847. return model.get(sign > 0 ? positiveColorQuery : negativeColorQuery);
  37848. }
  37849. function getBorderColor(sign, model) {
  37850. return model.get(sign > 0 ? positiveBorderColorQuery : negativeBorderColorQuery);
  37851. }
  37852. }
  37853. };
  37854. /*
  37855. * Licensed to the Apache Software Foundation (ASF) under one
  37856. * or more contributor license agreements. See the NOTICE file
  37857. * distributed with this work for additional information
  37858. * regarding copyright ownership. The ASF licenses this file
  37859. * to you under the Apache License, Version 2.0 (the
  37860. * "License"); you may not use this file except in compliance
  37861. * with the License. You may obtain a copy of the License at
  37862. *
  37863. * http://www.apache.org/licenses/LICENSE-2.0
  37864. *
  37865. * Unless required by applicable law or agreed to in writing,
  37866. * software distributed under the License is distributed on an
  37867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  37868. * KIND, either express or implied. See the License for the
  37869. * specific language governing permissions and limitations
  37870. * under the License.
  37871. */
  37872. /* global Float32Array */
  37873. var LargeArr$1 = typeof Float32Array !== 'undefined' ? Float32Array : Array;
  37874. var candlestickLayout = {
  37875. seriesType: 'candlestick',
  37876. plan: createRenderPlanner(),
  37877. reset: function (seriesModel) {
  37878. var coordSys = seriesModel.coordinateSystem;
  37879. var data = seriesModel.getData();
  37880. var candleWidth = calculateCandleWidth(seriesModel, data);
  37881. var cDimIdx = 0;
  37882. var vDimIdx = 1;
  37883. var coordDims = ['x', 'y'];
  37884. var cDim = data.mapDimension(coordDims[cDimIdx]);
  37885. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  37886. var openDim = vDims[0];
  37887. var closeDim = vDims[1];
  37888. var lowestDim = vDims[2];
  37889. var highestDim = vDims[3];
  37890. data.setLayout({
  37891. candleWidth: candleWidth,
  37892. // The value is experimented visually.
  37893. isSimpleBox: candleWidth <= 1.3
  37894. });
  37895. if (cDim == null || vDims.length < 4) {
  37896. return;
  37897. }
  37898. return {
  37899. progress: seriesModel.pipelineContext.large ? largeProgress : normalProgress
  37900. };
  37901. function normalProgress(params, data) {
  37902. var dataIndex;
  37903. while ((dataIndex = params.next()) != null) {
  37904. var axisDimVal = data.get(cDim, dataIndex);
  37905. var openVal = data.get(openDim, dataIndex);
  37906. var closeVal = data.get(closeDim, dataIndex);
  37907. var lowestVal = data.get(lowestDim, dataIndex);
  37908. var highestVal = data.get(highestDim, dataIndex);
  37909. var ocLow = Math.min(openVal, closeVal);
  37910. var ocHigh = Math.max(openVal, closeVal);
  37911. var ocLowPoint = getPoint(ocLow, axisDimVal);
  37912. var ocHighPoint = getPoint(ocHigh, axisDimVal);
  37913. var lowestPoint = getPoint(lowestVal, axisDimVal);
  37914. var highestPoint = getPoint(highestVal, axisDimVal);
  37915. var ends = [];
  37916. addBodyEnd(ends, ocHighPoint, 0);
  37917. addBodyEnd(ends, ocLowPoint, 1);
  37918. ends.push(subPixelOptimizePoint(highestPoint), subPixelOptimizePoint(ocHighPoint), subPixelOptimizePoint(lowestPoint), subPixelOptimizePoint(ocLowPoint));
  37919. data.setItemLayout(dataIndex, {
  37920. sign: getSign(data, dataIndex, openVal, closeVal, closeDim),
  37921. initBaseline: openVal > closeVal ? ocHighPoint[vDimIdx] : ocLowPoint[vDimIdx],
  37922. // open point.
  37923. ends: ends,
  37924. brushRect: makeBrushRect(lowestVal, highestVal, axisDimVal)
  37925. });
  37926. }
  37927. function getPoint(val, axisDimVal) {
  37928. var p = [];
  37929. p[cDimIdx] = axisDimVal;
  37930. p[vDimIdx] = val;
  37931. return isNaN(axisDimVal) || isNaN(val) ? [NaN, NaN] : coordSys.dataToPoint(p);
  37932. }
  37933. function addBodyEnd(ends, point, start) {
  37934. var point1 = point.slice();
  37935. var point2 = point.slice();
  37936. point1[cDimIdx] = subPixelOptimize(point1[cDimIdx] + candleWidth / 2, 1, false);
  37937. point2[cDimIdx] = subPixelOptimize(point2[cDimIdx] - candleWidth / 2, 1, true);
  37938. start ? ends.push(point1, point2) : ends.push(point2, point1);
  37939. }
  37940. function makeBrushRect(lowestVal, highestVal, axisDimVal) {
  37941. var pmin = getPoint(lowestVal, axisDimVal);
  37942. var pmax = getPoint(highestVal, axisDimVal);
  37943. pmin[cDimIdx] -= candleWidth / 2;
  37944. pmax[cDimIdx] -= candleWidth / 2;
  37945. return {
  37946. x: pmin[0],
  37947. y: pmin[1],
  37948. width: vDimIdx ? candleWidth : pmax[0] - pmin[0],
  37949. height: vDimIdx ? pmax[1] - pmin[1] : candleWidth
  37950. };
  37951. }
  37952. function subPixelOptimizePoint(point) {
  37953. point[cDimIdx] = subPixelOptimize(point[cDimIdx], 1);
  37954. return point;
  37955. }
  37956. }
  37957. function largeProgress(params, data) {
  37958. // Structure: [sign, x, yhigh, ylow, sign, x, yhigh, ylow, ...]
  37959. var points = new LargeArr$1(params.count * 4);
  37960. var offset = 0;
  37961. var point;
  37962. var tmpIn = [];
  37963. var tmpOut = [];
  37964. var dataIndex;
  37965. while ((dataIndex = params.next()) != null) {
  37966. var axisDimVal = data.get(cDim, dataIndex);
  37967. var openVal = data.get(openDim, dataIndex);
  37968. var closeVal = data.get(closeDim, dataIndex);
  37969. var lowestVal = data.get(lowestDim, dataIndex);
  37970. var highestVal = data.get(highestDim, dataIndex);
  37971. if (isNaN(axisDimVal) || isNaN(lowestVal) || isNaN(highestVal)) {
  37972. points[offset++] = NaN;
  37973. offset += 3;
  37974. continue;
  37975. }
  37976. points[offset++] = getSign(data, dataIndex, openVal, closeVal, closeDim);
  37977. tmpIn[cDimIdx] = axisDimVal;
  37978. tmpIn[vDimIdx] = lowestVal;
  37979. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  37980. points[offset++] = point ? point[0] : NaN;
  37981. points[offset++] = point ? point[1] : NaN;
  37982. tmpIn[vDimIdx] = highestVal;
  37983. point = coordSys.dataToPoint(tmpIn, null, tmpOut);
  37984. points[offset++] = point ? point[1] : NaN;
  37985. }
  37986. data.setLayout('largePoints', points);
  37987. }
  37988. }
  37989. };
  37990. function getSign(data, dataIndex, openVal, closeVal, closeDim) {
  37991. var sign;
  37992. if (openVal > closeVal) {
  37993. sign = -1;
  37994. } else if (openVal < closeVal) {
  37995. sign = 1;
  37996. } else {
  37997. sign = dataIndex > 0 // If close === open, compare with close of last record
  37998. ? data.get(closeDim, dataIndex - 1) <= closeVal ? 1 : -1 : // No record of previous, set to be positive
  37999. 1;
  38000. }
  38001. return sign;
  38002. }
  38003. function calculateCandleWidth(seriesModel, data) {
  38004. var baseAxis = seriesModel.getBaseAxis();
  38005. var extent;
  38006. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / data.count());
  38007. var barMaxWidth = parsePercent$1(retrieve2(seriesModel.get('barMaxWidth'), bandWidth), bandWidth);
  38008. var barMinWidth = parsePercent$1(retrieve2(seriesModel.get('barMinWidth'), 1), bandWidth);
  38009. var barWidth = seriesModel.get('barWidth');
  38010. return barWidth != null ? parsePercent$1(barWidth, bandWidth) // Put max outer to ensure bar visible in spite of overlap.
  38011. : Math.max(Math.min(bandWidth / 2, barMaxWidth), barMinWidth);
  38012. }
  38013. /*
  38014. * Licensed to the Apache Software Foundation (ASF) under one
  38015. * or more contributor license agreements. See the NOTICE file
  38016. * distributed with this work for additional information
  38017. * regarding copyright ownership. The ASF licenses this file
  38018. * to you under the Apache License, Version 2.0 (the
  38019. * "License"); you may not use this file except in compliance
  38020. * with the License. You may obtain a copy of the License at
  38021. *
  38022. * http://www.apache.org/licenses/LICENSE-2.0
  38023. *
  38024. * Unless required by applicable law or agreed to in writing,
  38025. * software distributed under the License is distributed on an
  38026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38027. * KIND, either express or implied. See the License for the
  38028. * specific language governing permissions and limitations
  38029. * under the License.
  38030. */
  38031. registerPreprocessor(preprocessor);
  38032. registerVisual(candlestickVisual);
  38033. registerLayout(candlestickLayout);
  38034. /*
  38035. * Licensed to the Apache Software Foundation (ASF) under one
  38036. * or more contributor license agreements. See the NOTICE file
  38037. * distributed with this work for additional information
  38038. * regarding copyright ownership. The ASF licenses this file
  38039. * to you under the Apache License, Version 2.0 (the
  38040. * "License"); you may not use this file except in compliance
  38041. * with the License. You may obtain a copy of the License at
  38042. *
  38043. * http://www.apache.org/licenses/LICENSE-2.0
  38044. *
  38045. * Unless required by applicable law or agreed to in writing,
  38046. * software distributed under the License is distributed on an
  38047. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38048. * KIND, either express or implied. See the License for the
  38049. * specific language governing permissions and limitations
  38050. * under the License.
  38051. */
  38052. function IndicatorAxis(dim, scale, radiusExtent) {
  38053. Axis.call(this, dim, scale, radiusExtent);
  38054. /**
  38055. * Axis type
  38056. * - 'category'
  38057. * - 'value'
  38058. * - 'time'
  38059. * - 'log'
  38060. * @type {string}
  38061. */
  38062. this.type = 'value';
  38063. this.angle = 0;
  38064. /**
  38065. * Indicator name
  38066. * @type {string}
  38067. */
  38068. this.name = '';
  38069. /**
  38070. * @type {module:echarts/model/Model}
  38071. */
  38072. this.model;
  38073. }
  38074. inherits(IndicatorAxis, Axis);
  38075. /*
  38076. * Licensed to the Apache Software Foundation (ASF) under one
  38077. * or more contributor license agreements. See the NOTICE file
  38078. * distributed with this work for additional information
  38079. * regarding copyright ownership. The ASF licenses this file
  38080. * to you under the Apache License, Version 2.0 (the
  38081. * "License"); you may not use this file except in compliance
  38082. * with the License. You may obtain a copy of the License at
  38083. *
  38084. * http://www.apache.org/licenses/LICENSE-2.0
  38085. *
  38086. * Unless required by applicable law or agreed to in writing,
  38087. * software distributed under the License is distributed on an
  38088. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38089. * KIND, either express or implied. See the License for the
  38090. * specific language governing permissions and limitations
  38091. * under the License.
  38092. */
  38093. // TODO clockwise
  38094. function Radar(radarModel, ecModel, api) {
  38095. this._model = radarModel;
  38096. /**
  38097. * Radar dimensions
  38098. * @type {Array.<string>}
  38099. */
  38100. this.dimensions = [];
  38101. this._indicatorAxes = map(radarModel.getIndicatorModels(), function (indicatorModel, idx) {
  38102. var dim = 'indicator_' + idx;
  38103. var indicatorAxis = new IndicatorAxis(dim, indicatorModel.get('axisType') === 'log' ? new LogScale() : new IntervalScale());
  38104. indicatorAxis.name = indicatorModel.get('name'); // Inject model and axis
  38105. indicatorAxis.model = indicatorModel;
  38106. indicatorModel.axis = indicatorAxis;
  38107. this.dimensions.push(dim);
  38108. return indicatorAxis;
  38109. }, this);
  38110. this.resize(radarModel, api);
  38111. /**
  38112. * @type {number}
  38113. * @readOnly
  38114. */
  38115. this.cx;
  38116. /**
  38117. * @type {number}
  38118. * @readOnly
  38119. */
  38120. this.cy;
  38121. /**
  38122. * @type {number}
  38123. * @readOnly
  38124. */
  38125. this.r;
  38126. /**
  38127. * @type {number}
  38128. * @readOnly
  38129. */
  38130. this.r0;
  38131. /**
  38132. * @type {number}
  38133. * @readOnly
  38134. */
  38135. this.startAngle;
  38136. }
  38137. Radar.prototype.getIndicatorAxes = function () {
  38138. return this._indicatorAxes;
  38139. };
  38140. Radar.prototype.dataToPoint = function (value, indicatorIndex) {
  38141. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  38142. return this.coordToPoint(indicatorAxis.dataToCoord(value), indicatorIndex);
  38143. };
  38144. Radar.prototype.coordToPoint = function (coord, indicatorIndex) {
  38145. var indicatorAxis = this._indicatorAxes[indicatorIndex];
  38146. var angle = indicatorAxis.angle;
  38147. var x = this.cx + coord * Math.cos(angle);
  38148. var y = this.cy - coord * Math.sin(angle);
  38149. return [x, y];
  38150. };
  38151. Radar.prototype.pointToData = function (pt) {
  38152. var dx = pt[0] - this.cx;
  38153. var dy = pt[1] - this.cy;
  38154. var radius = Math.sqrt(dx * dx + dy * dy);
  38155. dx /= radius;
  38156. dy /= radius;
  38157. var radian = Math.atan2(-dy, dx); // Find the closest angle
  38158. // FIXME index can calculated directly
  38159. var minRadianDiff = Infinity;
  38160. var closestAxis;
  38161. var closestAxisIdx = -1;
  38162. for (var i = 0; i < this._indicatorAxes.length; i++) {
  38163. var indicatorAxis = this._indicatorAxes[i];
  38164. var diff = Math.abs(radian - indicatorAxis.angle);
  38165. if (diff < minRadianDiff) {
  38166. closestAxis = indicatorAxis;
  38167. closestAxisIdx = i;
  38168. minRadianDiff = diff;
  38169. }
  38170. }
  38171. return [closestAxisIdx, +(closestAxis && closestAxis.coordToData(radius))];
  38172. };
  38173. Radar.prototype.resize = function (radarModel, api) {
  38174. var center = radarModel.get('center');
  38175. var viewWidth = api.getWidth();
  38176. var viewHeight = api.getHeight();
  38177. var viewSize = Math.min(viewWidth, viewHeight) / 2;
  38178. this.cx = parsePercent$1(center[0], viewWidth);
  38179. this.cy = parsePercent$1(center[1], viewHeight);
  38180. this.startAngle = radarModel.get('startAngle') * Math.PI / 180; // radius may be single value like `20`, `'80%'`, or array like `[10, '80%']`
  38181. var radius = radarModel.get('radius');
  38182. if (typeof radius === 'string' || typeof radius === 'number') {
  38183. radius = [0, radius];
  38184. }
  38185. this.r0 = parsePercent$1(radius[0], viewSize);
  38186. this.r = parsePercent$1(radius[1], viewSize);
  38187. each$1(this._indicatorAxes, function (indicatorAxis, idx) {
  38188. indicatorAxis.setExtent(this.r0, this.r);
  38189. var angle = this.startAngle + idx * Math.PI * 2 / this._indicatorAxes.length; // Normalize to [-PI, PI]
  38190. angle = Math.atan2(Math.sin(angle), Math.cos(angle));
  38191. indicatorAxis.angle = angle;
  38192. }, this);
  38193. };
  38194. Radar.prototype.update = function (ecModel, api) {
  38195. var indicatorAxes = this._indicatorAxes;
  38196. var radarModel = this._model;
  38197. each$1(indicatorAxes, function (indicatorAxis) {
  38198. indicatorAxis.scale.setExtent(Infinity, -Infinity);
  38199. });
  38200. ecModel.eachSeriesByType('radar', function (radarSeries, idx) {
  38201. if (radarSeries.get('coordinateSystem') !== 'radar' || ecModel.getComponent('radar', radarSeries.get('radarIndex')) !== radarModel) {
  38202. return;
  38203. }
  38204. var data = radarSeries.getData();
  38205. each$1(indicatorAxes, function (indicatorAxis) {
  38206. indicatorAxis.scale.unionExtentFromData(data, data.mapDimension(indicatorAxis.dim));
  38207. });
  38208. }, this);
  38209. var splitNumber = radarModel.get('splitNumber');
  38210. function increaseInterval(interval) {
  38211. var exp10 = Math.pow(10, Math.floor(Math.log(interval) / Math.LN10)); // Increase interval
  38212. var f = interval / exp10;
  38213. if (f === 2) {
  38214. f = 5;
  38215. } else {
  38216. // f is 2 or 5
  38217. f *= 2;
  38218. }
  38219. return f * exp10;
  38220. } // Force all the axis fixing the maxSplitNumber.
  38221. each$1(indicatorAxes, function (indicatorAxis, idx) {
  38222. var rawExtent = getScaleExtent(indicatorAxis.scale, indicatorAxis.model).extent;
  38223. niceScaleExtent(indicatorAxis.scale, indicatorAxis.model);
  38224. var axisModel = indicatorAxis.model;
  38225. var scale = indicatorAxis.scale;
  38226. var fixedMin = axisModel.getMin();
  38227. var fixedMax = axisModel.getMax();
  38228. var interval = scale.getInterval();
  38229. if (fixedMin != null && fixedMax != null) {
  38230. // User set min, max, divide to get new interval
  38231. scale.setExtent(+fixedMin, +fixedMax);
  38232. scale.setInterval((fixedMax - fixedMin) / splitNumber);
  38233. } else if (fixedMin != null) {
  38234. var max; // User set min, expand extent on the other side
  38235. do {
  38236. max = fixedMin + interval * splitNumber;
  38237. scale.setExtent(+fixedMin, max); // Interval must been set after extent
  38238. // FIXME
  38239. scale.setInterval(interval);
  38240. interval = increaseInterval(interval);
  38241. } while (max < rawExtent[1] && isFinite(max) && isFinite(rawExtent[1]));
  38242. } else if (fixedMax != null) {
  38243. var min; // User set min, expand extent on the other side
  38244. do {
  38245. min = fixedMax - interval * splitNumber;
  38246. scale.setExtent(min, +fixedMax);
  38247. scale.setInterval(interval);
  38248. interval = increaseInterval(interval);
  38249. } while (min > rawExtent[0] && isFinite(min) && isFinite(rawExtent[0]));
  38250. } else {
  38251. var nicedSplitNumber = scale.getTicks().length - 1;
  38252. if (nicedSplitNumber > splitNumber) {
  38253. interval = increaseInterval(interval);
  38254. } // TODO
  38255. var max = Math.ceil(rawExtent[1] / interval) * interval;
  38256. var min = round$1(max - interval * splitNumber);
  38257. scale.setExtent(min, max);
  38258. scale.setInterval(interval);
  38259. }
  38260. });
  38261. };
  38262. /**
  38263. * Radar dimensions is based on the data
  38264. * @type {Array}
  38265. */
  38266. Radar.dimensions = [];
  38267. Radar.create = function (ecModel, api) {
  38268. var radarList = [];
  38269. ecModel.eachComponent('radar', function (radarModel) {
  38270. var radar = new Radar(radarModel, ecModel, api);
  38271. radarList.push(radar);
  38272. radarModel.coordinateSystem = radar;
  38273. });
  38274. ecModel.eachSeriesByType('radar', function (radarSeries) {
  38275. if (radarSeries.get('coordinateSystem') === 'radar') {
  38276. // Inject coordinate system
  38277. radarSeries.coordinateSystem = radarList[radarSeries.get('radarIndex') || 0];
  38278. }
  38279. });
  38280. return radarList;
  38281. };
  38282. CoordinateSystemManager.register('radar', Radar);
  38283. /*
  38284. * Licensed to the Apache Software Foundation (ASF) under one
  38285. * or more contributor license agreements. See the NOTICE file
  38286. * distributed with this work for additional information
  38287. * regarding copyright ownership. The ASF licenses this file
  38288. * to you under the Apache License, Version 2.0 (the
  38289. * "License"); you may not use this file except in compliance
  38290. * with the License. You may obtain a copy of the License at
  38291. *
  38292. * http://www.apache.org/licenses/LICENSE-2.0
  38293. *
  38294. * Unless required by applicable law or agreed to in writing,
  38295. * software distributed under the License is distributed on an
  38296. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38297. * KIND, either express or implied. See the License for the
  38298. * specific language governing permissions and limitations
  38299. * under the License.
  38300. */
  38301. var valueAxisDefault = axisDefault.valueAxis;
  38302. function defaultsShow(opt, show) {
  38303. return defaults({
  38304. show: show
  38305. }, opt);
  38306. }
  38307. var RadarModel = extendComponentModel({
  38308. type: 'radar',
  38309. optionUpdated: function () {
  38310. var boundaryGap = this.get('boundaryGap');
  38311. var splitNumber = this.get('splitNumber');
  38312. var scale = this.get('scale');
  38313. var axisLine = this.get('axisLine');
  38314. var axisTick = this.get('axisTick');
  38315. var axisType = this.get('axisType');
  38316. var axisLabel = this.get('axisLabel');
  38317. var nameTextStyle = this.get('name');
  38318. var showName = this.get('name.show');
  38319. var nameFormatter = this.get('name.formatter');
  38320. var nameGap = this.get('nameGap');
  38321. var triggerEvent = this.get('triggerEvent');
  38322. var indicatorModels = map(this.get('indicator') || [], function (indicatorOpt) {
  38323. // PENDING
  38324. if (indicatorOpt.max != null && indicatorOpt.max > 0 && !indicatorOpt.min) {
  38325. indicatorOpt.min = 0;
  38326. } else if (indicatorOpt.min != null && indicatorOpt.min < 0 && !indicatorOpt.max) {
  38327. indicatorOpt.max = 0;
  38328. }
  38329. var iNameTextStyle = nameTextStyle;
  38330. if (indicatorOpt.color != null) {
  38331. iNameTextStyle = defaults({
  38332. color: indicatorOpt.color
  38333. }, nameTextStyle);
  38334. } // Use same configuration
  38335. indicatorOpt = merge(clone(indicatorOpt), {
  38336. boundaryGap: boundaryGap,
  38337. splitNumber: splitNumber,
  38338. scale: scale,
  38339. axisLine: axisLine,
  38340. axisTick: axisTick,
  38341. axisType: axisType,
  38342. axisLabel: axisLabel,
  38343. // Compatible with 2 and use text
  38344. name: indicatorOpt.text,
  38345. nameLocation: 'end',
  38346. nameGap: nameGap,
  38347. // min: 0,
  38348. nameTextStyle: iNameTextStyle,
  38349. triggerEvent: triggerEvent
  38350. }, false);
  38351. if (!showName) {
  38352. indicatorOpt.name = '';
  38353. }
  38354. if (typeof nameFormatter === 'string') {
  38355. var indName = indicatorOpt.name;
  38356. indicatorOpt.name = nameFormatter.replace('{value}', indName != null ? indName : '');
  38357. } else if (typeof nameFormatter === 'function') {
  38358. indicatorOpt.name = nameFormatter(indicatorOpt.name, indicatorOpt);
  38359. }
  38360. var model = extend(new Model(indicatorOpt, null, this.ecModel), axisModelCommonMixin); // For triggerEvent.
  38361. model.mainType = 'radar';
  38362. model.componentIndex = this.componentIndex;
  38363. return model;
  38364. }, this);
  38365. this.getIndicatorModels = function () {
  38366. return indicatorModels;
  38367. };
  38368. },
  38369. defaultOption: {
  38370. zlevel: 0,
  38371. z: 0,
  38372. center: ['50%', '50%'],
  38373. radius: '75%',
  38374. startAngle: 90,
  38375. name: {
  38376. show: true // formatter: null
  38377. // textStyle: {}
  38378. },
  38379. boundaryGap: [0, 0],
  38380. splitNumber: 5,
  38381. nameGap: 15,
  38382. scale: false,
  38383. // Polygon or circle
  38384. shape: 'polygon',
  38385. axisLine: merge({
  38386. lineStyle: {
  38387. color: '#bbb'
  38388. }
  38389. }, valueAxisDefault.axisLine),
  38390. axisLabel: defaultsShow(valueAxisDefault.axisLabel, false),
  38391. axisTick: defaultsShow(valueAxisDefault.axisTick, false),
  38392. axisType: 'interval',
  38393. splitLine: defaultsShow(valueAxisDefault.splitLine, true),
  38394. splitArea: defaultsShow(valueAxisDefault.splitArea, true),
  38395. // {text, min, max}
  38396. indicator: []
  38397. }
  38398. });
  38399. /*
  38400. * Licensed to the Apache Software Foundation (ASF) under one
  38401. * or more contributor license agreements. See the NOTICE file
  38402. * distributed with this work for additional information
  38403. * regarding copyright ownership. The ASF licenses this file
  38404. * to you under the Apache License, Version 2.0 (the
  38405. * "License"); you may not use this file except in compliance
  38406. * with the License. You may obtain a copy of the License at
  38407. *
  38408. * http://www.apache.org/licenses/LICENSE-2.0
  38409. *
  38410. * Unless required by applicable law or agreed to in writing,
  38411. * software distributed under the License is distributed on an
  38412. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38413. * KIND, either express or implied. See the License for the
  38414. * specific language governing permissions and limitations
  38415. * under the License.
  38416. */
  38417. var axisBuilderAttrs$1 = ['axisLine', 'axisTickLabel', 'axisName'];
  38418. extendComponentView({
  38419. type: 'radar',
  38420. render: function (radarModel, ecModel, api) {
  38421. var group = this.group;
  38422. group.removeAll();
  38423. this._buildAxes(radarModel);
  38424. this._buildSplitLineAndArea(radarModel);
  38425. },
  38426. _buildAxes: function (radarModel) {
  38427. var radar = radarModel.coordinateSystem;
  38428. var indicatorAxes = radar.getIndicatorAxes();
  38429. var axisBuilders = map(indicatorAxes, function (indicatorAxis) {
  38430. var axisBuilder = new AxisBuilder(indicatorAxis.model, {
  38431. position: [radar.cx, radar.cy],
  38432. rotation: indicatorAxis.angle,
  38433. labelDirection: -1,
  38434. tickDirection: -1,
  38435. nameDirection: 1
  38436. });
  38437. return axisBuilder;
  38438. });
  38439. each$1(axisBuilders, function (axisBuilder) {
  38440. each$1(axisBuilderAttrs$1, axisBuilder.add, axisBuilder);
  38441. this.group.add(axisBuilder.getGroup());
  38442. }, this);
  38443. },
  38444. _buildSplitLineAndArea: function (radarModel) {
  38445. var radar = radarModel.coordinateSystem;
  38446. var indicatorAxes = radar.getIndicatorAxes();
  38447. if (!indicatorAxes.length) {
  38448. return;
  38449. }
  38450. var shape = radarModel.get('shape');
  38451. var splitLineModel = radarModel.getModel('splitLine');
  38452. var splitAreaModel = radarModel.getModel('splitArea');
  38453. var lineStyleModel = splitLineModel.getModel('lineStyle');
  38454. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  38455. var showSplitLine = splitLineModel.get('show');
  38456. var showSplitArea = splitAreaModel.get('show');
  38457. var splitLineColors = lineStyleModel.get('color');
  38458. var splitAreaColors = areaStyleModel.get('color');
  38459. splitLineColors = isArray(splitLineColors) ? splitLineColors : [splitLineColors];
  38460. splitAreaColors = isArray(splitAreaColors) ? splitAreaColors : [splitAreaColors];
  38461. var splitLines = [];
  38462. var splitAreas = [];
  38463. function getColorIndex(areaOrLine, areaOrLineColorList, idx) {
  38464. var colorIndex = idx % areaOrLineColorList.length;
  38465. areaOrLine[colorIndex] = areaOrLine[colorIndex] || [];
  38466. return colorIndex;
  38467. }
  38468. if (shape === 'circle') {
  38469. var ticksRadius = indicatorAxes[0].getTicksCoords();
  38470. var cx = radar.cx;
  38471. var cy = radar.cy;
  38472. for (var i = 0; i < ticksRadius.length; i++) {
  38473. if (showSplitLine) {
  38474. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38475. splitLines[colorIndex].push(new Circle({
  38476. shape: {
  38477. cx: cx,
  38478. cy: cy,
  38479. r: ticksRadius[i].coord
  38480. }
  38481. }));
  38482. }
  38483. if (showSplitArea && i < ticksRadius.length - 1) {
  38484. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i);
  38485. splitAreas[colorIndex].push(new Ring({
  38486. shape: {
  38487. cx: cx,
  38488. cy: cy,
  38489. r0: ticksRadius[i].coord,
  38490. r: ticksRadius[i + 1].coord
  38491. }
  38492. }));
  38493. }
  38494. }
  38495. } // Polyyon
  38496. else {
  38497. var realSplitNumber;
  38498. var axesTicksPoints = map(indicatorAxes, function (indicatorAxis, idx) {
  38499. var ticksCoords = indicatorAxis.getTicksCoords();
  38500. realSplitNumber = realSplitNumber == null ? ticksCoords.length - 1 : Math.min(ticksCoords.length - 1, realSplitNumber);
  38501. return map(ticksCoords, function (tickCoord) {
  38502. return radar.coordToPoint(tickCoord.coord, idx);
  38503. });
  38504. });
  38505. var prevPoints = [];
  38506. for (var i = 0; i <= realSplitNumber; i++) {
  38507. var points = [];
  38508. for (var j = 0; j < indicatorAxes.length; j++) {
  38509. points.push(axesTicksPoints[j][i]);
  38510. } // Close
  38511. if (points[0]) {
  38512. points.push(points[0].slice());
  38513. } else {}
  38514. if (showSplitLine) {
  38515. var colorIndex = getColorIndex(splitLines, splitLineColors, i);
  38516. splitLines[colorIndex].push(new Polyline({
  38517. shape: {
  38518. points: points
  38519. }
  38520. }));
  38521. }
  38522. if (showSplitArea && prevPoints) {
  38523. var colorIndex = getColorIndex(splitAreas, splitAreaColors, i - 1);
  38524. splitAreas[colorIndex].push(new Polygon({
  38525. shape: {
  38526. points: points.concat(prevPoints)
  38527. }
  38528. }));
  38529. }
  38530. prevPoints = points.slice().reverse();
  38531. }
  38532. }
  38533. var lineStyle = lineStyleModel.getLineStyle();
  38534. var areaStyle = areaStyleModel.getAreaStyle(); // Add splitArea before splitLine
  38535. each$1(splitAreas, function (splitAreas, idx) {
  38536. this.group.add(mergePath(splitAreas, {
  38537. style: defaults({
  38538. stroke: 'none',
  38539. fill: splitAreaColors[idx % splitAreaColors.length]
  38540. }, areaStyle),
  38541. silent: true
  38542. }));
  38543. }, this);
  38544. each$1(splitLines, function (splitLines, idx) {
  38545. this.group.add(mergePath(splitLines, {
  38546. style: defaults({
  38547. fill: 'none',
  38548. stroke: splitLineColors[idx % splitLineColors.length]
  38549. }, lineStyle),
  38550. silent: true
  38551. }));
  38552. }, this);
  38553. }
  38554. });
  38555. /*
  38556. * Licensed to the Apache Software Foundation (ASF) under one
  38557. * or more contributor license agreements. See the NOTICE file
  38558. * distributed with this work for additional information
  38559. * regarding copyright ownership. The ASF licenses this file
  38560. * to you under the Apache License, Version 2.0 (the
  38561. * "License"); you may not use this file except in compliance
  38562. * with the License. You may obtain a copy of the License at
  38563. *
  38564. * http://www.apache.org/licenses/LICENSE-2.0
  38565. *
  38566. * Unless required by applicable law or agreed to in writing,
  38567. * software distributed under the License is distributed on an
  38568. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38569. * KIND, either express or implied. See the License for the
  38570. * specific language governing permissions and limitations
  38571. * under the License.
  38572. */
  38573. /*
  38574. * Licensed to the Apache Software Foundation (ASF) under one
  38575. * or more contributor license agreements. See the NOTICE file
  38576. * distributed with this work for additional information
  38577. * regarding copyright ownership. The ASF licenses this file
  38578. * to you under the Apache License, Version 2.0 (the
  38579. * "License"); you may not use this file except in compliance
  38580. * with the License. You may obtain a copy of the License at
  38581. *
  38582. * http://www.apache.org/licenses/LICENSE-2.0
  38583. *
  38584. * Unless required by applicable law or agreed to in writing,
  38585. * software distributed under the License is distributed on an
  38586. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38587. * KIND, either express or implied. See the License for the
  38588. * specific language governing permissions and limitations
  38589. * under the License.
  38590. */
  38591. var RadarSeries = SeriesModel.extend({
  38592. type: 'series.radar',
  38593. dependencies: ['radar'],
  38594. // Overwrite
  38595. init: function (option) {
  38596. RadarSeries.superApply(this, 'init', arguments); // Enable legend selection for each data item
  38597. // Use a function instead of direct access because data reference may changed
  38598. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  38599. },
  38600. getInitialData: function (option, ecModel) {
  38601. return createListSimply(this, {
  38602. generateCoord: 'indicator_',
  38603. generateCoordCount: Infinity
  38604. });
  38605. },
  38606. formatTooltip: function (dataIndex) {
  38607. var data = this.getData();
  38608. var coordSys = this.coordinateSystem;
  38609. var indicatorAxes = coordSys.getIndicatorAxes();
  38610. var name = this.getData().getName(dataIndex);
  38611. return encodeHTML(name === '' ? this.name : name) + '<br/>' + map(indicatorAxes, function (axis, idx) {
  38612. var val = data.get(data.mapDimension(axis.dim), dataIndex);
  38613. return encodeHTML(axis.name + ' : ' + val);
  38614. }).join('<br />');
  38615. },
  38616. /**
  38617. * @implement
  38618. */
  38619. getTooltipPosition: function (dataIndex) {
  38620. if (dataIndex != null) {
  38621. var data = this.getData();
  38622. var coordSys = this.coordinateSystem;
  38623. var values = data.getValues(map(coordSys.dimensions, function (dim) {
  38624. return data.mapDimension(dim);
  38625. }), dataIndex, true);
  38626. for (var i = 0, len = values.length; i < len; i++) {
  38627. if (!isNaN(values[i])) {
  38628. var indicatorAxes = coordSys.getIndicatorAxes();
  38629. return coordSys.coordToPoint(indicatorAxes[i].dataToCoord(values[i]), i);
  38630. }
  38631. }
  38632. }
  38633. },
  38634. defaultOption: {
  38635. zlevel: 0,
  38636. z: 2,
  38637. coordinateSystem: 'radar',
  38638. legendHoverLink: true,
  38639. radarIndex: 0,
  38640. lineStyle: {
  38641. width: 2,
  38642. type: 'solid'
  38643. },
  38644. label: {
  38645. position: 'top'
  38646. },
  38647. // areaStyle: {
  38648. // },
  38649. // itemStyle: {}
  38650. symbol: 'emptyCircle',
  38651. symbolSize: 4 // symbolRotate: null
  38652. }
  38653. });
  38654. /*
  38655. * Licensed to the Apache Software Foundation (ASF) under one
  38656. * or more contributor license agreements. See the NOTICE file
  38657. * distributed with this work for additional information
  38658. * regarding copyright ownership. The ASF licenses this file
  38659. * to you under the Apache License, Version 2.0 (the
  38660. * "License"); you may not use this file except in compliance
  38661. * with the License. You may obtain a copy of the License at
  38662. *
  38663. * http://www.apache.org/licenses/LICENSE-2.0
  38664. *
  38665. * Unless required by applicable law or agreed to in writing,
  38666. * software distributed under the License is distributed on an
  38667. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38668. * KIND, either express or implied. See the License for the
  38669. * specific language governing permissions and limitations
  38670. * under the License.
  38671. */
  38672. function normalizeSymbolSize$1(symbolSize) {
  38673. if (!isArray(symbolSize)) {
  38674. symbolSize = [+symbolSize, +symbolSize];
  38675. }
  38676. return symbolSize;
  38677. }
  38678. extendChartView({
  38679. type: 'radar',
  38680. render: function (seriesModel, ecModel, api) {
  38681. var polar = seriesModel.coordinateSystem;
  38682. var group = this.group;
  38683. var data = seriesModel.getData();
  38684. var oldData = this._data;
  38685. function createSymbol$$1(data, idx) {
  38686. var symbolType = data.getItemVisual(idx, 'symbol') || 'circle';
  38687. var color = data.getItemVisual(idx, 'color');
  38688. if (symbolType === 'none') {
  38689. return;
  38690. }
  38691. var symbolSize = normalizeSymbolSize$1(data.getItemVisual(idx, 'symbolSize'));
  38692. var symbolPath = createSymbol(symbolType, -1, -1, 2, 2, color);
  38693. symbolPath.attr({
  38694. style: {
  38695. strokeNoScale: true
  38696. },
  38697. z2: 100,
  38698. scale: [symbolSize[0] / 2, symbolSize[1] / 2]
  38699. });
  38700. return symbolPath;
  38701. }
  38702. function updateSymbols(oldPoints, newPoints, symbolGroup, data, idx, isInit) {
  38703. // Simply rerender all
  38704. symbolGroup.removeAll();
  38705. for (var i = 0; i < newPoints.length - 1; i++) {
  38706. var symbolPath = createSymbol$$1(data, idx);
  38707. if (symbolPath) {
  38708. symbolPath.__dimIdx = i;
  38709. if (oldPoints[i]) {
  38710. symbolPath.attr('position', oldPoints[i]);
  38711. graphic[isInit ? 'initProps' : 'updateProps'](symbolPath, {
  38712. position: newPoints[i]
  38713. }, seriesModel, idx);
  38714. } else {
  38715. symbolPath.attr('position', newPoints[i]);
  38716. }
  38717. symbolGroup.add(symbolPath);
  38718. }
  38719. }
  38720. }
  38721. function getInitialPoints(points) {
  38722. return map(points, function (pt) {
  38723. return [polar.cx, polar.cy];
  38724. });
  38725. }
  38726. data.diff(oldData).add(function (idx) {
  38727. var points = data.getItemLayout(idx);
  38728. if (!points) {
  38729. return;
  38730. }
  38731. var polygon = new Polygon();
  38732. var polyline = new Polyline();
  38733. var target = {
  38734. shape: {
  38735. points: points
  38736. }
  38737. };
  38738. polygon.shape.points = getInitialPoints(points);
  38739. polyline.shape.points = getInitialPoints(points);
  38740. initProps(polygon, target, seriesModel, idx);
  38741. initProps(polyline, target, seriesModel, idx);
  38742. var itemGroup = new Group();
  38743. var symbolGroup = new Group();
  38744. itemGroup.add(polyline);
  38745. itemGroup.add(polygon);
  38746. itemGroup.add(symbolGroup);
  38747. updateSymbols(polyline.shape.points, points, symbolGroup, data, idx, true);
  38748. data.setItemGraphicEl(idx, itemGroup);
  38749. }).update(function (newIdx, oldIdx) {
  38750. var itemGroup = oldData.getItemGraphicEl(oldIdx);
  38751. var polyline = itemGroup.childAt(0);
  38752. var polygon = itemGroup.childAt(1);
  38753. var symbolGroup = itemGroup.childAt(2);
  38754. var target = {
  38755. shape: {
  38756. points: data.getItemLayout(newIdx)
  38757. }
  38758. };
  38759. if (!target.shape.points) {
  38760. return;
  38761. }
  38762. updateSymbols(polyline.shape.points, target.shape.points, symbolGroup, data, newIdx, false);
  38763. updateProps(polyline, target, seriesModel);
  38764. updateProps(polygon, target, seriesModel);
  38765. data.setItemGraphicEl(newIdx, itemGroup);
  38766. }).remove(function (idx) {
  38767. group.remove(oldData.getItemGraphicEl(idx));
  38768. }).execute();
  38769. data.eachItemGraphicEl(function (itemGroup, idx) {
  38770. var itemModel = data.getItemModel(idx);
  38771. var polyline = itemGroup.childAt(0);
  38772. var polygon = itemGroup.childAt(1);
  38773. var symbolGroup = itemGroup.childAt(2);
  38774. var color = data.getItemVisual(idx, 'color');
  38775. group.add(itemGroup);
  38776. polyline.useStyle(defaults(itemModel.getModel('lineStyle').getLineStyle(), {
  38777. fill: 'none',
  38778. stroke: color
  38779. }));
  38780. polyline.hoverStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  38781. var areaStyleModel = itemModel.getModel('areaStyle');
  38782. var hoverAreaStyleModel = itemModel.getModel('emphasis.areaStyle');
  38783. var polygonIgnore = areaStyleModel.isEmpty() && areaStyleModel.parentModel.isEmpty();
  38784. var hoverPolygonIgnore = hoverAreaStyleModel.isEmpty() && hoverAreaStyleModel.parentModel.isEmpty();
  38785. hoverPolygonIgnore = hoverPolygonIgnore && polygonIgnore;
  38786. polygon.ignore = polygonIgnore;
  38787. polygon.useStyle(defaults(areaStyleModel.getAreaStyle(), {
  38788. fill: color,
  38789. opacity: 0.7
  38790. }));
  38791. polygon.hoverStyle = hoverAreaStyleModel.getAreaStyle();
  38792. var itemStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  38793. var itemHoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  38794. var labelModel = itemModel.getModel('label');
  38795. var labelHoverModel = itemModel.getModel('emphasis.label');
  38796. symbolGroup.eachChild(function (symbolPath) {
  38797. symbolPath.setStyle(itemStyle);
  38798. symbolPath.hoverStyle = clone(itemHoverStyle);
  38799. var defaultText = data.get(data.dimensions[symbolPath.__dimIdx], idx);
  38800. (defaultText == null || isNaN(defaultText)) && (defaultText = '');
  38801. setLabelStyle(symbolPath.style, symbolPath.hoverStyle, labelModel, labelHoverModel, {
  38802. labelFetcher: data.hostModel,
  38803. labelDataIndex: idx,
  38804. labelDimIndex: symbolPath.__dimIdx,
  38805. defaultText: defaultText,
  38806. autoColor: color,
  38807. isRectText: true
  38808. });
  38809. });
  38810. itemGroup.highDownOnUpdate = function (fromState, toState) {
  38811. polygon.attr('ignore', toState === 'emphasis' ? hoverPolygonIgnore : polygonIgnore);
  38812. };
  38813. setHoverStyle(itemGroup);
  38814. });
  38815. this._data = data;
  38816. },
  38817. remove: function () {
  38818. this.group.removeAll();
  38819. this._data = null;
  38820. },
  38821. dispose: function () {}
  38822. });
  38823. /*
  38824. * Licensed to the Apache Software Foundation (ASF) under one
  38825. * or more contributor license agreements. See the NOTICE file
  38826. * distributed with this work for additional information
  38827. * regarding copyright ownership. The ASF licenses this file
  38828. * to you under the Apache License, Version 2.0 (the
  38829. * "License"); you may not use this file except in compliance
  38830. * with the License. You may obtain a copy of the License at
  38831. *
  38832. * http://www.apache.org/licenses/LICENSE-2.0
  38833. *
  38834. * Unless required by applicable law or agreed to in writing,
  38835. * software distributed under the License is distributed on an
  38836. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38837. * KIND, either express or implied. See the License for the
  38838. * specific language governing permissions and limitations
  38839. * under the License.
  38840. */
  38841. var radarLayout = function (ecModel) {
  38842. ecModel.eachSeriesByType('radar', function (seriesModel) {
  38843. var data = seriesModel.getData();
  38844. var points = [];
  38845. var coordSys = seriesModel.coordinateSystem;
  38846. if (!coordSys) {
  38847. return;
  38848. }
  38849. var axes = coordSys.getIndicatorAxes();
  38850. each$1(axes, function (axis, axisIndex) {
  38851. data.each(data.mapDimension(axes[axisIndex].dim), function (val, dataIndex) {
  38852. points[dataIndex] = points[dataIndex] || [];
  38853. var point = coordSys.dataToPoint(val, axisIndex);
  38854. points[dataIndex][axisIndex] = isValidPoint(point) ? point : getValueMissingPoint(coordSys);
  38855. });
  38856. }); // Close polygon
  38857. data.each(function (idx) {
  38858. // TODO
  38859. // Is it appropriate to connect to the next data when some data is missing?
  38860. // Or, should trade it like `connectNull` in line chart?
  38861. var firstPoint = find(points[idx], function (point) {
  38862. return isValidPoint(point);
  38863. }) || getValueMissingPoint(coordSys); // Copy the first actual point to the end of the array
  38864. points[idx].push(firstPoint.slice());
  38865. data.setItemLayout(idx, points[idx]);
  38866. });
  38867. });
  38868. };
  38869. function isValidPoint(point) {
  38870. return !isNaN(point[0]) && !isNaN(point[1]);
  38871. }
  38872. function getValueMissingPoint(coordSys) {
  38873. // It is error-prone to input [NaN, NaN] into polygon, polygon.
  38874. // (probably cause problem when refreshing or animating)
  38875. return [coordSys.cx, coordSys.cy];
  38876. }
  38877. /*
  38878. * Licensed to the Apache Software Foundation (ASF) under one
  38879. * or more contributor license agreements. See the NOTICE file
  38880. * distributed with this work for additional information
  38881. * regarding copyright ownership. The ASF licenses this file
  38882. * to you under the Apache License, Version 2.0 (the
  38883. * "License"); you may not use this file except in compliance
  38884. * with the License. You may obtain a copy of the License at
  38885. *
  38886. * http://www.apache.org/licenses/LICENSE-2.0
  38887. *
  38888. * Unless required by applicable law or agreed to in writing,
  38889. * software distributed under the License is distributed on an
  38890. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38891. * KIND, either express or implied. See the License for the
  38892. * specific language governing permissions and limitations
  38893. * under the License.
  38894. */
  38895. // Backward compat for radar chart in 2
  38896. var backwardCompat$1 = function (option) {
  38897. var polarOptArr = option.polar;
  38898. if (polarOptArr) {
  38899. if (!isArray(polarOptArr)) {
  38900. polarOptArr = [polarOptArr];
  38901. }
  38902. var polarNotRadar = [];
  38903. each$1(polarOptArr, function (polarOpt, idx) {
  38904. if (polarOpt.indicator) {
  38905. if (polarOpt.type && !polarOpt.shape) {
  38906. polarOpt.shape = polarOpt.type;
  38907. }
  38908. option.radar = option.radar || [];
  38909. if (!isArray(option.radar)) {
  38910. option.radar = [option.radar];
  38911. }
  38912. option.radar.push(polarOpt);
  38913. } else {
  38914. polarNotRadar.push(polarOpt);
  38915. }
  38916. });
  38917. option.polar = polarNotRadar;
  38918. }
  38919. each$1(option.series, function (seriesOpt) {
  38920. if (seriesOpt && seriesOpt.type === 'radar' && seriesOpt.polarIndex) {
  38921. seriesOpt.radarIndex = seriesOpt.polarIndex;
  38922. }
  38923. });
  38924. };
  38925. /*
  38926. * Licensed to the Apache Software Foundation (ASF) under one
  38927. * or more contributor license agreements. See the NOTICE file
  38928. * distributed with this work for additional information
  38929. * regarding copyright ownership. The ASF licenses this file
  38930. * to you under the Apache License, Version 2.0 (the
  38931. * "License"); you may not use this file except in compliance
  38932. * with the License. You may obtain a copy of the License at
  38933. *
  38934. * http://www.apache.org/licenses/LICENSE-2.0
  38935. *
  38936. * Unless required by applicable law or agreed to in writing,
  38937. * software distributed under the License is distributed on an
  38938. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38939. * KIND, either express or implied. See the License for the
  38940. * specific language governing permissions and limitations
  38941. * under the License.
  38942. */
  38943. registerVisual(dataColor('radar'));
  38944. registerVisual(visualSymbol('radar', 'circle'));
  38945. registerLayout(radarLayout);
  38946. registerProcessor(dataFilter('radar'));
  38947. registerPreprocessor(backwardCompat$1);
  38948. /*
  38949. * Licensed to the Apache Software Foundation (ASF) under one
  38950. * or more contributor license agreements. See the NOTICE file
  38951. * distributed with this work for additional information
  38952. * regarding copyright ownership. The ASF licenses this file
  38953. * to you under the Apache License, Version 2.0 (the
  38954. * "License"); you may not use this file except in compliance
  38955. * with the License. You may obtain a copy of the License at
  38956. *
  38957. * http://www.apache.org/licenses/LICENSE-2.0
  38958. *
  38959. * Unless required by applicable law or agreed to in writing,
  38960. * software distributed under the License is distributed on an
  38961. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  38962. * KIND, either express or implied. See the License for the
  38963. * specific language governing permissions and limitations
  38964. * under the License.
  38965. */
  38966. SeriesModel.extend({
  38967. type: 'series.heatmap',
  38968. getInitialData: function (option, ecModel) {
  38969. return createListFromArray(this.getSource(), this, {
  38970. generateCoord: 'value'
  38971. });
  38972. },
  38973. preventIncremental: function () {
  38974. var coordSysCreator = CoordinateSystemManager.get(this.get('coordinateSystem'));
  38975. if (coordSysCreator && coordSysCreator.dimensions) {
  38976. return coordSysCreator.dimensions[0] === 'lng' && coordSysCreator.dimensions[1] === 'lat';
  38977. }
  38978. },
  38979. defaultOption: {
  38980. // Cartesian2D or geo
  38981. coordinateSystem: 'cartesian2d',
  38982. zlevel: 0,
  38983. z: 2,
  38984. // Cartesian coordinate system
  38985. // xAxisIndex: 0,
  38986. // yAxisIndex: 0,
  38987. // Geo coordinate system
  38988. geoIndex: 0,
  38989. blurSize: 30,
  38990. pointSize: 20,
  38991. maxOpacity: 1,
  38992. minOpacity: 0
  38993. }
  38994. });
  38995. /*
  38996. * Licensed to the Apache Software Foundation (ASF) under one
  38997. * or more contributor license agreements. See the NOTICE file
  38998. * distributed with this work for additional information
  38999. * regarding copyright ownership. The ASF licenses this file
  39000. * to you under the Apache License, Version 2.0 (the
  39001. * "License"); you may not use this file except in compliance
  39002. * with the License. You may obtain a copy of the License at
  39003. *
  39004. * http://www.apache.org/licenses/LICENSE-2.0
  39005. *
  39006. * Unless required by applicable law or agreed to in writing,
  39007. * software distributed under the License is distributed on an
  39008. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39009. * KIND, either express or implied. See the License for the
  39010. * specific language governing permissions and limitations
  39011. * under the License.
  39012. */
  39013. /* global Uint8ClampedArray */
  39014. var GRADIENT_LEVELS = 256;
  39015. /**
  39016. * Heatmap Chart
  39017. *
  39018. * @class
  39019. */
  39020. function Heatmap() {
  39021. var canvas = createCanvas();
  39022. this.canvas = canvas;
  39023. this.blurSize = 30;
  39024. this.pointSize = 20;
  39025. this.maxOpacity = 1;
  39026. this.minOpacity = 0;
  39027. this._gradientPixels = {};
  39028. }
  39029. Heatmap.prototype = {
  39030. /**
  39031. * Renders Heatmap and returns the rendered canvas
  39032. * @param {Array} data array of data, each has x, y, value
  39033. * @param {number} width canvas width
  39034. * @param {number} height canvas height
  39035. */
  39036. update: function (data, width, height, normalize, colorFunc, isInRange) {
  39037. var brush = this._getBrush();
  39038. var gradientInRange = this._getGradient(data, colorFunc, 'inRange');
  39039. var gradientOutOfRange = this._getGradient(data, colorFunc, 'outOfRange');
  39040. var r = this.pointSize + this.blurSize;
  39041. var canvas = this.canvas;
  39042. var ctx = canvas.getContext('2d');
  39043. var len = data.length;
  39044. canvas.width = width;
  39045. canvas.height = height;
  39046. for (var i = 0; i < len; ++i) {
  39047. var p = data[i];
  39048. var x = p[0];
  39049. var y = p[1];
  39050. var value = p[2]; // calculate alpha using value
  39051. var alpha = normalize(value); // draw with the circle brush with alpha
  39052. ctx.globalAlpha = alpha;
  39053. ctx.drawImage(brush, x - r, y - r);
  39054. }
  39055. if (!canvas.width || !canvas.height) {
  39056. // Avoid "Uncaught DOMException: Failed to execute 'getImageData' on
  39057. // 'CanvasRenderingContext2D': The source height is 0."
  39058. return canvas;
  39059. } // colorize the canvas using alpha value and set with gradient
  39060. var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);
  39061. var pixels = imageData.data;
  39062. var offset = 0;
  39063. var pixelLen = pixels.length;
  39064. var minOpacity = this.minOpacity;
  39065. var maxOpacity = this.maxOpacity;
  39066. var diffOpacity = maxOpacity - minOpacity;
  39067. while (offset < pixelLen) {
  39068. var alpha = pixels[offset + 3] / 256;
  39069. var gradientOffset = Math.floor(alpha * (GRADIENT_LEVELS - 1)) * 4; // Simple optimize to ignore the empty data
  39070. if (alpha > 0) {
  39071. var gradient = isInRange(alpha) ? gradientInRange : gradientOutOfRange; // Any alpha > 0 will be mapped to [minOpacity, maxOpacity]
  39072. alpha > 0 && (alpha = alpha * diffOpacity + minOpacity);
  39073. pixels[offset++] = gradient[gradientOffset];
  39074. pixels[offset++] = gradient[gradientOffset + 1];
  39075. pixels[offset++] = gradient[gradientOffset + 2];
  39076. pixels[offset++] = gradient[gradientOffset + 3] * alpha * 256;
  39077. } else {
  39078. offset += 4;
  39079. }
  39080. }
  39081. ctx.putImageData(imageData, 0, 0);
  39082. return canvas;
  39083. },
  39084. /**
  39085. * get canvas of a black circle brush used for canvas to draw later
  39086. * @private
  39087. * @returns {Object} circle brush canvas
  39088. */
  39089. _getBrush: function () {
  39090. var brushCanvas = this._brushCanvas || (this._brushCanvas = createCanvas()); // set brush size
  39091. var r = this.pointSize + this.blurSize;
  39092. var d = r * 2;
  39093. brushCanvas.width = d;
  39094. brushCanvas.height = d;
  39095. var ctx = brushCanvas.getContext('2d');
  39096. ctx.clearRect(0, 0, d, d); // in order to render shadow without the distinct circle,
  39097. // draw the distinct circle in an invisible place,
  39098. // and use shadowOffset to draw shadow in the center of the canvas
  39099. ctx.shadowOffsetX = d;
  39100. ctx.shadowBlur = this.blurSize; // draw the shadow in black, and use alpha and shadow blur to generate
  39101. // color in color map
  39102. ctx.shadowColor = '#000'; // draw circle in the left to the canvas
  39103. ctx.beginPath();
  39104. ctx.arc(-r, r, this.pointSize, 0, Math.PI * 2, true);
  39105. ctx.closePath();
  39106. ctx.fill();
  39107. return brushCanvas;
  39108. },
  39109. /**
  39110. * get gradient color map
  39111. * @private
  39112. */
  39113. _getGradient: function (data, colorFunc, state) {
  39114. var gradientPixels = this._gradientPixels;
  39115. var pixelsSingleState = gradientPixels[state] || (gradientPixels[state] = new Uint8ClampedArray(256 * 4));
  39116. var color = [0, 0, 0, 0];
  39117. var off = 0;
  39118. for (var i = 0; i < 256; i++) {
  39119. colorFunc[state](i / 255, true, color);
  39120. pixelsSingleState[off++] = color[0];
  39121. pixelsSingleState[off++] = color[1];
  39122. pixelsSingleState[off++] = color[2];
  39123. pixelsSingleState[off++] = color[3];
  39124. }
  39125. return pixelsSingleState;
  39126. }
  39127. };
  39128. /*
  39129. * Licensed to the Apache Software Foundation (ASF) under one
  39130. * or more contributor license agreements. See the NOTICE file
  39131. * distributed with this work for additional information
  39132. * regarding copyright ownership. The ASF licenses this file
  39133. * to you under the Apache License, Version 2.0 (the
  39134. * "License"); you may not use this file except in compliance
  39135. * with the License. You may obtain a copy of the License at
  39136. *
  39137. * http://www.apache.org/licenses/LICENSE-2.0
  39138. *
  39139. * Unless required by applicable law or agreed to in writing,
  39140. * software distributed under the License is distributed on an
  39141. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39142. * KIND, either express or implied. See the License for the
  39143. * specific language governing permissions and limitations
  39144. * under the License.
  39145. */
  39146. function getIsInPiecewiseRange(dataExtent, pieceList, selected) {
  39147. var dataSpan = dataExtent[1] - dataExtent[0];
  39148. pieceList = map(pieceList, function (piece) {
  39149. return {
  39150. interval: [(piece.interval[0] - dataExtent[0]) / dataSpan, (piece.interval[1] - dataExtent[0]) / dataSpan]
  39151. };
  39152. });
  39153. var len = pieceList.length;
  39154. var lastIndex = 0;
  39155. return function (val) {
  39156. // Try to find in the location of the last found
  39157. for (var i = lastIndex; i < len; i++) {
  39158. var interval = pieceList[i].interval;
  39159. if (interval[0] <= val && val <= interval[1]) {
  39160. lastIndex = i;
  39161. break;
  39162. }
  39163. }
  39164. if (i === len) {
  39165. // Not found, back interation
  39166. for (var i = lastIndex - 1; i >= 0; i--) {
  39167. var interval = pieceList[i].interval;
  39168. if (interval[0] <= val && val <= interval[1]) {
  39169. lastIndex = i;
  39170. break;
  39171. }
  39172. }
  39173. }
  39174. return i >= 0 && i < len && selected[i];
  39175. };
  39176. }
  39177. function getIsInContinuousRange(dataExtent, range) {
  39178. var dataSpan = dataExtent[1] - dataExtent[0];
  39179. range = [(range[0] - dataExtent[0]) / dataSpan, (range[1] - dataExtent[0]) / dataSpan];
  39180. return function (val) {
  39181. return val >= range[0] && val <= range[1];
  39182. };
  39183. }
  39184. function isGeoCoordSys(coordSys) {
  39185. var dimensions = coordSys.dimensions; // Not use coorSys.type === 'geo' because coordSys maybe extended
  39186. return dimensions[0] === 'lng' && dimensions[1] === 'lat';
  39187. }
  39188. extendChartView({
  39189. type: 'heatmap',
  39190. render: function (seriesModel, ecModel, api) {
  39191. var visualMapOfThisSeries;
  39192. ecModel.eachComponent('visualMap', function (visualMap) {
  39193. visualMap.eachTargetSeries(function (targetSeries) {
  39194. if (targetSeries === seriesModel) {
  39195. visualMapOfThisSeries = visualMap;
  39196. }
  39197. });
  39198. });
  39199. this.group.removeAll();
  39200. this._incrementalDisplayable = null;
  39201. var coordSys = seriesModel.coordinateSystem;
  39202. if (coordSys.type === 'cartesian2d' || coordSys.type === 'calendar') {
  39203. this._renderOnCartesianAndCalendar(seriesModel, api, 0, seriesModel.getData().count());
  39204. } else if (isGeoCoordSys(coordSys)) {
  39205. this._renderOnGeo(coordSys, seriesModel, visualMapOfThisSeries, api);
  39206. }
  39207. },
  39208. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  39209. this.group.removeAll();
  39210. },
  39211. incrementalRender: function (params, seriesModel, ecModel, api) {
  39212. var coordSys = seriesModel.coordinateSystem;
  39213. if (coordSys) {
  39214. this._renderOnCartesianAndCalendar(seriesModel, api, params.start, params.end, true);
  39215. }
  39216. },
  39217. _renderOnCartesianAndCalendar: function (seriesModel, api, start, end, incremental) {
  39218. var coordSys = seriesModel.coordinateSystem;
  39219. var width;
  39220. var height;
  39221. if (coordSys.type === 'cartesian2d') {
  39222. var xAxis = coordSys.getAxis('x');
  39223. var yAxis = coordSys.getAxis('y');
  39224. width = xAxis.getBandWidth();
  39225. height = yAxis.getBandWidth();
  39226. }
  39227. var group = this.group;
  39228. var data = seriesModel.getData();
  39229. var itemStyleQuery = 'itemStyle';
  39230. var hoverItemStyleQuery = 'emphasis.itemStyle';
  39231. var labelQuery = 'label';
  39232. var hoverLabelQuery = 'emphasis.label';
  39233. var style = seriesModel.getModel(itemStyleQuery).getItemStyle(['color']);
  39234. var hoverStl = seriesModel.getModel(hoverItemStyleQuery).getItemStyle();
  39235. var labelModel = seriesModel.getModel(labelQuery);
  39236. var hoverLabelModel = seriesModel.getModel(hoverLabelQuery);
  39237. var coordSysType = coordSys.type;
  39238. var dataDims = coordSysType === 'cartesian2d' ? [data.mapDimension('x'), data.mapDimension('y'), data.mapDimension('value')] : [data.mapDimension('time'), data.mapDimension('value')];
  39239. for (var idx = start; idx < end; idx++) {
  39240. var rect;
  39241. if (coordSysType === 'cartesian2d') {
  39242. // Ignore empty data
  39243. if (isNaN(data.get(dataDims[2], idx))) {
  39244. continue;
  39245. }
  39246. var point = coordSys.dataToPoint([data.get(dataDims[0], idx), data.get(dataDims[1], idx)]);
  39247. rect = new Rect({
  39248. shape: {
  39249. x: Math.floor(Math.round(point[0]) - width / 2),
  39250. y: Math.floor(Math.round(point[1]) - height / 2),
  39251. width: Math.ceil(width),
  39252. height: Math.ceil(height)
  39253. },
  39254. style: {
  39255. fill: data.getItemVisual(idx, 'color'),
  39256. opacity: data.getItemVisual(idx, 'opacity')
  39257. }
  39258. });
  39259. } else {
  39260. // Ignore empty data
  39261. if (isNaN(data.get(dataDims[1], idx))) {
  39262. continue;
  39263. }
  39264. rect = new Rect({
  39265. z2: 1,
  39266. shape: coordSys.dataToRect([data.get(dataDims[0], idx)]).contentShape,
  39267. style: {
  39268. fill: data.getItemVisual(idx, 'color'),
  39269. opacity: data.getItemVisual(idx, 'opacity')
  39270. }
  39271. });
  39272. }
  39273. var itemModel = data.getItemModel(idx); // Optimization for large datset
  39274. if (data.hasItemOption) {
  39275. style = itemModel.getModel(itemStyleQuery).getItemStyle(['color']);
  39276. hoverStl = itemModel.getModel(hoverItemStyleQuery).getItemStyle();
  39277. labelModel = itemModel.getModel(labelQuery);
  39278. hoverLabelModel = itemModel.getModel(hoverLabelQuery);
  39279. }
  39280. var rawValue = seriesModel.getRawValue(idx);
  39281. var defaultText = '-';
  39282. if (rawValue && rawValue[2] != null) {
  39283. defaultText = rawValue[2];
  39284. }
  39285. setLabelStyle(style, hoverStl, labelModel, hoverLabelModel, {
  39286. labelFetcher: seriesModel,
  39287. labelDataIndex: idx,
  39288. defaultText: defaultText,
  39289. isRectText: true
  39290. });
  39291. rect.setStyle(style);
  39292. setHoverStyle(rect, data.hasItemOption ? hoverStl : extend({}, hoverStl));
  39293. rect.incremental = incremental; // PENDING
  39294. if (incremental) {
  39295. // Rect must use hover layer if it's incremental.
  39296. rect.useHoverLayer = true;
  39297. }
  39298. group.add(rect);
  39299. data.setItemGraphicEl(idx, rect);
  39300. }
  39301. },
  39302. _renderOnGeo: function (geo, seriesModel, visualMapModel, api) {
  39303. var inRangeVisuals = visualMapModel.targetVisuals.inRange;
  39304. var outOfRangeVisuals = visualMapModel.targetVisuals.outOfRange; // if (!visualMapping) {
  39305. // throw new Error('Data range must have color visuals');
  39306. // }
  39307. var data = seriesModel.getData();
  39308. var hmLayer = this._hmLayer || this._hmLayer || new Heatmap();
  39309. hmLayer.blurSize = seriesModel.get('blurSize');
  39310. hmLayer.pointSize = seriesModel.get('pointSize');
  39311. hmLayer.minOpacity = seriesModel.get('minOpacity');
  39312. hmLayer.maxOpacity = seriesModel.get('maxOpacity');
  39313. var rect = geo.getViewRect().clone();
  39314. var roamTransform = geo.getRoamTransform();
  39315. rect.applyTransform(roamTransform); // Clamp on viewport
  39316. var x = Math.max(rect.x, 0);
  39317. var y = Math.max(rect.y, 0);
  39318. var x2 = Math.min(rect.width + rect.x, api.getWidth());
  39319. var y2 = Math.min(rect.height + rect.y, api.getHeight());
  39320. var width = x2 - x;
  39321. var height = y2 - y;
  39322. var dims = [data.mapDimension('lng'), data.mapDimension('lat'), data.mapDimension('value')];
  39323. var points = data.mapArray(dims, function (lng, lat, value) {
  39324. var pt = geo.dataToPoint([lng, lat]);
  39325. pt[0] -= x;
  39326. pt[1] -= y;
  39327. pt.push(value);
  39328. return pt;
  39329. });
  39330. var dataExtent = visualMapModel.getExtent();
  39331. var isInRange = visualMapModel.type === 'visualMap.continuous' ? getIsInContinuousRange(dataExtent, visualMapModel.option.range) : getIsInPiecewiseRange(dataExtent, visualMapModel.getPieceList(), visualMapModel.option.selected);
  39332. hmLayer.update(points, width, height, inRangeVisuals.color.getNormalizer(), {
  39333. inRange: inRangeVisuals.color.getColorMapper(),
  39334. outOfRange: outOfRangeVisuals.color.getColorMapper()
  39335. }, isInRange);
  39336. var img = new ZImage({
  39337. style: {
  39338. width: width,
  39339. height: height,
  39340. x: x,
  39341. y: y,
  39342. image: hmLayer.canvas
  39343. },
  39344. silent: true
  39345. });
  39346. this.group.add(img);
  39347. },
  39348. dispose: function () {}
  39349. });
  39350. /*
  39351. * Licensed to the Apache Software Foundation (ASF) under one
  39352. * or more contributor license agreements. See the NOTICE file
  39353. * distributed with this work for additional information
  39354. * regarding copyright ownership. The ASF licenses this file
  39355. * to you under the Apache License, Version 2.0 (the
  39356. * "License"); you may not use this file except in compliance
  39357. * with the License. You may obtain a copy of the License at
  39358. *
  39359. * http://www.apache.org/licenses/LICENSE-2.0
  39360. *
  39361. * Unless required by applicable law or agreed to in writing,
  39362. * software distributed under the License is distributed on an
  39363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39364. * KIND, either express or implied. See the License for the
  39365. * specific language governing permissions and limitations
  39366. * under the License.
  39367. */
  39368. /*
  39369. * Licensed to the Apache Software Foundation (ASF) under one
  39370. * or more contributor license agreements. See the NOTICE file
  39371. * distributed with this work for additional information
  39372. * regarding copyright ownership. The ASF licenses this file
  39373. * to you under the Apache License, Version 2.0 (the
  39374. * "License"); you may not use this file except in compliance
  39375. * with the License. You may obtain a copy of the License at
  39376. *
  39377. * http://www.apache.org/licenses/LICENSE-2.0
  39378. *
  39379. * Unless required by applicable law or agreed to in writing,
  39380. * software distributed under the License is distributed on an
  39381. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39382. * KIND, either express or implied. See the License for the
  39383. * specific language governing permissions and limitations
  39384. * under the License.
  39385. */
  39386. /**
  39387. * Link lists and struct (graph or tree)
  39388. */
  39389. var each$7 = each$1;
  39390. var DATAS = '\0__link_datas';
  39391. var MAIN_DATA = '\0__link_mainData'; // Caution:
  39392. // In most case, either list or its shallow clones (see list.cloneShallow)
  39393. // is active in echarts process. So considering heap memory consumption,
  39394. // we do not clone tree or graph, but share them among list and its shallow clones.
  39395. // But in some rare case, we have to keep old list (like do animation in chart). So
  39396. // please take care that both the old list and the new list share the same tree/graph.
  39397. /**
  39398. * @param {Object} opt
  39399. * @param {module:echarts/data/List} opt.mainData
  39400. * @param {Object} [opt.struct] For example, instance of Graph or Tree.
  39401. * @param {string} [opt.structAttr] designation: list[structAttr] = struct;
  39402. * @param {Object} [opt.datas] {dataType: data},
  39403. * like: {node: nodeList, edge: edgeList}.
  39404. * Should contain mainData.
  39405. * @param {Object} [opt.datasAttr] {dataType: attr},
  39406. * designation: struct[datasAttr[dataType]] = list;
  39407. */
  39408. function linkList(opt) {
  39409. var mainData = opt.mainData;
  39410. var datas = opt.datas;
  39411. if (!datas) {
  39412. datas = {
  39413. main: mainData
  39414. };
  39415. opt.datasAttr = {
  39416. main: 'data'
  39417. };
  39418. }
  39419. opt.datas = opt.mainData = null;
  39420. linkAll(mainData, datas, opt); // Porxy data original methods.
  39421. each$7(datas, function (data) {
  39422. each$7(mainData.TRANSFERABLE_METHODS, function (methodName) {
  39423. data.wrapMethod(methodName, curry(transferInjection, opt));
  39424. });
  39425. }); // Beyond transfer, additional features should be added to `cloneShallow`.
  39426. mainData.wrapMethod('cloneShallow', curry(cloneShallowInjection, opt)); // Only mainData trigger change, because struct.update may trigger
  39427. // another changable methods, which may bring about dead lock.
  39428. each$7(mainData.CHANGABLE_METHODS, function (methodName) {
  39429. mainData.wrapMethod(methodName, curry(changeInjection, opt));
  39430. }); // Make sure datas contains mainData.
  39431. assert$1(datas[mainData.dataType] === mainData);
  39432. }
  39433. function transferInjection(opt, res) {
  39434. if (isMainData(this)) {
  39435. // Transfer datas to new main data.
  39436. var datas = extend({}, this[DATAS]);
  39437. datas[this.dataType] = res;
  39438. linkAll(res, datas, opt);
  39439. } else {
  39440. // Modify the reference in main data to point newData.
  39441. linkSingle(res, this.dataType, this[MAIN_DATA], opt);
  39442. }
  39443. return res;
  39444. }
  39445. function changeInjection(opt, res) {
  39446. opt.struct && opt.struct.update(this);
  39447. return res;
  39448. }
  39449. function cloneShallowInjection(opt, res) {
  39450. // cloneShallow, which brings about some fragilities, may be inappropriate
  39451. // to be exposed as an API. So for implementation simplicity we can make
  39452. // the restriction that cloneShallow of not-mainData should not be invoked
  39453. // outside, but only be invoked here.
  39454. each$7(res[DATAS], function (data, dataType) {
  39455. data !== res && linkSingle(data.cloneShallow(), dataType, res, opt);
  39456. });
  39457. return res;
  39458. }
  39459. /**
  39460. * Supplement method to List.
  39461. *
  39462. * @public
  39463. * @param {string} [dataType] If not specified, return mainData.
  39464. * @return {module:echarts/data/List}
  39465. */
  39466. function getLinkedData(dataType) {
  39467. var mainData = this[MAIN_DATA];
  39468. return dataType == null || mainData == null ? mainData : mainData[DATAS][dataType];
  39469. }
  39470. function isMainData(data) {
  39471. return data[MAIN_DATA] === data;
  39472. }
  39473. function linkAll(mainData, datas, opt) {
  39474. mainData[DATAS] = {};
  39475. each$7(datas, function (data, dataType) {
  39476. linkSingle(data, dataType, mainData, opt);
  39477. });
  39478. }
  39479. function linkSingle(data, dataType, mainData, opt) {
  39480. mainData[DATAS][dataType] = data;
  39481. data[MAIN_DATA] = mainData;
  39482. data.dataType = dataType;
  39483. if (opt.struct) {
  39484. data[opt.structAttr] = opt.struct;
  39485. opt.struct[opt.datasAttr[dataType]] = data;
  39486. } // Supplement method.
  39487. data.getLinkedData = getLinkedData;
  39488. }
  39489. /*
  39490. * Licensed to the Apache Software Foundation (ASF) under one
  39491. * or more contributor license agreements. See the NOTICE file
  39492. * distributed with this work for additional information
  39493. * regarding copyright ownership. The ASF licenses this file
  39494. * to you under the Apache License, Version 2.0 (the
  39495. * "License"); you may not use this file except in compliance
  39496. * with the License. You may obtain a copy of the License at
  39497. *
  39498. * http://www.apache.org/licenses/LICENSE-2.0
  39499. *
  39500. * Unless required by applicable law or agreed to in writing,
  39501. * software distributed under the License is distributed on an
  39502. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39503. * KIND, either express or implied. See the License for the
  39504. * specific language governing permissions and limitations
  39505. * under the License.
  39506. */
  39507. /**
  39508. * Tree data structure
  39509. *
  39510. * @module echarts/data/Tree
  39511. */
  39512. /**
  39513. * @constructor module:echarts/data/Tree~TreeNode
  39514. * @param {string} name
  39515. * @param {module:echarts/data/Tree} hostTree
  39516. */
  39517. var TreeNode = function (name, hostTree) {
  39518. /**
  39519. * @type {string}
  39520. */
  39521. this.name = name || '';
  39522. /**
  39523. * Depth of node
  39524. *
  39525. * @type {number}
  39526. * @readOnly
  39527. */
  39528. this.depth = 0;
  39529. /**
  39530. * Height of the subtree rooted at this node.
  39531. * @type {number}
  39532. * @readOnly
  39533. */
  39534. this.height = 0;
  39535. /**
  39536. * @type {module:echarts/data/Tree~TreeNode}
  39537. * @readOnly
  39538. */
  39539. this.parentNode = null;
  39540. /**
  39541. * Reference to list item.
  39542. * Do not persistent dataIndex outside,
  39543. * besause it may be changed by list.
  39544. * If dataIndex -1,
  39545. * this node is logical deleted (filtered) in list.
  39546. *
  39547. * @type {Object}
  39548. * @readOnly
  39549. */
  39550. this.dataIndex = -1;
  39551. /**
  39552. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39553. * @readOnly
  39554. */
  39555. this.children = [];
  39556. /**
  39557. * @type {Array.<module:echarts/data/Tree~TreeNode>}
  39558. * @pubilc
  39559. */
  39560. this.viewChildren = [];
  39561. /**
  39562. * @type {moduel:echarts/data/Tree}
  39563. * @readOnly
  39564. */
  39565. this.hostTree = hostTree;
  39566. };
  39567. TreeNode.prototype = {
  39568. constructor: TreeNode,
  39569. /**
  39570. * The node is removed.
  39571. * @return {boolean} is removed.
  39572. */
  39573. isRemoved: function () {
  39574. return this.dataIndex < 0;
  39575. },
  39576. /**
  39577. * Travel this subtree (include this node).
  39578. * Usage:
  39579. * node.eachNode(function () { ... }); // preorder
  39580. * node.eachNode('preorder', function () { ... }); // preorder
  39581. * node.eachNode('postorder', function () { ... }); // postorder
  39582. * node.eachNode(
  39583. * {order: 'postorder', attr: 'viewChildren'},
  39584. * function () { ... }
  39585. * ); // postorder
  39586. *
  39587. * @param {(Object|string)} options If string, means order.
  39588. * @param {string=} options.order 'preorder' or 'postorder'
  39589. * @param {string=} options.attr 'children' or 'viewChildren'
  39590. * @param {Function} cb If in preorder and return false,
  39591. * its subtree will not be visited.
  39592. * @param {Object} [context]
  39593. */
  39594. eachNode: function (options, cb, context) {
  39595. if (typeof options === 'function') {
  39596. context = cb;
  39597. cb = options;
  39598. options = null;
  39599. }
  39600. options = options || {};
  39601. if (isString(options)) {
  39602. options = {
  39603. order: options
  39604. };
  39605. }
  39606. var order = options.order || 'preorder';
  39607. var children = this[options.attr || 'children'];
  39608. var suppressVisitSub;
  39609. order === 'preorder' && (suppressVisitSub = cb.call(context, this));
  39610. for (var i = 0; !suppressVisitSub && i < children.length; i++) {
  39611. children[i].eachNode(options, cb, context);
  39612. }
  39613. order === 'postorder' && cb.call(context, this);
  39614. },
  39615. /**
  39616. * Update depth and height of this subtree.
  39617. *
  39618. * @param {number} depth
  39619. */
  39620. updateDepthAndHeight: function (depth) {
  39621. var height = 0;
  39622. this.depth = depth;
  39623. for (var i = 0; i < this.children.length; i++) {
  39624. var child = this.children[i];
  39625. child.updateDepthAndHeight(depth + 1);
  39626. if (child.height > height) {
  39627. height = child.height;
  39628. }
  39629. }
  39630. this.height = height + 1;
  39631. },
  39632. /**
  39633. * @param {string} id
  39634. * @return {module:echarts/data/Tree~TreeNode}
  39635. */
  39636. getNodeById: function (id) {
  39637. if (this.getId() === id) {
  39638. return this;
  39639. }
  39640. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39641. var res = children[i].getNodeById(id);
  39642. if (res) {
  39643. return res;
  39644. }
  39645. }
  39646. },
  39647. /**
  39648. * @param {module:echarts/data/Tree~TreeNode} node
  39649. * @return {boolean}
  39650. */
  39651. contains: function (node) {
  39652. if (node === this) {
  39653. return true;
  39654. }
  39655. for (var i = 0, children = this.children, len = children.length; i < len; i++) {
  39656. var res = children[i].contains(node);
  39657. if (res) {
  39658. return res;
  39659. }
  39660. }
  39661. },
  39662. /**
  39663. * @param {boolean} includeSelf Default false.
  39664. * @return {Array.<module:echarts/data/Tree~TreeNode>} order: [root, child, grandchild, ...]
  39665. */
  39666. getAncestors: function (includeSelf) {
  39667. var ancestors = [];
  39668. var node = includeSelf ? this : this.parentNode;
  39669. while (node) {
  39670. ancestors.push(node);
  39671. node = node.parentNode;
  39672. }
  39673. ancestors.reverse();
  39674. return ancestors;
  39675. },
  39676. /**
  39677. * @param {string|Array=} [dimension='value'] Default 'value'. can be 0, 1, 2, 3
  39678. * @return {number} Value.
  39679. */
  39680. getValue: function (dimension) {
  39681. var data = this.hostTree.data;
  39682. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  39683. },
  39684. /**
  39685. * @param {Object} layout
  39686. * @param {boolean=} [merge=false]
  39687. */
  39688. setLayout: function (layout, merge$$1) {
  39689. this.dataIndex >= 0 && this.hostTree.data.setItemLayout(this.dataIndex, layout, merge$$1);
  39690. },
  39691. /**
  39692. * @return {Object} layout
  39693. */
  39694. getLayout: function () {
  39695. return this.hostTree.data.getItemLayout(this.dataIndex);
  39696. },
  39697. /**
  39698. * @param {string} [path]
  39699. * @return {module:echarts/model/Model}
  39700. */
  39701. getModel: function (path) {
  39702. if (this.dataIndex < 0) {
  39703. return;
  39704. }
  39705. var hostTree = this.hostTree;
  39706. var itemModel = hostTree.data.getItemModel(this.dataIndex);
  39707. var levelModel = this.getLevelModel(); // FIXME: refactor levelModel to "beforeLink", and remove levelModel here.
  39708. if (levelModel) {
  39709. return itemModel.getModel(path, levelModel.getModel(path));
  39710. } else {
  39711. return itemModel.getModel(path);
  39712. }
  39713. },
  39714. /**
  39715. * @return {module:echarts/model/Model}
  39716. */
  39717. getLevelModel: function () {
  39718. return (this.hostTree.levelModels || [])[this.depth];
  39719. },
  39720. /**
  39721. * @example
  39722. * setItemVisual('color', color);
  39723. * setItemVisual({
  39724. * 'color': color
  39725. * });
  39726. */
  39727. setVisual: function (key, value) {
  39728. this.dataIndex >= 0 && this.hostTree.data.setItemVisual(this.dataIndex, key, value);
  39729. },
  39730. /**
  39731. * Get item visual
  39732. */
  39733. getVisual: function (key, ignoreParent) {
  39734. return this.hostTree.data.getItemVisual(this.dataIndex, key, ignoreParent);
  39735. },
  39736. /**
  39737. * @public
  39738. * @return {number}
  39739. */
  39740. getRawIndex: function () {
  39741. return this.hostTree.data.getRawIndex(this.dataIndex);
  39742. },
  39743. /**
  39744. * @public
  39745. * @return {string}
  39746. */
  39747. getId: function () {
  39748. return this.hostTree.data.getId(this.dataIndex);
  39749. },
  39750. /**
  39751. * if this is an ancestor of another node
  39752. *
  39753. * @public
  39754. * @param {TreeNode} node another node
  39755. * @return {boolean} if is ancestor
  39756. */
  39757. isAncestorOf: function (node) {
  39758. var parent = node.parentNode;
  39759. while (parent) {
  39760. if (parent === this) {
  39761. return true;
  39762. }
  39763. parent = parent.parentNode;
  39764. }
  39765. return false;
  39766. },
  39767. /**
  39768. * if this is an descendant of another node
  39769. *
  39770. * @public
  39771. * @param {TreeNode} node another node
  39772. * @return {boolean} if is descendant
  39773. */
  39774. isDescendantOf: function (node) {
  39775. return node !== this && node.isAncestorOf(this);
  39776. }
  39777. };
  39778. /**
  39779. * @constructor
  39780. * @alias module:echarts/data/Tree
  39781. * @param {module:echarts/model/Model} hostModel
  39782. * @param {Array.<Object>} levelOptions
  39783. */
  39784. function Tree(hostModel, levelOptions) {
  39785. /**
  39786. * @type {module:echarts/data/Tree~TreeNode}
  39787. * @readOnly
  39788. */
  39789. this.root;
  39790. /**
  39791. * @type {module:echarts/data/List}
  39792. * @readOnly
  39793. */
  39794. this.data;
  39795. /**
  39796. * Index of each item is the same as the raw index of coresponding list item.
  39797. * @private
  39798. * @type {Array.<module:echarts/data/Tree~TreeNode}
  39799. */
  39800. this._nodes = [];
  39801. /**
  39802. * @private
  39803. * @readOnly
  39804. * @type {module:echarts/model/Model}
  39805. */
  39806. this.hostModel = hostModel;
  39807. /**
  39808. * @private
  39809. * @readOnly
  39810. * @type {Array.<module:echarts/model/Model}
  39811. */
  39812. this.levelModels = map(levelOptions || [], function (levelDefine) {
  39813. return new Model(levelDefine, hostModel, hostModel.ecModel);
  39814. });
  39815. }
  39816. Tree.prototype = {
  39817. constructor: Tree,
  39818. type: 'tree',
  39819. /**
  39820. * Travel this subtree (include this node).
  39821. * Usage:
  39822. * node.eachNode(function () { ... }); // preorder
  39823. * node.eachNode('preorder', function () { ... }); // preorder
  39824. * node.eachNode('postorder', function () { ... }); // postorder
  39825. * node.eachNode(
  39826. * {order: 'postorder', attr: 'viewChildren'},
  39827. * function () { ... }
  39828. * ); // postorder
  39829. *
  39830. * @param {(Object|string)} options If string, means order.
  39831. * @param {string=} options.order 'preorder' or 'postorder'
  39832. * @param {string=} options.attr 'children' or 'viewChildren'
  39833. * @param {Function} cb
  39834. * @param {Object} [context]
  39835. */
  39836. eachNode: function (options, cb, context) {
  39837. this.root.eachNode(options, cb, context);
  39838. },
  39839. /**
  39840. * @param {number} dataIndex
  39841. * @return {module:echarts/data/Tree~TreeNode}
  39842. */
  39843. getNodeByDataIndex: function (dataIndex) {
  39844. var rawIndex = this.data.getRawIndex(dataIndex);
  39845. return this._nodes[rawIndex];
  39846. },
  39847. /**
  39848. * @param {string} name
  39849. * @return {module:echarts/data/Tree~TreeNode}
  39850. */
  39851. getNodeByName: function (name) {
  39852. return this.root.getNodeByName(name);
  39853. },
  39854. /**
  39855. * Update item available by list,
  39856. * when list has been performed options like 'filterSelf' or 'map'.
  39857. */
  39858. update: function () {
  39859. var data = this.data;
  39860. var nodes = this._nodes;
  39861. for (var i = 0, len = nodes.length; i < len; i++) {
  39862. nodes[i].dataIndex = -1;
  39863. }
  39864. for (var i = 0, len = data.count(); i < len; i++) {
  39865. nodes[data.getRawIndex(i)].dataIndex = i;
  39866. }
  39867. },
  39868. /**
  39869. * Clear all layouts
  39870. */
  39871. clearLayouts: function () {
  39872. this.data.clearItemLayouts();
  39873. }
  39874. };
  39875. /**
  39876. * data node format:
  39877. * {
  39878. * name: ...
  39879. * value: ...
  39880. * children: [
  39881. * {
  39882. * name: ...
  39883. * value: ...
  39884. * children: ...
  39885. * },
  39886. * ...
  39887. * ]
  39888. * }
  39889. *
  39890. * @static
  39891. * @param {Object} dataRoot Root node.
  39892. * @param {module:echarts/model/Model} hostModel
  39893. * @param {Object} treeOptions
  39894. * @param {Array.<Object>} treeOptions.levels
  39895. * @return module:echarts/data/Tree
  39896. */
  39897. Tree.createTree = function (dataRoot, hostModel, treeOptions, beforeLink) {
  39898. var tree = new Tree(hostModel, treeOptions && treeOptions.levels);
  39899. var listData = [];
  39900. var dimMax = 1;
  39901. buildHierarchy(dataRoot);
  39902. function buildHierarchy(dataNode, parentNode) {
  39903. var value = dataNode.value;
  39904. dimMax = Math.max(dimMax, isArray(value) ? value.length : 1);
  39905. listData.push(dataNode);
  39906. var node = new TreeNode(dataNode.name, tree);
  39907. parentNode ? addChild(node, parentNode) : tree.root = node;
  39908. tree._nodes.push(node);
  39909. var children = dataNode.children;
  39910. if (children) {
  39911. for (var i = 0; i < children.length; i++) {
  39912. buildHierarchy(children[i], node);
  39913. }
  39914. }
  39915. }
  39916. tree.root.updateDepthAndHeight(0);
  39917. var dimensionsInfo = createDimensions(listData, {
  39918. coordDimensions: ['value'],
  39919. dimensionsCount: dimMax
  39920. });
  39921. var list = new List(dimensionsInfo, hostModel);
  39922. list.initData(listData);
  39923. beforeLink && beforeLink(list);
  39924. linkList({
  39925. mainData: list,
  39926. struct: tree,
  39927. structAttr: 'tree'
  39928. });
  39929. tree.update();
  39930. return tree;
  39931. };
  39932. /**
  39933. * It is needed to consider the mess of 'list', 'hostModel' when creating a TreeNote,
  39934. * so this function is not ready and not necessary to be public.
  39935. *
  39936. * @param {(module:echarts/data/Tree~TreeNode|Object)} child
  39937. */
  39938. function addChild(child, node) {
  39939. var children = node.children;
  39940. if (child.parentNode === node) {
  39941. return;
  39942. }
  39943. children.push(child);
  39944. child.parentNode = node;
  39945. }
  39946. /*
  39947. * Licensed to the Apache Software Foundation (ASF) under one
  39948. * or more contributor license agreements. See the NOTICE file
  39949. * distributed with this work for additional information
  39950. * regarding copyright ownership. The ASF licenses this file
  39951. * to you under the Apache License, Version 2.0 (the
  39952. * "License"); you may not use this file except in compliance
  39953. * with the License. You may obtain a copy of the License at
  39954. *
  39955. * http://www.apache.org/licenses/LICENSE-2.0
  39956. *
  39957. * Unless required by applicable law or agreed to in writing,
  39958. * software distributed under the License is distributed on an
  39959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  39960. * KIND, either express or implied. See the License for the
  39961. * specific language governing permissions and limitations
  39962. * under the License.
  39963. */
  39964. SeriesModel.extend({
  39965. type: 'series.tree',
  39966. layoutInfo: null,
  39967. // can support the position parameters 'left', 'top','right','bottom', 'width',
  39968. // 'height' in the setOption() with 'merge' mode normal.
  39969. layoutMode: 'box',
  39970. /**
  39971. * Init a tree data structure from data in option series
  39972. * @param {Object} option the object used to config echarts view
  39973. * @return {module:echarts/data/List} storage initial data
  39974. */
  39975. getInitialData: function (option) {
  39976. //create an virtual root
  39977. var root = {
  39978. name: option.name,
  39979. children: option.data
  39980. };
  39981. var leaves = option.leaves || {};
  39982. var leavesModel = new Model(leaves, this, this.ecModel);
  39983. var tree = Tree.createTree(root, this, {}, beforeLink);
  39984. function beforeLink(nodeData) {
  39985. nodeData.wrapMethod('getItemModel', function (model, idx) {
  39986. var node = tree.getNodeByDataIndex(idx);
  39987. if (!node.children.length || !node.isExpand) {
  39988. model.parentModel = leavesModel;
  39989. }
  39990. return model;
  39991. });
  39992. }
  39993. var treeDepth = 0;
  39994. tree.eachNode('preorder', function (node) {
  39995. if (node.depth > treeDepth) {
  39996. treeDepth = node.depth;
  39997. }
  39998. });
  39999. var expandAndCollapse = option.expandAndCollapse;
  40000. var expandTreeDepth = expandAndCollapse && option.initialTreeDepth >= 0 ? option.initialTreeDepth : treeDepth;
  40001. tree.root.eachNode('preorder', function (node) {
  40002. var item = node.hostTree.data.getRawDataItem(node.dataIndex); // Add item.collapsed != null, because users can collapse node original in the series.data.
  40003. node.isExpand = item && item.collapsed != null ? !item.collapsed : node.depth <= expandTreeDepth;
  40004. });
  40005. return tree.data;
  40006. },
  40007. /**
  40008. * Make the configuration 'orient' backward compatibly, with 'horizontal = LR', 'vertical = TB'.
  40009. * @returns {string} orient
  40010. */
  40011. getOrient: function () {
  40012. var orient = this.get('orient');
  40013. if (orient === 'horizontal') {
  40014. orient = 'LR';
  40015. } else if (orient === 'vertical') {
  40016. orient = 'TB';
  40017. }
  40018. return orient;
  40019. },
  40020. setZoom: function (zoom) {
  40021. this.option.zoom = zoom;
  40022. },
  40023. setCenter: function (center) {
  40024. this.option.center = center;
  40025. },
  40026. /**
  40027. * @override
  40028. * @param {number} dataIndex
  40029. */
  40030. formatTooltip: function (dataIndex) {
  40031. var tree = this.getData().tree;
  40032. var realRoot = tree.root.children[0];
  40033. var node = tree.getNodeByDataIndex(dataIndex);
  40034. var value = node.getValue();
  40035. var name = node.name;
  40036. while (node && node !== realRoot) {
  40037. name = node.parentNode.name + '.' + name;
  40038. node = node.parentNode;
  40039. }
  40040. return encodeHTML(name + (isNaN(value) || value == null ? '' : ' : ' + value));
  40041. },
  40042. defaultOption: {
  40043. zlevel: 0,
  40044. z: 2,
  40045. coordinateSystem: 'view',
  40046. // the position of the whole view
  40047. left: '12%',
  40048. top: '12%',
  40049. right: '12%',
  40050. bottom: '12%',
  40051. // the layout of the tree, two value can be selected, 'orthogonal' or 'radial'
  40052. layout: 'orthogonal',
  40053. // value can be 'polyline'
  40054. edgeShape: 'curve',
  40055. edgeForkPosition: '50%',
  40056. // true | false | 'move' | 'scale', see module:component/helper/RoamController.
  40057. roam: false,
  40058. // Symbol size scale ratio in roam
  40059. nodeScaleRatio: 0.4,
  40060. // Default on center of graph
  40061. center: null,
  40062. zoom: 1,
  40063. // The orient of orthoginal layout, can be setted to 'LR', 'TB', 'RL', 'BT'.
  40064. // and the backward compatibility configuration 'horizontal = LR', 'vertical = TB'.
  40065. orient: 'LR',
  40066. symbol: 'emptyCircle',
  40067. symbolSize: 7,
  40068. expandAndCollapse: true,
  40069. initialTreeDepth: 2,
  40070. lineStyle: {
  40071. color: '#ccc',
  40072. width: 1.5,
  40073. curveness: 0.5
  40074. },
  40075. itemStyle: {
  40076. color: 'lightsteelblue',
  40077. borderColor: '#c23531',
  40078. borderWidth: 1.5
  40079. },
  40080. label: {
  40081. show: true,
  40082. color: '#555'
  40083. },
  40084. leaves: {
  40085. label: {
  40086. show: true
  40087. }
  40088. },
  40089. animationEasing: 'linear',
  40090. animationDuration: 700,
  40091. animationDurationUpdate: 1000
  40092. }
  40093. });
  40094. /*
  40095. * Licensed to the Apache Software Foundation (ASF) under one
  40096. * or more contributor license agreements. See the NOTICE file
  40097. * distributed with this work for additional information
  40098. * regarding copyright ownership. The ASF licenses this file
  40099. * to you under the Apache License, Version 2.0 (the
  40100. * "License"); you may not use this file except in compliance
  40101. * with the License. You may obtain a copy of the License at
  40102. *
  40103. * http://www.apache.org/licenses/LICENSE-2.0
  40104. *
  40105. * Unless required by applicable law or agreed to in writing,
  40106. * software distributed under the License is distributed on an
  40107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40108. * KIND, either express or implied. See the License for the
  40109. * specific language governing permissions and limitations
  40110. * under the License.
  40111. */
  40112. /*
  40113. * A third-party license is embeded for some of the code in this file:
  40114. * The tree layoutHelper implementation was originally copied from
  40115. * "d3.js"(https://github.com/d3/d3-hierarchy) with
  40116. * some modifications made for this project.
  40117. * (see more details in the comment of the specific method below.)
  40118. * The use of the source code of this file is also subject to the terms
  40119. * and consitions of the licence of "d3.js" (BSD-3Clause, see
  40120. * </licenses/LICENSE-d3>).
  40121. */
  40122. /**
  40123. * @file The layout algorithm of node-link tree diagrams. Here we using Reingold-Tilford algorithm to drawing
  40124. * the tree.
  40125. */
  40126. /**
  40127. * Initialize all computational message for following algorithm.
  40128. *
  40129. * @param {module:echarts/data/Tree~TreeNode} root The virtual root of the tree.
  40130. */
  40131. function init$2(root) {
  40132. root.hierNode = {
  40133. defaultAncestor: null,
  40134. ancestor: root,
  40135. prelim: 0,
  40136. modifier: 0,
  40137. change: 0,
  40138. shift: 0,
  40139. i: 0,
  40140. thread: null
  40141. };
  40142. var nodes = [root];
  40143. var node;
  40144. var children;
  40145. while (node = nodes.pop()) {
  40146. // jshint ignore:line
  40147. children = node.children;
  40148. if (node.isExpand && children.length) {
  40149. var n = children.length;
  40150. for (var i = n - 1; i >= 0; i--) {
  40151. var child = children[i];
  40152. child.hierNode = {
  40153. defaultAncestor: null,
  40154. ancestor: child,
  40155. prelim: 0,
  40156. modifier: 0,
  40157. change: 0,
  40158. shift: 0,
  40159. i: i,
  40160. thread: null
  40161. };
  40162. nodes.push(child);
  40163. }
  40164. }
  40165. }
  40166. }
  40167. /**
  40168. * The implementation of this function was originally copied from "d3.js"
  40169. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  40170. * with some modifications made for this program.
  40171. * See the license statement at the head of this file.
  40172. *
  40173. * Computes a preliminary x coordinate for node. Before that, this function is
  40174. * applied recursively to the children of node, as well as the function
  40175. * apportion(). After spacing out the children by calling executeShifts(), the
  40176. * node is placed to the midpoint of its outermost children.
  40177. *
  40178. * @param {module:echarts/data/Tree~TreeNode} node
  40179. * @param {Function} separation
  40180. */
  40181. function firstWalk(node, separation) {
  40182. var children = node.isExpand ? node.children : [];
  40183. var siblings = node.parentNode.children;
  40184. var subtreeW = node.hierNode.i ? siblings[node.hierNode.i - 1] : null;
  40185. if (children.length) {
  40186. executeShifts(node);
  40187. var midPoint = (children[0].hierNode.prelim + children[children.length - 1].hierNode.prelim) / 2;
  40188. if (subtreeW) {
  40189. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40190. node.hierNode.modifier = node.hierNode.prelim - midPoint;
  40191. } else {
  40192. node.hierNode.prelim = midPoint;
  40193. }
  40194. } else if (subtreeW) {
  40195. node.hierNode.prelim = subtreeW.hierNode.prelim + separation(node, subtreeW);
  40196. }
  40197. node.parentNode.hierNode.defaultAncestor = apportion(node, subtreeW, node.parentNode.hierNode.defaultAncestor || siblings[0], separation);
  40198. }
  40199. /**
  40200. * The implementation of this function was originally copied from "d3.js"
  40201. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  40202. * with some modifications made for this program.
  40203. * See the license statement at the head of this file.
  40204. *
  40205. * Computes all real x-coordinates by summing up the modifiers recursively.
  40206. *
  40207. * @param {module:echarts/data/Tree~TreeNode} node
  40208. */
  40209. function secondWalk(node) {
  40210. var nodeX = node.hierNode.prelim + node.parentNode.hierNode.modifier;
  40211. node.setLayout({
  40212. x: nodeX
  40213. }, true);
  40214. node.hierNode.modifier += node.parentNode.hierNode.modifier;
  40215. }
  40216. function separation(cb) {
  40217. return arguments.length ? cb : defaultSeparation;
  40218. }
  40219. /**
  40220. * Transform the common coordinate to radial coordinate.
  40221. *
  40222. * @param {number} x
  40223. * @param {number} y
  40224. * @return {Object}
  40225. */
  40226. function radialCoordinate(x, y) {
  40227. var radialCoor = {};
  40228. x -= Math.PI / 2;
  40229. radialCoor.x = y * Math.cos(x);
  40230. radialCoor.y = y * Math.sin(x);
  40231. return radialCoor;
  40232. }
  40233. /**
  40234. * Get the layout position of the whole view.
  40235. *
  40236. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  40237. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  40238. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  40239. */
  40240. function getViewRect$1(seriesModel, api) {
  40241. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  40242. width: api.getWidth(),
  40243. height: api.getHeight()
  40244. });
  40245. }
  40246. /**
  40247. * All other shifts, applied to the smaller subtrees between w- and w+, are
  40248. * performed by this function.
  40249. *
  40250. * The implementation of this function was originally copied from "d3.js"
  40251. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  40252. * with some modifications made for this program.
  40253. * See the license statement at the head of this file.
  40254. *
  40255. * @param {module:echarts/data/Tree~TreeNode} node
  40256. */
  40257. function executeShifts(node) {
  40258. var children = node.children;
  40259. var n = children.length;
  40260. var shift = 0;
  40261. var change = 0;
  40262. while (--n >= 0) {
  40263. var child = children[n];
  40264. child.hierNode.prelim += shift;
  40265. child.hierNode.modifier += shift;
  40266. change += child.hierNode.change;
  40267. shift += child.hierNode.shift + change;
  40268. }
  40269. }
  40270. /**
  40271. * The implementation of this function was originally copied from "d3.js"
  40272. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  40273. * with some modifications made for this program.
  40274. * See the license statement at the head of this file.
  40275. *
  40276. * The core of the algorithm. Here, a new subtree is combined with the
  40277. * previous subtrees. Threads are used to traverse the inside and outside
  40278. * contours of the left and right subtree up to the highest common level.
  40279. * Whenever two nodes of the inside contours conflict, we compute the left
  40280. * one of the greatest uncommon ancestors using the function nextAncestor()
  40281. * and call moveSubtree() to shift the subtree and prepare the shifts of
  40282. * smaller subtrees. Finally, we add a new thread (if necessary).
  40283. *
  40284. * @param {module:echarts/data/Tree~TreeNode} subtreeV
  40285. * @param {module:echarts/data/Tree~TreeNode} subtreeW
  40286. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40287. * @param {Function} separation
  40288. * @return {module:echarts/data/Tree~TreeNode}
  40289. */
  40290. function apportion(subtreeV, subtreeW, ancestor, separation) {
  40291. if (subtreeW) {
  40292. var nodeOutRight = subtreeV;
  40293. var nodeInRight = subtreeV;
  40294. var nodeOutLeft = nodeInRight.parentNode.children[0];
  40295. var nodeInLeft = subtreeW;
  40296. var sumOutRight = nodeOutRight.hierNode.modifier;
  40297. var sumInRight = nodeInRight.hierNode.modifier;
  40298. var sumOutLeft = nodeOutLeft.hierNode.modifier;
  40299. var sumInLeft = nodeInLeft.hierNode.modifier;
  40300. while (nodeInLeft = nextRight(nodeInLeft), nodeInRight = nextLeft(nodeInRight), nodeInLeft && nodeInRight) {
  40301. nodeOutRight = nextRight(nodeOutRight);
  40302. nodeOutLeft = nextLeft(nodeOutLeft);
  40303. nodeOutRight.hierNode.ancestor = subtreeV;
  40304. var shift = nodeInLeft.hierNode.prelim + sumInLeft - nodeInRight.hierNode.prelim - sumInRight + separation(nodeInLeft, nodeInRight);
  40305. if (shift > 0) {
  40306. moveSubtree(nextAncestor(nodeInLeft, subtreeV, ancestor), subtreeV, shift);
  40307. sumInRight += shift;
  40308. sumOutRight += shift;
  40309. }
  40310. sumInLeft += nodeInLeft.hierNode.modifier;
  40311. sumInRight += nodeInRight.hierNode.modifier;
  40312. sumOutRight += nodeOutRight.hierNode.modifier;
  40313. sumOutLeft += nodeOutLeft.hierNode.modifier;
  40314. }
  40315. if (nodeInLeft && !nextRight(nodeOutRight)) {
  40316. nodeOutRight.hierNode.thread = nodeInLeft;
  40317. nodeOutRight.hierNode.modifier += sumInLeft - sumOutRight;
  40318. }
  40319. if (nodeInRight && !nextLeft(nodeOutLeft)) {
  40320. nodeOutLeft.hierNode.thread = nodeInRight;
  40321. nodeOutLeft.hierNode.modifier += sumInRight - sumOutLeft;
  40322. ancestor = subtreeV;
  40323. }
  40324. }
  40325. return ancestor;
  40326. }
  40327. /**
  40328. * This function is used to traverse the right contour of a subtree.
  40329. * It returns the rightmost child of node or the thread of node. The function
  40330. * returns null if and only if node is on the highest depth of its subtree.
  40331. *
  40332. * @param {module:echarts/data/Tree~TreeNode} node
  40333. * @return {module:echarts/data/Tree~TreeNode}
  40334. */
  40335. function nextRight(node) {
  40336. var children = node.children;
  40337. return children.length && node.isExpand ? children[children.length - 1] : node.hierNode.thread;
  40338. }
  40339. /**
  40340. * This function is used to traverse the left contour of a subtree (or a subforest).
  40341. * It returns the leftmost child of node or the thread of node. The function
  40342. * returns null if and only if node is on the highest depth of its subtree.
  40343. *
  40344. * @param {module:echarts/data/Tree~TreeNode} node
  40345. * @return {module:echarts/data/Tree~TreeNode}
  40346. */
  40347. function nextLeft(node) {
  40348. var children = node.children;
  40349. return children.length && node.isExpand ? children[0] : node.hierNode.thread;
  40350. }
  40351. /**
  40352. * If nodeInLeft’s ancestor is a sibling of node, returns nodeInLeft’s ancestor.
  40353. * Otherwise, returns the specified ancestor.
  40354. *
  40355. * @param {module:echarts/data/Tree~TreeNode} nodeInLeft
  40356. * @param {module:echarts/data/Tree~TreeNode} node
  40357. * @param {module:echarts/data/Tree~TreeNode} ancestor
  40358. * @return {module:echarts/data/Tree~TreeNode}
  40359. */
  40360. function nextAncestor(nodeInLeft, node, ancestor) {
  40361. return nodeInLeft.hierNode.ancestor.parentNode === node.parentNode ? nodeInLeft.hierNode.ancestor : ancestor;
  40362. }
  40363. /**
  40364. * The implementation of this function was originally copied from "d3.js"
  40365. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  40366. * with some modifications made for this program.
  40367. * See the license statement at the head of this file.
  40368. *
  40369. * Shifts the current subtree rooted at wr.
  40370. * This is done by increasing prelim(w+) and modifier(w+) by shift.
  40371. *
  40372. * @param {module:echarts/data/Tree~TreeNode} wl
  40373. * @param {module:echarts/data/Tree~TreeNode} wr
  40374. * @param {number} shift [description]
  40375. */
  40376. function moveSubtree(wl, wr, shift) {
  40377. var change = shift / (wr.hierNode.i - wl.hierNode.i);
  40378. wr.hierNode.change -= change;
  40379. wr.hierNode.shift += shift;
  40380. wr.hierNode.modifier += shift;
  40381. wr.hierNode.prelim += shift;
  40382. wl.hierNode.change += change;
  40383. }
  40384. /**
  40385. * The implementation of this function was originally copied from "d3.js"
  40386. * <https://github.com/d3/d3-hierarchy/blob/4c1f038f2725d6eae2e49b61d01456400694bac4/src/tree.js>
  40387. * with some modifications made for this program.
  40388. * See the license statement at the head of this file.
  40389. */
  40390. function defaultSeparation(node1, node2) {
  40391. return node1.parentNode === node2.parentNode ? 1 : 2;
  40392. }
  40393. /*
  40394. * Licensed to the Apache Software Foundation (ASF) under one
  40395. * or more contributor license agreements. See the NOTICE file
  40396. * distributed with this work for additional information
  40397. * regarding copyright ownership. The ASF licenses this file
  40398. * to you under the Apache License, Version 2.0 (the
  40399. * "License"); you may not use this file except in compliance
  40400. * with the License. You may obtain a copy of the License at
  40401. *
  40402. * http://www.apache.org/licenses/LICENSE-2.0
  40403. *
  40404. * Unless required by applicable law or agreed to in writing,
  40405. * software distributed under the License is distributed on an
  40406. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40407. * KIND, either express or implied. See the License for the
  40408. * specific language governing permissions and limitations
  40409. * under the License.
  40410. */
  40411. /**
  40412. * Simple view coordinate system
  40413. * Mapping given x, y to transformd view x, y
  40414. */
  40415. var v2ApplyTransform$1 = applyTransform; // Dummy transform node
  40416. function TransformDummy() {
  40417. Transformable.call(this);
  40418. }
  40419. mixin(TransformDummy, Transformable);
  40420. function View(name) {
  40421. /**
  40422. * @type {string}
  40423. */
  40424. this.name = name;
  40425. /**
  40426. * @type {Object}
  40427. */
  40428. this.zoomLimit;
  40429. Transformable.call(this);
  40430. this._roamTransformable = new TransformDummy();
  40431. this._rawTransformable = new TransformDummy();
  40432. this._center;
  40433. this._zoom;
  40434. }
  40435. View.prototype = {
  40436. constructor: View,
  40437. type: 'view',
  40438. /**
  40439. * @param {Array.<string>}
  40440. * @readOnly
  40441. */
  40442. dimensions: ['x', 'y'],
  40443. /**
  40444. * Set bounding rect
  40445. * @param {number} x
  40446. * @param {number} y
  40447. * @param {number} width
  40448. * @param {number} height
  40449. */
  40450. // PENDING to getRect
  40451. setBoundingRect: function (x, y, width, height) {
  40452. this._rect = new BoundingRect(x, y, width, height);
  40453. return this._rect;
  40454. },
  40455. /**
  40456. * @return {module:zrender/core/BoundingRect}
  40457. */
  40458. // PENDING to getRect
  40459. getBoundingRect: function () {
  40460. return this._rect;
  40461. },
  40462. /**
  40463. * @param {number} x
  40464. * @param {number} y
  40465. * @param {number} width
  40466. * @param {number} height
  40467. */
  40468. setViewRect: function (x, y, width, height) {
  40469. this.transformTo(x, y, width, height);
  40470. this._viewRect = new BoundingRect(x, y, width, height);
  40471. },
  40472. /**
  40473. * Transformed to particular position and size
  40474. * @param {number} x
  40475. * @param {number} y
  40476. * @param {number} width
  40477. * @param {number} height
  40478. */
  40479. transformTo: function (x, y, width, height) {
  40480. var rect = this.getBoundingRect();
  40481. var rawTransform = this._rawTransformable;
  40482. rawTransform.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  40483. rawTransform.decomposeTransform();
  40484. this._updateTransform();
  40485. },
  40486. /**
  40487. * Set center of view
  40488. * @param {Array.<number>} [centerCoord]
  40489. */
  40490. setCenter: function (centerCoord) {
  40491. if (!centerCoord) {
  40492. return;
  40493. }
  40494. this._center = centerCoord;
  40495. this._updateCenterAndZoom();
  40496. },
  40497. /**
  40498. * @param {number} zoom
  40499. */
  40500. setZoom: function (zoom) {
  40501. zoom = zoom || 1;
  40502. var zoomLimit = this.zoomLimit;
  40503. if (zoomLimit) {
  40504. if (zoomLimit.max != null) {
  40505. zoom = Math.min(zoomLimit.max, zoom);
  40506. }
  40507. if (zoomLimit.min != null) {
  40508. zoom = Math.max(zoomLimit.min, zoom);
  40509. }
  40510. }
  40511. this._zoom = zoom;
  40512. this._updateCenterAndZoom();
  40513. },
  40514. /**
  40515. * Get default center without roam
  40516. */
  40517. getDefaultCenter: function () {
  40518. // Rect before any transform
  40519. var rawRect = this.getBoundingRect();
  40520. var cx = rawRect.x + rawRect.width / 2;
  40521. var cy = rawRect.y + rawRect.height / 2;
  40522. return [cx, cy];
  40523. },
  40524. getCenter: function () {
  40525. return this._center || this.getDefaultCenter();
  40526. },
  40527. getZoom: function () {
  40528. return this._zoom || 1;
  40529. },
  40530. /**
  40531. * @return {Array.<number}
  40532. */
  40533. getRoamTransform: function () {
  40534. return this._roamTransformable.getLocalTransform();
  40535. },
  40536. /**
  40537. * Remove roam
  40538. */
  40539. _updateCenterAndZoom: function () {
  40540. // Must update after view transform updated
  40541. var rawTransformMatrix = this._rawTransformable.getLocalTransform();
  40542. var roamTransform = this._roamTransformable;
  40543. var defaultCenter = this.getDefaultCenter();
  40544. var center = this.getCenter();
  40545. var zoom = this.getZoom();
  40546. center = applyTransform([], center, rawTransformMatrix);
  40547. defaultCenter = applyTransform([], defaultCenter, rawTransformMatrix);
  40548. roamTransform.origin = center;
  40549. roamTransform.position = [defaultCenter[0] - center[0], defaultCenter[1] - center[1]];
  40550. roamTransform.scale = [zoom, zoom];
  40551. this._updateTransform();
  40552. },
  40553. /**
  40554. * Update transform from roam and mapLocation
  40555. * @private
  40556. */
  40557. _updateTransform: function () {
  40558. var roamTransformable = this._roamTransformable;
  40559. var rawTransformable = this._rawTransformable;
  40560. rawTransformable.parent = roamTransformable;
  40561. roamTransformable.updateTransform();
  40562. rawTransformable.updateTransform();
  40563. copy$1(this.transform || (this.transform = []), rawTransformable.transform || create$1());
  40564. this._rawTransform = rawTransformable.getLocalTransform();
  40565. this.invTransform = this.invTransform || [];
  40566. invert(this.invTransform, this.transform);
  40567. this.decomposeTransform();
  40568. },
  40569. getTransformInfo: function () {
  40570. var roamTransform = this._roamTransformable.transform;
  40571. var rawTransformable = this._rawTransformable;
  40572. return {
  40573. roamTransform: roamTransform ? slice(roamTransform) : create$1(),
  40574. rawScale: slice(rawTransformable.scale),
  40575. rawPosition: slice(rawTransformable.position)
  40576. };
  40577. },
  40578. /**
  40579. * @return {module:zrender/core/BoundingRect}
  40580. */
  40581. getViewRect: function () {
  40582. return this._viewRect;
  40583. },
  40584. /**
  40585. * Get view rect after roam transform
  40586. * @return {module:zrender/core/BoundingRect}
  40587. */
  40588. getViewRectAfterRoam: function () {
  40589. var rect = this.getBoundingRect().clone();
  40590. rect.applyTransform(this.transform);
  40591. return rect;
  40592. },
  40593. /**
  40594. * Convert a single (lon, lat) data item to (x, y) point.
  40595. * @param {Array.<number>} data
  40596. * @param {boolean} noRoam
  40597. * @param {Array.<number>} [out]
  40598. * @return {Array.<number>}
  40599. */
  40600. dataToPoint: function (data, noRoam, out) {
  40601. var transform = noRoam ? this._rawTransform : this.transform;
  40602. out = out || [];
  40603. return transform ? v2ApplyTransform$1(out, data, transform) : copy(out, data);
  40604. },
  40605. /**
  40606. * Convert a (x, y) point to (lon, lat) data
  40607. * @param {Array.<number>} point
  40608. * @return {Array.<number>}
  40609. */
  40610. pointToData: function (point) {
  40611. var invTransform = this.invTransform;
  40612. return invTransform ? v2ApplyTransform$1([], point, invTransform) : [point[0], point[1]];
  40613. },
  40614. /**
  40615. * @implements
  40616. * see {module:echarts/CoodinateSystem}
  40617. */
  40618. convertToPixel: curry(doConvert, 'dataToPoint'),
  40619. /**
  40620. * @implements
  40621. * see {module:echarts/CoodinateSystem}
  40622. */
  40623. convertFromPixel: curry(doConvert, 'pointToData'),
  40624. /**
  40625. * @implements
  40626. * see {module:echarts/CoodinateSystem}
  40627. */
  40628. containPoint: function (point) {
  40629. return this.getViewRectAfterRoam().contain(point[0], point[1]);
  40630. }
  40631. /**
  40632. * @return {number}
  40633. */
  40634. // getScalarScale: function () {
  40635. // // Use determinant square root of transform to mutiply scalar
  40636. // var m = this.transform;
  40637. // var det = Math.sqrt(Math.abs(m[0] * m[3] - m[2] * m[1]));
  40638. // return det;
  40639. // }
  40640. };
  40641. mixin(View, Transformable);
  40642. function doConvert(methodName, ecModel, finder, value) {
  40643. var seriesModel = finder.seriesModel;
  40644. var coordSys = seriesModel ? seriesModel.coordinateSystem : null; // e.g., graph.
  40645. return coordSys === this ? coordSys[methodName](value) : null;
  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. * For geo and graph.
  40667. *
  40668. * @param {Object} controllerHost
  40669. * @param {module:zrender/Element} controllerHost.target
  40670. */
  40671. function updateViewOnPan(controllerHost, dx, dy) {
  40672. var target = controllerHost.target;
  40673. var pos = target.position;
  40674. pos[0] += dx;
  40675. pos[1] += dy;
  40676. target.dirty();
  40677. }
  40678. /**
  40679. * For geo and graph.
  40680. *
  40681. * @param {Object} controllerHost
  40682. * @param {module:zrender/Element} controllerHost.target
  40683. * @param {number} controllerHost.zoom
  40684. * @param {number} controllerHost.zoomLimit like: {min: 1, max: 2}
  40685. */
  40686. function updateViewOnZoom(controllerHost, zoomDelta, zoomX, zoomY) {
  40687. var target = controllerHost.target;
  40688. var zoomLimit = controllerHost.zoomLimit;
  40689. var pos = target.position;
  40690. var scale = target.scale;
  40691. var newZoom = controllerHost.zoom = controllerHost.zoom || 1;
  40692. newZoom *= zoomDelta;
  40693. if (zoomLimit) {
  40694. var zoomMin = zoomLimit.min || 0;
  40695. var zoomMax = zoomLimit.max || Infinity;
  40696. newZoom = Math.max(Math.min(zoomMax, newZoom), zoomMin);
  40697. }
  40698. var zoomScale = newZoom / controllerHost.zoom;
  40699. controllerHost.zoom = newZoom; // Keep the mouse center when scaling
  40700. pos[0] -= (zoomX - pos[0]) * (zoomScale - 1);
  40701. pos[1] -= (zoomY - pos[1]) * (zoomScale - 1);
  40702. scale[0] *= zoomScale;
  40703. scale[1] *= zoomScale;
  40704. target.dirty();
  40705. }
  40706. /*
  40707. * Licensed to the Apache Software Foundation (ASF) under one
  40708. * or more contributor license agreements. See the NOTICE file
  40709. * distributed with this work for additional information
  40710. * regarding copyright ownership. The ASF licenses this file
  40711. * to you under the Apache License, Version 2.0 (the
  40712. * "License"); you may not use this file except in compliance
  40713. * with the License. You may obtain a copy of the License at
  40714. *
  40715. * http://www.apache.org/licenses/LICENSE-2.0
  40716. *
  40717. * Unless required by applicable law or agreed to in writing,
  40718. * software distributed under the License is distributed on an
  40719. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40720. * KIND, either express or implied. See the License for the
  40721. * specific language governing permissions and limitations
  40722. * under the License.
  40723. */
  40724. var ATTR = '\0_ec_interaction_mutex';
  40725. function take(zr, resourceKey, userKey) {
  40726. var store = getStore(zr);
  40727. store[resourceKey] = userKey;
  40728. }
  40729. function release(zr, resourceKey, userKey) {
  40730. var store = getStore(zr);
  40731. var uKey = store[resourceKey];
  40732. if (uKey === userKey) {
  40733. store[resourceKey] = null;
  40734. }
  40735. }
  40736. function isTaken(zr, resourceKey) {
  40737. return !!getStore(zr)[resourceKey];
  40738. }
  40739. function getStore(zr) {
  40740. return zr[ATTR] || (zr[ATTR] = {});
  40741. }
  40742. /**
  40743. * payload: {
  40744. * type: 'takeGlobalCursor',
  40745. * key: 'dataZoomSelect', or 'brush', or ...,
  40746. * If no userKey, release global cursor.
  40747. * }
  40748. */
  40749. registerAction({
  40750. type: 'takeGlobalCursor',
  40751. event: 'globalCursorTaken',
  40752. update: 'update'
  40753. }, function () {});
  40754. /*
  40755. * Licensed to the Apache Software Foundation (ASF) under one
  40756. * or more contributor license agreements. See the NOTICE file
  40757. * distributed with this work for additional information
  40758. * regarding copyright ownership. The ASF licenses this file
  40759. * to you under the Apache License, Version 2.0 (the
  40760. * "License"); you may not use this file except in compliance
  40761. * with the License. You may obtain a copy of the License at
  40762. *
  40763. * http://www.apache.org/licenses/LICENSE-2.0
  40764. *
  40765. * Unless required by applicable law or agreed to in writing,
  40766. * software distributed under the License is distributed on an
  40767. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40768. * KIND, either express or implied. See the License for the
  40769. * specific language governing permissions and limitations
  40770. * under the License.
  40771. */
  40772. /**
  40773. * @alias module:echarts/component/helper/RoamController
  40774. * @constructor
  40775. * @mixin {module:zrender/mixin/Eventful}
  40776. *
  40777. * @param {module:zrender/zrender~ZRender} zr
  40778. */
  40779. function RoamController(zr) {
  40780. /**
  40781. * @type {Function}
  40782. */
  40783. this.pointerChecker;
  40784. /**
  40785. * @type {module:zrender}
  40786. */
  40787. this._zr = zr;
  40788. /**
  40789. * @type {Object}
  40790. */
  40791. this._opt = {}; // Avoid two roamController bind the same handler
  40792. var bind$$1 = bind;
  40793. var mousedownHandler = bind$$1(mousedown, this);
  40794. var mousemoveHandler = bind$$1(mousemove, this);
  40795. var mouseupHandler = bind$$1(mouseup, this);
  40796. var mousewheelHandler = bind$$1(mousewheel, this);
  40797. var pinchHandler = bind$$1(pinch, this);
  40798. Eventful.call(this);
  40799. /**
  40800. * @param {Function} pointerChecker
  40801. * input: x, y
  40802. * output: boolean
  40803. */
  40804. this.setPointerChecker = function (pointerChecker) {
  40805. this.pointerChecker = pointerChecker;
  40806. };
  40807. /**
  40808. * Notice: only enable needed types. For example, if 'zoom'
  40809. * is not needed, 'zoom' should not be enabled, otherwise
  40810. * default mousewheel behaviour (scroll page) will be disabled.
  40811. *
  40812. * @param {boolean|string} [controlType=true] Specify the control type,
  40813. * which can be null/undefined or true/false
  40814. * or 'pan/move' or 'zoom'/'scale'
  40815. * @param {Object} [opt]
  40816. * @param {Object} [opt.zoomOnMouseWheel=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40817. * @param {Object} [opt.moveOnMouseMove=true] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40818. * @param {Object} [opt.moveOnMouseWheel=false] The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40819. * @param {Object} [opt.preventDefaultMouseMove=true] When pan.
  40820. */
  40821. this.enable = function (controlType, opt) {
  40822. // Disable previous first
  40823. this.disable();
  40824. this._opt = defaults(clone(opt) || {}, {
  40825. zoomOnMouseWheel: true,
  40826. moveOnMouseMove: true,
  40827. // By default, wheel do not trigger move.
  40828. moveOnMouseWheel: false,
  40829. preventDefaultMouseMove: true
  40830. });
  40831. if (controlType == null) {
  40832. controlType = true;
  40833. }
  40834. if (controlType === true || controlType === 'move' || controlType === 'pan') {
  40835. zr.on('mousedown', mousedownHandler);
  40836. zr.on('mousemove', mousemoveHandler);
  40837. zr.on('mouseup', mouseupHandler);
  40838. }
  40839. if (controlType === true || controlType === 'scale' || controlType === 'zoom') {
  40840. zr.on('mousewheel', mousewheelHandler);
  40841. zr.on('pinch', pinchHandler);
  40842. }
  40843. };
  40844. this.disable = function () {
  40845. zr.off('mousedown', mousedownHandler);
  40846. zr.off('mousemove', mousemoveHandler);
  40847. zr.off('mouseup', mouseupHandler);
  40848. zr.off('mousewheel', mousewheelHandler);
  40849. zr.off('pinch', pinchHandler);
  40850. };
  40851. this.dispose = this.disable;
  40852. this.isDragging = function () {
  40853. return this._dragging;
  40854. };
  40855. this.isPinching = function () {
  40856. return this._pinching;
  40857. };
  40858. }
  40859. mixin(RoamController, Eventful);
  40860. function mousedown(e) {
  40861. if (isMiddleOrRightButtonOnMouseUpDown(e) || e.target && e.target.draggable) {
  40862. return;
  40863. }
  40864. var x = e.offsetX;
  40865. var y = e.offsetY; // Only check on mosedown, but not mousemove.
  40866. // Mouse can be out of target when mouse moving.
  40867. if (this.pointerChecker && this.pointerChecker(e, x, y)) {
  40868. this._x = x;
  40869. this._y = y;
  40870. this._dragging = true;
  40871. }
  40872. }
  40873. function mousemove(e) {
  40874. if (!this._dragging || !isAvailableBehavior('moveOnMouseMove', e, this._opt) || e.gestureEvent === 'pinch' || isTaken(this._zr, 'globalPan')) {
  40875. return;
  40876. }
  40877. var x = e.offsetX;
  40878. var y = e.offsetY;
  40879. var oldX = this._x;
  40880. var oldY = this._y;
  40881. var dx = x - oldX;
  40882. var dy = y - oldY;
  40883. this._x = x;
  40884. this._y = y;
  40885. this._opt.preventDefaultMouseMove && stop(e.event);
  40886. trigger(this, 'pan', 'moveOnMouseMove', e, {
  40887. dx: dx,
  40888. dy: dy,
  40889. oldX: oldX,
  40890. oldY: oldY,
  40891. newX: x,
  40892. newY: y
  40893. });
  40894. }
  40895. function mouseup(e) {
  40896. if (!isMiddleOrRightButtonOnMouseUpDown(e)) {
  40897. this._dragging = false;
  40898. }
  40899. }
  40900. function mousewheel(e) {
  40901. var shouldZoom = isAvailableBehavior('zoomOnMouseWheel', e, this._opt);
  40902. var shouldMove = isAvailableBehavior('moveOnMouseWheel', e, this._opt);
  40903. var wheelDelta = e.wheelDelta;
  40904. var absWheelDeltaDelta = Math.abs(wheelDelta);
  40905. var originX = e.offsetX;
  40906. var originY = e.offsetY; // wheelDelta maybe -0 in chrome mac.
  40907. if (wheelDelta === 0 || !shouldZoom && !shouldMove) {
  40908. return;
  40909. } // If both `shouldZoom` and `shouldMove` is true, trigger
  40910. // their event both, and the final behavior is determined
  40911. // by event listener themselves.
  40912. if (shouldZoom) {
  40913. // Convenience:
  40914. // Mac and VM Windows on Mac: scroll up: zoom out.
  40915. // Windows: scroll up: zoom in.
  40916. // FIXME: Should do more test in different environment.
  40917. // wheelDelta is too complicated in difference nvironment
  40918. // (https://developer.mozilla.org/en-US/docs/Web/Events/mousewheel),
  40919. // although it has been normallized by zrender.
  40920. // wheelDelta of mouse wheel is bigger than touch pad.
  40921. var factor = absWheelDeltaDelta > 3 ? 1.4 : absWheelDeltaDelta > 1 ? 1.2 : 1.1;
  40922. var scale = wheelDelta > 0 ? factor : 1 / factor;
  40923. checkPointerAndTrigger(this, 'zoom', 'zoomOnMouseWheel', e, {
  40924. scale: scale,
  40925. originX: originX,
  40926. originY: originY
  40927. });
  40928. }
  40929. if (shouldMove) {
  40930. // FIXME: Should do more test in different environment.
  40931. var absDelta = Math.abs(wheelDelta); // wheelDelta of mouse wheel is bigger than touch pad.
  40932. var scrollDelta = (wheelDelta > 0 ? 1 : -1) * (absDelta > 3 ? 0.4 : absDelta > 1 ? 0.15 : 0.05);
  40933. checkPointerAndTrigger(this, 'scrollMove', 'moveOnMouseWheel', e, {
  40934. scrollDelta: scrollDelta,
  40935. originX: originX,
  40936. originY: originY
  40937. });
  40938. }
  40939. }
  40940. function pinch(e) {
  40941. if (isTaken(this._zr, 'globalPan')) {
  40942. return;
  40943. }
  40944. var scale = e.pinchScale > 1 ? 1.1 : 1 / 1.1;
  40945. checkPointerAndTrigger(this, 'zoom', null, e, {
  40946. scale: scale,
  40947. originX: e.pinchX,
  40948. originY: e.pinchY
  40949. });
  40950. }
  40951. function checkPointerAndTrigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  40952. if (controller.pointerChecker && controller.pointerChecker(e, contollerEvent.originX, contollerEvent.originY)) {
  40953. // When mouse is out of roamController rect,
  40954. // default befavoius should not be be disabled, otherwise
  40955. // page sliding is disabled, contrary to expectation.
  40956. stop(e.event);
  40957. trigger(controller, eventName, behaviorToCheck, e, contollerEvent);
  40958. }
  40959. }
  40960. function trigger(controller, eventName, behaviorToCheck, e, contollerEvent) {
  40961. // Also provide behavior checker for event listener, for some case that
  40962. // multiple components share one listener.
  40963. contollerEvent.isAvailableBehavior = bind(isAvailableBehavior, null, behaviorToCheck, e);
  40964. controller.trigger(eventName, contollerEvent);
  40965. } // settings: {
  40966. // zoomOnMouseWheel
  40967. // moveOnMouseMove
  40968. // moveOnMouseWheel
  40969. // }
  40970. // The value can be: true / false / 'shift' / 'ctrl' / 'alt'.
  40971. function isAvailableBehavior(behaviorToCheck, e, settings) {
  40972. var setting = settings[behaviorToCheck];
  40973. return !behaviorToCheck || setting && (!isString(setting) || e.event[setting + 'Key']);
  40974. }
  40975. /*
  40976. * Licensed to the Apache Software Foundation (ASF) under one
  40977. * or more contributor license agreements. See the NOTICE file
  40978. * distributed with this work for additional information
  40979. * regarding copyright ownership. The ASF licenses this file
  40980. * to you under the Apache License, Version 2.0 (the
  40981. * "License"); you may not use this file except in compliance
  40982. * with the License. You may obtain a copy of the License at
  40983. *
  40984. * http://www.apache.org/licenses/LICENSE-2.0
  40985. *
  40986. * Unless required by applicable law or agreed to in writing,
  40987. * software distributed under the License is distributed on an
  40988. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  40989. * KIND, either express or implied. See the License for the
  40990. * specific language governing permissions and limitations
  40991. * under the License.
  40992. */
  40993. var IRRELEVANT_EXCLUDES = {
  40994. 'axisPointer': 1,
  40995. 'tooltip': 1,
  40996. 'brush': 1
  40997. };
  40998. /**
  40999. * Avoid that: mouse click on a elements that is over geo or graph,
  41000. * but roam is triggered.
  41001. */
  41002. function onIrrelevantElement(e, api, targetCoordSysModel) {
  41003. var model = api.getComponentByElement(e.topTarget); // If model is axisModel, it works only if it is injected with coordinateSystem.
  41004. var coordSys = model && model.coordinateSystem;
  41005. return model && model !== targetCoordSysModel && !IRRELEVANT_EXCLUDES[model.mainType] && coordSys && coordSys.model !== targetCoordSysModel;
  41006. }
  41007. /*
  41008. * Licensed to the Apache Software Foundation (ASF) under one
  41009. * or more contributor license agreements. See the NOTICE file
  41010. * distributed with this work for additional information
  41011. * regarding copyright ownership. The ASF licenses this file
  41012. * to you under the Apache License, Version 2.0 (the
  41013. * "License"); you may not use this file except in compliance
  41014. * with the License. You may obtain a copy of the License at
  41015. *
  41016. * http://www.apache.org/licenses/LICENSE-2.0
  41017. *
  41018. * Unless required by applicable law or agreed to in writing,
  41019. * software distributed under the License is distributed on an
  41020. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41021. * KIND, either express or implied. See the License for the
  41022. * specific language governing permissions and limitations
  41023. * under the License.
  41024. */
  41025. var TreeShape = extendShape({
  41026. shape: {
  41027. parentPoint: [],
  41028. childPoints: [],
  41029. orient: '',
  41030. forkPosition: ''
  41031. },
  41032. style: {
  41033. stroke: '#000',
  41034. fill: null
  41035. },
  41036. buildPath: function (ctx, shape) {
  41037. var childPoints = shape.childPoints;
  41038. var childLen = childPoints.length;
  41039. var parentPoint = shape.parentPoint;
  41040. var firstChildPos = childPoints[0];
  41041. var lastChildPos = childPoints[childLen - 1];
  41042. if (childLen === 1) {
  41043. ctx.moveTo(parentPoint[0], parentPoint[1]);
  41044. ctx.lineTo(firstChildPos[0], firstChildPos[1]);
  41045. return;
  41046. }
  41047. var orient = shape.orient;
  41048. var forkDim = orient === 'TB' || orient === 'BT' ? 0 : 1;
  41049. var otherDim = 1 - forkDim;
  41050. var forkPosition = parsePercent$1(shape.forkPosition, 1);
  41051. var tmpPoint = [];
  41052. tmpPoint[forkDim] = parentPoint[forkDim];
  41053. tmpPoint[otherDim] = parentPoint[otherDim] + (lastChildPos[otherDim] - parentPoint[otherDim]) * forkPosition;
  41054. ctx.moveTo(parentPoint[0], parentPoint[1]);
  41055. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  41056. ctx.moveTo(firstChildPos[0], firstChildPos[1]);
  41057. tmpPoint[forkDim] = firstChildPos[forkDim];
  41058. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  41059. tmpPoint[forkDim] = lastChildPos[forkDim];
  41060. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  41061. ctx.lineTo(lastChildPos[0], lastChildPos[1]);
  41062. for (var i = 1; i < childLen - 1; i++) {
  41063. var point = childPoints[i];
  41064. ctx.moveTo(point[0], point[1]);
  41065. tmpPoint[forkDim] = point[forkDim];
  41066. ctx.lineTo(tmpPoint[0], tmpPoint[1]);
  41067. }
  41068. }
  41069. });
  41070. extendChartView({
  41071. type: 'tree',
  41072. /**
  41073. * Init the chart
  41074. * @override
  41075. * @param {module:echarts/model/Global} ecModel
  41076. * @param {module:echarts/ExtensionAPI} api
  41077. */
  41078. init: function (ecModel, api) {
  41079. /**
  41080. * @private
  41081. * @type {module:echarts/data/Tree}
  41082. */
  41083. this._oldTree;
  41084. /**
  41085. * @private
  41086. * @type {module:zrender/container/Group}
  41087. */
  41088. this._mainGroup = new Group();
  41089. /**
  41090. * @private
  41091. * @type {module:echarts/componet/helper/RoamController}
  41092. */
  41093. this._controller = new RoamController(api.getZr());
  41094. this._controllerHost = {
  41095. target: this.group
  41096. };
  41097. this.group.add(this._mainGroup);
  41098. },
  41099. render: function (seriesModel, ecModel, api, payload) {
  41100. var data = seriesModel.getData();
  41101. var layoutInfo = seriesModel.layoutInfo;
  41102. var group = this._mainGroup;
  41103. var layout = seriesModel.get('layout');
  41104. if (layout === 'radial') {
  41105. group.attr('position', [layoutInfo.x + layoutInfo.width / 2, layoutInfo.y + layoutInfo.height / 2]);
  41106. } else {
  41107. group.attr('position', [layoutInfo.x, layoutInfo.y]);
  41108. }
  41109. this._updateViewCoordSys(seriesModel, layoutInfo, layout);
  41110. this._updateController(seriesModel, ecModel, api);
  41111. var oldData = this._data;
  41112. var seriesScope = {
  41113. expandAndCollapse: seriesModel.get('expandAndCollapse'),
  41114. layout: layout,
  41115. edgeShape: seriesModel.get('edgeShape'),
  41116. edgeForkPosition: seriesModel.get('edgeForkPosition'),
  41117. orient: seriesModel.getOrient(),
  41118. curvature: seriesModel.get('lineStyle.curveness'),
  41119. symbolRotate: seriesModel.get('symbolRotate'),
  41120. symbolOffset: seriesModel.get('symbolOffset'),
  41121. hoverAnimation: seriesModel.get('hoverAnimation'),
  41122. useNameLabel: true,
  41123. fadeIn: true
  41124. };
  41125. data.diff(oldData).add(function (newIdx) {
  41126. if (symbolNeedsDraw$1(data, newIdx)) {
  41127. // Create node and edge
  41128. updateNode(data, newIdx, null, group, seriesModel, seriesScope);
  41129. }
  41130. }).update(function (newIdx, oldIdx) {
  41131. var symbolEl = oldData.getItemGraphicEl(oldIdx);
  41132. if (!symbolNeedsDraw$1(data, newIdx)) {
  41133. symbolEl && removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  41134. return;
  41135. } // Update node and edge
  41136. updateNode(data, newIdx, symbolEl, group, seriesModel, seriesScope);
  41137. }).remove(function (oldIdx) {
  41138. var symbolEl = oldData.getItemGraphicEl(oldIdx); // When remove a collapsed node of subtree, since the collapsed
  41139. // node haven't been initialized with a symbol element,
  41140. // you can't found it's symbol element through index.
  41141. // so if we want to remove the symbol element we should insure
  41142. // that the symbol element is not null.
  41143. if (symbolEl) {
  41144. removeNode(oldData, oldIdx, symbolEl, group, seriesModel, seriesScope);
  41145. }
  41146. }).execute();
  41147. this._nodeScaleRatio = seriesModel.get('nodeScaleRatio');
  41148. this._updateNodeAndLinkScale(seriesModel);
  41149. if (seriesScope.expandAndCollapse === true) {
  41150. data.eachItemGraphicEl(function (el, dataIndex) {
  41151. el.off('click').on('click', function () {
  41152. api.dispatchAction({
  41153. type: 'treeExpandAndCollapse',
  41154. seriesId: seriesModel.id,
  41155. dataIndex: dataIndex
  41156. });
  41157. });
  41158. });
  41159. }
  41160. this._data = data;
  41161. },
  41162. _updateViewCoordSys: function (seriesModel) {
  41163. var data = seriesModel.getData();
  41164. var points = [];
  41165. data.each(function (idx) {
  41166. var layout = data.getItemLayout(idx);
  41167. if (layout && !isNaN(layout.x) && !isNaN(layout.y)) {
  41168. points.push([+layout.x, +layout.y]);
  41169. }
  41170. });
  41171. var min = [];
  41172. var max = [];
  41173. fromPoints(points, min, max); // If don't Store min max when collapse the root node after roam,
  41174. // the root node will disappear.
  41175. var oldMin = this._min;
  41176. var oldMax = this._max; // If width or height is 0
  41177. if (max[0] - min[0] === 0) {
  41178. min[0] = oldMin ? oldMin[0] : min[0] - 1;
  41179. max[0] = oldMax ? oldMax[0] : max[0] + 1;
  41180. }
  41181. if (max[1] - min[1] === 0) {
  41182. min[1] = oldMin ? oldMin[1] : min[1] - 1;
  41183. max[1] = oldMax ? oldMax[1] : max[1] + 1;
  41184. }
  41185. var viewCoordSys = seriesModel.coordinateSystem = new View();
  41186. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  41187. viewCoordSys.setBoundingRect(min[0], min[1], max[0] - min[0], max[1] - min[1]);
  41188. viewCoordSys.setCenter(seriesModel.get('center'));
  41189. viewCoordSys.setZoom(seriesModel.get('zoom')); // Here we use viewCoordSys just for computing the 'position' and 'scale' of the group
  41190. this.group.attr({
  41191. position: viewCoordSys.position,
  41192. scale: viewCoordSys.scale
  41193. });
  41194. this._viewCoordSys = viewCoordSys;
  41195. this._min = min;
  41196. this._max = max;
  41197. },
  41198. _updateController: function (seriesModel, ecModel, api) {
  41199. var controller = this._controller;
  41200. var controllerHost = this._controllerHost;
  41201. var group = this.group;
  41202. controller.setPointerChecker(function (e, x, y) {
  41203. var rect = group.getBoundingRect();
  41204. rect.applyTransform(group.transform);
  41205. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  41206. });
  41207. controller.enable(seriesModel.get('roam'));
  41208. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  41209. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  41210. controller.off('pan').off('zoom').on('pan', function (e) {
  41211. updateViewOnPan(controllerHost, e.dx, e.dy);
  41212. api.dispatchAction({
  41213. seriesId: seriesModel.id,
  41214. type: 'treeRoam',
  41215. dx: e.dx,
  41216. dy: e.dy
  41217. });
  41218. }, this).on('zoom', function (e) {
  41219. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  41220. api.dispatchAction({
  41221. seriesId: seriesModel.id,
  41222. type: 'treeRoam',
  41223. zoom: e.scale,
  41224. originX: e.originX,
  41225. originY: e.originY
  41226. });
  41227. this._updateNodeAndLinkScale(seriesModel);
  41228. }, this);
  41229. },
  41230. _updateNodeAndLinkScale: function (seriesModel) {
  41231. var data = seriesModel.getData();
  41232. var nodeScale = this._getNodeGlobalScale(seriesModel);
  41233. var invScale = [nodeScale, nodeScale];
  41234. data.eachItemGraphicEl(function (el, idx) {
  41235. el.attr('scale', invScale);
  41236. });
  41237. },
  41238. _getNodeGlobalScale: function (seriesModel) {
  41239. var coordSys = seriesModel.coordinateSystem;
  41240. if (coordSys.type !== 'view') {
  41241. return 1;
  41242. }
  41243. var nodeScaleRatio = this._nodeScaleRatio;
  41244. var groupScale = coordSys.scale;
  41245. var groupZoom = groupScale && groupScale[0] || 1; // Scale node when zoom changes
  41246. var roamZoom = coordSys.getZoom();
  41247. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  41248. return nodeScale / groupZoom;
  41249. },
  41250. dispose: function () {
  41251. this._controller && this._controller.dispose();
  41252. this._controllerHost = {};
  41253. },
  41254. remove: function () {
  41255. this._mainGroup.removeAll();
  41256. this._data = null;
  41257. }
  41258. });
  41259. function symbolNeedsDraw$1(data, dataIndex) {
  41260. var layout = data.getItemLayout(dataIndex);
  41261. return layout && !isNaN(layout.x) && !isNaN(layout.y) && data.getItemVisual(dataIndex, 'symbol') !== 'none';
  41262. }
  41263. function getTreeNodeStyle(node, itemModel, seriesScope) {
  41264. seriesScope.itemModel = itemModel;
  41265. seriesScope.itemStyle = itemModel.getModel('itemStyle').getItemStyle();
  41266. seriesScope.hoverItemStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  41267. seriesScope.lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  41268. seriesScope.labelModel = itemModel.getModel('label');
  41269. seriesScope.hoverLabelModel = itemModel.getModel('emphasis.label');
  41270. if (node.isExpand === false && node.children.length !== 0) {
  41271. seriesScope.symbolInnerColor = seriesScope.itemStyle.fill;
  41272. } else {
  41273. seriesScope.symbolInnerColor = '#fff';
  41274. }
  41275. return seriesScope;
  41276. }
  41277. function updateNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  41278. var isInit = !symbolEl;
  41279. var node = data.tree.getNodeByDataIndex(dataIndex);
  41280. var itemModel = node.getModel();
  41281. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  41282. var virtualRoot = data.tree.root;
  41283. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  41284. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  41285. var sourceLayout = source.getLayout();
  41286. var sourceOldLayout = sourceSymbolEl ? {
  41287. x: sourceSymbolEl.position[0],
  41288. y: sourceSymbolEl.position[1],
  41289. rawX: sourceSymbolEl.__radialOldRawX,
  41290. rawY: sourceSymbolEl.__radialOldRawY
  41291. } : sourceLayout;
  41292. var targetLayout = node.getLayout();
  41293. if (isInit) {
  41294. symbolEl = new SymbolClz$1(data, dataIndex, seriesScope);
  41295. symbolEl.attr('position', [sourceOldLayout.x, sourceOldLayout.y]);
  41296. } else {
  41297. symbolEl.updateData(data, dataIndex, seriesScope);
  41298. }
  41299. symbolEl.__radialOldRawX = symbolEl.__radialRawX;
  41300. symbolEl.__radialOldRawY = symbolEl.__radialRawY;
  41301. symbolEl.__radialRawX = targetLayout.rawX;
  41302. symbolEl.__radialRawY = targetLayout.rawY;
  41303. group.add(symbolEl);
  41304. data.setItemGraphicEl(dataIndex, symbolEl);
  41305. updateProps(symbolEl, {
  41306. position: [targetLayout.x, targetLayout.y]
  41307. }, seriesModel);
  41308. var symbolPath = symbolEl.getSymbolPath();
  41309. if (seriesScope.layout === 'radial') {
  41310. var realRoot = virtualRoot.children[0];
  41311. var rootLayout = realRoot.getLayout();
  41312. var length = realRoot.children.length;
  41313. var rad;
  41314. var isLeft;
  41315. if (targetLayout.x === rootLayout.x && node.isExpand === true) {
  41316. var center = {};
  41317. center.x = (realRoot.children[0].getLayout().x + realRoot.children[length - 1].getLayout().x) / 2;
  41318. center.y = (realRoot.children[0].getLayout().y + realRoot.children[length - 1].getLayout().y) / 2;
  41319. rad = Math.atan2(center.y - rootLayout.y, center.x - rootLayout.x);
  41320. if (rad < 0) {
  41321. rad = Math.PI * 2 + rad;
  41322. }
  41323. isLeft = center.x < rootLayout.x;
  41324. if (isLeft) {
  41325. rad = rad - Math.PI;
  41326. }
  41327. } else {
  41328. rad = Math.atan2(targetLayout.y - rootLayout.y, targetLayout.x - rootLayout.x);
  41329. if (rad < 0) {
  41330. rad = Math.PI * 2 + rad;
  41331. }
  41332. if (node.children.length === 0 || node.children.length !== 0 && node.isExpand === false) {
  41333. isLeft = targetLayout.x < rootLayout.x;
  41334. if (isLeft) {
  41335. rad = rad - Math.PI;
  41336. }
  41337. } else {
  41338. isLeft = targetLayout.x > rootLayout.x;
  41339. if (!isLeft) {
  41340. rad = rad - Math.PI;
  41341. }
  41342. }
  41343. }
  41344. var textPosition = isLeft ? 'left' : 'right';
  41345. var rotate = seriesScope.labelModel.get('rotate');
  41346. var labelRotateRadian = rotate * (Math.PI / 180);
  41347. symbolPath.setStyle({
  41348. textPosition: seriesScope.labelModel.get('position') || textPosition,
  41349. textRotation: rotate == null ? -rad : labelRotateRadian,
  41350. textOrigin: 'center',
  41351. verticalAlign: 'middle'
  41352. });
  41353. }
  41354. drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group, seriesScope);
  41355. }
  41356. function drawEdge(seriesModel, node, virtualRoot, symbolEl, sourceOldLayout, sourceLayout, targetLayout, group, seriesScope) {
  41357. var edgeShape = seriesScope.edgeShape;
  41358. var edge = symbolEl.__edge;
  41359. if (edgeShape === 'curve') {
  41360. if (node.parentNode && node.parentNode !== virtualRoot) {
  41361. if (!edge) {
  41362. edge = symbolEl.__edge = new BezierCurve({
  41363. shape: getEdgeShape(seriesScope, sourceOldLayout, sourceOldLayout),
  41364. style: defaults({
  41365. opacity: 0,
  41366. strokeNoScale: true
  41367. }, seriesScope.lineStyle)
  41368. });
  41369. }
  41370. updateProps(edge, {
  41371. shape: getEdgeShape(seriesScope, sourceLayout, targetLayout),
  41372. style: {
  41373. opacity: 1
  41374. }
  41375. }, seriesModel);
  41376. }
  41377. } else if (edgeShape === 'polyline') {
  41378. if (seriesScope.layout === 'orthogonal') {
  41379. if (node !== virtualRoot && node.children && node.children.length !== 0 && node.isExpand === true) {
  41380. var children = node.children;
  41381. var childPoints = [];
  41382. for (var i = 0; i < children.length; i++) {
  41383. var childLayout = children[i].getLayout();
  41384. childPoints.push([childLayout.x, childLayout.y]);
  41385. }
  41386. if (!edge) {
  41387. edge = symbolEl.__edge = new TreeShape({
  41388. shape: {
  41389. parentPoint: [targetLayout.x, targetLayout.y],
  41390. childPoints: [[targetLayout.x, targetLayout.y]],
  41391. orient: seriesScope.orient,
  41392. forkPosition: seriesScope.edgeForkPosition
  41393. },
  41394. style: defaults({
  41395. opacity: 0,
  41396. strokeNoScale: true
  41397. }, seriesScope.lineStyle)
  41398. });
  41399. }
  41400. updateProps(edge, {
  41401. shape: {
  41402. parentPoint: [targetLayout.x, targetLayout.y],
  41403. childPoints: childPoints
  41404. },
  41405. style: {
  41406. opacity: 1
  41407. }
  41408. }, seriesModel);
  41409. }
  41410. } else {}
  41411. }
  41412. group.add(edge);
  41413. }
  41414. function removeNode(data, dataIndex, symbolEl, group, seriesModel, seriesScope) {
  41415. var node = data.tree.getNodeByDataIndex(dataIndex);
  41416. var virtualRoot = data.tree.root;
  41417. var itemModel = node.getModel();
  41418. var seriesScope = getTreeNodeStyle(node, itemModel, seriesScope);
  41419. var source = node.parentNode === virtualRoot ? node : node.parentNode || node;
  41420. var edgeShape = seriesScope.edgeShape;
  41421. var sourceLayout;
  41422. while (sourceLayout = source.getLayout(), sourceLayout == null) {
  41423. source = source.parentNode === virtualRoot ? source : source.parentNode || source;
  41424. }
  41425. updateProps(symbolEl, {
  41426. position: [sourceLayout.x + 1, sourceLayout.y + 1]
  41427. }, seriesModel, function () {
  41428. group.remove(symbolEl);
  41429. data.setItemGraphicEl(dataIndex, null);
  41430. });
  41431. symbolEl.fadeOut(null, {
  41432. keepLabel: true
  41433. });
  41434. var sourceSymbolEl = data.getItemGraphicEl(source.dataIndex);
  41435. var sourceEdge = sourceSymbolEl.__edge; // 1. when expand the sub tree, delete the children node should delete the edge of
  41436. // the source at the same time. because the polyline edge shape is only owned by the source.
  41437. // 2.when the node is the only children of the source, delete the node should delete the edge of
  41438. // the source at the same time. the same reason as above.
  41439. var edge = symbolEl.__edge || (source.isExpand === false || source.children.length === 1 ? sourceEdge : undefined);
  41440. var edgeShape = seriesScope.edgeShape;
  41441. if (edge) {
  41442. if (edgeShape === 'curve') {
  41443. updateProps(edge, {
  41444. shape: getEdgeShape(seriesScope, sourceLayout, sourceLayout),
  41445. style: {
  41446. opacity: 0
  41447. }
  41448. }, seriesModel, function () {
  41449. group.remove(edge);
  41450. });
  41451. } else if (edgeShape === 'polyline' && seriesScope.layout === 'orthogonal') {
  41452. updateProps(edge, {
  41453. shape: {
  41454. parentPoint: [sourceLayout.x, sourceLayout.y],
  41455. childPoints: [[sourceLayout.x, sourceLayout.y]]
  41456. },
  41457. style: {
  41458. opacity: 0
  41459. }
  41460. }, seriesModel, function () {
  41461. group.remove(edge);
  41462. });
  41463. }
  41464. }
  41465. }
  41466. function getEdgeShape(seriesScope, sourceLayout, targetLayout) {
  41467. var cpx1;
  41468. var cpy1;
  41469. var cpx2;
  41470. var cpy2;
  41471. var orient = seriesScope.orient;
  41472. var x1;
  41473. var x2;
  41474. var y1;
  41475. var y2;
  41476. if (seriesScope.layout === 'radial') {
  41477. x1 = sourceLayout.rawX;
  41478. y1 = sourceLayout.rawY;
  41479. x2 = targetLayout.rawX;
  41480. y2 = targetLayout.rawY;
  41481. var radialCoor1 = radialCoordinate(x1, y1);
  41482. var radialCoor2 = radialCoordinate(x1, y1 + (y2 - y1) * seriesScope.curvature);
  41483. var radialCoor3 = radialCoordinate(x2, y2 + (y1 - y2) * seriesScope.curvature);
  41484. var radialCoor4 = radialCoordinate(x2, y2);
  41485. return {
  41486. x1: radialCoor1.x,
  41487. y1: radialCoor1.y,
  41488. x2: radialCoor4.x,
  41489. y2: radialCoor4.y,
  41490. cpx1: radialCoor2.x,
  41491. cpy1: radialCoor2.y,
  41492. cpx2: radialCoor3.x,
  41493. cpy2: radialCoor3.y
  41494. };
  41495. } else {
  41496. x1 = sourceLayout.x;
  41497. y1 = sourceLayout.y;
  41498. x2 = targetLayout.x;
  41499. y2 = targetLayout.y;
  41500. if (orient === 'LR' || orient === 'RL') {
  41501. cpx1 = x1 + (x2 - x1) * seriesScope.curvature;
  41502. cpy1 = y1;
  41503. cpx2 = x2 + (x1 - x2) * seriesScope.curvature;
  41504. cpy2 = y2;
  41505. }
  41506. if (orient === 'TB' || orient === 'BT') {
  41507. cpx1 = x1;
  41508. cpy1 = y1 + (y2 - y1) * seriesScope.curvature;
  41509. cpx2 = x2;
  41510. cpy2 = y2 + (y1 - y2) * seriesScope.curvature;
  41511. }
  41512. }
  41513. return {
  41514. x1: x1,
  41515. y1: y1,
  41516. x2: x2,
  41517. y2: y2,
  41518. cpx1: cpx1,
  41519. cpy1: cpy1,
  41520. cpx2: cpx2,
  41521. cpy2: cpy2
  41522. };
  41523. }
  41524. /*
  41525. * Licensed to the Apache Software Foundation (ASF) under one
  41526. * or more contributor license agreements. See the NOTICE file
  41527. * distributed with this work for additional information
  41528. * regarding copyright ownership. The ASF licenses this file
  41529. * to you under the Apache License, Version 2.0 (the
  41530. * "License"); you may not use this file except in compliance
  41531. * with the License. You may obtain a copy of the License at
  41532. *
  41533. * http://www.apache.org/licenses/LICENSE-2.0
  41534. *
  41535. * Unless required by applicable law or agreed to in writing,
  41536. * software distributed under the License is distributed on an
  41537. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41538. * KIND, either express or implied. See the License for the
  41539. * specific language governing permissions and limitations
  41540. * under the License.
  41541. */
  41542. /**
  41543. * @param {module:echarts/coord/View} view
  41544. * @param {Object} payload
  41545. * @param {Object} [zoomLimit]
  41546. */
  41547. function updateCenterAndZoom(view, payload, zoomLimit) {
  41548. var previousZoom = view.getZoom();
  41549. var center = view.getCenter();
  41550. var zoom = payload.zoom;
  41551. var point = view.dataToPoint(center);
  41552. if (payload.dx != null && payload.dy != null) {
  41553. point[0] -= payload.dx;
  41554. point[1] -= payload.dy;
  41555. var center = view.pointToData(point);
  41556. view.setCenter(center);
  41557. }
  41558. if (zoom != null) {
  41559. if (zoomLimit) {
  41560. var zoomMin = zoomLimit.min || 0;
  41561. var zoomMax = zoomLimit.max || Infinity;
  41562. zoom = Math.max(Math.min(previousZoom * zoom, zoomMax), zoomMin) / previousZoom;
  41563. } // Zoom on given point(originX, originY)
  41564. view.scale[0] *= zoom;
  41565. view.scale[1] *= zoom;
  41566. var position = view.position;
  41567. var fixX = (payload.originX - position[0]) * (zoom - 1);
  41568. var fixY = (payload.originY - position[1]) * (zoom - 1);
  41569. position[0] -= fixX;
  41570. position[1] -= fixY;
  41571. view.updateTransform(); // Get the new center
  41572. var center = view.pointToData(point);
  41573. view.setCenter(center);
  41574. view.setZoom(zoom * previousZoom);
  41575. }
  41576. return {
  41577. center: view.getCenter(),
  41578. zoom: view.getZoom()
  41579. };
  41580. }
  41581. /*
  41582. * Licensed to the Apache Software Foundation (ASF) under one
  41583. * or more contributor license agreements. See the NOTICE file
  41584. * distributed with this work for additional information
  41585. * regarding copyright ownership. The ASF licenses this file
  41586. * to you under the Apache License, Version 2.0 (the
  41587. * "License"); you may not use this file except in compliance
  41588. * with the License. You may obtain a copy of the License at
  41589. *
  41590. * http://www.apache.org/licenses/LICENSE-2.0
  41591. *
  41592. * Unless required by applicable law or agreed to in writing,
  41593. * software distributed under the License is distributed on an
  41594. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41595. * KIND, either express or implied. See the License for the
  41596. * specific language governing permissions and limitations
  41597. * under the License.
  41598. */
  41599. registerAction({
  41600. type: 'treeExpandAndCollapse',
  41601. event: 'treeExpandAndCollapse',
  41602. update: 'update'
  41603. }, function (payload, ecModel) {
  41604. ecModel.eachComponent({
  41605. mainType: 'series',
  41606. subType: 'tree',
  41607. query: payload
  41608. }, function (seriesModel) {
  41609. var dataIndex = payload.dataIndex;
  41610. var tree = seriesModel.getData().tree;
  41611. var node = tree.getNodeByDataIndex(dataIndex);
  41612. node.isExpand = !node.isExpand;
  41613. });
  41614. });
  41615. registerAction({
  41616. type: 'treeRoam',
  41617. event: 'treeRoam',
  41618. // Here we set 'none' instead of 'update', because roam action
  41619. // just need to update the transform matrix without having to recalculate
  41620. // the layout. So don't need to go through the whole update process, such
  41621. // as 'dataPrcocess', 'coordSystemUpdate', 'layout' and so on.
  41622. update: 'none'
  41623. }, function (payload, ecModel) {
  41624. ecModel.eachComponent({
  41625. mainType: 'series',
  41626. subType: 'tree',
  41627. query: payload
  41628. }, function (seriesModel) {
  41629. var coordSys = seriesModel.coordinateSystem;
  41630. var res = updateCenterAndZoom(coordSys, payload);
  41631. seriesModel.setCenter && seriesModel.setCenter(res.center);
  41632. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  41633. });
  41634. });
  41635. /*
  41636. * Licensed to the Apache Software Foundation (ASF) under one
  41637. * or more contributor license agreements. See the NOTICE file
  41638. * distributed with this work for additional information
  41639. * regarding copyright ownership. The ASF licenses this file
  41640. * to you under the Apache License, Version 2.0 (the
  41641. * "License"); you may not use this file except in compliance
  41642. * with the License. You may obtain a copy of the License at
  41643. *
  41644. * http://www.apache.org/licenses/LICENSE-2.0
  41645. *
  41646. * Unless required by applicable law or agreed to in writing,
  41647. * software distributed under the License is distributed on an
  41648. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41649. * KIND, either express or implied. See the License for the
  41650. * specific language governing permissions and limitations
  41651. * under the License.
  41652. */
  41653. /**
  41654. * Traverse the tree from bottom to top and do something
  41655. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  41656. * @param {Function} callback
  41657. */
  41658. function eachAfter(root, callback, separation) {
  41659. var nodes = [root];
  41660. var next = [];
  41661. var node;
  41662. while (node = nodes.pop()) {
  41663. // jshint ignore:line
  41664. next.push(node);
  41665. if (node.isExpand) {
  41666. var children = node.children;
  41667. if (children.length) {
  41668. for (var i = 0; i < children.length; i++) {
  41669. nodes.push(children[i]);
  41670. }
  41671. }
  41672. }
  41673. }
  41674. while (node = next.pop()) {
  41675. // jshint ignore:line
  41676. callback(node, separation);
  41677. }
  41678. }
  41679. /**
  41680. * Traverse the tree from top to bottom and do something
  41681. * @param {module:echarts/data/Tree~TreeNode} root The real root of the tree
  41682. * @param {Function} callback
  41683. */
  41684. function eachBefore(root, callback) {
  41685. var nodes = [root];
  41686. var node;
  41687. while (node = nodes.pop()) {
  41688. // jshint ignore:line
  41689. callback(node);
  41690. if (node.isExpand) {
  41691. var children = node.children;
  41692. if (children.length) {
  41693. for (var i = children.length - 1; i >= 0; i--) {
  41694. nodes.push(children[i]);
  41695. }
  41696. }
  41697. }
  41698. }
  41699. }
  41700. /*
  41701. * Licensed to the Apache Software Foundation (ASF) under one
  41702. * or more contributor license agreements. See the NOTICE file
  41703. * distributed with this work for additional information
  41704. * regarding copyright ownership. The ASF licenses this file
  41705. * to you under the Apache License, Version 2.0 (the
  41706. * "License"); you may not use this file except in compliance
  41707. * with the License. You may obtain a copy of the License at
  41708. *
  41709. * http://www.apache.org/licenses/LICENSE-2.0
  41710. *
  41711. * Unless required by applicable law or agreed to in writing,
  41712. * software distributed under the License is distributed on an
  41713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41714. * KIND, either express or implied. See the License for the
  41715. * specific language governing permissions and limitations
  41716. * under the License.
  41717. */
  41718. var treeLayout = function (ecModel, api) {
  41719. ecModel.eachSeriesByType('tree', function (seriesModel) {
  41720. commonLayout(seriesModel, api);
  41721. });
  41722. };
  41723. function commonLayout(seriesModel, api) {
  41724. var layoutInfo = getViewRect$1(seriesModel, api);
  41725. seriesModel.layoutInfo = layoutInfo;
  41726. var layout = seriesModel.get('layout');
  41727. var width = 0;
  41728. var height = 0;
  41729. var separation$$1 = null;
  41730. if (layout === 'radial') {
  41731. width = 2 * Math.PI;
  41732. height = Math.min(layoutInfo.height, layoutInfo.width) / 2;
  41733. separation$$1 = separation(function (node1, node2) {
  41734. return (node1.parentNode === node2.parentNode ? 1 : 2) / node1.depth;
  41735. });
  41736. } else {
  41737. width = layoutInfo.width;
  41738. height = layoutInfo.height;
  41739. separation$$1 = separation();
  41740. }
  41741. var virtualRoot = seriesModel.getData().tree.root;
  41742. var realRoot = virtualRoot.children[0];
  41743. if (realRoot) {
  41744. init$2(virtualRoot);
  41745. eachAfter(realRoot, firstWalk, separation$$1);
  41746. virtualRoot.hierNode.modifier = -realRoot.hierNode.prelim;
  41747. eachBefore(realRoot, secondWalk);
  41748. var left = realRoot;
  41749. var right = realRoot;
  41750. var bottom = realRoot;
  41751. eachBefore(realRoot, function (node) {
  41752. var x = node.getLayout().x;
  41753. if (x < left.getLayout().x) {
  41754. left = node;
  41755. }
  41756. if (x > right.getLayout().x) {
  41757. right = node;
  41758. }
  41759. if (node.depth > bottom.depth) {
  41760. bottom = node;
  41761. }
  41762. });
  41763. var delta = left === right ? 1 : separation$$1(left, right) / 2;
  41764. var tx = delta - left.getLayout().x;
  41765. var kx = 0;
  41766. var ky = 0;
  41767. var coorX = 0;
  41768. var coorY = 0;
  41769. if (layout === 'radial') {
  41770. kx = width / (right.getLayout().x + delta + tx); // here we use (node.depth - 1), bucause the real root's depth is 1
  41771. ky = height / (bottom.depth - 1 || 1);
  41772. eachBefore(realRoot, function (node) {
  41773. coorX = (node.getLayout().x + tx) * kx;
  41774. coorY = (node.depth - 1) * ky;
  41775. var finalCoor = radialCoordinate(coorX, coorY);
  41776. node.setLayout({
  41777. x: finalCoor.x,
  41778. y: finalCoor.y,
  41779. rawX: coorX,
  41780. rawY: coorY
  41781. }, true);
  41782. });
  41783. } else {
  41784. var orient = seriesModel.getOrient();
  41785. if (orient === 'RL' || orient === 'LR') {
  41786. ky = height / (right.getLayout().x + delta + tx);
  41787. kx = width / (bottom.depth - 1 || 1);
  41788. eachBefore(realRoot, function (node) {
  41789. coorY = (node.getLayout().x + tx) * ky;
  41790. coorX = orient === 'LR' ? (node.depth - 1) * kx : width - (node.depth - 1) * kx;
  41791. node.setLayout({
  41792. x: coorX,
  41793. y: coorY
  41794. }, true);
  41795. });
  41796. } else if (orient === 'TB' || orient === 'BT') {
  41797. kx = width / (right.getLayout().x + delta + tx);
  41798. ky = height / (bottom.depth - 1 || 1);
  41799. eachBefore(realRoot, function (node) {
  41800. coorX = (node.getLayout().x + tx) * kx;
  41801. coorY = orient === 'TB' ? (node.depth - 1) * ky : height - (node.depth - 1) * ky;
  41802. node.setLayout({
  41803. x: coorX,
  41804. y: coorY
  41805. }, true);
  41806. });
  41807. }
  41808. }
  41809. }
  41810. }
  41811. /*
  41812. * Licensed to the Apache Software Foundation (ASF) under one
  41813. * or more contributor license agreements. See the NOTICE file
  41814. * distributed with this work for additional information
  41815. * regarding copyright ownership. The ASF licenses this file
  41816. * to you under the Apache License, Version 2.0 (the
  41817. * "License"); you may not use this file except in compliance
  41818. * with the License. You may obtain a copy of the License at
  41819. *
  41820. * http://www.apache.org/licenses/LICENSE-2.0
  41821. *
  41822. * Unless required by applicable law or agreed to in writing,
  41823. * software distributed under the License is distributed on an
  41824. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41825. * KIND, either express or implied. See the License for the
  41826. * specific language governing permissions and limitations
  41827. * under the License.
  41828. */
  41829. registerVisual(visualSymbol('tree', 'circle'));
  41830. registerLayout(treeLayout);
  41831. /*
  41832. * Licensed to the Apache Software Foundation (ASF) under one
  41833. * or more contributor license agreements. See the NOTICE file
  41834. * distributed with this work for additional information
  41835. * regarding copyright ownership. The ASF licenses this file
  41836. * to you under the Apache License, Version 2.0 (the
  41837. * "License"); you may not use this file except in compliance
  41838. * with the License. You may obtain a copy of the License at
  41839. *
  41840. * http://www.apache.org/licenses/LICENSE-2.0
  41841. *
  41842. * Unless required by applicable law or agreed to in writing,
  41843. * software distributed under the License is distributed on an
  41844. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41845. * KIND, either express or implied. See the License for the
  41846. * specific language governing permissions and limitations
  41847. * under the License.
  41848. */
  41849. function retrieveTargetInfo(payload, validPayloadTypes, seriesModel) {
  41850. if (payload && indexOf(validPayloadTypes, payload.type) >= 0) {
  41851. var root = seriesModel.getData().tree.root;
  41852. var targetNode = payload.targetNode;
  41853. if (typeof targetNode === 'string') {
  41854. targetNode = root.getNodeById(targetNode);
  41855. }
  41856. if (targetNode && root.contains(targetNode)) {
  41857. return {
  41858. node: targetNode
  41859. };
  41860. }
  41861. var targetNodeId = payload.targetNodeId;
  41862. if (targetNodeId != null && (targetNode = root.getNodeById(targetNodeId))) {
  41863. return {
  41864. node: targetNode
  41865. };
  41866. }
  41867. }
  41868. } // Not includes the given node at the last item.
  41869. function getPathToRoot(node) {
  41870. var path = [];
  41871. while (node) {
  41872. node = node.parentNode;
  41873. node && path.push(node);
  41874. }
  41875. return path.reverse();
  41876. }
  41877. function aboveViewRoot(viewRoot, node) {
  41878. var viewPath = getPathToRoot(viewRoot);
  41879. return indexOf(viewPath, node) >= 0;
  41880. } // From root to the input node (the input node will be included).
  41881. function wrapTreePathInfo(node, seriesModel) {
  41882. var treePathInfo = [];
  41883. while (node) {
  41884. var nodeDataIndex = node.dataIndex;
  41885. treePathInfo.push({
  41886. name: node.name,
  41887. dataIndex: nodeDataIndex,
  41888. value: seriesModel.getRawValue(nodeDataIndex)
  41889. });
  41890. node = node.parentNode;
  41891. }
  41892. treePathInfo.reverse();
  41893. return treePathInfo;
  41894. }
  41895. /*
  41896. * Licensed to the Apache Software Foundation (ASF) under one
  41897. * or more contributor license agreements. See the NOTICE file
  41898. * distributed with this work for additional information
  41899. * regarding copyright ownership. The ASF licenses this file
  41900. * to you under the Apache License, Version 2.0 (the
  41901. * "License"); you may not use this file except in compliance
  41902. * with the License. You may obtain a copy of the License at
  41903. *
  41904. * http://www.apache.org/licenses/LICENSE-2.0
  41905. *
  41906. * Unless required by applicable law or agreed to in writing,
  41907. * software distributed under the License is distributed on an
  41908. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  41909. * KIND, either express or implied. See the License for the
  41910. * specific language governing permissions and limitations
  41911. * under the License.
  41912. */
  41913. SeriesModel.extend({
  41914. type: 'series.treemap',
  41915. layoutMode: 'box',
  41916. dependencies: ['grid', 'polar'],
  41917. preventUsingHoverLayer: true,
  41918. /**
  41919. * @type {module:echarts/data/Tree~Node}
  41920. */
  41921. _viewRoot: null,
  41922. defaultOption: {
  41923. // Disable progressive rendering
  41924. progressive: 0,
  41925. // center: ['50%', '50%'], // not supported in ec3.
  41926. // size: ['80%', '80%'], // deprecated, compatible with ec2.
  41927. left: 'center',
  41928. top: 'middle',
  41929. right: null,
  41930. bottom: null,
  41931. width: '80%',
  41932. height: '80%',
  41933. sort: true,
  41934. // Can be null or false or true
  41935. // (order by desc default, asc not supported yet (strange effect))
  41936. clipWindow: 'origin',
  41937. // Size of clipped window when zooming. 'origin' or 'fullscreen'
  41938. squareRatio: 0.5 * (1 + Math.sqrt(5)),
  41939. // golden ratio
  41940. leafDepth: null,
  41941. // Nodes on depth from root are regarded as leaves.
  41942. // Count from zero (zero represents only view root).
  41943. drillDownIcon: '▶',
  41944. // Use html character temporarily because it is complicated
  41945. // to align specialized icon. ▷▶❒❐▼✚
  41946. zoomToNodeRatio: 0.32 * 0.32,
  41947. // Be effective when using zoomToNode. Specify the proportion of the
  41948. // target node area in the view area.
  41949. roam: true,
  41950. // true, false, 'scale' or 'zoom', 'move'.
  41951. nodeClick: 'zoomToNode',
  41952. // Leaf node click behaviour: 'zoomToNode', 'link', false.
  41953. // If leafDepth is set and clicking a node which has children but
  41954. // be on left depth, the behaviour would be changing root. Otherwise
  41955. // use behavious defined above.
  41956. animation: true,
  41957. animationDurationUpdate: 900,
  41958. animationEasing: 'quinticInOut',
  41959. breadcrumb: {
  41960. show: true,
  41961. height: 22,
  41962. left: 'center',
  41963. top: 'bottom',
  41964. // right
  41965. // bottom
  41966. emptyItemWidth: 25,
  41967. // Width of empty node.
  41968. itemStyle: {
  41969. color: 'rgba(0,0,0,0.7)',
  41970. //'#5793f3',
  41971. borderColor: 'rgba(255,255,255,0.7)',
  41972. borderWidth: 1,
  41973. shadowColor: 'rgba(150,150,150,1)',
  41974. shadowBlur: 3,
  41975. shadowOffsetX: 0,
  41976. shadowOffsetY: 0,
  41977. textStyle: {
  41978. color: '#fff'
  41979. }
  41980. },
  41981. emphasis: {
  41982. textStyle: {}
  41983. }
  41984. },
  41985. label: {
  41986. show: true,
  41987. // Do not use textDistance, for ellipsis rect just the same as treemap node rect.
  41988. distance: 0,
  41989. padding: 5,
  41990. position: 'inside',
  41991. // Can be [5, '5%'] or position stirng like 'insideTopLeft', ...
  41992. // formatter: null,
  41993. color: '#fff',
  41994. ellipsis: true // align
  41995. // verticalAlign
  41996. },
  41997. upperLabel: {
  41998. // Label when node is parent.
  41999. show: false,
  42000. position: [0, '50%'],
  42001. height: 20,
  42002. // formatter: null,
  42003. color: '#fff',
  42004. ellipsis: true,
  42005. // align: null,
  42006. verticalAlign: 'middle'
  42007. },
  42008. itemStyle: {
  42009. color: null,
  42010. // Can be 'none' if not necessary.
  42011. colorAlpha: null,
  42012. // Can be 'none' if not necessary.
  42013. colorSaturation: null,
  42014. // Can be 'none' if not necessary.
  42015. borderWidth: 0,
  42016. gapWidth: 0,
  42017. borderColor: '#fff',
  42018. borderColorSaturation: null // If specified, borderColor will be ineffective, and the
  42019. // border color is evaluated by color of current node and
  42020. // borderColorSaturation.
  42021. },
  42022. emphasis: {
  42023. upperLabel: {
  42024. show: true,
  42025. position: [0, '50%'],
  42026. color: '#fff',
  42027. ellipsis: true,
  42028. verticalAlign: 'middle'
  42029. }
  42030. },
  42031. visualDimension: 0,
  42032. // Can be 0, 1, 2, 3.
  42033. visualMin: null,
  42034. visualMax: null,
  42035. color: [],
  42036. // + treemapSeries.color should not be modified. Please only modified
  42037. // level[n].color (if necessary).
  42038. // + Specify color list of each level. level[0].color would be global
  42039. // color list if not specified. (see method `setDefault`).
  42040. // + But set as a empty array to forbid fetch color from global palette
  42041. // when using nodeModel.get('color'), otherwise nodes on deep level
  42042. // will always has color palette set and are not able to inherit color
  42043. // from parent node.
  42044. // + TreemapSeries.color can not be set as 'none', otherwise effect
  42045. // legend color fetching (see seriesColor.js).
  42046. colorAlpha: null,
  42047. // Array. Specify color alpha range of each level, like [0.2, 0.8]
  42048. colorSaturation: null,
  42049. // Array. Specify color saturation of each level, like [0.2, 0.5]
  42050. colorMappingBy: 'index',
  42051. // 'value' or 'index' or 'id'.
  42052. visibleMin: 10,
  42053. // If area less than this threshold (unit: pixel^2), node will not
  42054. // be rendered. Only works when sort is 'asc' or 'desc'.
  42055. childrenVisibleMin: null,
  42056. // If area of a node less than this threshold (unit: pixel^2),
  42057. // grandchildren will not show.
  42058. // Why grandchildren? If not grandchildren but children,
  42059. // some siblings show children and some not,
  42060. // the appearance may be mess and not consistent,
  42061. levels: [] // Each item: {
  42062. // visibleMin, itemStyle, visualDimension, label
  42063. // }
  42064. // data: {
  42065. // value: [],
  42066. // children: [],
  42067. // link: 'http://xxx.xxx.xxx',
  42068. // target: 'blank' or 'self'
  42069. // }
  42070. },
  42071. /**
  42072. * @override
  42073. */
  42074. getInitialData: function (option, ecModel) {
  42075. // Create a virtual root.
  42076. var root = {
  42077. name: option.name,
  42078. children: option.data
  42079. };
  42080. completeTreeValue(root);
  42081. var levels = option.levels || [];
  42082. levels = option.levels = setDefault(levels, ecModel);
  42083. var levelModels = map(levels || [], function (levelDefine) {
  42084. return new Model(levelDefine, this, ecModel);
  42085. }, this); // Make sure always a new tree is created when setOption,
  42086. // in TreemapView, we check whether oldTree === newTree
  42087. // to choose mappings approach among old shapes and new shapes.
  42088. var tree = Tree.createTree(root, this, null, beforeLink);
  42089. function beforeLink(nodeData) {
  42090. nodeData.wrapMethod('getItemModel', function (model, idx) {
  42091. var node = tree.getNodeByDataIndex(idx);
  42092. var levelModel = levelModels[node.depth];
  42093. levelModel && (model.parentModel = levelModel);
  42094. return model;
  42095. });
  42096. }
  42097. return tree.data;
  42098. },
  42099. optionUpdated: function () {
  42100. this.resetViewRoot();
  42101. },
  42102. /**
  42103. * @override
  42104. * @param {number} dataIndex
  42105. * @param {boolean} [mutipleSeries=false]
  42106. */
  42107. formatTooltip: function (dataIndex) {
  42108. var data = this.getData();
  42109. var value = this.getRawValue(dataIndex);
  42110. var formattedValue = isArray(value) ? addCommas(value[0]) : addCommas(value);
  42111. var name = data.getName(dataIndex);
  42112. return encodeHTML(name + ': ' + formattedValue);
  42113. },
  42114. /**
  42115. * Add tree path to tooltip param
  42116. *
  42117. * @override
  42118. * @param {number} dataIndex
  42119. * @return {Object}
  42120. */
  42121. getDataParams: function (dataIndex) {
  42122. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  42123. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  42124. params.treePathInfo = wrapTreePathInfo(node, this);
  42125. return params;
  42126. },
  42127. /**
  42128. * @public
  42129. * @param {Object} layoutInfo {
  42130. * x: containerGroup x
  42131. * y: containerGroup y
  42132. * width: containerGroup width
  42133. * height: containerGroup height
  42134. * }
  42135. */
  42136. setLayoutInfo: function (layoutInfo) {
  42137. /**
  42138. * @readOnly
  42139. * @type {Object}
  42140. */
  42141. this.layoutInfo = this.layoutInfo || {};
  42142. extend(this.layoutInfo, layoutInfo);
  42143. },
  42144. /**
  42145. * @param {string} id
  42146. * @return {number} index
  42147. */
  42148. mapIdToIndex: function (id) {
  42149. // A feature is implemented:
  42150. // index is monotone increasing with the sequence of
  42151. // input id at the first time.
  42152. // This feature can make sure that each data item and its
  42153. // mapped color have the same index between data list and
  42154. // color list at the beginning, which is useful for user
  42155. // to adjust data-color mapping.
  42156. /**
  42157. * @private
  42158. * @type {Object}
  42159. */
  42160. var idIndexMap = this._idIndexMap;
  42161. if (!idIndexMap) {
  42162. idIndexMap = this._idIndexMap = createHashMap();
  42163. /**
  42164. * @private
  42165. * @type {number}
  42166. */
  42167. this._idIndexMapCount = 0;
  42168. }
  42169. var index = idIndexMap.get(id);
  42170. if (index == null) {
  42171. idIndexMap.set(id, index = this._idIndexMapCount++);
  42172. }
  42173. return index;
  42174. },
  42175. getViewRoot: function () {
  42176. return this._viewRoot;
  42177. },
  42178. /**
  42179. * @param {module:echarts/data/Tree~Node} [viewRoot]
  42180. */
  42181. resetViewRoot: function (viewRoot) {
  42182. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  42183. var root = this.getRawData().tree.root;
  42184. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  42185. this._viewRoot = root;
  42186. }
  42187. }
  42188. });
  42189. /**
  42190. * @param {Object} dataNode
  42191. */
  42192. function completeTreeValue(dataNode) {
  42193. // Postorder travel tree.
  42194. // If value of none-leaf node is not set,
  42195. // calculate it by suming up the value of all children.
  42196. var sum = 0;
  42197. each$1(dataNode.children, function (child) {
  42198. completeTreeValue(child);
  42199. var childValue = child.value;
  42200. isArray(childValue) && (childValue = childValue[0]);
  42201. sum += childValue;
  42202. });
  42203. var thisValue = dataNode.value;
  42204. if (isArray(thisValue)) {
  42205. thisValue = thisValue[0];
  42206. }
  42207. if (thisValue == null || isNaN(thisValue)) {
  42208. thisValue = sum;
  42209. } // Value should not less than 0.
  42210. if (thisValue < 0) {
  42211. thisValue = 0;
  42212. }
  42213. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  42214. }
  42215. /**
  42216. * set default to level configuration
  42217. */
  42218. function setDefault(levels, ecModel) {
  42219. var globalColorList = ecModel.get('color');
  42220. if (!globalColorList) {
  42221. return;
  42222. }
  42223. levels = levels || [];
  42224. var hasColorDefine;
  42225. each$1(levels, function (levelDefine) {
  42226. var model = new Model(levelDefine);
  42227. var modelColor = model.get('color');
  42228. if (model.get('itemStyle.color') || modelColor && modelColor !== 'none') {
  42229. hasColorDefine = true;
  42230. }
  42231. });
  42232. if (!hasColorDefine) {
  42233. var level0 = levels[0] || (levels[0] = {});
  42234. level0.color = globalColorList.slice();
  42235. }
  42236. return levels;
  42237. }
  42238. /*
  42239. * Licensed to the Apache Software Foundation (ASF) under one
  42240. * or more contributor license agreements. See the NOTICE file
  42241. * distributed with this work for additional information
  42242. * regarding copyright ownership. The ASF licenses this file
  42243. * to you under the Apache License, Version 2.0 (the
  42244. * "License"); you may not use this file except in compliance
  42245. * with the License. You may obtain a copy of the License at
  42246. *
  42247. * http://www.apache.org/licenses/LICENSE-2.0
  42248. *
  42249. * Unless required by applicable law or agreed to in writing,
  42250. * software distributed under the License is distributed on an
  42251. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42252. * KIND, either express or implied. See the License for the
  42253. * specific language governing permissions and limitations
  42254. * under the License.
  42255. */
  42256. var TEXT_PADDING = 8;
  42257. var ITEM_GAP = 8;
  42258. var ARRAY_LENGTH = 5;
  42259. function Breadcrumb(containerGroup) {
  42260. /**
  42261. * @private
  42262. * @type {module:zrender/container/Group}
  42263. */
  42264. this.group = new Group();
  42265. containerGroup.add(this.group);
  42266. }
  42267. Breadcrumb.prototype = {
  42268. constructor: Breadcrumb,
  42269. render: function (seriesModel, api, targetNode, onSelect) {
  42270. var model = seriesModel.getModel('breadcrumb');
  42271. var thisGroup = this.group;
  42272. thisGroup.removeAll();
  42273. if (!model.get('show') || !targetNode) {
  42274. return;
  42275. }
  42276. var normalStyleModel = model.getModel('itemStyle'); // var emphasisStyleModel = model.getModel('emphasis.itemStyle');
  42277. var textStyleModel = normalStyleModel.getModel('textStyle');
  42278. var layoutParam = {
  42279. pos: {
  42280. left: model.get('left'),
  42281. right: model.get('right'),
  42282. top: model.get('top'),
  42283. bottom: model.get('bottom')
  42284. },
  42285. box: {
  42286. width: api.getWidth(),
  42287. height: api.getHeight()
  42288. },
  42289. emptyItemWidth: model.get('emptyItemWidth'),
  42290. totalWidth: 0,
  42291. renderList: []
  42292. };
  42293. this._prepare(targetNode, layoutParam, textStyleModel);
  42294. this._renderContent(seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect);
  42295. positionElement(thisGroup, layoutParam.pos, layoutParam.box);
  42296. },
  42297. /**
  42298. * Prepare render list and total width
  42299. * @private
  42300. */
  42301. _prepare: function (targetNode, layoutParam, textStyleModel) {
  42302. for (var node = targetNode; node; node = node.parentNode) {
  42303. var text = node.getModel().get('name');
  42304. var textRect = textStyleModel.getTextRect(text);
  42305. var itemWidth = Math.max(textRect.width + TEXT_PADDING * 2, layoutParam.emptyItemWidth);
  42306. layoutParam.totalWidth += itemWidth + ITEM_GAP;
  42307. layoutParam.renderList.push({
  42308. node: node,
  42309. text: text,
  42310. width: itemWidth
  42311. });
  42312. }
  42313. },
  42314. /**
  42315. * @private
  42316. */
  42317. _renderContent: function (seriesModel, layoutParam, normalStyleModel, textStyleModel, onSelect) {
  42318. // Start rendering.
  42319. var lastX = 0;
  42320. var emptyItemWidth = layoutParam.emptyItemWidth;
  42321. var height = seriesModel.get('breadcrumb.height');
  42322. var availableSize = getAvailableSize(layoutParam.pos, layoutParam.box);
  42323. var totalWidth = layoutParam.totalWidth;
  42324. var renderList = layoutParam.renderList;
  42325. for (var i = renderList.length - 1; i >= 0; i--) {
  42326. var item = renderList[i];
  42327. var itemNode = item.node;
  42328. var itemWidth = item.width;
  42329. var text = item.text; // Hdie text and shorten width if necessary.
  42330. if (totalWidth > availableSize.width) {
  42331. totalWidth -= itemWidth - emptyItemWidth;
  42332. itemWidth = emptyItemWidth;
  42333. text = null;
  42334. }
  42335. var el = new Polygon({
  42336. shape: {
  42337. points: makeItemPoints(lastX, 0, itemWidth, height, i === renderList.length - 1, i === 0)
  42338. },
  42339. style: defaults(normalStyleModel.getItemStyle(), {
  42340. lineJoin: 'bevel',
  42341. text: text,
  42342. textFill: textStyleModel.getTextColor(),
  42343. textFont: textStyleModel.getFont()
  42344. }),
  42345. z: 10,
  42346. onclick: curry(onSelect, itemNode)
  42347. });
  42348. this.group.add(el);
  42349. packEventData(el, seriesModel, itemNode);
  42350. lastX += itemWidth + ITEM_GAP;
  42351. }
  42352. },
  42353. /**
  42354. * @override
  42355. */
  42356. remove: function () {
  42357. this.group.removeAll();
  42358. }
  42359. };
  42360. function makeItemPoints(x, y, itemWidth, itemHeight, head, tail) {
  42361. var points = [[head ? x : x - ARRAY_LENGTH, y], [x + itemWidth, y], [x + itemWidth, y + itemHeight], [head ? x : x - ARRAY_LENGTH, y + itemHeight]];
  42362. !tail && points.splice(2, 0, [x + itemWidth + ARRAY_LENGTH, y + itemHeight / 2]);
  42363. !head && points.push([x, y + itemHeight / 2]);
  42364. return points;
  42365. } // Package custom mouse event.
  42366. function packEventData(el, seriesModel, itemNode) {
  42367. el.eventData = {
  42368. componentType: 'series',
  42369. componentSubType: 'treemap',
  42370. componentIndex: seriesModel.componentIndex,
  42371. seriesIndex: seriesModel.componentIndex,
  42372. seriesName: seriesModel.name,
  42373. seriesType: 'treemap',
  42374. selfType: 'breadcrumb',
  42375. // Distinguish with click event on treemap node.
  42376. nodeData: {
  42377. dataIndex: itemNode && itemNode.dataIndex,
  42378. name: itemNode && itemNode.name
  42379. },
  42380. treePathInfo: itemNode && wrapTreePathInfo(itemNode, seriesModel)
  42381. };
  42382. }
  42383. /*
  42384. * Licensed to the Apache Software Foundation (ASF) under one
  42385. * or more contributor license agreements. See the NOTICE file
  42386. * distributed with this work for additional information
  42387. * regarding copyright ownership. The ASF licenses this file
  42388. * to you under the Apache License, Version 2.0 (the
  42389. * "License"); you may not use this file except in compliance
  42390. * with the License. You may obtain a copy of the License at
  42391. *
  42392. * http://www.apache.org/licenses/LICENSE-2.0
  42393. *
  42394. * Unless required by applicable law or agreed to in writing,
  42395. * software distributed under the License is distributed on an
  42396. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42397. * KIND, either express or implied. See the License for the
  42398. * specific language governing permissions and limitations
  42399. * under the License.
  42400. */
  42401. /**
  42402. * @param {number} [time=500] Time in ms
  42403. * @param {string} [easing='linear']
  42404. * @param {number} [delay=0]
  42405. * @param {Function} [callback]
  42406. *
  42407. * @example
  42408. * // Animate position
  42409. * animation
  42410. * .createWrap()
  42411. * .add(el1, {position: [10, 10]})
  42412. * .add(el2, {shape: {width: 500}, style: {fill: 'red'}}, 400)
  42413. * .done(function () { // done })
  42414. * .start('cubicOut');
  42415. */
  42416. function createWrap() {
  42417. var storage = [];
  42418. var elExistsMap = {};
  42419. var doneCallback;
  42420. return {
  42421. /**
  42422. * Caution: a el can only be added once, otherwise 'done'
  42423. * might not be called. This method checks this (by el.id),
  42424. * suppresses adding and returns false when existing el found.
  42425. *
  42426. * @param {modele:zrender/Element} el
  42427. * @param {Object} target
  42428. * @param {number} [time=500]
  42429. * @param {number} [delay=0]
  42430. * @param {string} [easing='linear']
  42431. * @return {boolean} Whether adding succeeded.
  42432. *
  42433. * @example
  42434. * add(el, target, time, delay, easing);
  42435. * add(el, target, time, easing);
  42436. * add(el, target, time);
  42437. * add(el, target);
  42438. */
  42439. add: function (el, target, time, delay, easing) {
  42440. if (isString(delay)) {
  42441. easing = delay;
  42442. delay = 0;
  42443. }
  42444. if (elExistsMap[el.id]) {
  42445. return false;
  42446. }
  42447. elExistsMap[el.id] = 1;
  42448. storage.push({
  42449. el: el,
  42450. target: target,
  42451. time: time,
  42452. delay: delay,
  42453. easing: easing
  42454. });
  42455. return true;
  42456. },
  42457. /**
  42458. * Only execute when animation finished. Will not execute when any
  42459. * of 'stop' or 'stopAnimation' called.
  42460. *
  42461. * @param {Function} callback
  42462. */
  42463. done: function (callback) {
  42464. doneCallback = callback;
  42465. return this;
  42466. },
  42467. /**
  42468. * Will stop exist animation firstly.
  42469. */
  42470. start: function () {
  42471. var count = storage.length;
  42472. for (var i = 0, len = storage.length; i < len; i++) {
  42473. var item = storage[i];
  42474. item.el.animateTo(item.target, item.time, item.delay, item.easing, done);
  42475. }
  42476. return this;
  42477. function done() {
  42478. count--;
  42479. if (!count) {
  42480. storage.length = 0;
  42481. elExistsMap = {};
  42482. doneCallback && doneCallback();
  42483. }
  42484. }
  42485. }
  42486. };
  42487. }
  42488. /*
  42489. * Licensed to the Apache Software Foundation (ASF) under one
  42490. * or more contributor license agreements. See the NOTICE file
  42491. * distributed with this work for additional information
  42492. * regarding copyright ownership. The ASF licenses this file
  42493. * to you under the Apache License, Version 2.0 (the
  42494. * "License"); you may not use this file except in compliance
  42495. * with the License. You may obtain a copy of the License at
  42496. *
  42497. * http://www.apache.org/licenses/LICENSE-2.0
  42498. *
  42499. * Unless required by applicable law or agreed to in writing,
  42500. * software distributed under the License is distributed on an
  42501. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  42502. * KIND, either express or implied. See the License for the
  42503. * specific language governing permissions and limitations
  42504. * under the License.
  42505. */
  42506. var bind$1 = bind;
  42507. var Group$2 = Group;
  42508. var Rect$1 = Rect;
  42509. var each$8 = each$1;
  42510. var DRAG_THRESHOLD = 3;
  42511. var PATH_LABEL_NOAMAL = ['label'];
  42512. var PATH_LABEL_EMPHASIS = ['emphasis', 'label'];
  42513. var PATH_UPPERLABEL_NORMAL = ['upperLabel'];
  42514. var PATH_UPPERLABEL_EMPHASIS = ['emphasis', 'upperLabel'];
  42515. var Z_BASE = 10; // Should bigger than every z.
  42516. var Z_BG = 1;
  42517. var Z_CONTENT = 2;
  42518. var getItemStyleEmphasis = makeStyleMapper([['fill', 'color'], // `borderColor` and `borderWidth` has been occupied,
  42519. // so use `stroke` to indicate the stroke of the rect.
  42520. ['stroke', 'strokeColor'], ['lineWidth', 'strokeWidth'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor']]);
  42521. var getItemStyleNormal = function (model) {
  42522. // Normal style props should include emphasis style props.
  42523. var itemStyle = getItemStyleEmphasis(model); // Clear styles set by emphasis.
  42524. itemStyle.stroke = itemStyle.fill = itemStyle.lineWidth = null;
  42525. return itemStyle;
  42526. };
  42527. extendChartView({
  42528. type: 'treemap',
  42529. /**
  42530. * @override
  42531. */
  42532. init: function (o, api) {
  42533. /**
  42534. * @private
  42535. * @type {module:zrender/container/Group}
  42536. */
  42537. this._containerGroup;
  42538. /**
  42539. * @private
  42540. * @type {Object.<string, Array.<module:zrender/container/Group>>}
  42541. */
  42542. this._storage = createStorage();
  42543. /**
  42544. * @private
  42545. * @type {module:echarts/data/Tree}
  42546. */
  42547. this._oldTree;
  42548. /**
  42549. * @private
  42550. * @type {module:echarts/chart/treemap/Breadcrumb}
  42551. */
  42552. this._breadcrumb;
  42553. /**
  42554. * @private
  42555. * @type {module:echarts/component/helper/RoamController}
  42556. */
  42557. this._controller;
  42558. /**
  42559. * 'ready', 'animating'
  42560. * @private
  42561. */
  42562. this._state = 'ready';
  42563. },
  42564. /**
  42565. * @override
  42566. */
  42567. render: function (seriesModel, ecModel, api, payload) {
  42568. var models = ecModel.findComponents({
  42569. mainType: 'series',
  42570. subType: 'treemap',
  42571. query: payload
  42572. });
  42573. if (indexOf(models, seriesModel) < 0) {
  42574. return;
  42575. }
  42576. this.seriesModel = seriesModel;
  42577. this.api = api;
  42578. this.ecModel = ecModel;
  42579. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  42580. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  42581. var payloadType = payload && payload.type;
  42582. var layoutInfo = seriesModel.layoutInfo;
  42583. var isInit = !this._oldTree;
  42584. var thisStorage = this._storage; // Mark new root when action is treemapRootToNode.
  42585. var reRoot = payloadType === 'treemapRootToNode' && targetInfo && thisStorage ? {
  42586. rootNodeGroup: thisStorage.nodeGroup[targetInfo.node.getRawIndex()],
  42587. direction: payload.direction
  42588. } : null;
  42589. var containerGroup = this._giveContainerGroup(layoutInfo);
  42590. var renderResult = this._doRender(containerGroup, seriesModel, reRoot);
  42591. !isInit && (!payloadType || payloadType === 'treemapZoomToNode' || payloadType === 'treemapRootToNode') ? this._doAnimation(containerGroup, renderResult, seriesModel, reRoot) : renderResult.renderFinally();
  42592. this._resetController(api);
  42593. this._renderBreadcrumb(seriesModel, api, targetInfo);
  42594. },
  42595. /**
  42596. * @private
  42597. */
  42598. _giveContainerGroup: function (layoutInfo) {
  42599. var containerGroup = this._containerGroup;
  42600. if (!containerGroup) {
  42601. // FIXME
  42602. // 加一层containerGroup是为了clip,但是现在clip功能并没有实现。
  42603. containerGroup = this._containerGroup = new Group$2();
  42604. this._initEvents(containerGroup);
  42605. this.group.add(containerGroup);
  42606. }
  42607. containerGroup.attr('position', [layoutInfo.x, layoutInfo.y]);
  42608. return containerGroup;
  42609. },
  42610. /**
  42611. * @private
  42612. */
  42613. _doRender: function (containerGroup, seriesModel, reRoot) {
  42614. var thisTree = seriesModel.getData().tree;
  42615. var oldTree = this._oldTree; // Clear last shape records.
  42616. var lastsForAnimation = createStorage();
  42617. var thisStorage = createStorage();
  42618. var oldStorage = this._storage;
  42619. var willInvisibleEls = [];
  42620. var doRenderNode = curry(renderNode, seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls); // Notice: when thisTree and oldTree are the same tree (see list.cloneShallow),
  42621. // the oldTree is actually losted, so we can not find all of the old graphic
  42622. // elements from tree. So we use this stragegy: make element storage, move
  42623. // from old storage to new storage, clear old storage.
  42624. dualTravel(thisTree.root ? [thisTree.root] : [], oldTree && oldTree.root ? [oldTree.root] : [], containerGroup, thisTree === oldTree || !oldTree, 0); // Process all removing.
  42625. var willDeleteEls = clearStorage(oldStorage);
  42626. this._oldTree = thisTree;
  42627. this._storage = thisStorage;
  42628. return {
  42629. lastsForAnimation: lastsForAnimation,
  42630. willDeleteEls: willDeleteEls,
  42631. renderFinally: renderFinally
  42632. };
  42633. function dualTravel(thisViewChildren, oldViewChildren, parentGroup, sameTree, depth) {
  42634. // When 'render' is triggered by action,
  42635. // 'this' and 'old' may be the same tree,
  42636. // we use rawIndex in that case.
  42637. if (sameTree) {
  42638. oldViewChildren = thisViewChildren;
  42639. each$8(thisViewChildren, function (child, index) {
  42640. !child.isRemoved() && processNode(index, index);
  42641. });
  42642. } // Diff hierarchically (diff only in each subtree, but not whole).
  42643. // because, consistency of view is important.
  42644. else {
  42645. new DataDiffer(oldViewChildren, thisViewChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  42646. }
  42647. function getKey(node) {
  42648. // Identify by name or raw index.
  42649. return node.getId();
  42650. }
  42651. function processNode(newIndex, oldIndex) {
  42652. var thisNode = newIndex != null ? thisViewChildren[newIndex] : null;
  42653. var oldNode = oldIndex != null ? oldViewChildren[oldIndex] : null;
  42654. var group = doRenderNode(thisNode, oldNode, parentGroup, depth);
  42655. group && dualTravel(thisNode && thisNode.viewChildren || [], oldNode && oldNode.viewChildren || [], group, sameTree, depth + 1);
  42656. }
  42657. }
  42658. function clearStorage(storage) {
  42659. var willDeleteEls = createStorage();
  42660. storage && each$8(storage, function (store, storageName) {
  42661. var delEls = willDeleteEls[storageName];
  42662. each$8(store, function (el) {
  42663. el && (delEls.push(el), el.__tmWillDelete = 1);
  42664. });
  42665. });
  42666. return willDeleteEls;
  42667. }
  42668. function renderFinally() {
  42669. each$8(willDeleteEls, function (els) {
  42670. each$8(els, function (el) {
  42671. el.parent && el.parent.remove(el);
  42672. });
  42673. });
  42674. each$8(willInvisibleEls, function (el) {
  42675. el.invisible = true; // Setting invisible is for optimizing, so no need to set dirty,
  42676. // just mark as invisible.
  42677. el.dirty();
  42678. });
  42679. }
  42680. },
  42681. /**
  42682. * @private
  42683. */
  42684. _doAnimation: function (containerGroup, renderResult, seriesModel, reRoot) {
  42685. if (!seriesModel.get('animation')) {
  42686. return;
  42687. }
  42688. var duration = seriesModel.get('animationDurationUpdate');
  42689. var easing = seriesModel.get('animationEasing');
  42690. var animationWrap = createWrap(); // Make delete animations.
  42691. each$8(renderResult.willDeleteEls, function (store, storageName) {
  42692. each$8(store, function (el, rawIndex) {
  42693. if (el.invisible) {
  42694. return;
  42695. }
  42696. var parent = el.parent; // Always has parent, and parent is nodeGroup.
  42697. var target;
  42698. if (reRoot && reRoot.direction === 'drillDown') {
  42699. target = parent === reRoot.rootNodeGroup // This is the content element of view root.
  42700. // Only `content` will enter this branch, because
  42701. // `background` and `nodeGroup` will not be deleted.
  42702. ? {
  42703. shape: {
  42704. x: 0,
  42705. y: 0,
  42706. width: parent.__tmNodeWidth,
  42707. height: parent.__tmNodeHeight
  42708. },
  42709. style: {
  42710. opacity: 0
  42711. } // Others.
  42712. } : {
  42713. style: {
  42714. opacity: 0
  42715. }
  42716. };
  42717. } else {
  42718. var targetX = 0;
  42719. var targetY = 0;
  42720. if (!parent.__tmWillDelete) {
  42721. // Let node animate to right-bottom corner, cooperating with fadeout,
  42722. // which is appropriate for user understanding.
  42723. // Divided by 2 for reRoot rolling up effect.
  42724. targetX = parent.__tmNodeWidth / 2;
  42725. targetY = parent.__tmNodeHeight / 2;
  42726. }
  42727. target = storageName === 'nodeGroup' ? {
  42728. position: [targetX, targetY],
  42729. style: {
  42730. opacity: 0
  42731. }
  42732. } : {
  42733. shape: {
  42734. x: targetX,
  42735. y: targetY,
  42736. width: 0,
  42737. height: 0
  42738. },
  42739. style: {
  42740. opacity: 0
  42741. }
  42742. };
  42743. }
  42744. target && animationWrap.add(el, target, duration, easing);
  42745. });
  42746. }); // Make other animations
  42747. each$8(this._storage, function (store, storageName) {
  42748. each$8(store, function (el, rawIndex) {
  42749. var last = renderResult.lastsForAnimation[storageName][rawIndex];
  42750. var target = {};
  42751. if (!last) {
  42752. return;
  42753. }
  42754. if (storageName === 'nodeGroup') {
  42755. if (last.old) {
  42756. target.position = el.position.slice();
  42757. el.attr('position', last.old);
  42758. }
  42759. } else {
  42760. if (last.old) {
  42761. target.shape = extend({}, el.shape);
  42762. el.setShape(last.old);
  42763. }
  42764. if (last.fadein) {
  42765. el.setStyle('opacity', 0);
  42766. target.style = {
  42767. opacity: 1
  42768. };
  42769. } // When animation is stopped for succedent animation starting,
  42770. // el.style.opacity might not be 1
  42771. else if (el.style.opacity !== 1) {
  42772. target.style = {
  42773. opacity: 1
  42774. };
  42775. }
  42776. }
  42777. animationWrap.add(el, target, duration, easing);
  42778. });
  42779. }, this);
  42780. this._state = 'animating';
  42781. animationWrap.done(bind$1(function () {
  42782. this._state = 'ready';
  42783. renderResult.renderFinally();
  42784. }, this)).start();
  42785. },
  42786. /**
  42787. * @private
  42788. */
  42789. _resetController: function (api) {
  42790. var controller = this._controller; // Init controller.
  42791. if (!controller) {
  42792. controller = this._controller = new RoamController(api.getZr());
  42793. controller.enable(this.seriesModel.get('roam'));
  42794. controller.on('pan', bind$1(this._onPan, this));
  42795. controller.on('zoom', bind$1(this._onZoom, this));
  42796. }
  42797. var rect = new BoundingRect(0, 0, api.getWidth(), api.getHeight());
  42798. controller.setPointerChecker(function (e, x, y) {
  42799. return rect.contain(x, y);
  42800. });
  42801. },
  42802. /**
  42803. * @private
  42804. */
  42805. _clearController: function () {
  42806. var controller = this._controller;
  42807. if (controller) {
  42808. controller.dispose();
  42809. controller = null;
  42810. }
  42811. },
  42812. /**
  42813. * @private
  42814. */
  42815. _onPan: function (e) {
  42816. if (this._state !== 'animating' && (Math.abs(e.dx) > DRAG_THRESHOLD || Math.abs(e.dy) > DRAG_THRESHOLD)) {
  42817. // These param must not be cached.
  42818. var root = this.seriesModel.getData().tree.root;
  42819. if (!root) {
  42820. return;
  42821. }
  42822. var rootLayout = root.getLayout();
  42823. if (!rootLayout) {
  42824. return;
  42825. }
  42826. this.api.dispatchAction({
  42827. type: 'treemapMove',
  42828. from: this.uid,
  42829. seriesId: this.seriesModel.id,
  42830. rootRect: {
  42831. x: rootLayout.x + e.dx,
  42832. y: rootLayout.y + e.dy,
  42833. width: rootLayout.width,
  42834. height: rootLayout.height
  42835. }
  42836. });
  42837. }
  42838. },
  42839. /**
  42840. * @private
  42841. */
  42842. _onZoom: function (e) {
  42843. var mouseX = e.originX;
  42844. var mouseY = e.originY;
  42845. if (this._state !== 'animating') {
  42846. // These param must not be cached.
  42847. var root = this.seriesModel.getData().tree.root;
  42848. if (!root) {
  42849. return;
  42850. }
  42851. var rootLayout = root.getLayout();
  42852. if (!rootLayout) {
  42853. return;
  42854. }
  42855. var rect = new BoundingRect(rootLayout.x, rootLayout.y, rootLayout.width, rootLayout.height);
  42856. var layoutInfo = this.seriesModel.layoutInfo; // Transform mouse coord from global to containerGroup.
  42857. mouseX -= layoutInfo.x;
  42858. mouseY -= layoutInfo.y; // Scale root bounding rect.
  42859. var m = create$1();
  42860. translate(m, m, [-mouseX, -mouseY]);
  42861. scale$1(m, m, [e.scale, e.scale]);
  42862. translate(m, m, [mouseX, mouseY]);
  42863. rect.applyTransform(m);
  42864. this.api.dispatchAction({
  42865. type: 'treemapRender',
  42866. from: this.uid,
  42867. seriesId: this.seriesModel.id,
  42868. rootRect: {
  42869. x: rect.x,
  42870. y: rect.y,
  42871. width: rect.width,
  42872. height: rect.height
  42873. }
  42874. });
  42875. }
  42876. },
  42877. /**
  42878. * @private
  42879. */
  42880. _initEvents: function (containerGroup) {
  42881. containerGroup.on('click', function (e) {
  42882. if (this._state !== 'ready') {
  42883. return;
  42884. }
  42885. var nodeClick = this.seriesModel.get('nodeClick', true);
  42886. if (!nodeClick) {
  42887. return;
  42888. }
  42889. var targetInfo = this.findTarget(e.offsetX, e.offsetY);
  42890. if (!targetInfo) {
  42891. return;
  42892. }
  42893. var node = targetInfo.node;
  42894. if (node.getLayout().isLeafRoot) {
  42895. this._rootToNode(targetInfo);
  42896. } else {
  42897. if (nodeClick === 'zoomToNode') {
  42898. this._zoomToNode(targetInfo);
  42899. } else if (nodeClick === 'link') {
  42900. var itemModel = node.hostTree.data.getItemModel(node.dataIndex);
  42901. var link = itemModel.get('link', true);
  42902. var linkTarget = itemModel.get('target', true) || 'blank';
  42903. link && windowOpen(link, linkTarget);
  42904. }
  42905. }
  42906. }, this);
  42907. },
  42908. /**
  42909. * @private
  42910. */
  42911. _renderBreadcrumb: function (seriesModel, api, targetInfo) {
  42912. if (!targetInfo) {
  42913. targetInfo = seriesModel.get('leafDepth', true) != null ? {
  42914. node: seriesModel.getViewRoot() // FIXME
  42915. // better way?
  42916. // Find breadcrumb tail on center of containerGroup.
  42917. } : this.findTarget(api.getWidth() / 2, api.getHeight() / 2);
  42918. if (!targetInfo) {
  42919. targetInfo = {
  42920. node: seriesModel.getData().tree.root
  42921. };
  42922. }
  42923. }
  42924. (this._breadcrumb || (this._breadcrumb = new Breadcrumb(this.group))).render(seriesModel, api, targetInfo.node, bind$1(onSelect, this));
  42925. function onSelect(node) {
  42926. if (this._state !== 'animating') {
  42927. aboveViewRoot(seriesModel.getViewRoot(), node) ? this._rootToNode({
  42928. node: node
  42929. }) : this._zoomToNode({
  42930. node: node
  42931. });
  42932. }
  42933. }
  42934. },
  42935. /**
  42936. * @override
  42937. */
  42938. remove: function () {
  42939. this._clearController();
  42940. this._containerGroup && this._containerGroup.removeAll();
  42941. this._storage = createStorage();
  42942. this._state = 'ready';
  42943. this._breadcrumb && this._breadcrumb.remove();
  42944. },
  42945. dispose: function () {
  42946. this._clearController();
  42947. },
  42948. /**
  42949. * @private
  42950. */
  42951. _zoomToNode: function (targetInfo) {
  42952. this.api.dispatchAction({
  42953. type: 'treemapZoomToNode',
  42954. from: this.uid,
  42955. seriesId: this.seriesModel.id,
  42956. targetNode: targetInfo.node
  42957. });
  42958. },
  42959. /**
  42960. * @private
  42961. */
  42962. _rootToNode: function (targetInfo) {
  42963. this.api.dispatchAction({
  42964. type: 'treemapRootToNode',
  42965. from: this.uid,
  42966. seriesId: this.seriesModel.id,
  42967. targetNode: targetInfo.node
  42968. });
  42969. },
  42970. /**
  42971. * @public
  42972. * @param {number} x Global coord x.
  42973. * @param {number} y Global coord y.
  42974. * @return {Object} info If not found, return undefined;
  42975. * @return {number} info.node Target node.
  42976. * @return {number} info.offsetX x refer to target node.
  42977. * @return {number} info.offsetY y refer to target node.
  42978. */
  42979. findTarget: function (x, y) {
  42980. var targetInfo;
  42981. var viewRoot = this.seriesModel.getViewRoot();
  42982. viewRoot.eachNode({
  42983. attr: 'viewChildren',
  42984. order: 'preorder'
  42985. }, function (node) {
  42986. var bgEl = this._storage.background[node.getRawIndex()]; // If invisible, there might be no element.
  42987. if (bgEl) {
  42988. var point = bgEl.transformCoordToLocal(x, y);
  42989. var shape = bgEl.shape; // For performance consideration, dont use 'getBoundingRect'.
  42990. if (shape.x <= point[0] && point[0] <= shape.x + shape.width && shape.y <= point[1] && point[1] <= shape.y + shape.height) {
  42991. targetInfo = {
  42992. node: node,
  42993. offsetX: point[0],
  42994. offsetY: point[1]
  42995. };
  42996. } else {
  42997. return false; // Suppress visit subtree.
  42998. }
  42999. }
  43000. }, this);
  43001. return targetInfo;
  43002. }
  43003. });
  43004. /**
  43005. * @inner
  43006. */
  43007. function createStorage() {
  43008. return {
  43009. nodeGroup: [],
  43010. background: [],
  43011. content: []
  43012. };
  43013. }
  43014. /**
  43015. * @inner
  43016. * @return Return undefined means do not travel further.
  43017. */
  43018. function renderNode(seriesModel, thisStorage, oldStorage, reRoot, lastsForAnimation, willInvisibleEls, thisNode, oldNode, parentGroup, depth) {
  43019. // Whether under viewRoot.
  43020. if (!thisNode) {
  43021. // Deleting nodes will be performed finally. This method just find
  43022. // element from old storage, or create new element, set them to new
  43023. // storage, and set styles.
  43024. return;
  43025. } // -------------------------------------------------------------------
  43026. // Start of closure variables available in "Procedures in renderNode".
  43027. var thisLayout = thisNode.getLayout();
  43028. var data = seriesModel.getData(); // Only for enabling highlight/downplay. Clear firstly.
  43029. // Because some node will not be rendered.
  43030. data.setItemGraphicEl(thisNode.dataIndex, null);
  43031. if (!thisLayout || !thisLayout.isInView) {
  43032. return;
  43033. }
  43034. var thisWidth = thisLayout.width;
  43035. var thisHeight = thisLayout.height;
  43036. var borderWidth = thisLayout.borderWidth;
  43037. var thisInvisible = thisLayout.invisible;
  43038. var thisRawIndex = thisNode.getRawIndex();
  43039. var oldRawIndex = oldNode && oldNode.getRawIndex();
  43040. var thisViewChildren = thisNode.viewChildren;
  43041. var upperHeight = thisLayout.upperHeight;
  43042. var isParent = thisViewChildren && thisViewChildren.length;
  43043. var itemStyleNormalModel = thisNode.getModel('itemStyle');
  43044. var itemStyleEmphasisModel = thisNode.getModel('emphasis.itemStyle'); // End of closure ariables available in "Procedures in renderNode".
  43045. // -----------------------------------------------------------------
  43046. // Node group
  43047. var group = giveGraphic('nodeGroup', Group$2);
  43048. if (!group) {
  43049. return;
  43050. }
  43051. parentGroup.add(group); // x,y are not set when el is above view root.
  43052. group.attr('position', [thisLayout.x || 0, thisLayout.y || 0]);
  43053. group.__tmNodeWidth = thisWidth;
  43054. group.__tmNodeHeight = thisHeight;
  43055. if (thisLayout.isAboveViewRoot) {
  43056. return group;
  43057. }
  43058. var nodeModel = thisNode.getModel(); // Background
  43059. var bg = giveGraphic('background', Rect$1, depth, Z_BG);
  43060. bg && renderBackground(group, bg, isParent && thisLayout.upperLabelHeight); // No children, render content.
  43061. if (isParent) {
  43062. // Because of the implementation about "traverse" in graphic hover style, we
  43063. // can not set hover listener on the "group" of non-leaf node. Otherwise the
  43064. // hover event from the descendents will be listenered.
  43065. if (isHighDownDispatcher(group)) {
  43066. setAsHighDownDispatcher(group, false);
  43067. }
  43068. if (bg) {
  43069. setAsHighDownDispatcher(bg, true); // Only for enabling highlight/downplay.
  43070. data.setItemGraphicEl(thisNode.dataIndex, bg);
  43071. }
  43072. } else {
  43073. var content = giveGraphic('content', Rect$1, depth, Z_CONTENT);
  43074. content && renderContent(group, content);
  43075. if (bg && isHighDownDispatcher(bg)) {
  43076. setAsHighDownDispatcher(bg, false);
  43077. }
  43078. setAsHighDownDispatcher(group, true); // Only for enabling highlight/downplay.
  43079. data.setItemGraphicEl(thisNode.dataIndex, group);
  43080. }
  43081. return group; // ----------------------------
  43082. // | Procedures in renderNode |
  43083. // ----------------------------
  43084. function renderBackground(group, bg, useUpperLabel) {
  43085. // For tooltip.
  43086. bg.dataIndex = thisNode.dataIndex;
  43087. bg.seriesIndex = seriesModel.seriesIndex;
  43088. bg.setShape({
  43089. x: 0,
  43090. y: 0,
  43091. width: thisWidth,
  43092. height: thisHeight
  43093. });
  43094. if (thisInvisible) {
  43095. // If invisible, do not set visual, otherwise the element will
  43096. // change immediately before animation. We think it is OK to
  43097. // remain its origin color when moving out of the view window.
  43098. processInvisible(bg);
  43099. } else {
  43100. bg.invisible = false;
  43101. var visualBorderColor = thisNode.getVisual('borderColor', true);
  43102. var emphasisBorderColor = itemStyleEmphasisModel.get('borderColor');
  43103. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  43104. normalStyle.fill = visualBorderColor;
  43105. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  43106. emphasisStyle.fill = emphasisBorderColor;
  43107. if (useUpperLabel) {
  43108. var upperLabelWidth = thisWidth - 2 * borderWidth;
  43109. prepareText(normalStyle, emphasisStyle, visualBorderColor, upperLabelWidth, upperHeight, {
  43110. x: borderWidth,
  43111. y: 0,
  43112. width: upperLabelWidth,
  43113. height: upperHeight
  43114. });
  43115. } // For old bg.
  43116. else {
  43117. normalStyle.text = emphasisStyle.text = null;
  43118. }
  43119. bg.setStyle(normalStyle);
  43120. setElementHoverStyle(bg, emphasisStyle);
  43121. }
  43122. group.add(bg);
  43123. }
  43124. function renderContent(group, content) {
  43125. // For tooltip.
  43126. content.dataIndex = thisNode.dataIndex;
  43127. content.seriesIndex = seriesModel.seriesIndex;
  43128. var contentWidth = Math.max(thisWidth - 2 * borderWidth, 0);
  43129. var contentHeight = Math.max(thisHeight - 2 * borderWidth, 0);
  43130. content.culling = true;
  43131. content.setShape({
  43132. x: borderWidth,
  43133. y: borderWidth,
  43134. width: contentWidth,
  43135. height: contentHeight
  43136. });
  43137. if (thisInvisible) {
  43138. // If invisible, do not set visual, otherwise the element will
  43139. // change immediately before animation. We think it is OK to
  43140. // remain its origin color when moving out of the view window.
  43141. processInvisible(content);
  43142. } else {
  43143. content.invisible = false;
  43144. var visualColor = thisNode.getVisual('color', true);
  43145. var normalStyle = getItemStyleNormal(itemStyleNormalModel);
  43146. normalStyle.fill = visualColor;
  43147. var emphasisStyle = getItemStyleEmphasis(itemStyleEmphasisModel);
  43148. prepareText(normalStyle, emphasisStyle, visualColor, contentWidth, contentHeight);
  43149. content.setStyle(normalStyle);
  43150. setElementHoverStyle(content, emphasisStyle);
  43151. }
  43152. group.add(content);
  43153. }
  43154. function processInvisible(element) {
  43155. // Delay invisible setting utill animation finished,
  43156. // avoid element vanish suddenly before animation.
  43157. !element.invisible && willInvisibleEls.push(element);
  43158. }
  43159. function prepareText(normalStyle, emphasisStyle, visualColor, width, height, upperLabelRect) {
  43160. var defaultText = nodeModel.get('name');
  43161. var normalLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_NORMAL : PATH_LABEL_NOAMAL);
  43162. var emphasisLabelModel = nodeModel.getModel(upperLabelRect ? PATH_UPPERLABEL_EMPHASIS : PATH_LABEL_EMPHASIS);
  43163. var isShow = normalLabelModel.getShallow('show');
  43164. setLabelStyle(normalStyle, emphasisStyle, normalLabelModel, emphasisLabelModel, {
  43165. defaultText: isShow ? defaultText : null,
  43166. autoColor: visualColor,
  43167. isRectText: true,
  43168. labelFetcher: seriesModel,
  43169. labelDataIndex: thisNode.dataIndex,
  43170. labelProp: upperLabelRect ? 'upperLabel' : 'label'
  43171. });
  43172. addDrillDownIcon(normalStyle, upperLabelRect, thisLayout);
  43173. addDrillDownIcon(emphasisStyle, upperLabelRect, thisLayout);
  43174. upperLabelRect && (normalStyle.textRect = clone(upperLabelRect));
  43175. normalStyle.truncate = isShow && normalLabelModel.get('ellipsis') ? {
  43176. outerWidth: width,
  43177. outerHeight: height,
  43178. minChar: 2
  43179. } : null;
  43180. }
  43181. function addDrillDownIcon(style, upperLabelRect, thisLayout) {
  43182. var text = style.text;
  43183. if (!upperLabelRect && thisLayout.isLeafRoot && text != null) {
  43184. var iconChar = seriesModel.get('drillDownIcon', true);
  43185. style.text = iconChar ? iconChar + ' ' + text : text;
  43186. }
  43187. }
  43188. function giveGraphic(storageName, Ctor, depth, z) {
  43189. var element = oldRawIndex != null && oldStorage[storageName][oldRawIndex];
  43190. var lasts = lastsForAnimation[storageName];
  43191. if (element) {
  43192. // Remove from oldStorage
  43193. oldStorage[storageName][oldRawIndex] = null;
  43194. prepareAnimationWhenHasOld(lasts, element, storageName);
  43195. } // If invisible and no old element, do not create new element (for optimizing).
  43196. else if (!thisInvisible) {
  43197. element = new Ctor({
  43198. z: calculateZ(depth, z)
  43199. });
  43200. element.__tmDepth = depth;
  43201. element.__tmStorageName = storageName;
  43202. prepareAnimationWhenNoOld(lasts, element, storageName);
  43203. } // Set to thisStorage
  43204. return thisStorage[storageName][thisRawIndex] = element;
  43205. }
  43206. function prepareAnimationWhenHasOld(lasts, element, storageName) {
  43207. var lastCfg = lasts[thisRawIndex] = {};
  43208. lastCfg.old = storageName === 'nodeGroup' ? element.position.slice() : extend({}, element.shape);
  43209. } // If a element is new, we need to find the animation start point carefully,
  43210. // otherwise it will looks strange when 'zoomToNode'.
  43211. function prepareAnimationWhenNoOld(lasts, element, storageName) {
  43212. var lastCfg = lasts[thisRawIndex] = {};
  43213. var parentNode = thisNode.parentNode;
  43214. if (parentNode && (!reRoot || reRoot.direction === 'drillDown')) {
  43215. var parentOldX = 0;
  43216. var parentOldY = 0; // New nodes appear from right-bottom corner in 'zoomToNode' animation.
  43217. // For convenience, get old bounding rect from background.
  43218. var parentOldBg = lastsForAnimation.background[parentNode.getRawIndex()];
  43219. if (!reRoot && parentOldBg && parentOldBg.old) {
  43220. parentOldX = parentOldBg.old.width;
  43221. parentOldY = parentOldBg.old.height;
  43222. } // When no parent old shape found, its parent is new too,
  43223. // so we can just use {x:0, y:0}.
  43224. lastCfg.old = storageName === 'nodeGroup' ? [0, parentOldY] : {
  43225. x: parentOldX,
  43226. y: parentOldY,
  43227. width: 0,
  43228. height: 0
  43229. };
  43230. } // Fade in, user can be aware that these nodes are new.
  43231. lastCfg.fadein = storageName !== 'nodeGroup';
  43232. }
  43233. } // We can not set all backgroud with the same z, Because the behaviour of
  43234. // drill down and roll up differ background creation sequence from tree
  43235. // hierarchy sequence, which cause that lowser background element overlap
  43236. // upper ones. So we calculate z based on depth.
  43237. // Moreover, we try to shrink down z interval to [0, 1] to avoid that
  43238. // treemap with large z overlaps other components.
  43239. function calculateZ(depth, zInLevel) {
  43240. var zb = depth * Z_BASE + zInLevel;
  43241. return (zb - 1) / zb;
  43242. }
  43243. /*
  43244. * Licensed to the Apache Software Foundation (ASF) under one
  43245. * or more contributor license agreements. See the NOTICE file
  43246. * distributed with this work for additional information
  43247. * regarding copyright ownership. The ASF licenses this file
  43248. * to you under the Apache License, Version 2.0 (the
  43249. * "License"); you may not use this file except in compliance
  43250. * with the License. You may obtain a copy of the License at
  43251. *
  43252. * http://www.apache.org/licenses/LICENSE-2.0
  43253. *
  43254. * Unless required by applicable law or agreed to in writing,
  43255. * software distributed under the License is distributed on an
  43256. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43257. * KIND, either express or implied. See the License for the
  43258. * specific language governing permissions and limitations
  43259. * under the License.
  43260. */
  43261. /**
  43262. * @file Treemap action
  43263. */
  43264. var noop$1 = function () {};
  43265. var actionTypes = ['treemapZoomToNode', 'treemapRender', 'treemapMove'];
  43266. for (var i$1 = 0; i$1 < actionTypes.length; i$1++) {
  43267. registerAction({
  43268. type: actionTypes[i$1],
  43269. update: 'updateView'
  43270. }, noop$1);
  43271. }
  43272. registerAction({
  43273. type: 'treemapRootToNode',
  43274. update: 'updateView'
  43275. }, function (payload, ecModel) {
  43276. ecModel.eachComponent({
  43277. mainType: 'series',
  43278. subType: 'treemap',
  43279. query: payload
  43280. }, handleRootToNode);
  43281. function handleRootToNode(model, index) {
  43282. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  43283. var targetInfo = retrieveTargetInfo(payload, types, model);
  43284. if (targetInfo) {
  43285. var originViewRoot = model.getViewRoot();
  43286. if (originViewRoot) {
  43287. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  43288. }
  43289. model.resetViewRoot(targetInfo.node);
  43290. }
  43291. }
  43292. });
  43293. /*
  43294. * Licensed to the Apache Software Foundation (ASF) under one
  43295. * or more contributor license agreements. See the NOTICE file
  43296. * distributed with this work for additional information
  43297. * regarding copyright ownership. The ASF licenses this file
  43298. * to you under the Apache License, Version 2.0 (the
  43299. * "License"); you may not use this file except in compliance
  43300. * with the License. You may obtain a copy of the License at
  43301. *
  43302. * http://www.apache.org/licenses/LICENSE-2.0
  43303. *
  43304. * Unless required by applicable law or agreed to in writing,
  43305. * software distributed under the License is distributed on an
  43306. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43307. * KIND, either express or implied. See the License for the
  43308. * specific language governing permissions and limitations
  43309. * under the License.
  43310. */
  43311. var each$9 = each$1;
  43312. var isObject$5 = isObject$1;
  43313. var CATEGORY_DEFAULT_VISUAL_INDEX = -1;
  43314. /**
  43315. * @param {Object} option
  43316. * @param {string} [option.type] See visualHandlers.
  43317. * @param {string} [option.mappingMethod] 'linear' or 'piecewise' or 'category' or 'fixed'
  43318. * @param {Array.<number>=} [option.dataExtent] [minExtent, maxExtent],
  43319. * required when mappingMethod is 'linear'
  43320. * @param {Array.<Object>=} [option.pieceList] [
  43321. * {value: someValue},
  43322. * {interval: [min1, max1], visual: {...}},
  43323. * {interval: [min2, max2]}
  43324. * ],
  43325. * required when mappingMethod is 'piecewise'.
  43326. * Visual for only each piece can be specified.
  43327. * @param {Array.<string|Object>=} [option.categories] ['cate1', 'cate2']
  43328. * required when mappingMethod is 'category'.
  43329. * If no option.categories, categories is set
  43330. * as [0, 1, 2, ...].
  43331. * @param {boolean} [option.loop=false] Whether loop mapping when mappingMethod is 'category'.
  43332. * @param {(Array|Object|*)} [option.visual] Visual data.
  43333. * when mappingMethod is 'category',
  43334. * visual data can be array or object
  43335. * (like: {cate1: '#222', none: '#fff'})
  43336. * or primary types (which represents
  43337. * defualt category visual), otherwise visual
  43338. * can be array or primary (which will be
  43339. * normalized to array).
  43340. *
  43341. */
  43342. var VisualMapping = function (option) {
  43343. var mappingMethod = option.mappingMethod;
  43344. var visualType = option.type;
  43345. /**
  43346. * @readOnly
  43347. * @type {Object}
  43348. */
  43349. var thisOption = this.option = clone(option);
  43350. /**
  43351. * @readOnly
  43352. * @type {string}
  43353. */
  43354. this.type = visualType;
  43355. /**
  43356. * @readOnly
  43357. * @type {string}
  43358. */
  43359. this.mappingMethod = mappingMethod;
  43360. /**
  43361. * @private
  43362. * @type {Function}
  43363. */
  43364. this._normalizeData = normalizers[mappingMethod];
  43365. var visualHandler = visualHandlers[visualType];
  43366. /**
  43367. * @public
  43368. * @type {Function}
  43369. */
  43370. this.applyVisual = visualHandler.applyVisual;
  43371. /**
  43372. * @public
  43373. * @type {Function}
  43374. */
  43375. this.getColorMapper = visualHandler.getColorMapper;
  43376. /**
  43377. * @private
  43378. * @type {Function}
  43379. */
  43380. this._doMap = visualHandler._doMap[mappingMethod];
  43381. if (mappingMethod === 'piecewise') {
  43382. normalizeVisualRange(thisOption);
  43383. preprocessForPiecewise(thisOption);
  43384. } else if (mappingMethod === 'category') {
  43385. thisOption.categories ? preprocessForSpecifiedCategory(thisOption) // categories is ordinal when thisOption.categories not specified,
  43386. // which need no more preprocess except normalize visual.
  43387. : normalizeVisualRange(thisOption, true);
  43388. } else {
  43389. // mappingMethod === 'linear' or 'fixed'
  43390. assert$1(mappingMethod !== 'linear' || thisOption.dataExtent);
  43391. normalizeVisualRange(thisOption);
  43392. }
  43393. };
  43394. VisualMapping.prototype = {
  43395. constructor: VisualMapping,
  43396. mapValueToVisual: function (value) {
  43397. var normalized = this._normalizeData(value);
  43398. return this._doMap(normalized, value);
  43399. },
  43400. getNormalizer: function () {
  43401. return bind(this._normalizeData, this);
  43402. }
  43403. };
  43404. var visualHandlers = VisualMapping.visualHandlers = {
  43405. color: {
  43406. applyVisual: makeApplyVisual('color'),
  43407. /**
  43408. * Create a mapper function
  43409. * @return {Function}
  43410. */
  43411. getColorMapper: function () {
  43412. var thisOption = this.option;
  43413. return bind(thisOption.mappingMethod === 'category' ? function (value, isNormalized) {
  43414. !isNormalized && (value = this._normalizeData(value));
  43415. return doMapCategory.call(this, value);
  43416. } : function (value, isNormalized, out) {
  43417. // If output rgb array
  43418. // which will be much faster and useful in pixel manipulation
  43419. var returnRGBArray = !!out;
  43420. !isNormalized && (value = this._normalizeData(value));
  43421. out = fastLerp(value, thisOption.parsedVisual, out);
  43422. return returnRGBArray ? out : stringify(out, 'rgba');
  43423. }, this);
  43424. },
  43425. _doMap: {
  43426. linear: function (normalized) {
  43427. return stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  43428. },
  43429. category: doMapCategory,
  43430. piecewise: function (normalized, value) {
  43431. var result = getSpecifiedVisual.call(this, value);
  43432. if (result == null) {
  43433. result = stringify(fastLerp(normalized, this.option.parsedVisual), 'rgba');
  43434. }
  43435. return result;
  43436. },
  43437. fixed: doMapFixed
  43438. }
  43439. },
  43440. colorHue: makePartialColorVisualHandler(function (color, value) {
  43441. return modifyHSL(color, value);
  43442. }),
  43443. colorSaturation: makePartialColorVisualHandler(function (color, value) {
  43444. return modifyHSL(color, null, value);
  43445. }),
  43446. colorLightness: makePartialColorVisualHandler(function (color, value) {
  43447. return modifyHSL(color, null, null, value);
  43448. }),
  43449. colorAlpha: makePartialColorVisualHandler(function (color, value) {
  43450. return modifyAlpha(color, value);
  43451. }),
  43452. opacity: {
  43453. applyVisual: makeApplyVisual('opacity'),
  43454. _doMap: makeDoMap([0, 1])
  43455. },
  43456. liftZ: {
  43457. applyVisual: makeApplyVisual('liftZ'),
  43458. _doMap: {
  43459. linear: doMapFixed,
  43460. category: doMapFixed,
  43461. piecewise: doMapFixed,
  43462. fixed: doMapFixed
  43463. }
  43464. },
  43465. symbol: {
  43466. applyVisual: function (value, getter, setter) {
  43467. var symbolCfg = this.mapValueToVisual(value);
  43468. if (isString(symbolCfg)) {
  43469. setter('symbol', symbolCfg);
  43470. } else if (isObject$5(symbolCfg)) {
  43471. for (var name in symbolCfg) {
  43472. if (symbolCfg.hasOwnProperty(name)) {
  43473. setter(name, symbolCfg[name]);
  43474. }
  43475. }
  43476. }
  43477. },
  43478. _doMap: {
  43479. linear: doMapToArray,
  43480. category: doMapCategory,
  43481. piecewise: function (normalized, value) {
  43482. var result = getSpecifiedVisual.call(this, value);
  43483. if (result == null) {
  43484. result = doMapToArray.call(this, normalized);
  43485. }
  43486. return result;
  43487. },
  43488. fixed: doMapFixed
  43489. }
  43490. },
  43491. symbolSize: {
  43492. applyVisual: makeApplyVisual('symbolSize'),
  43493. _doMap: makeDoMap([0, 1])
  43494. }
  43495. };
  43496. function preprocessForPiecewise(thisOption) {
  43497. var pieceList = thisOption.pieceList;
  43498. thisOption.hasSpecialVisual = false;
  43499. each$1(pieceList, function (piece, index) {
  43500. piece.originIndex = index; // piece.visual is "result visual value" but not
  43501. // a visual range, so it does not need to be normalized.
  43502. if (piece.visual != null) {
  43503. thisOption.hasSpecialVisual = true;
  43504. }
  43505. });
  43506. }
  43507. function preprocessForSpecifiedCategory(thisOption) {
  43508. // Hash categories.
  43509. var categories = thisOption.categories;
  43510. var visual = thisOption.visual;
  43511. var categoryMap = thisOption.categoryMap = {};
  43512. each$9(categories, function (cate, index) {
  43513. categoryMap[cate] = index;
  43514. }); // Process visual map input.
  43515. if (!isArray(visual)) {
  43516. var visualArr = [];
  43517. if (isObject$1(visual)) {
  43518. each$9(visual, function (v, cate) {
  43519. var index = categoryMap[cate];
  43520. visualArr[index != null ? index : CATEGORY_DEFAULT_VISUAL_INDEX] = v;
  43521. });
  43522. } else {
  43523. // Is primary type, represents default visual.
  43524. visualArr[CATEGORY_DEFAULT_VISUAL_INDEX] = visual;
  43525. }
  43526. visual = setVisualToOption(thisOption, visualArr);
  43527. } // Remove categories that has no visual,
  43528. // then we can mapping them to CATEGORY_DEFAULT_VISUAL_INDEX.
  43529. for (var i = categories.length - 1; i >= 0; i--) {
  43530. if (visual[i] == null) {
  43531. delete categoryMap[categories[i]];
  43532. categories.pop();
  43533. }
  43534. }
  43535. }
  43536. function normalizeVisualRange(thisOption, isCategory) {
  43537. var visual = thisOption.visual;
  43538. var visualArr = [];
  43539. if (isObject$1(visual)) {
  43540. each$9(visual, function (v) {
  43541. visualArr.push(v);
  43542. });
  43543. } else if (visual != null) {
  43544. visualArr.push(visual);
  43545. }
  43546. var doNotNeedPair = {
  43547. color: 1,
  43548. symbol: 1
  43549. };
  43550. if (!isCategory && visualArr.length === 1 && !doNotNeedPair.hasOwnProperty(thisOption.type)) {
  43551. // Do not care visualArr.length === 0, which is illegal.
  43552. visualArr[1] = visualArr[0];
  43553. }
  43554. setVisualToOption(thisOption, visualArr);
  43555. }
  43556. function makePartialColorVisualHandler(applyValue) {
  43557. return {
  43558. applyVisual: function (value, getter, setter) {
  43559. value = this.mapValueToVisual(value); // Must not be array value
  43560. setter('color', applyValue(getter('color'), value));
  43561. },
  43562. _doMap: makeDoMap([0, 1])
  43563. };
  43564. }
  43565. function doMapToArray(normalized) {
  43566. var visual = this.option.visual;
  43567. return visual[Math.round(linearMap(normalized, [0, 1], [0, visual.length - 1], true))] || {};
  43568. }
  43569. function makeApplyVisual(visualType) {
  43570. return function (value, getter, setter) {
  43571. setter(visualType, this.mapValueToVisual(value));
  43572. };
  43573. }
  43574. function doMapCategory(normalized) {
  43575. var visual = this.option.visual;
  43576. return visual[this.option.loop && normalized !== CATEGORY_DEFAULT_VISUAL_INDEX ? normalized % visual.length : normalized];
  43577. }
  43578. function doMapFixed() {
  43579. return this.option.visual[0];
  43580. }
  43581. function makeDoMap(sourceExtent) {
  43582. return {
  43583. linear: function (normalized) {
  43584. return linearMap(normalized, sourceExtent, this.option.visual, true);
  43585. },
  43586. category: doMapCategory,
  43587. piecewise: function (normalized, value) {
  43588. var result = getSpecifiedVisual.call(this, value);
  43589. if (result == null) {
  43590. result = linearMap(normalized, sourceExtent, this.option.visual, true);
  43591. }
  43592. return result;
  43593. },
  43594. fixed: doMapFixed
  43595. };
  43596. }
  43597. function getSpecifiedVisual(value) {
  43598. var thisOption = this.option;
  43599. var pieceList = thisOption.pieceList;
  43600. if (thisOption.hasSpecialVisual) {
  43601. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList);
  43602. var piece = pieceList[pieceIndex];
  43603. if (piece && piece.visual) {
  43604. return piece.visual[this.type];
  43605. }
  43606. }
  43607. }
  43608. function setVisualToOption(thisOption, visualArr) {
  43609. thisOption.visual = visualArr;
  43610. if (thisOption.type === 'color') {
  43611. thisOption.parsedVisual = map(visualArr, function (item) {
  43612. return parse(item);
  43613. });
  43614. }
  43615. return visualArr;
  43616. }
  43617. /**
  43618. * Normalizers by mapping methods.
  43619. */
  43620. var normalizers = {
  43621. linear: function (value) {
  43622. return linearMap(value, this.option.dataExtent, [0, 1], true);
  43623. },
  43624. piecewise: function (value) {
  43625. var pieceList = this.option.pieceList;
  43626. var pieceIndex = VisualMapping.findPieceIndex(value, pieceList, true);
  43627. if (pieceIndex != null) {
  43628. return linearMap(pieceIndex, [0, pieceList.length - 1], [0, 1], true);
  43629. }
  43630. },
  43631. category: function (value) {
  43632. var index = this.option.categories ? this.option.categoryMap[value] : value; // ordinal
  43633. return index == null ? CATEGORY_DEFAULT_VISUAL_INDEX : index;
  43634. },
  43635. fixed: noop
  43636. };
  43637. /**
  43638. * List available visual types.
  43639. *
  43640. * @public
  43641. * @return {Array.<string>}
  43642. */
  43643. VisualMapping.listVisualTypes = function () {
  43644. var visualTypes = [];
  43645. each$1(visualHandlers, function (handler, key) {
  43646. visualTypes.push(key);
  43647. });
  43648. return visualTypes;
  43649. };
  43650. /**
  43651. * @public
  43652. */
  43653. VisualMapping.addVisualHandler = function (name, handler) {
  43654. visualHandlers[name] = handler;
  43655. };
  43656. /**
  43657. * @public
  43658. */
  43659. VisualMapping.isValidType = function (visualType) {
  43660. return visualHandlers.hasOwnProperty(visualType);
  43661. };
  43662. /**
  43663. * Convinent method.
  43664. * Visual can be Object or Array or primary type.
  43665. *
  43666. * @public
  43667. */
  43668. VisualMapping.eachVisual = function (visual, callback, context) {
  43669. if (isObject$1(visual)) {
  43670. each$1(visual, callback, context);
  43671. } else {
  43672. callback.call(context, visual);
  43673. }
  43674. };
  43675. VisualMapping.mapVisual = function (visual, callback, context) {
  43676. var isPrimary;
  43677. var newVisual = isArray(visual) ? [] : isObject$1(visual) ? {} : (isPrimary = true, null);
  43678. VisualMapping.eachVisual(visual, function (v, key) {
  43679. var newVal = callback.call(context, v, key);
  43680. isPrimary ? newVisual = newVal : newVisual[key] = newVal;
  43681. });
  43682. return newVisual;
  43683. };
  43684. /**
  43685. * @public
  43686. * @param {Object} obj
  43687. * @return {Object} new object containers visual values.
  43688. * If no visuals, return null.
  43689. */
  43690. VisualMapping.retrieveVisuals = function (obj) {
  43691. var ret = {};
  43692. var hasVisual;
  43693. obj && each$9(visualHandlers, function (h, visualType) {
  43694. if (obj.hasOwnProperty(visualType)) {
  43695. ret[visualType] = obj[visualType];
  43696. hasVisual = true;
  43697. }
  43698. });
  43699. return hasVisual ? ret : null;
  43700. };
  43701. /**
  43702. * Give order to visual types, considering colorSaturation, colorAlpha depends on color.
  43703. *
  43704. * @public
  43705. * @param {(Object|Array)} visualTypes If Object, like: {color: ..., colorSaturation: ...}
  43706. * IF Array, like: ['color', 'symbol', 'colorSaturation']
  43707. * @return {Array.<string>} Sorted visual types.
  43708. */
  43709. VisualMapping.prepareVisualTypes = function (visualTypes) {
  43710. if (isObject$5(visualTypes)) {
  43711. var types = [];
  43712. each$9(visualTypes, function (item, type) {
  43713. types.push(type);
  43714. });
  43715. visualTypes = types;
  43716. } else if (isArray(visualTypes)) {
  43717. visualTypes = visualTypes.slice();
  43718. } else {
  43719. return [];
  43720. }
  43721. visualTypes.sort(function (type1, type2) {
  43722. // color should be front of colorSaturation, colorAlpha, ...
  43723. // symbol and symbolSize do not matter.
  43724. return type2 === 'color' && type1 !== 'color' && type1.indexOf('color') === 0 ? 1 : -1;
  43725. });
  43726. return visualTypes;
  43727. };
  43728. /**
  43729. * 'color', 'colorSaturation', 'colorAlpha', ... are depends on 'color'.
  43730. * Other visuals are only depends on themself.
  43731. *
  43732. * @public
  43733. * @param {string} visualType1
  43734. * @param {string} visualType2
  43735. * @return {boolean}
  43736. */
  43737. VisualMapping.dependsOn = function (visualType1, visualType2) {
  43738. return visualType2 === 'color' ? !!(visualType1 && visualType1.indexOf(visualType2) === 0) : visualType1 === visualType2;
  43739. };
  43740. /**
  43741. * @param {number} value
  43742. * @param {Array.<Object>} pieceList [{value: ..., interval: [min, max]}, ...]
  43743. * Always from small to big.
  43744. * @param {boolean} [findClosestWhenOutside=false]
  43745. * @return {number} index
  43746. */
  43747. VisualMapping.findPieceIndex = function (value, pieceList, findClosestWhenOutside) {
  43748. var possibleI;
  43749. var abs = Infinity; // value has the higher priority.
  43750. for (var i = 0, len = pieceList.length; i < len; i++) {
  43751. var pieceValue = pieceList[i].value;
  43752. if (pieceValue != null) {
  43753. if (pieceValue === value // FIXME
  43754. // It is supposed to compare value according to value type of dimension,
  43755. // but currently value type can exactly be string or number.
  43756. // Compromise for numeric-like string (like '12'), especially
  43757. // in the case that visualMap.categories is ['22', '33'].
  43758. || typeof pieceValue === 'string' && pieceValue === value + '') {
  43759. return i;
  43760. }
  43761. findClosestWhenOutside && updatePossible(pieceValue, i);
  43762. }
  43763. }
  43764. for (var i = 0, len = pieceList.length; i < len; i++) {
  43765. var piece = pieceList[i];
  43766. var interval = piece.interval;
  43767. var close = piece.close;
  43768. if (interval) {
  43769. if (interval[0] === -Infinity) {
  43770. if (littleThan(close[1], value, interval[1])) {
  43771. return i;
  43772. }
  43773. } else if (interval[1] === Infinity) {
  43774. if (littleThan(close[0], interval[0], value)) {
  43775. return i;
  43776. }
  43777. } else if (littleThan(close[0], interval[0], value) && littleThan(close[1], value, interval[1])) {
  43778. return i;
  43779. }
  43780. findClosestWhenOutside && updatePossible(interval[0], i);
  43781. findClosestWhenOutside && updatePossible(interval[1], i);
  43782. }
  43783. }
  43784. if (findClosestWhenOutside) {
  43785. return value === Infinity ? pieceList.length - 1 : value === -Infinity ? 0 : possibleI;
  43786. }
  43787. function updatePossible(val, index) {
  43788. var newAbs = Math.abs(val - value);
  43789. if (newAbs < abs) {
  43790. abs = newAbs;
  43791. possibleI = index;
  43792. }
  43793. }
  43794. };
  43795. function littleThan(close, a, b) {
  43796. return close ? a <= b : a < b;
  43797. }
  43798. /*
  43799. * Licensed to the Apache Software Foundation (ASF) under one
  43800. * or more contributor license agreements. See the NOTICE file
  43801. * distributed with this work for additional information
  43802. * regarding copyright ownership. The ASF licenses this file
  43803. * to you under the Apache License, Version 2.0 (the
  43804. * "License"); you may not use this file except in compliance
  43805. * with the License. You may obtain a copy of the License at
  43806. *
  43807. * http://www.apache.org/licenses/LICENSE-2.0
  43808. *
  43809. * Unless required by applicable law or agreed to in writing,
  43810. * software distributed under the License is distributed on an
  43811. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43812. * KIND, either express or implied. See the License for the
  43813. * specific language governing permissions and limitations
  43814. * under the License.
  43815. */
  43816. var isArray$2 = isArray;
  43817. var ITEM_STYLE_NORMAL = 'itemStyle';
  43818. var treemapVisual = {
  43819. seriesType: 'treemap',
  43820. reset: function (seriesModel, ecModel, api, payload) {
  43821. var tree = seriesModel.getData().tree;
  43822. var root = tree.root;
  43823. var seriesItemStyleModel = seriesModel.getModel(ITEM_STYLE_NORMAL);
  43824. if (root.isRemoved()) {
  43825. return;
  43826. }
  43827. var levelItemStyles = map(tree.levelModels, function (levelModel) {
  43828. return levelModel ? levelModel.get(ITEM_STYLE_NORMAL) : null;
  43829. });
  43830. travelTree(root, // Visual should calculate from tree root but not view root.
  43831. {}, levelItemStyles, seriesItemStyleModel, seriesModel.getViewRoot().getAncestors(), seriesModel);
  43832. }
  43833. };
  43834. function travelTree(node, designatedVisual, levelItemStyles, seriesItemStyleModel, viewRootAncestors, seriesModel) {
  43835. var nodeModel = node.getModel();
  43836. var nodeLayout = node.getLayout(); // Optimize
  43837. if (!nodeLayout || nodeLayout.invisible || !nodeLayout.isInView) {
  43838. return;
  43839. }
  43840. var nodeItemStyleModel = node.getModel(ITEM_STYLE_NORMAL);
  43841. var levelItemStyle = levelItemStyles[node.depth];
  43842. var visuals = buildVisuals(nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel); // calculate border color
  43843. var borderColor = nodeItemStyleModel.get('borderColor');
  43844. var borderColorSaturation = nodeItemStyleModel.get('borderColorSaturation');
  43845. var thisNodeColor;
  43846. if (borderColorSaturation != null) {
  43847. // For performance, do not always execute 'calculateColor'.
  43848. thisNodeColor = calculateColor(visuals, node);
  43849. borderColor = calculateBorderColor(borderColorSaturation, thisNodeColor);
  43850. }
  43851. node.setVisual('borderColor', borderColor);
  43852. var viewChildren = node.viewChildren;
  43853. if (!viewChildren || !viewChildren.length) {
  43854. thisNodeColor = calculateColor(visuals, node); // Apply visual to this node.
  43855. node.setVisual('color', thisNodeColor);
  43856. } else {
  43857. var mapping = buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren); // Designate visual to children.
  43858. each$1(viewChildren, function (child, index) {
  43859. // If higher than viewRoot, only ancestors of viewRoot is needed to visit.
  43860. if (child.depth >= viewRootAncestors.length || child === viewRootAncestors[child.depth]) {
  43861. var childVisual = mapVisual(nodeModel, visuals, child, index, mapping, seriesModel);
  43862. travelTree(child, childVisual, levelItemStyles, seriesItemStyleModel, viewRootAncestors, seriesModel);
  43863. }
  43864. });
  43865. }
  43866. }
  43867. function buildVisuals(nodeItemStyleModel, designatedVisual, levelItemStyle, seriesItemStyleModel) {
  43868. var visuals = extend({}, designatedVisual);
  43869. each$1(['color', 'colorAlpha', 'colorSaturation'], function (visualName) {
  43870. // Priority: thisNode > thisLevel > parentNodeDesignated > seriesModel
  43871. var val = nodeItemStyleModel.get(visualName, true); // Ignore parent
  43872. val == null && levelItemStyle && (val = levelItemStyle[visualName]);
  43873. val == null && (val = designatedVisual[visualName]);
  43874. val == null && (val = seriesItemStyleModel.get(visualName));
  43875. val != null && (visuals[visualName] = val);
  43876. });
  43877. return visuals;
  43878. }
  43879. function calculateColor(visuals) {
  43880. var color = getValueVisualDefine(visuals, 'color');
  43881. if (color) {
  43882. var colorAlpha = getValueVisualDefine(visuals, 'colorAlpha');
  43883. var colorSaturation = getValueVisualDefine(visuals, 'colorSaturation');
  43884. if (colorSaturation) {
  43885. color = modifyHSL(color, null, null, colorSaturation);
  43886. }
  43887. if (colorAlpha) {
  43888. color = modifyAlpha(color, colorAlpha);
  43889. }
  43890. return color;
  43891. }
  43892. }
  43893. function calculateBorderColor(borderColorSaturation, thisNodeColor) {
  43894. return thisNodeColor != null ? modifyHSL(thisNodeColor, null, null, borderColorSaturation) : null;
  43895. }
  43896. function getValueVisualDefine(visuals, name) {
  43897. var value = visuals[name];
  43898. if (value != null && value !== 'none') {
  43899. return value;
  43900. }
  43901. }
  43902. function buildVisualMapping(node, nodeModel, nodeLayout, nodeItemStyleModel, visuals, viewChildren) {
  43903. if (!viewChildren || !viewChildren.length) {
  43904. return;
  43905. }
  43906. var rangeVisual = getRangeVisual(nodeModel, 'color') || visuals.color != null && visuals.color !== 'none' && (getRangeVisual(nodeModel, 'colorAlpha') || getRangeVisual(nodeModel, 'colorSaturation'));
  43907. if (!rangeVisual) {
  43908. return;
  43909. }
  43910. var visualMin = nodeModel.get('visualMin');
  43911. var visualMax = nodeModel.get('visualMax');
  43912. var dataExtent = nodeLayout.dataExtent.slice();
  43913. visualMin != null && visualMin < dataExtent[0] && (dataExtent[0] = visualMin);
  43914. visualMax != null && visualMax > dataExtent[1] && (dataExtent[1] = visualMax);
  43915. var colorMappingBy = nodeModel.get('colorMappingBy');
  43916. var opt = {
  43917. type: rangeVisual.name,
  43918. dataExtent: dataExtent,
  43919. visual: rangeVisual.range
  43920. };
  43921. if (opt.type === 'color' && (colorMappingBy === 'index' || colorMappingBy === 'id')) {
  43922. opt.mappingMethod = 'category';
  43923. opt.loop = true; // categories is ordinal, so do not set opt.categories.
  43924. } else {
  43925. opt.mappingMethod = 'linear';
  43926. }
  43927. var mapping = new VisualMapping(opt);
  43928. mapping.__drColorMappingBy = colorMappingBy;
  43929. return mapping;
  43930. } // Notice: If we dont have the attribute 'colorRange', but only use
  43931. // attribute 'color' to represent both concepts of 'colorRange' and 'color',
  43932. // (It means 'colorRange' when 'color' is Array, means 'color' when not array),
  43933. // this problem will be encountered:
  43934. // If a level-1 node dont have children, and its siblings has children,
  43935. // and colorRange is set on level-1, then the node can not be colored.
  43936. // So we separate 'colorRange' and 'color' to different attributes.
  43937. function getRangeVisual(nodeModel, name) {
  43938. // 'colorRange', 'colorARange', 'colorSRange'.
  43939. // If not exsits on this node, fetch from levels and series.
  43940. var range = nodeModel.get(name);
  43941. return isArray$2(range) && range.length ? {
  43942. name: name,
  43943. range: range
  43944. } : null;
  43945. }
  43946. function mapVisual(nodeModel, visuals, child, index, mapping, seriesModel) {
  43947. var childVisuals = extend({}, visuals);
  43948. if (mapping) {
  43949. var mappingType = mapping.type;
  43950. var colorMappingBy = mappingType === 'color' && mapping.__drColorMappingBy;
  43951. var value = colorMappingBy === 'index' ? index : colorMappingBy === 'id' ? seriesModel.mapIdToIndex(child.getId()) : child.getValue(nodeModel.get('visualDimension'));
  43952. childVisuals[mappingType] = mapping.mapValueToVisual(value);
  43953. }
  43954. return childVisuals;
  43955. }
  43956. /*
  43957. * Licensed to the Apache Software Foundation (ASF) under one
  43958. * or more contributor license agreements. See the NOTICE file
  43959. * distributed with this work for additional information
  43960. * regarding copyright ownership. The ASF licenses this file
  43961. * to you under the Apache License, Version 2.0 (the
  43962. * "License"); you may not use this file except in compliance
  43963. * with the License. You may obtain a copy of the License at
  43964. *
  43965. * http://www.apache.org/licenses/LICENSE-2.0
  43966. *
  43967. * Unless required by applicable law or agreed to in writing,
  43968. * software distributed under the License is distributed on an
  43969. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  43970. * KIND, either express or implied. See the License for the
  43971. * specific language governing permissions and limitations
  43972. * under the License.
  43973. */
  43974. /*
  43975. * A third-party license is embeded for some of the code in this file:
  43976. * The treemap layout implementation was originally copied from
  43977. * "d3.js" with some modifications made for this project.
  43978. * (See more details in the comment of the method "squarify" below.)
  43979. * The use of the source code of this file is also subject to the terms
  43980. * and consitions of the license of "d3.js" (BSD-3Clause, see
  43981. * </licenses/LICENSE-d3>).
  43982. */
  43983. var mathMax$5 = Math.max;
  43984. var mathMin$5 = Math.min;
  43985. var retrieveValue = retrieve;
  43986. var each$10 = each$1;
  43987. var PATH_BORDER_WIDTH = ['itemStyle', 'borderWidth'];
  43988. var PATH_GAP_WIDTH = ['itemStyle', 'gapWidth'];
  43989. var PATH_UPPER_LABEL_SHOW = ['upperLabel', 'show'];
  43990. var PATH_UPPER_LABEL_HEIGHT = ['upperLabel', 'height'];
  43991. /**
  43992. * @public
  43993. */
  43994. var treemapLayout = {
  43995. seriesType: 'treemap',
  43996. reset: function (seriesModel, ecModel, api, payload) {
  43997. // Layout result in each node:
  43998. // {x, y, width, height, area, borderWidth}
  43999. var ecWidth = api.getWidth();
  44000. var ecHeight = api.getHeight();
  44001. var seriesOption = seriesModel.option;
  44002. var layoutInfo = getLayoutRect(seriesModel.getBoxLayoutParams(), {
  44003. width: api.getWidth(),
  44004. height: api.getHeight()
  44005. });
  44006. var size = seriesOption.size || []; // Compatible with ec2.
  44007. var containerWidth = parsePercent$1(retrieveValue(layoutInfo.width, size[0]), ecWidth);
  44008. var containerHeight = parsePercent$1(retrieveValue(layoutInfo.height, size[1]), ecHeight); // Fetch payload info.
  44009. var payloadType = payload && payload.type;
  44010. var types = ['treemapZoomToNode', 'treemapRootToNode'];
  44011. var targetInfo = retrieveTargetInfo(payload, types, seriesModel);
  44012. var rootRect = payloadType === 'treemapRender' || payloadType === 'treemapMove' ? payload.rootRect : null;
  44013. var viewRoot = seriesModel.getViewRoot();
  44014. var viewAbovePath = getPathToRoot(viewRoot);
  44015. if (payloadType !== 'treemapMove') {
  44016. var rootSize = payloadType === 'treemapZoomToNode' ? estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) : rootRect ? [rootRect.width, rootRect.height] : [containerWidth, containerHeight];
  44017. var sort = seriesOption.sort;
  44018. if (sort && sort !== 'asc' && sort !== 'desc') {
  44019. sort = 'desc';
  44020. }
  44021. var options = {
  44022. squareRatio: seriesOption.squareRatio,
  44023. sort: sort,
  44024. leafDepth: seriesOption.leafDepth
  44025. }; // layout should be cleared because using updateView but not update.
  44026. viewRoot.hostTree.clearLayouts(); // TODO
  44027. // optimize: if out of view clip, do not layout.
  44028. // But take care that if do not render node out of view clip,
  44029. // how to calculate start po
  44030. var viewRootLayout = {
  44031. x: 0,
  44032. y: 0,
  44033. width: rootSize[0],
  44034. height: rootSize[1],
  44035. area: rootSize[0] * rootSize[1]
  44036. };
  44037. viewRoot.setLayout(viewRootLayout);
  44038. squarify(viewRoot, options, false, 0); // Supplement layout.
  44039. var viewRootLayout = viewRoot.getLayout();
  44040. each$10(viewAbovePath, function (node, index) {
  44041. var childValue = (viewAbovePath[index + 1] || viewRoot).getValue();
  44042. node.setLayout(extend({
  44043. dataExtent: [childValue, childValue],
  44044. borderWidth: 0,
  44045. upperHeight: 0
  44046. }, viewRootLayout));
  44047. });
  44048. }
  44049. var treeRoot = seriesModel.getData().tree.root;
  44050. treeRoot.setLayout(calculateRootPosition(layoutInfo, rootRect, targetInfo), true);
  44051. seriesModel.setLayoutInfo(layoutInfo); // FIXME
  44052. // 现在没有clip功能,暂时取ec高宽。
  44053. prunning(treeRoot, // Transform to base element coordinate system.
  44054. new BoundingRect(-layoutInfo.x, -layoutInfo.y, ecWidth, ecHeight), viewAbovePath, viewRoot, 0);
  44055. }
  44056. };
  44057. /**
  44058. * Layout treemap with squarify algorithm.
  44059. * The original presentation of this algorithm
  44060. * was made by Mark Bruls, Kees Huizing, and Jarke J. van Wijk
  44061. * <https://graphics.ethz.ch/teaching/scivis_common/Literature/squarifiedTreeMaps.pdf>.
  44062. * The implementation of this algorithm was originally copied from "d3.js"
  44063. * <https://github.com/d3/d3/blob/9cc9a875e636a1dcf36cc1e07bdf77e1ad6e2c74/src/layout/treemap.js>
  44064. * with some modifications made for this program.
  44065. * See the license statement at the head of this file.
  44066. *
  44067. * @protected
  44068. * @param {module:echarts/data/Tree~TreeNode} node
  44069. * @param {Object} options
  44070. * @param {string} options.sort 'asc' or 'desc'
  44071. * @param {number} options.squareRatio
  44072. * @param {boolean} hideChildren
  44073. * @param {number} depth
  44074. */
  44075. function squarify(node, options, hideChildren, depth) {
  44076. var width;
  44077. var height;
  44078. if (node.isRemoved()) {
  44079. return;
  44080. }
  44081. var thisLayout = node.getLayout();
  44082. width = thisLayout.width;
  44083. height = thisLayout.height; // Considering border and gap
  44084. var nodeModel = node.getModel();
  44085. var borderWidth = nodeModel.get(PATH_BORDER_WIDTH);
  44086. var halfGapWidth = nodeModel.get(PATH_GAP_WIDTH) / 2;
  44087. var upperLabelHeight = getUpperLabelHeight(nodeModel);
  44088. var upperHeight = Math.max(borderWidth, upperLabelHeight);
  44089. var layoutOffset = borderWidth - halfGapWidth;
  44090. var layoutOffsetUpper = upperHeight - halfGapWidth;
  44091. var nodeModel = node.getModel();
  44092. node.setLayout({
  44093. borderWidth: borderWidth,
  44094. upperHeight: upperHeight,
  44095. upperLabelHeight: upperLabelHeight
  44096. }, true);
  44097. width = mathMax$5(width - 2 * layoutOffset, 0);
  44098. height = mathMax$5(height - layoutOffset - layoutOffsetUpper, 0);
  44099. var totalArea = width * height;
  44100. var viewChildren = initChildren(node, nodeModel, totalArea, options, hideChildren, depth);
  44101. if (!viewChildren.length) {
  44102. return;
  44103. }
  44104. var rect = {
  44105. x: layoutOffset,
  44106. y: layoutOffsetUpper,
  44107. width: width,
  44108. height: height
  44109. };
  44110. var rowFixedLength = mathMin$5(width, height);
  44111. var best = Infinity; // the best row score so far
  44112. var row = [];
  44113. row.area = 0;
  44114. for (var i = 0, len = viewChildren.length; i < len;) {
  44115. var child = viewChildren[i];
  44116. row.push(child);
  44117. row.area += child.getLayout().area;
  44118. var score = worst(row, rowFixedLength, options.squareRatio); // continue with this orientation
  44119. if (score <= best) {
  44120. i++;
  44121. best = score;
  44122. } // abort, and try a different orientation
  44123. else {
  44124. row.area -= row.pop().getLayout().area;
  44125. position(row, rowFixedLength, rect, halfGapWidth, false);
  44126. rowFixedLength = mathMin$5(rect.width, rect.height);
  44127. row.length = row.area = 0;
  44128. best = Infinity;
  44129. }
  44130. }
  44131. if (row.length) {
  44132. position(row, rowFixedLength, rect, halfGapWidth, true);
  44133. }
  44134. if (!hideChildren) {
  44135. var childrenVisibleMin = nodeModel.get('childrenVisibleMin');
  44136. if (childrenVisibleMin != null && totalArea < childrenVisibleMin) {
  44137. hideChildren = true;
  44138. }
  44139. }
  44140. for (var i = 0, len = viewChildren.length; i < len; i++) {
  44141. squarify(viewChildren[i], options, hideChildren, depth + 1);
  44142. }
  44143. }
  44144. /**
  44145. * Set area to each child, and calculate data extent for visual coding.
  44146. */
  44147. function initChildren(node, nodeModel, totalArea, options, hideChildren, depth) {
  44148. var viewChildren = node.children || [];
  44149. var orderBy = options.sort;
  44150. orderBy !== 'asc' && orderBy !== 'desc' && (orderBy = null);
  44151. var overLeafDepth = options.leafDepth != null && options.leafDepth <= depth; // leafDepth has higher priority.
  44152. if (hideChildren && !overLeafDepth) {
  44153. return node.viewChildren = [];
  44154. } // Sort children, order by desc.
  44155. viewChildren = filter(viewChildren, function (child) {
  44156. return !child.isRemoved();
  44157. });
  44158. sort$1(viewChildren, orderBy);
  44159. var info = statistic(nodeModel, viewChildren, orderBy);
  44160. if (info.sum === 0) {
  44161. return node.viewChildren = [];
  44162. }
  44163. info.sum = filterByThreshold(nodeModel, totalArea, info.sum, orderBy, viewChildren);
  44164. if (info.sum === 0) {
  44165. return node.viewChildren = [];
  44166. } // Set area to each child.
  44167. for (var i = 0, len = viewChildren.length; i < len; i++) {
  44168. var area = viewChildren[i].getValue() / info.sum * totalArea; // Do not use setLayout({...}, true), because it is needed to clear last layout.
  44169. viewChildren[i].setLayout({
  44170. area: area
  44171. });
  44172. }
  44173. if (overLeafDepth) {
  44174. viewChildren.length && node.setLayout({
  44175. isLeafRoot: true
  44176. }, true);
  44177. viewChildren.length = 0;
  44178. }
  44179. node.viewChildren = viewChildren;
  44180. node.setLayout({
  44181. dataExtent: info.dataExtent
  44182. }, true);
  44183. return viewChildren;
  44184. }
  44185. /**
  44186. * Consider 'visibleMin'. Modify viewChildren and get new sum.
  44187. */
  44188. function filterByThreshold(nodeModel, totalArea, sum, orderBy, orderedChildren) {
  44189. // visibleMin is not supported yet when no option.sort.
  44190. if (!orderBy) {
  44191. return sum;
  44192. }
  44193. var visibleMin = nodeModel.get('visibleMin');
  44194. var len = orderedChildren.length;
  44195. var deletePoint = len; // Always travel from little value to big value.
  44196. for (var i = len - 1; i >= 0; i--) {
  44197. var value = orderedChildren[orderBy === 'asc' ? len - i - 1 : i].getValue();
  44198. if (value / sum * totalArea < visibleMin) {
  44199. deletePoint = i;
  44200. sum -= value;
  44201. }
  44202. }
  44203. orderBy === 'asc' ? orderedChildren.splice(0, len - deletePoint) : orderedChildren.splice(deletePoint, len - deletePoint);
  44204. return sum;
  44205. }
  44206. /**
  44207. * Sort
  44208. */
  44209. function sort$1(viewChildren, orderBy) {
  44210. if (orderBy) {
  44211. viewChildren.sort(function (a, b) {
  44212. var diff = orderBy === 'asc' ? a.getValue() - b.getValue() : b.getValue() - a.getValue();
  44213. return diff === 0 ? orderBy === 'asc' ? a.dataIndex - b.dataIndex : b.dataIndex - a.dataIndex : diff;
  44214. });
  44215. }
  44216. return viewChildren;
  44217. }
  44218. /**
  44219. * Statistic
  44220. */
  44221. function statistic(nodeModel, children, orderBy) {
  44222. // Calculate sum.
  44223. var sum = 0;
  44224. for (var i = 0, len = children.length; i < len; i++) {
  44225. sum += children[i].getValue();
  44226. } // Statistic data extent for latter visual coding.
  44227. // Notice: data extent should be calculate based on raw children
  44228. // but not filtered view children, otherwise visual mapping will not
  44229. // be stable when zoom (where children is filtered by visibleMin).
  44230. var dimension = nodeModel.get('visualDimension');
  44231. var dataExtent; // The same as area dimension.
  44232. if (!children || !children.length) {
  44233. dataExtent = [NaN, NaN];
  44234. } else if (dimension === 'value' && orderBy) {
  44235. dataExtent = [children[children.length - 1].getValue(), children[0].getValue()];
  44236. orderBy === 'asc' && dataExtent.reverse();
  44237. } // Other dimension.
  44238. else {
  44239. var dataExtent = [Infinity, -Infinity];
  44240. each$10(children, function (child) {
  44241. var value = child.getValue(dimension);
  44242. value < dataExtent[0] && (dataExtent[0] = value);
  44243. value > dataExtent[1] && (dataExtent[1] = value);
  44244. });
  44245. }
  44246. return {
  44247. sum: sum,
  44248. dataExtent: dataExtent
  44249. };
  44250. }
  44251. /**
  44252. * Computes the score for the specified row,
  44253. * as the worst aspect ratio.
  44254. */
  44255. function worst(row, rowFixedLength, ratio) {
  44256. var areaMax = 0;
  44257. var areaMin = Infinity;
  44258. for (var i = 0, area, len = row.length; i < len; i++) {
  44259. area = row[i].getLayout().area;
  44260. if (area) {
  44261. area < areaMin && (areaMin = area);
  44262. area > areaMax && (areaMax = area);
  44263. }
  44264. }
  44265. var squareArea = row.area * row.area;
  44266. var f = rowFixedLength * rowFixedLength * ratio;
  44267. return squareArea ? mathMax$5(f * areaMax / squareArea, squareArea / (f * areaMin)) : Infinity;
  44268. }
  44269. /**
  44270. * Positions the specified row of nodes. Modifies `rect`.
  44271. */
  44272. function position(row, rowFixedLength, rect, halfGapWidth, flush) {
  44273. // When rowFixedLength === rect.width,
  44274. // it is horizontal subdivision,
  44275. // rowFixedLength is the width of the subdivision,
  44276. // rowOtherLength is the height of the subdivision,
  44277. // and nodes will be positioned from left to right.
  44278. // wh[idx0WhenH] means: when horizontal,
  44279. // wh[idx0WhenH] => wh[0] => 'width'.
  44280. // xy[idx1WhenH] => xy[1] => 'y'.
  44281. var idx0WhenH = rowFixedLength === rect.width ? 0 : 1;
  44282. var idx1WhenH = 1 - idx0WhenH;
  44283. var xy = ['x', 'y'];
  44284. var wh = ['width', 'height'];
  44285. var last = rect[xy[idx0WhenH]];
  44286. var rowOtherLength = rowFixedLength ? row.area / rowFixedLength : 0;
  44287. if (flush || rowOtherLength > rect[wh[idx1WhenH]]) {
  44288. rowOtherLength = rect[wh[idx1WhenH]]; // over+underflow
  44289. }
  44290. for (var i = 0, rowLen = row.length; i < rowLen; i++) {
  44291. var node = row[i];
  44292. var nodeLayout = {};
  44293. var step = rowOtherLength ? node.getLayout().area / rowOtherLength : 0;
  44294. var wh1 = nodeLayout[wh[idx1WhenH]] = mathMax$5(rowOtherLength - 2 * halfGapWidth, 0); // We use Math.max/min to avoid negative width/height when considering gap width.
  44295. var remain = rect[xy[idx0WhenH]] + rect[wh[idx0WhenH]] - last;
  44296. var modWH = i === rowLen - 1 || remain < step ? remain : step;
  44297. var wh0 = nodeLayout[wh[idx0WhenH]] = mathMax$5(modWH - 2 * halfGapWidth, 0);
  44298. nodeLayout[xy[idx1WhenH]] = rect[xy[idx1WhenH]] + mathMin$5(halfGapWidth, wh1 / 2);
  44299. nodeLayout[xy[idx0WhenH]] = last + mathMin$5(halfGapWidth, wh0 / 2);
  44300. last += modWH;
  44301. node.setLayout(nodeLayout, true);
  44302. }
  44303. rect[xy[idx1WhenH]] += rowOtherLength;
  44304. rect[wh[idx1WhenH]] -= rowOtherLength;
  44305. } // Return [containerWidth, containerHeight] as defualt.
  44306. function estimateRootSize(seriesModel, targetInfo, viewRoot, containerWidth, containerHeight) {
  44307. // If targetInfo.node exists, we zoom to the node,
  44308. // so estimate whold width and heigth by target node.
  44309. var currNode = (targetInfo || {}).node;
  44310. var defaultSize = [containerWidth, containerHeight];
  44311. if (!currNode || currNode === viewRoot) {
  44312. return defaultSize;
  44313. }
  44314. var parent;
  44315. var viewArea = containerWidth * containerHeight;
  44316. var area = viewArea * seriesModel.option.zoomToNodeRatio;
  44317. while (parent = currNode.parentNode) {
  44318. // jshint ignore:line
  44319. var sum = 0;
  44320. var siblings = parent.children;
  44321. for (var i = 0, len = siblings.length; i < len; i++) {
  44322. sum += siblings[i].getValue();
  44323. }
  44324. var currNodeValue = currNode.getValue();
  44325. if (currNodeValue === 0) {
  44326. return defaultSize;
  44327. }
  44328. area *= sum / currNodeValue; // Considering border, suppose aspect ratio is 1.
  44329. var parentModel = parent.getModel();
  44330. var borderWidth = parentModel.get(PATH_BORDER_WIDTH);
  44331. var upperHeight = Math.max(borderWidth, getUpperLabelHeight(parentModel, borderWidth));
  44332. area += 4 * borderWidth * borderWidth + (3 * borderWidth + upperHeight) * Math.pow(area, 0.5);
  44333. area > MAX_SAFE_INTEGER && (area = MAX_SAFE_INTEGER);
  44334. currNode = parent;
  44335. }
  44336. area < viewArea && (area = viewArea);
  44337. var scale = Math.pow(area / viewArea, 0.5);
  44338. return [containerWidth * scale, containerHeight * scale];
  44339. } // Root postion base on coord of containerGroup
  44340. function calculateRootPosition(layoutInfo, rootRect, targetInfo) {
  44341. if (rootRect) {
  44342. return {
  44343. x: rootRect.x,
  44344. y: rootRect.y
  44345. };
  44346. }
  44347. var defaultPosition = {
  44348. x: 0,
  44349. y: 0
  44350. };
  44351. if (!targetInfo) {
  44352. return defaultPosition;
  44353. } // If targetInfo is fetched by 'retrieveTargetInfo',
  44354. // old tree and new tree are the same tree,
  44355. // so the node still exists and we can visit it.
  44356. var targetNode = targetInfo.node;
  44357. var layout = targetNode.getLayout();
  44358. if (!layout) {
  44359. return defaultPosition;
  44360. } // Transform coord from local to container.
  44361. var targetCenter = [layout.width / 2, layout.height / 2];
  44362. var node = targetNode;
  44363. while (node) {
  44364. var nodeLayout = node.getLayout();
  44365. targetCenter[0] += nodeLayout.x;
  44366. targetCenter[1] += nodeLayout.y;
  44367. node = node.parentNode;
  44368. }
  44369. return {
  44370. x: layoutInfo.width / 2 - targetCenter[0],
  44371. y: layoutInfo.height / 2 - targetCenter[1]
  44372. };
  44373. } // Mark nodes visible for prunning when visual coding and rendering.
  44374. // Prunning depends on layout and root position, so we have to do it after layout.
  44375. function prunning(node, clipRect, viewAbovePath, viewRoot, depth) {
  44376. var nodeLayout = node.getLayout();
  44377. var nodeInViewAbovePath = viewAbovePath[depth];
  44378. var isAboveViewRoot = nodeInViewAbovePath && nodeInViewAbovePath === node;
  44379. if (nodeInViewAbovePath && !isAboveViewRoot || depth === viewAbovePath.length && node !== viewRoot) {
  44380. return;
  44381. }
  44382. node.setLayout({
  44383. // isInView means: viewRoot sub tree + viewAbovePath
  44384. isInView: true,
  44385. // invisible only means: outside view clip so that the node can not
  44386. // see but still layout for animation preparation but not render.
  44387. invisible: !isAboveViewRoot && !clipRect.intersect(nodeLayout),
  44388. isAboveViewRoot: isAboveViewRoot
  44389. }, true); // Transform to child coordinate.
  44390. var childClipRect = new BoundingRect(clipRect.x - nodeLayout.x, clipRect.y - nodeLayout.y, clipRect.width, clipRect.height);
  44391. each$10(node.viewChildren || [], function (child) {
  44392. prunning(child, childClipRect, viewAbovePath, viewRoot, depth + 1);
  44393. });
  44394. }
  44395. function getUpperLabelHeight(model) {
  44396. return model.get(PATH_UPPER_LABEL_SHOW) ? model.get(PATH_UPPER_LABEL_HEIGHT) : 0;
  44397. }
  44398. /*
  44399. * Licensed to the Apache Software Foundation (ASF) under one
  44400. * or more contributor license agreements. See the NOTICE file
  44401. * distributed with this work for additional information
  44402. * regarding copyright ownership. The ASF licenses this file
  44403. * to you under the Apache License, Version 2.0 (the
  44404. * "License"); you may not use this file except in compliance
  44405. * with the License. You may obtain a copy of the License at
  44406. *
  44407. * http://www.apache.org/licenses/LICENSE-2.0
  44408. *
  44409. * Unless required by applicable law or agreed to in writing,
  44410. * software distributed under the License is distributed on an
  44411. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44412. * KIND, either express or implied. See the License for the
  44413. * specific language governing permissions and limitations
  44414. * under the License.
  44415. */
  44416. registerVisual(treemapVisual);
  44417. registerLayout(treemapLayout);
  44418. /*
  44419. * Licensed to the Apache Software Foundation (ASF) under one
  44420. * or more contributor license agreements. See the NOTICE file
  44421. * distributed with this work for additional information
  44422. * regarding copyright ownership. The ASF licenses this file
  44423. * to you under the Apache License, Version 2.0 (the
  44424. * "License"); you may not use this file except in compliance
  44425. * with the License. You may obtain a copy of the License at
  44426. *
  44427. * http://www.apache.org/licenses/LICENSE-2.0
  44428. *
  44429. * Unless required by applicable law or agreed to in writing,
  44430. * software distributed under the License is distributed on an
  44431. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44432. * KIND, either express or implied. See the License for the
  44433. * specific language governing permissions and limitations
  44434. * under the License.
  44435. */
  44436. SeriesModel.extend({
  44437. type: 'series.sunburst',
  44438. /**
  44439. * @type {module:echarts/data/Tree~Node}
  44440. */
  44441. _viewRoot: null,
  44442. getInitialData: function (option, ecModel) {
  44443. // Create a virtual root.
  44444. var root = {
  44445. name: option.name,
  44446. children: option.data
  44447. };
  44448. completeTreeValue$1(root);
  44449. var levels = option.levels || []; // levels = option.levels = setDefault(levels, ecModel);
  44450. var treeOption = {};
  44451. treeOption.levels = levels; // Make sure always a new tree is created when setOption,
  44452. // in TreemapView, we check whether oldTree === newTree
  44453. // to choose mappings approach among old shapes and new shapes.
  44454. return Tree.createTree(root, this, treeOption).data;
  44455. },
  44456. optionUpdated: function () {
  44457. this.resetViewRoot();
  44458. },
  44459. /*
  44460. * @override
  44461. */
  44462. getDataParams: function (dataIndex) {
  44463. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  44464. var node = this.getData().tree.getNodeByDataIndex(dataIndex);
  44465. params.treePathInfo = wrapTreePathInfo(node, this);
  44466. return params;
  44467. },
  44468. defaultOption: {
  44469. zlevel: 0,
  44470. z: 2,
  44471. // 默认全局居中
  44472. center: ['50%', '50%'],
  44473. radius: [0, '75%'],
  44474. // 默认顺时针
  44475. clockwise: true,
  44476. startAngle: 90,
  44477. // 最小角度改为0
  44478. minAngle: 0,
  44479. percentPrecision: 2,
  44480. // If still show when all data zero.
  44481. stillShowZeroSum: true,
  44482. // Policy of highlighting pieces when hover on one
  44483. // Valid values: 'none' (for not downplay others), 'descendant',
  44484. // 'ancestor', 'self'
  44485. highlightPolicy: 'descendant',
  44486. // 'rootToNode', 'link', or false
  44487. nodeClick: 'rootToNode',
  44488. renderLabelForZeroData: false,
  44489. label: {
  44490. // could be: 'radial', 'tangential', or 'none'
  44491. rotate: 'radial',
  44492. show: true,
  44493. opacity: 1,
  44494. // 'left' is for inner side of inside, and 'right' is for outter
  44495. // side for inside
  44496. align: 'center',
  44497. position: 'inside',
  44498. distance: 5,
  44499. silent: true
  44500. },
  44501. itemStyle: {
  44502. borderWidth: 1,
  44503. borderColor: 'white',
  44504. borderType: 'solid',
  44505. shadowBlur: 0,
  44506. shadowColor: 'rgba(0, 0, 0, 0.2)',
  44507. shadowOffsetX: 0,
  44508. shadowOffsetY: 0,
  44509. opacity: 1
  44510. },
  44511. highlight: {
  44512. itemStyle: {
  44513. opacity: 1
  44514. }
  44515. },
  44516. downplay: {
  44517. itemStyle: {
  44518. opacity: 0.5
  44519. },
  44520. label: {
  44521. opacity: 0.6
  44522. }
  44523. },
  44524. // Animation type canbe expansion, scale
  44525. animationType: 'expansion',
  44526. animationDuration: 1000,
  44527. animationDurationUpdate: 500,
  44528. animationEasing: 'cubicOut',
  44529. data: [],
  44530. levels: [],
  44531. /**
  44532. * Sort order.
  44533. *
  44534. * Valid values: 'desc', 'asc', null, or callback function.
  44535. * 'desc' and 'asc' for descend and ascendant order;
  44536. * null for not sorting;
  44537. * example of callback function:
  44538. * function(nodeA, nodeB) {
  44539. * return nodeA.getValue() - nodeB.getValue();
  44540. * }
  44541. */
  44542. sort: 'desc'
  44543. },
  44544. getViewRoot: function () {
  44545. return this._viewRoot;
  44546. },
  44547. /**
  44548. * @param {module:echarts/data/Tree~Node} [viewRoot]
  44549. */
  44550. resetViewRoot: function (viewRoot) {
  44551. viewRoot ? this._viewRoot = viewRoot : viewRoot = this._viewRoot;
  44552. var root = this.getRawData().tree.root;
  44553. if (!viewRoot || viewRoot !== root && !root.contains(viewRoot)) {
  44554. this._viewRoot = root;
  44555. }
  44556. }
  44557. });
  44558. /**
  44559. * @param {Object} dataNode
  44560. */
  44561. function completeTreeValue$1(dataNode) {
  44562. // Postorder travel tree.
  44563. // If value of none-leaf node is not set,
  44564. // calculate it by suming up the value of all children.
  44565. var sum = 0;
  44566. each$1(dataNode.children, function (child) {
  44567. completeTreeValue$1(child);
  44568. var childValue = child.value;
  44569. isArray(childValue) && (childValue = childValue[0]);
  44570. sum += childValue;
  44571. });
  44572. var thisValue = dataNode.value;
  44573. if (isArray(thisValue)) {
  44574. thisValue = thisValue[0];
  44575. }
  44576. if (thisValue == null || isNaN(thisValue)) {
  44577. thisValue = sum;
  44578. } // Value should not less than 0.
  44579. if (thisValue < 0) {
  44580. thisValue = 0;
  44581. }
  44582. isArray(dataNode.value) ? dataNode.value[0] = thisValue : dataNode.value = thisValue;
  44583. }
  44584. /*
  44585. * Licensed to the Apache Software Foundation (ASF) under one
  44586. * or more contributor license agreements. See the NOTICE file
  44587. * distributed with this work for additional information
  44588. * regarding copyright ownership. The ASF licenses this file
  44589. * to you under the Apache License, Version 2.0 (the
  44590. * "License"); you may not use this file except in compliance
  44591. * with the License. You may obtain a copy of the License at
  44592. *
  44593. * http://www.apache.org/licenses/LICENSE-2.0
  44594. *
  44595. * Unless required by applicable law or agreed to in writing,
  44596. * software distributed under the License is distributed on an
  44597. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44598. * KIND, either express or implied. See the License for the
  44599. * specific language governing permissions and limitations
  44600. * under the License.
  44601. */
  44602. var NodeHighlightPolicy = {
  44603. NONE: 'none',
  44604. // not downplay others
  44605. DESCENDANT: 'descendant',
  44606. ANCESTOR: 'ancestor',
  44607. SELF: 'self'
  44608. };
  44609. var DEFAULT_SECTOR_Z = 2;
  44610. var DEFAULT_TEXT_Z = 4;
  44611. /**
  44612. * Sunburstce of Sunburst including Sector, Label, LabelLine
  44613. * @constructor
  44614. * @extends {module:zrender/graphic/Group}
  44615. */
  44616. function SunburstPiece(node, seriesModel, ecModel) {
  44617. Group.call(this);
  44618. var sector = new Sector({
  44619. z2: DEFAULT_SECTOR_Z
  44620. });
  44621. sector.seriesIndex = seriesModel.seriesIndex;
  44622. var text = new Text({
  44623. z2: DEFAULT_TEXT_Z,
  44624. silent: node.getModel('label').get('silent')
  44625. });
  44626. this.add(sector);
  44627. this.add(text);
  44628. this.updateData(true, node, 'normal', seriesModel, ecModel); // Hover to change label and labelLine
  44629. function onEmphasis() {
  44630. text.ignore = text.hoverIgnore;
  44631. }
  44632. function onNormal() {
  44633. text.ignore = text.normalIgnore;
  44634. }
  44635. this.on('emphasis', onEmphasis).on('normal', onNormal).on('mouseover', onEmphasis).on('mouseout', onNormal);
  44636. }
  44637. var SunburstPieceProto = SunburstPiece.prototype;
  44638. SunburstPieceProto.updateData = function (firstCreate, node, state, seriesModel, ecModel) {
  44639. this.node = node;
  44640. node.piece = this;
  44641. seriesModel = seriesModel || this._seriesModel;
  44642. ecModel = ecModel || this._ecModel;
  44643. var sector = this.childAt(0);
  44644. sector.dataIndex = node.dataIndex;
  44645. var itemModel = node.getModel();
  44646. var layout = node.getLayout(); // if (!layout) {
  44647. // console.log(node.getLayout());
  44648. // }
  44649. var sectorShape = extend({}, layout);
  44650. sectorShape.label = null;
  44651. var visualColor = getNodeColor(node, seriesModel, ecModel);
  44652. fillDefaultColor(node, seriesModel, visualColor);
  44653. var normalStyle = itemModel.getModel('itemStyle').getItemStyle();
  44654. var style;
  44655. if (state === 'normal') {
  44656. style = normalStyle;
  44657. } else {
  44658. var stateStyle = itemModel.getModel(state + '.itemStyle').getItemStyle();
  44659. style = merge(stateStyle, normalStyle);
  44660. }
  44661. style = defaults({
  44662. lineJoin: 'bevel',
  44663. fill: style.fill || visualColor
  44664. }, style);
  44665. if (firstCreate) {
  44666. sector.setShape(sectorShape);
  44667. sector.shape.r = layout.r0;
  44668. updateProps(sector, {
  44669. shape: {
  44670. r: layout.r
  44671. }
  44672. }, seriesModel, node.dataIndex);
  44673. sector.useStyle(style);
  44674. } else if (typeof style.fill === 'object' && style.fill.type || typeof sector.style.fill === 'object' && sector.style.fill.type) {
  44675. // Disable animation for gradient since no interpolation method
  44676. // is supported for gradient
  44677. updateProps(sector, {
  44678. shape: sectorShape
  44679. }, seriesModel);
  44680. sector.useStyle(style);
  44681. } else {
  44682. updateProps(sector, {
  44683. shape: sectorShape,
  44684. style: style
  44685. }, seriesModel);
  44686. }
  44687. this._updateLabel(seriesModel, visualColor, state);
  44688. var cursorStyle = itemModel.getShallow('cursor');
  44689. cursorStyle && sector.attr('cursor', cursorStyle);
  44690. if (firstCreate) {
  44691. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  44692. this._initEvents(sector, node, seriesModel, highlightPolicy);
  44693. }
  44694. this._seriesModel = seriesModel || this._seriesModel;
  44695. this._ecModel = ecModel || this._ecModel;
  44696. setHoverStyle(this);
  44697. };
  44698. SunburstPieceProto.onEmphasis = function (highlightPolicy) {
  44699. var that = this;
  44700. this.node.hostTree.root.eachNode(function (n) {
  44701. if (n.piece) {
  44702. if (that.node === n) {
  44703. n.piece.updateData(false, n, 'emphasis');
  44704. } else if (isNodeHighlighted(n, that.node, highlightPolicy)) {
  44705. n.piece.childAt(0).trigger('highlight');
  44706. } else if (highlightPolicy !== NodeHighlightPolicy.NONE) {
  44707. n.piece.childAt(0).trigger('downplay');
  44708. }
  44709. }
  44710. });
  44711. };
  44712. SunburstPieceProto.onNormal = function () {
  44713. this.node.hostTree.root.eachNode(function (n) {
  44714. if (n.piece) {
  44715. n.piece.updateData(false, n, 'normal');
  44716. }
  44717. });
  44718. };
  44719. SunburstPieceProto.onHighlight = function () {
  44720. this.updateData(false, this.node, 'highlight');
  44721. };
  44722. SunburstPieceProto.onDownplay = function () {
  44723. this.updateData(false, this.node, 'downplay');
  44724. };
  44725. SunburstPieceProto._updateLabel = function (seriesModel, visualColor, state) {
  44726. var itemModel = this.node.getModel();
  44727. var normalModel = itemModel.getModel('label');
  44728. var labelModel = state === 'normal' || state === 'emphasis' ? normalModel : itemModel.getModel(state + '.label');
  44729. var labelHoverModel = itemModel.getModel('emphasis.label');
  44730. var text = retrieve(seriesModel.getFormattedLabel(this.node.dataIndex, state, null, null, 'label'), this.node.name);
  44731. if (getLabelAttr('show') === false) {
  44732. text = '';
  44733. }
  44734. var layout = this.node.getLayout();
  44735. var labelMinAngle = labelModel.get('minAngle');
  44736. if (labelMinAngle == null) {
  44737. labelMinAngle = normalModel.get('minAngle');
  44738. }
  44739. labelMinAngle = labelMinAngle / 180 * Math.PI;
  44740. var angle = layout.endAngle - layout.startAngle;
  44741. if (labelMinAngle != null && Math.abs(angle) < labelMinAngle) {
  44742. // Not displaying text when angle is too small
  44743. text = '';
  44744. }
  44745. var label = this.childAt(1);
  44746. setLabelStyle(label.style, label.hoverStyle || {}, normalModel, labelHoverModel, {
  44747. defaultText: labelModel.getShallow('show') ? text : null,
  44748. autoColor: visualColor,
  44749. useInsideStyle: true
  44750. });
  44751. var midAngle = (layout.startAngle + layout.endAngle) / 2;
  44752. var dx = Math.cos(midAngle);
  44753. var dy = Math.sin(midAngle);
  44754. var r;
  44755. var labelPosition = getLabelAttr('position');
  44756. var labelPadding = getLabelAttr('distance') || 0;
  44757. var textAlign = getLabelAttr('align');
  44758. if (labelPosition === 'outside') {
  44759. r = layout.r + labelPadding;
  44760. textAlign = midAngle > Math.PI / 2 ? 'right' : 'left';
  44761. } else {
  44762. if (!textAlign || textAlign === 'center') {
  44763. r = (layout.r + layout.r0) / 2;
  44764. textAlign = 'center';
  44765. } else if (textAlign === 'left') {
  44766. r = layout.r0 + labelPadding;
  44767. if (midAngle > Math.PI / 2) {
  44768. textAlign = 'right';
  44769. }
  44770. } else if (textAlign === 'right') {
  44771. r = layout.r - labelPadding;
  44772. if (midAngle > Math.PI / 2) {
  44773. textAlign = 'left';
  44774. }
  44775. }
  44776. }
  44777. label.attr('style', {
  44778. text: text,
  44779. textAlign: textAlign,
  44780. textVerticalAlign: getLabelAttr('verticalAlign') || 'middle',
  44781. opacity: getLabelAttr('opacity')
  44782. });
  44783. var textX = r * dx + layout.cx;
  44784. var textY = r * dy + layout.cy;
  44785. label.attr('position', [textX, textY]);
  44786. var rotateType = getLabelAttr('rotate');
  44787. var rotate = 0;
  44788. if (rotateType === 'radial') {
  44789. rotate = -midAngle;
  44790. if (rotate < -Math.PI / 2) {
  44791. rotate += Math.PI;
  44792. }
  44793. } else if (rotateType === 'tangential') {
  44794. rotate = Math.PI / 2 - midAngle;
  44795. if (rotate > Math.PI / 2) {
  44796. rotate -= Math.PI;
  44797. } else if (rotate < -Math.PI / 2) {
  44798. rotate += Math.PI;
  44799. }
  44800. } else if (typeof rotateType === 'number') {
  44801. rotate = rotateType * Math.PI / 180;
  44802. }
  44803. label.attr('rotation', rotate);
  44804. function getLabelAttr(name) {
  44805. var stateAttr = labelModel.get(name);
  44806. if (stateAttr == null) {
  44807. return normalModel.get(name);
  44808. } else {
  44809. return stateAttr;
  44810. }
  44811. }
  44812. };
  44813. SunburstPieceProto._initEvents = function (sector, node, seriesModel, highlightPolicy) {
  44814. sector.off('mouseover').off('mouseout').off('emphasis').off('normal');
  44815. var that = this;
  44816. var onEmphasis = function () {
  44817. that.onEmphasis(highlightPolicy);
  44818. };
  44819. var onNormal = function () {
  44820. that.onNormal();
  44821. };
  44822. var onDownplay = function () {
  44823. that.onDownplay();
  44824. };
  44825. var onHighlight = function () {
  44826. that.onHighlight();
  44827. };
  44828. if (seriesModel.isAnimationEnabled()) {
  44829. sector.on('mouseover', onEmphasis).on('mouseout', onNormal).on('emphasis', onEmphasis).on('normal', onNormal).on('downplay', onDownplay).on('highlight', onHighlight);
  44830. }
  44831. };
  44832. inherits(SunburstPiece, Group);
  44833. /**
  44834. * Get node color
  44835. *
  44836. * @param {TreeNode} node the node to get color
  44837. * @param {module:echarts/model/Series} seriesModel series
  44838. * @param {module:echarts/model/Global} ecModel echarts defaults
  44839. */
  44840. function getNodeColor(node, seriesModel, ecModel) {
  44841. // Color from visualMap
  44842. var visualColor = node.getVisual('color');
  44843. var visualMetaList = node.getVisual('visualMeta');
  44844. if (!visualMetaList || visualMetaList.length === 0) {
  44845. // Use first-generation color if has no visualMap
  44846. visualColor = null;
  44847. } // Self color or level color
  44848. var color = node.getModel('itemStyle').get('color');
  44849. if (color) {
  44850. return color;
  44851. } else if (visualColor) {
  44852. // Color mapping
  44853. return visualColor;
  44854. } else if (node.depth === 0) {
  44855. // Virtual root node
  44856. return ecModel.option.color[0];
  44857. } else {
  44858. // First-generation color
  44859. var length = ecModel.option.color.length;
  44860. color = ecModel.option.color[getRootId(node) % length];
  44861. }
  44862. return color;
  44863. }
  44864. /**
  44865. * Get index of root in sorted order
  44866. *
  44867. * @param {TreeNode} node current node
  44868. * @return {number} index in root
  44869. */
  44870. function getRootId(node) {
  44871. var ancestor = node;
  44872. while (ancestor.depth > 1) {
  44873. ancestor = ancestor.parentNode;
  44874. }
  44875. var virtualRoot = node.getAncestors()[0];
  44876. return indexOf(virtualRoot.children, ancestor);
  44877. }
  44878. function isNodeHighlighted(node, activeNode, policy) {
  44879. if (policy === NodeHighlightPolicy.NONE) {
  44880. return false;
  44881. } else if (policy === NodeHighlightPolicy.SELF) {
  44882. return node === activeNode;
  44883. } else if (policy === NodeHighlightPolicy.ANCESTOR) {
  44884. return node === activeNode || node.isAncestorOf(activeNode);
  44885. } else {
  44886. return node === activeNode || node.isDescendantOf(activeNode);
  44887. }
  44888. } // Fix tooltip callback function params.color incorrect when pick a default color
  44889. function fillDefaultColor(node, seriesModel, color) {
  44890. var data = seriesModel.getData();
  44891. data.setItemVisual(node.dataIndex, 'color', color);
  44892. }
  44893. /*
  44894. * Licensed to the Apache Software Foundation (ASF) under one
  44895. * or more contributor license agreements. See the NOTICE file
  44896. * distributed with this work for additional information
  44897. * regarding copyright ownership. The ASF licenses this file
  44898. * to you under the Apache License, Version 2.0 (the
  44899. * "License"); you may not use this file except in compliance
  44900. * with the License. You may obtain a copy of the License at
  44901. *
  44902. * http://www.apache.org/licenses/LICENSE-2.0
  44903. *
  44904. * Unless required by applicable law or agreed to in writing,
  44905. * software distributed under the License is distributed on an
  44906. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  44907. * KIND, either express or implied. See the License for the
  44908. * specific language governing permissions and limitations
  44909. * under the License.
  44910. */
  44911. var ROOT_TO_NODE_ACTION = 'sunburstRootToNode';
  44912. var SunburstView = Chart.extend({
  44913. type: 'sunburst',
  44914. init: function () {},
  44915. render: function (seriesModel, ecModel, api, payload) {
  44916. var that = this;
  44917. this.seriesModel = seriesModel;
  44918. this.api = api;
  44919. this.ecModel = ecModel;
  44920. var data = seriesModel.getData();
  44921. var virtualRoot = data.tree.root;
  44922. var newRoot = seriesModel.getViewRoot();
  44923. var group = this.group;
  44924. var renderLabelForZeroData = seriesModel.get('renderLabelForZeroData');
  44925. var newChildren = [];
  44926. newRoot.eachNode(function (node) {
  44927. newChildren.push(node);
  44928. });
  44929. var oldChildren = this._oldChildren || [];
  44930. dualTravel(newChildren, oldChildren);
  44931. renderRollUp(virtualRoot, newRoot);
  44932. if (payload && payload.highlight && payload.highlight.piece) {
  44933. var highlightPolicy = seriesModel.getShallow('highlightPolicy');
  44934. payload.highlight.piece.onEmphasis(highlightPolicy);
  44935. } else if (payload && payload.unhighlight) {
  44936. var piece = this.virtualPiece;
  44937. if (!piece && virtualRoot.children.length) {
  44938. piece = virtualRoot.children[0].piece;
  44939. }
  44940. if (piece) {
  44941. piece.onNormal();
  44942. }
  44943. }
  44944. this._initEvents();
  44945. this._oldChildren = newChildren;
  44946. function dualTravel(newChildren, oldChildren) {
  44947. if (newChildren.length === 0 && oldChildren.length === 0) {
  44948. return;
  44949. }
  44950. new DataDiffer(oldChildren, newChildren, getKey, getKey).add(processNode).update(processNode).remove(curry(processNode, null)).execute();
  44951. function getKey(node) {
  44952. return node.getId();
  44953. }
  44954. function processNode(newId, oldId) {
  44955. var newNode = newId == null ? null : newChildren[newId];
  44956. var oldNode = oldId == null ? null : oldChildren[oldId];
  44957. doRenderNode(newNode, oldNode);
  44958. }
  44959. }
  44960. function doRenderNode(newNode, oldNode) {
  44961. if (!renderLabelForZeroData && newNode && !newNode.getValue()) {
  44962. // Not render data with value 0
  44963. newNode = null;
  44964. }
  44965. if (newNode !== virtualRoot && oldNode !== virtualRoot) {
  44966. if (oldNode && oldNode.piece) {
  44967. if (newNode) {
  44968. // Update
  44969. oldNode.piece.updateData(false, newNode, 'normal', seriesModel, ecModel); // For tooltip
  44970. data.setItemGraphicEl(newNode.dataIndex, oldNode.piece);
  44971. } else {
  44972. // Remove
  44973. removeNode(oldNode);
  44974. }
  44975. } else if (newNode) {
  44976. // Add
  44977. var piece = new SunburstPiece(newNode, seriesModel, ecModel);
  44978. group.add(piece); // For tooltip
  44979. data.setItemGraphicEl(newNode.dataIndex, piece);
  44980. }
  44981. }
  44982. }
  44983. function removeNode(node) {
  44984. if (!node) {
  44985. return;
  44986. }
  44987. if (node.piece) {
  44988. group.remove(node.piece);
  44989. node.piece = null;
  44990. }
  44991. }
  44992. function renderRollUp(virtualRoot, viewRoot) {
  44993. if (viewRoot.depth > 0) {
  44994. // Render
  44995. if (that.virtualPiece) {
  44996. // Update
  44997. that.virtualPiece.updateData(false, virtualRoot, 'normal', seriesModel, ecModel);
  44998. } else {
  44999. // Add
  45000. that.virtualPiece = new SunburstPiece(virtualRoot, seriesModel, ecModel);
  45001. group.add(that.virtualPiece);
  45002. }
  45003. if (viewRoot.piece._onclickEvent) {
  45004. viewRoot.piece.off('click', viewRoot.piece._onclickEvent);
  45005. }
  45006. var event = function (e) {
  45007. that._rootToNode(viewRoot.parentNode);
  45008. };
  45009. viewRoot.piece._onclickEvent = event;
  45010. that.virtualPiece.on('click', event);
  45011. } else if (that.virtualPiece) {
  45012. // Remove
  45013. group.remove(that.virtualPiece);
  45014. that.virtualPiece = null;
  45015. }
  45016. }
  45017. },
  45018. dispose: function () {},
  45019. /**
  45020. * @private
  45021. */
  45022. _initEvents: function () {
  45023. var that = this;
  45024. var event = function (e) {
  45025. var targetFound = false;
  45026. var viewRoot = that.seriesModel.getViewRoot();
  45027. viewRoot.eachNode(function (node) {
  45028. if (!targetFound && node.piece && node.piece.childAt(0) === e.target) {
  45029. var nodeClick = node.getModel().get('nodeClick');
  45030. if (nodeClick === 'rootToNode') {
  45031. that._rootToNode(node);
  45032. } else if (nodeClick === 'link') {
  45033. var itemModel = node.getModel();
  45034. var link = itemModel.get('link');
  45035. if (link) {
  45036. var linkTarget = itemModel.get('target', true) || '_blank';
  45037. windowOpen(link, linkTarget);
  45038. }
  45039. }
  45040. targetFound = true;
  45041. }
  45042. });
  45043. };
  45044. if (this.group._onclickEvent) {
  45045. this.group.off('click', this.group._onclickEvent);
  45046. }
  45047. this.group.on('click', event);
  45048. this.group._onclickEvent = event;
  45049. },
  45050. /**
  45051. * @private
  45052. */
  45053. _rootToNode: function (node) {
  45054. if (node !== this.seriesModel.getViewRoot()) {
  45055. this.api.dispatchAction({
  45056. type: ROOT_TO_NODE_ACTION,
  45057. from: this.uid,
  45058. seriesId: this.seriesModel.id,
  45059. targetNode: node
  45060. });
  45061. }
  45062. },
  45063. /**
  45064. * @implement
  45065. */
  45066. containPoint: function (point, seriesModel) {
  45067. var treeRoot = seriesModel.getData();
  45068. var itemLayout = treeRoot.getItemLayout(0);
  45069. if (itemLayout) {
  45070. var dx = point[0] - itemLayout.cx;
  45071. var dy = point[1] - itemLayout.cy;
  45072. var radius = Math.sqrt(dx * dx + dy * dy);
  45073. return radius <= itemLayout.r && radius >= itemLayout.r0;
  45074. }
  45075. }
  45076. });
  45077. /*
  45078. * Licensed to the Apache Software Foundation (ASF) under one
  45079. * or more contributor license agreements. See the NOTICE file
  45080. * distributed with this work for additional information
  45081. * regarding copyright ownership. The ASF licenses this file
  45082. * to you under the Apache License, Version 2.0 (the
  45083. * "License"); you may not use this file except in compliance
  45084. * with the License. You may obtain a copy of the License at
  45085. *
  45086. * http://www.apache.org/licenses/LICENSE-2.0
  45087. *
  45088. * Unless required by applicable law or agreed to in writing,
  45089. * software distributed under the License is distributed on an
  45090. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45091. * KIND, either express or implied. See the License for the
  45092. * specific language governing permissions and limitations
  45093. * under the License.
  45094. */
  45095. /**
  45096. * @file Sunburst action
  45097. */
  45098. var ROOT_TO_NODE_ACTION$1 = 'sunburstRootToNode';
  45099. registerAction({
  45100. type: ROOT_TO_NODE_ACTION$1,
  45101. update: 'updateView'
  45102. }, function (payload, ecModel) {
  45103. ecModel.eachComponent({
  45104. mainType: 'series',
  45105. subType: 'sunburst',
  45106. query: payload
  45107. }, handleRootToNode);
  45108. function handleRootToNode(model, index) {
  45109. var targetInfo = retrieveTargetInfo(payload, [ROOT_TO_NODE_ACTION$1], model);
  45110. if (targetInfo) {
  45111. var originViewRoot = model.getViewRoot();
  45112. if (originViewRoot) {
  45113. payload.direction = aboveViewRoot(originViewRoot, targetInfo.node) ? 'rollUp' : 'drillDown';
  45114. }
  45115. model.resetViewRoot(targetInfo.node);
  45116. }
  45117. }
  45118. });
  45119. var HIGHLIGHT_ACTION = 'sunburstHighlight';
  45120. registerAction({
  45121. type: HIGHLIGHT_ACTION,
  45122. update: 'updateView'
  45123. }, function (payload, ecModel) {
  45124. ecModel.eachComponent({
  45125. mainType: 'series',
  45126. subType: 'sunburst',
  45127. query: payload
  45128. }, handleHighlight);
  45129. function handleHighlight(model, index) {
  45130. var targetInfo = retrieveTargetInfo(payload, [HIGHLIGHT_ACTION], model);
  45131. if (targetInfo) {
  45132. payload.highlight = targetInfo.node;
  45133. }
  45134. }
  45135. });
  45136. var UNHIGHLIGHT_ACTION = 'sunburstUnhighlight';
  45137. registerAction({
  45138. type: UNHIGHLIGHT_ACTION,
  45139. update: 'updateView'
  45140. }, function (payload, ecModel) {
  45141. ecModel.eachComponent({
  45142. mainType: 'series',
  45143. subType: 'sunburst',
  45144. query: payload
  45145. }, handleUnhighlight);
  45146. function handleUnhighlight(model, index) {
  45147. payload.unhighlight = true;
  45148. }
  45149. });
  45150. /*
  45151. * Licensed to the Apache Software Foundation (ASF) under one
  45152. * or more contributor license agreements. See the NOTICE file
  45153. * distributed with this work for additional information
  45154. * regarding copyright ownership. The ASF licenses this file
  45155. * to you under the Apache License, Version 2.0 (the
  45156. * "License"); you may not use this file except in compliance
  45157. * with the License. You may obtain a copy of the License at
  45158. *
  45159. * http://www.apache.org/licenses/LICENSE-2.0
  45160. *
  45161. * Unless required by applicable law or agreed to in writing,
  45162. * software distributed under the License is distributed on an
  45163. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45164. * KIND, either express or implied. See the License for the
  45165. * specific language governing permissions and limitations
  45166. * under the License.
  45167. */
  45168. var RADIAN$2 = Math.PI / 180;
  45169. var sunburstLayout = function (seriesType, ecModel, api, payload) {
  45170. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  45171. var center = seriesModel.get('center');
  45172. var radius = seriesModel.get('radius');
  45173. if (!isArray(radius)) {
  45174. radius = [0, radius];
  45175. }
  45176. if (!isArray(center)) {
  45177. center = [center, center];
  45178. }
  45179. var width = api.getWidth();
  45180. var height = api.getHeight();
  45181. var size = Math.min(width, height);
  45182. var cx = parsePercent$1(center[0], width);
  45183. var cy = parsePercent$1(center[1], height);
  45184. var r0 = parsePercent$1(radius[0], size / 2);
  45185. var r = parsePercent$1(radius[1], size / 2);
  45186. var startAngle = -seriesModel.get('startAngle') * RADIAN$2;
  45187. var minAngle = seriesModel.get('minAngle') * RADIAN$2;
  45188. var virtualRoot = seriesModel.getData().tree.root;
  45189. var treeRoot = seriesModel.getViewRoot();
  45190. var rootDepth = treeRoot.depth;
  45191. var sort = seriesModel.get('sort');
  45192. if (sort != null) {
  45193. initChildren$1(treeRoot, sort);
  45194. }
  45195. var validDataCount = 0;
  45196. each$1(treeRoot.children, function (child) {
  45197. !isNaN(child.getValue()) && validDataCount++;
  45198. });
  45199. var sum = treeRoot.getValue(); // Sum may be 0
  45200. var unitRadian = Math.PI / (sum || validDataCount) * 2;
  45201. var renderRollupNode = treeRoot.depth > 0;
  45202. var levels = treeRoot.height - (renderRollupNode ? -1 : 1);
  45203. var rPerLevel = (r - r0) / (levels || 1);
  45204. var clockwise = seriesModel.get('clockwise');
  45205. var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // In the case some sector angle is smaller than minAngle
  45206. // var restAngle = PI2;
  45207. // var valueSumLargerThanMinAngle = 0;
  45208. var dir = clockwise ? 1 : -1;
  45209. /**
  45210. * Render a tree
  45211. * @return increased angle
  45212. */
  45213. var renderNode = function (node, startAngle) {
  45214. if (!node) {
  45215. return;
  45216. }
  45217. var endAngle = startAngle; // Render self
  45218. if (node !== virtualRoot) {
  45219. // Tree node is virtual, so it doesn't need to be drawn
  45220. var value = node.getValue();
  45221. var angle = sum === 0 && stillShowZeroSum ? unitRadian : value * unitRadian;
  45222. if (angle < minAngle) {
  45223. angle = minAngle; // restAngle -= minAngle;
  45224. } // else {
  45225. // valueSumLargerThanMinAngle += value;
  45226. // }
  45227. endAngle = startAngle + dir * angle;
  45228. var depth = node.depth - rootDepth - (renderRollupNode ? -1 : 1);
  45229. var rStart = r0 + rPerLevel * depth;
  45230. var rEnd = r0 + rPerLevel * (depth + 1);
  45231. var itemModel = node.getModel();
  45232. if (itemModel.get('r0') != null) {
  45233. rStart = parsePercent$1(itemModel.get('r0'), size / 2);
  45234. }
  45235. if (itemModel.get('r') != null) {
  45236. rEnd = parsePercent$1(itemModel.get('r'), size / 2);
  45237. }
  45238. node.setLayout({
  45239. angle: angle,
  45240. startAngle: startAngle,
  45241. endAngle: endAngle,
  45242. clockwise: clockwise,
  45243. cx: cx,
  45244. cy: cy,
  45245. r0: rStart,
  45246. r: rEnd
  45247. });
  45248. } // Render children
  45249. if (node.children && node.children.length) {
  45250. // currentAngle = startAngle;
  45251. var siblingAngle = 0;
  45252. each$1(node.children, function (node) {
  45253. siblingAngle += renderNode(node, startAngle + siblingAngle);
  45254. });
  45255. }
  45256. return endAngle - startAngle;
  45257. }; // Virtual root node for roll up
  45258. if (renderRollupNode) {
  45259. var rStart = r0;
  45260. var rEnd = r0 + rPerLevel;
  45261. var angle = Math.PI * 2;
  45262. virtualRoot.setLayout({
  45263. angle: angle,
  45264. startAngle: startAngle,
  45265. endAngle: startAngle + angle,
  45266. clockwise: clockwise,
  45267. cx: cx,
  45268. cy: cy,
  45269. r0: rStart,
  45270. r: rEnd
  45271. });
  45272. }
  45273. renderNode(treeRoot, startAngle);
  45274. });
  45275. };
  45276. /**
  45277. * Init node children by order and update visual
  45278. *
  45279. * @param {TreeNode} node root node
  45280. * @param {boolean} isAsc if is in ascendant order
  45281. */
  45282. function initChildren$1(node, isAsc) {
  45283. var children = node.children || [];
  45284. node.children = sort$2(children, isAsc); // Init children recursively
  45285. if (children.length) {
  45286. each$1(node.children, function (child) {
  45287. initChildren$1(child, isAsc);
  45288. });
  45289. }
  45290. }
  45291. /**
  45292. * Sort children nodes
  45293. *
  45294. * @param {TreeNode[]} children children of node to be sorted
  45295. * @param {string | function | null} sort sort method
  45296. * See SunburstSeries.js for details.
  45297. */
  45298. function sort$2(children, sortOrder) {
  45299. if (typeof sortOrder === 'function') {
  45300. return children.sort(sortOrder);
  45301. } else {
  45302. var isAsc = sortOrder === 'asc';
  45303. return children.sort(function (a, b) {
  45304. var diff = (a.getValue() - b.getValue()) * (isAsc ? 1 : -1);
  45305. return diff === 0 ? (a.dataIndex - b.dataIndex) * (isAsc ? -1 : 1) : diff;
  45306. });
  45307. }
  45308. }
  45309. /*
  45310. * Licensed to the Apache Software Foundation (ASF) under one
  45311. * or more contributor license agreements. See the NOTICE file
  45312. * distributed with this work for additional information
  45313. * regarding copyright ownership. The ASF licenses this file
  45314. * to you under the Apache License, Version 2.0 (the
  45315. * "License"); you may not use this file except in compliance
  45316. * with the License. You may obtain a copy of the License at
  45317. *
  45318. * http://www.apache.org/licenses/LICENSE-2.0
  45319. *
  45320. * Unless required by applicable law or agreed to in writing,
  45321. * software distributed under the License is distributed on an
  45322. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45323. * KIND, either express or implied. See the License for the
  45324. * specific language governing permissions and limitations
  45325. * under the License.
  45326. */
  45327. registerVisual(curry(dataColor, 'sunburst'));
  45328. registerLayout(curry(sunburstLayout, 'sunburst'));
  45329. registerProcessor(curry(dataFilter, 'sunburst'));
  45330. /*
  45331. * Licensed to the Apache Software Foundation (ASF) under one
  45332. * or more contributor license agreements. See the NOTICE file
  45333. * distributed with this work for additional information
  45334. * regarding copyright ownership. The ASF licenses this file
  45335. * to you under the Apache License, Version 2.0 (the
  45336. * "License"); you may not use this file except in compliance
  45337. * with the License. You may obtain a copy of the License at
  45338. *
  45339. * http://www.apache.org/licenses/LICENSE-2.0
  45340. *
  45341. * Unless required by applicable law or agreed to in writing,
  45342. * software distributed under the License is distributed on an
  45343. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45344. * KIND, either express or implied. See the License for the
  45345. * specific language governing permissions and limitations
  45346. * under the License.
  45347. */
  45348. // Fix for 南海诸岛
  45349. var geoCoord = [126, 25];
  45350. var points$1 = [[[0, 3.5], [7, 11.2], [15, 11.9], [30, 7], [42, 0.7], [52, 0.7], [56, 7.7], [59, 0.7], [64, 0.7], [64, 0], [5, 0], [0, 3.5]], [[13, 16.1], [19, 14.7], [16, 21.7], [11, 23.1], [13, 16.1]], [[12, 32.2], [14, 38.5], [15, 38.5], [13, 32.2], [12, 32.2]], [[16, 47.6], [12, 53.2], [13, 53.2], [18, 47.6], [16, 47.6]], [[6, 64.4], [8, 70], [9, 70], [8, 64.4], [6, 64.4]], [[23, 82.6], [29, 79.8], [30, 79.8], [25, 82.6], [23, 82.6]], [[37, 70.7], [43, 62.3], [44, 62.3], [39, 70.7], [37, 70.7]], [[48, 51.1], [51, 45.5], [53, 45.5], [50, 51.1], [48, 51.1]], [[51, 35], [51, 28.7], [53, 28.7], [53, 35], [51, 35]], [[52, 22.4], [55, 17.5], [56, 17.5], [53, 22.4], [52, 22.4]], [[58, 12.6], [62, 7], [63, 7], [60, 12.6], [58, 12.6]], [[0, 3.5], [0, 93.1], [64, 93.1], [64, 0], [63, 0], [63, 92.4], [1, 92.4], [1, 3.5], [0, 3.5]]];
  45351. for (var i$2 = 0; i$2 < points$1.length; i$2++) {
  45352. for (var k = 0; k < points$1[i$2].length; k++) {
  45353. points$1[i$2][k][0] /= 10.5;
  45354. points$1[i$2][k][1] /= -10.5 / 0.75;
  45355. points$1[i$2][k][0] += geoCoord[0];
  45356. points$1[i$2][k][1] += geoCoord[1];
  45357. }
  45358. }
  45359. var fixNanhai = function (mapType, regions) {
  45360. if (mapType === 'china') {
  45361. regions.push(new Region('南海诸岛', map(points$1, function (exterior) {
  45362. return {
  45363. type: 'polygon',
  45364. exterior: exterior
  45365. };
  45366. }), geoCoord));
  45367. }
  45368. };
  45369. /*
  45370. * Licensed to the Apache Software Foundation (ASF) under one
  45371. * or more contributor license agreements. See the NOTICE file
  45372. * distributed with this work for additional information
  45373. * regarding copyright ownership. The ASF licenses this file
  45374. * to you under the Apache License, Version 2.0 (the
  45375. * "License"); you may not use this file except in compliance
  45376. * with the License. You may obtain a copy of the License at
  45377. *
  45378. * http://www.apache.org/licenses/LICENSE-2.0
  45379. *
  45380. * Unless required by applicable law or agreed to in writing,
  45381. * software distributed under the License is distributed on an
  45382. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45383. * KIND, either express or implied. See the License for the
  45384. * specific language governing permissions and limitations
  45385. * under the License.
  45386. */
  45387. var coordsOffsetMap = {
  45388. '南海诸岛': [32, 80],
  45389. // 全国
  45390. '广东': [0, -10],
  45391. '香港': [10, 5],
  45392. '澳门': [-10, 10],
  45393. //'北京': [-10, 0],
  45394. '天津': [5, 5]
  45395. };
  45396. var fixTextCoord = function (mapType, region) {
  45397. if (mapType === 'china') {
  45398. var coordFix = coordsOffsetMap[region.name];
  45399. if (coordFix) {
  45400. var cp = region.center;
  45401. cp[0] += coordFix[0] / 10.5;
  45402. cp[1] += -coordFix[1] / (10.5 / 0.75);
  45403. }
  45404. }
  45405. };
  45406. /*
  45407. * Licensed to the Apache Software Foundation (ASF) under one
  45408. * or more contributor license agreements. See the NOTICE file
  45409. * distributed with this work for additional information
  45410. * regarding copyright ownership. The ASF licenses this file
  45411. * to you under the Apache License, Version 2.0 (the
  45412. * "License"); you may not use this file except in compliance
  45413. * with the License. You may obtain a copy of the License at
  45414. *
  45415. * http://www.apache.org/licenses/LICENSE-2.0
  45416. *
  45417. * Unless required by applicable law or agreed to in writing,
  45418. * software distributed under the License is distributed on an
  45419. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45420. * KIND, either express or implied. See the License for the
  45421. * specific language governing permissions and limitations
  45422. * under the License.
  45423. */
  45424. var geoCoordMap = {
  45425. 'Russia': [100, 60],
  45426. 'United States': [-99, 38],
  45427. 'United States of America': [-99, 38]
  45428. };
  45429. var fixGeoCoord = function (mapType, region) {
  45430. if (mapType === 'world') {
  45431. var geoCoord = geoCoordMap[region.name];
  45432. if (geoCoord) {
  45433. var cp = region.center;
  45434. cp[0] = geoCoord[0];
  45435. cp[1] = geoCoord[1];
  45436. }
  45437. }
  45438. };
  45439. /*
  45440. * Licensed to the Apache Software Foundation (ASF) under one
  45441. * or more contributor license agreements. See the NOTICE file
  45442. * distributed with this work for additional information
  45443. * regarding copyright ownership. The ASF licenses this file
  45444. * to you under the Apache License, Version 2.0 (the
  45445. * "License"); you may not use this file except in compliance
  45446. * with the License. You may obtain a copy of the License at
  45447. *
  45448. * http://www.apache.org/licenses/LICENSE-2.0
  45449. *
  45450. * Unless required by applicable law or agreed to in writing,
  45451. * software distributed under the License is distributed on an
  45452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45453. * KIND, either express or implied. See the License for the
  45454. * specific language governing permissions and limitations
  45455. * under the License.
  45456. */
  45457. // Fix for 钓鱼岛
  45458. // var Region = require('../Region');
  45459. // var zrUtil = require('zrender/src/core/util');
  45460. // var geoCoord = [126, 25];
  45461. var points$2 = [[[123.45165252685547, 25.73527164402261], [123.49731445312499, 25.73527164402261], [123.49731445312499, 25.750734064600884], [123.45165252685547, 25.750734064600884], [123.45165252685547, 25.73527164402261]]];
  45462. var fixDiaoyuIsland = function (mapType, region) {
  45463. if (mapType === 'china' && region.name === '台湾') {
  45464. region.geometries.push({
  45465. type: 'polygon',
  45466. exterior: points$2[0]
  45467. });
  45468. }
  45469. };
  45470. /*
  45471. * Licensed to the Apache Software Foundation (ASF) under one
  45472. * or more contributor license agreements. See the NOTICE file
  45473. * distributed with this work for additional information
  45474. * regarding copyright ownership. The ASF licenses this file
  45475. * to you under the Apache License, Version 2.0 (the
  45476. * "License"); you may not use this file except in compliance
  45477. * with the License. You may obtain a copy of the License at
  45478. *
  45479. * http://www.apache.org/licenses/LICENSE-2.0
  45480. *
  45481. * Unless required by applicable law or agreed to in writing,
  45482. * software distributed under the License is distributed on an
  45483. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45484. * KIND, either express or implied. See the License for the
  45485. * specific language governing permissions and limitations
  45486. * under the License.
  45487. */
  45488. var inner$7 = makeInner();
  45489. var geoJSONLoader = {
  45490. /**
  45491. * @param {string} mapName
  45492. * @param {Object} mapRecord {specialAreas, geoJSON}
  45493. * @param {string} nameProperty
  45494. * @return {Object} {regions, boundingRect}
  45495. */
  45496. load: function (mapName, mapRecord, nameProperty) {
  45497. var parsed = inner$7(mapRecord).parsed;
  45498. if (parsed) {
  45499. return parsed;
  45500. }
  45501. var specialAreas = mapRecord.specialAreas || {};
  45502. var geoJSON = mapRecord.geoJSON;
  45503. var regions; // https://jsperf.com/try-catch-performance-overhead
  45504. try {
  45505. regions = geoJSON ? parseGeoJson$1(geoJSON, nameProperty) : [];
  45506. } catch (e) {
  45507. throw new Error('Invalid geoJson format\n' + e.message);
  45508. }
  45509. fixNanhai(mapName, regions);
  45510. each$1(regions, function (region) {
  45511. var regionName = region.name;
  45512. fixTextCoord(mapName, region);
  45513. fixGeoCoord(mapName, region);
  45514. fixDiaoyuIsland(mapName, region); // Some area like Alaska in USA map needs to be tansformed
  45515. // to look better
  45516. var specialArea = specialAreas[regionName];
  45517. if (specialArea) {
  45518. region.transformTo(specialArea.left, specialArea.top, specialArea.width, specialArea.height);
  45519. }
  45520. });
  45521. return inner$7(mapRecord).parsed = {
  45522. regions: regions,
  45523. boundingRect: getBoundingRect$1(regions)
  45524. };
  45525. }
  45526. };
  45527. function getBoundingRect$1(regions) {
  45528. var rect;
  45529. for (var i = 0; i < regions.length; i++) {
  45530. var regionRect = regions[i].getBoundingRect();
  45531. rect = rect || regionRect.clone();
  45532. rect.union(regionRect);
  45533. }
  45534. return rect;
  45535. }
  45536. /*
  45537. * Licensed to the Apache Software Foundation (ASF) under one
  45538. * or more contributor license agreements. See the NOTICE file
  45539. * distributed with this work for additional information
  45540. * regarding copyright ownership. The ASF licenses this file
  45541. * to you under the Apache License, Version 2.0 (the
  45542. * "License"); you may not use this file except in compliance
  45543. * with the License. You may obtain a copy of the License at
  45544. *
  45545. * http://www.apache.org/licenses/LICENSE-2.0
  45546. *
  45547. * Unless required by applicable law or agreed to in writing,
  45548. * software distributed under the License is distributed on an
  45549. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45550. * KIND, either express or implied. See the License for the
  45551. * specific language governing permissions and limitations
  45552. * under the License.
  45553. */
  45554. var inner$8 = makeInner();
  45555. var geoSVGLoader = {
  45556. /**
  45557. * @param {string} mapName
  45558. * @param {Object} mapRecord {specialAreas, geoJSON}
  45559. * @return {Object} {root, boundingRect}
  45560. */
  45561. load: function (mapName, mapRecord) {
  45562. var originRoot = inner$8(mapRecord).originRoot;
  45563. if (originRoot) {
  45564. return {
  45565. root: originRoot,
  45566. boundingRect: inner$8(mapRecord).boundingRect
  45567. };
  45568. }
  45569. var graphic = buildGraphic(mapRecord);
  45570. inner$8(mapRecord).originRoot = graphic.root;
  45571. inner$8(mapRecord).boundingRect = graphic.boundingRect;
  45572. return graphic;
  45573. },
  45574. makeGraphic: function (mapName, mapRecord, hostKey) {
  45575. // For performance consideration (in large SVG), graphic only maked
  45576. // when necessary and reuse them according to hostKey.
  45577. var field = inner$8(mapRecord);
  45578. var rootMap = field.rootMap || (field.rootMap = createHashMap());
  45579. var root = rootMap.get(hostKey);
  45580. if (root) {
  45581. return root;
  45582. }
  45583. var originRoot = field.originRoot;
  45584. var boundingRect = field.boundingRect; // For performance, if originRoot is not used by a view,
  45585. // assign it to a view, but not reproduce graphic elements.
  45586. if (!field.originRootHostKey) {
  45587. field.originRootHostKey = hostKey;
  45588. root = originRoot;
  45589. } else {
  45590. root = buildGraphic(mapRecord, boundingRect).root;
  45591. }
  45592. return rootMap.set(hostKey, root);
  45593. },
  45594. removeGraphic: function (mapName, mapRecord, hostKey) {
  45595. var field = inner$8(mapRecord);
  45596. var rootMap = field.rootMap;
  45597. rootMap && rootMap.removeKey(hostKey);
  45598. if (hostKey === field.originRootHostKey) {
  45599. field.originRootHostKey = null;
  45600. }
  45601. }
  45602. };
  45603. function buildGraphic(mapRecord, boundingRect) {
  45604. var svgXML = mapRecord.svgXML;
  45605. var result;
  45606. var root;
  45607. try {
  45608. result = svgXML && parseSVG(svgXML, {
  45609. ignoreViewBox: true,
  45610. ignoreRootClip: true
  45611. }) || {};
  45612. root = result.root;
  45613. assert$1(root != null);
  45614. } catch (e) {
  45615. throw new Error('Invalid svg format\n' + e.message);
  45616. }
  45617. var svgWidth = result.width;
  45618. var svgHeight = result.height;
  45619. var viewBoxRect = result.viewBoxRect;
  45620. if (!boundingRect) {
  45621. boundingRect = svgWidth == null || svgHeight == null ? // If svg width / height not specified, calculate
  45622. // bounding rect as the width / height
  45623. root.getBoundingRect() : new BoundingRect(0, 0, 0, 0);
  45624. if (svgWidth != null) {
  45625. boundingRect.width = svgWidth;
  45626. }
  45627. if (svgHeight != null) {
  45628. boundingRect.height = svgHeight;
  45629. }
  45630. }
  45631. if (viewBoxRect) {
  45632. var viewBoxTransform = makeViewBoxTransform(viewBoxRect, boundingRect.width, boundingRect.height);
  45633. var elRoot = root;
  45634. root = new Group();
  45635. root.add(elRoot);
  45636. elRoot.scale = viewBoxTransform.scale;
  45637. elRoot.position = viewBoxTransform.position;
  45638. }
  45639. root.setClipPath(new Rect({
  45640. shape: boundingRect.plain()
  45641. }));
  45642. return {
  45643. root: root,
  45644. boundingRect: boundingRect
  45645. };
  45646. }
  45647. /*
  45648. * Licensed to the Apache Software Foundation (ASF) under one
  45649. * or more contributor license agreements. See the NOTICE file
  45650. * distributed with this work for additional information
  45651. * regarding copyright ownership. The ASF licenses this file
  45652. * to you under the Apache License, Version 2.0 (the
  45653. * "License"); you may not use this file except in compliance
  45654. * with the License. You may obtain a copy of the License at
  45655. *
  45656. * http://www.apache.org/licenses/LICENSE-2.0
  45657. *
  45658. * Unless required by applicable law or agreed to in writing,
  45659. * software distributed under the License is distributed on an
  45660. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45661. * KIND, either express or implied. See the License for the
  45662. * specific language governing permissions and limitations
  45663. * under the License.
  45664. */
  45665. var loaders = {
  45666. geoJSON: geoJSONLoader,
  45667. svg: geoSVGLoader
  45668. };
  45669. var geoSourceManager = {
  45670. /**
  45671. * @param {string} mapName
  45672. * @param {Object} nameMap
  45673. * @param {string} nameProperty
  45674. * @return {Object} source {regions, regionsMap, nameCoordMap, boundingRect}
  45675. */
  45676. load: function (mapName, nameMap, nameProperty) {
  45677. var regions = [];
  45678. var regionsMap = createHashMap();
  45679. var nameCoordMap = createHashMap();
  45680. var boundingRect;
  45681. var mapRecords = retrieveMap(mapName);
  45682. each$1(mapRecords, function (record) {
  45683. var singleSource = loaders[record.type].load(mapName, record, nameProperty);
  45684. each$1(singleSource.regions, function (region) {
  45685. var regionName = region.name; // Try use the alias in geoNameMap
  45686. if (nameMap && nameMap.hasOwnProperty(regionName)) {
  45687. region = region.cloneShallow(regionName = nameMap[regionName]);
  45688. }
  45689. regions.push(region);
  45690. regionsMap.set(regionName, region);
  45691. nameCoordMap.set(regionName, region.center);
  45692. });
  45693. var rect = singleSource.boundingRect;
  45694. if (rect) {
  45695. boundingRect ? boundingRect.union(rect) : boundingRect = rect.clone();
  45696. }
  45697. });
  45698. return {
  45699. regions: regions,
  45700. regionsMap: regionsMap,
  45701. nameCoordMap: nameCoordMap,
  45702. // FIXME Always return new ?
  45703. boundingRect: boundingRect || new BoundingRect(0, 0, 0, 0)
  45704. };
  45705. },
  45706. /**
  45707. * @param {string} mapName
  45708. * @param {string} hostKey For cache.
  45709. * @return {Array.<module:zrender/Element>} Roots.
  45710. */
  45711. makeGraphic: makeInvoker('makeGraphic'),
  45712. /**
  45713. * @param {string} mapName
  45714. * @param {string} hostKey For cache.
  45715. */
  45716. removeGraphic: makeInvoker('removeGraphic')
  45717. };
  45718. function makeInvoker(methodName) {
  45719. return function (mapName, hostKey) {
  45720. var mapRecords = retrieveMap(mapName);
  45721. var results = [];
  45722. each$1(mapRecords, function (record) {
  45723. var method = loaders[record.type][methodName];
  45724. method && results.push(method(mapName, record, hostKey));
  45725. });
  45726. return results;
  45727. };
  45728. }
  45729. function retrieveMap(mapName) {
  45730. var mapRecords = mapDataStorage.retrieveMap(mapName) || [];
  45731. return mapRecords;
  45732. }
  45733. /*
  45734. * Licensed to the Apache Software Foundation (ASF) under one
  45735. * or more contributor license agreements. See the NOTICE file
  45736. * distributed with this work for additional information
  45737. * regarding copyright ownership. The ASF licenses this file
  45738. * to you under the Apache License, Version 2.0 (the
  45739. * "License"); you may not use this file except in compliance
  45740. * with the License. You may obtain a copy of the License at
  45741. *
  45742. * http://www.apache.org/licenses/LICENSE-2.0
  45743. *
  45744. * Unless required by applicable law or agreed to in writing,
  45745. * software distributed under the License is distributed on an
  45746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45747. * KIND, either express or implied. See the License for the
  45748. * specific language governing permissions and limitations
  45749. * under the License.
  45750. */
  45751. var MapSeries = SeriesModel.extend({
  45752. type: 'series.map',
  45753. dependencies: ['geo'],
  45754. layoutMode: 'box',
  45755. /**
  45756. * Only first map series of same mapType will drawMap
  45757. * @type {boolean}
  45758. */
  45759. needsDrawMap: false,
  45760. /**
  45761. * Group of all map series with same mapType
  45762. * @type {boolean}
  45763. */
  45764. seriesGroup: [],
  45765. getInitialData: function (option) {
  45766. var data = createListSimply(this, {
  45767. coordDimensions: ['value'],
  45768. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  45769. });
  45770. var valueDim = data.mapDimension('value');
  45771. var dataNameMap = createHashMap();
  45772. var selectTargetList = [];
  45773. var toAppendNames = [];
  45774. for (var i = 0, len = data.count(); i < len; i++) {
  45775. var name = data.getName(i);
  45776. dataNameMap.set(name, true);
  45777. selectTargetList.push({
  45778. name: name,
  45779. value: data.get(valueDim, i),
  45780. selected: retrieveRawAttr(data, i, 'selected')
  45781. });
  45782. }
  45783. var geoSource = geoSourceManager.load(this.getMapType(), this.option.nameMap, this.option.nameProperty);
  45784. each$1(geoSource.regions, function (region) {
  45785. var name = region.name;
  45786. if (!dataNameMap.get(name)) {
  45787. selectTargetList.push({
  45788. name: name
  45789. });
  45790. toAppendNames.push(name);
  45791. }
  45792. });
  45793. this.updateSelectedMap(selectTargetList); // Complete data with missing regions. The consequent processes (like visual
  45794. // map and render) can not be performed without a "full data". For example,
  45795. // find `dataIndex` by name.
  45796. data.appendValues([], toAppendNames);
  45797. return data;
  45798. },
  45799. /**
  45800. * If no host geo model, return null, which means using a
  45801. * inner exclusive geo model.
  45802. */
  45803. getHostGeoModel: function () {
  45804. var geoIndex = this.option.geoIndex;
  45805. return geoIndex != null ? this.dependentModels.geo[geoIndex] : null;
  45806. },
  45807. getMapType: function () {
  45808. return (this.getHostGeoModel() || this).option.map;
  45809. },
  45810. // _fillOption: function (option, mapName) {
  45811. // Shallow clone
  45812. // option = zrUtil.extend({}, option);
  45813. // option.data = geoCreator.getFilledRegions(option.data, mapName, option.nameMap);
  45814. // return option;
  45815. // },
  45816. getRawValue: function (dataIndex) {
  45817. // Use value stored in data instead because it is calculated from multiple series
  45818. // FIXME Provide all value of multiple series ?
  45819. var data = this.getData();
  45820. return data.get(data.mapDimension('value'), dataIndex);
  45821. },
  45822. /**
  45823. * Get model of region
  45824. * @param {string} name
  45825. * @return {module:echarts/model/Model}
  45826. */
  45827. getRegionModel: function (regionName) {
  45828. var data = this.getData();
  45829. return data.getItemModel(data.indexOfName(regionName));
  45830. },
  45831. /**
  45832. * Map tooltip formatter
  45833. *
  45834. * @param {number} dataIndex
  45835. */
  45836. formatTooltip: function (dataIndex) {
  45837. // FIXME orignalData and data is a bit confusing
  45838. var data = this.getData();
  45839. var formattedValue = addCommas(this.getRawValue(dataIndex));
  45840. var name = data.getName(dataIndex);
  45841. var seriesGroup = this.seriesGroup;
  45842. var seriesNames = [];
  45843. for (var i = 0; i < seriesGroup.length; i++) {
  45844. var otherIndex = seriesGroup[i].originalData.indexOfName(name);
  45845. var valueDim = data.mapDimension('value');
  45846. if (!isNaN(seriesGroup[i].originalData.get(valueDim, otherIndex))) {
  45847. seriesNames.push(encodeHTML(seriesGroup[i].name));
  45848. }
  45849. }
  45850. return seriesNames.join(', ') + '<br />' + encodeHTML(name + ' : ' + formattedValue);
  45851. },
  45852. /**
  45853. * @implement
  45854. */
  45855. getTooltipPosition: function (dataIndex) {
  45856. if (dataIndex != null) {
  45857. var name = this.getData().getName(dataIndex);
  45858. var geo = this.coordinateSystem;
  45859. var region = geo.getRegion(name);
  45860. return region && geo.dataToPoint(region.center);
  45861. }
  45862. },
  45863. setZoom: function (zoom) {
  45864. this.option.zoom = zoom;
  45865. },
  45866. setCenter: function (center) {
  45867. this.option.center = center;
  45868. },
  45869. defaultOption: {
  45870. // 一级层叠
  45871. zlevel: 0,
  45872. // 二级层叠
  45873. z: 2,
  45874. coordinateSystem: 'geo',
  45875. // map should be explicitly specified since ec3.
  45876. map: '',
  45877. // If `geoIndex` is not specified, a exclusive geo will be
  45878. // created. Otherwise use the specified geo component, and
  45879. // `map` and `mapType` are ignored.
  45880. // geoIndex: 0,
  45881. // 'center' | 'left' | 'right' | 'x%' | {number}
  45882. left: 'center',
  45883. // 'center' | 'top' | 'bottom' | 'x%' | {number}
  45884. top: 'center',
  45885. // right
  45886. // bottom
  45887. // width:
  45888. // height
  45889. // Aspect is width / height. Inited to be geoJson bbox aspect
  45890. // This parameter is used for scale this aspect
  45891. aspectScale: 0.75,
  45892. ///// Layout with center and size
  45893. // If you wan't to put map in a fixed size box with right aspect ratio
  45894. // This two properties may more conveninet
  45895. // layoutCenter: [50%, 50%]
  45896. // layoutSize: 100
  45897. // 数值合并方式,默认加和,可选为:
  45898. // 'sum' | 'average' | 'max' | 'min'
  45899. // mapValueCalculation: 'sum',
  45900. // 地图数值计算结果小数精度
  45901. // mapValuePrecision: 0,
  45902. // 显示图例颜色标识(系列标识的小圆点),图例开启时有效
  45903. showLegendSymbol: true,
  45904. // 选择模式,默认关闭,可选single,multiple
  45905. // selectedMode: false,
  45906. dataRangeHoverLink: true,
  45907. // 是否开启缩放及漫游模式
  45908. // roam: false,
  45909. // Define left-top, right-bottom coords to control view
  45910. // For example, [ [180, 90], [-180, -90] ],
  45911. // higher priority than center and zoom
  45912. boundingCoords: null,
  45913. // Default on center of map
  45914. center: null,
  45915. zoom: 1,
  45916. scaleLimit: null,
  45917. label: {
  45918. show: false,
  45919. color: '#000'
  45920. },
  45921. // scaleLimit: null,
  45922. itemStyle: {
  45923. borderWidth: 0.5,
  45924. borderColor: '#444',
  45925. areaColor: '#eee'
  45926. },
  45927. emphasis: {
  45928. label: {
  45929. show: true,
  45930. color: 'rgb(100,0,0)'
  45931. },
  45932. itemStyle: {
  45933. areaColor: 'rgba(255,215,0,0.8)'
  45934. }
  45935. },
  45936. nameProperty: 'name'
  45937. }
  45938. });
  45939. mixin(MapSeries, selectableMixin);
  45940. /*
  45941. * Licensed to the Apache Software Foundation (ASF) under one
  45942. * or more contributor license agreements. See the NOTICE file
  45943. * distributed with this work for additional information
  45944. * regarding copyright ownership. The ASF licenses this file
  45945. * to you under the Apache License, Version 2.0 (the
  45946. * "License"); you may not use this file except in compliance
  45947. * with the License. You may obtain a copy of the License at
  45948. *
  45949. * http://www.apache.org/licenses/LICENSE-2.0
  45950. *
  45951. * Unless required by applicable law or agreed to in writing,
  45952. * software distributed under the License is distributed on an
  45953. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  45954. * KIND, either express or implied. See the License for the
  45955. * specific language governing permissions and limitations
  45956. * under the License.
  45957. */
  45958. function getFixedItemStyle(model) {
  45959. var itemStyle = model.getItemStyle();
  45960. var areaColor = model.get('areaColor'); // If user want the color not to be changed when hover,
  45961. // they should both set areaColor and color to be null.
  45962. if (areaColor != null) {
  45963. itemStyle.fill = areaColor;
  45964. }
  45965. return itemStyle;
  45966. }
  45967. function updateMapSelectHandler(mapDraw, mapOrGeoModel, regionsGroup, api, fromView) {
  45968. regionsGroup.off('click');
  45969. regionsGroup.off('mousedown');
  45970. if (mapOrGeoModel.get('selectedMode')) {
  45971. regionsGroup.on('mousedown', function () {
  45972. mapDraw._mouseDownFlag = true;
  45973. });
  45974. regionsGroup.on('click', function (e) {
  45975. if (!mapDraw._mouseDownFlag) {
  45976. return;
  45977. }
  45978. mapDraw._mouseDownFlag = false;
  45979. var el = e.target;
  45980. while (!el.__regions) {
  45981. el = el.parent;
  45982. }
  45983. if (!el) {
  45984. return;
  45985. }
  45986. var action = {
  45987. type: (mapOrGeoModel.mainType === 'geo' ? 'geo' : 'map') + 'ToggleSelect',
  45988. batch: map(el.__regions, function (region) {
  45989. return {
  45990. name: region.name,
  45991. from: fromView.uid
  45992. };
  45993. })
  45994. };
  45995. action[mapOrGeoModel.mainType + 'Id'] = mapOrGeoModel.id;
  45996. api.dispatchAction(action);
  45997. updateMapSelected(mapOrGeoModel, regionsGroup);
  45998. });
  45999. }
  46000. }
  46001. function updateMapSelected(mapOrGeoModel, regionsGroup) {
  46002. // FIXME
  46003. regionsGroup.eachChild(function (otherRegionEl) {
  46004. each$1(otherRegionEl.__regions, function (region) {
  46005. otherRegionEl.trigger(mapOrGeoModel.isSelected(region.name) ? 'emphasis' : 'normal');
  46006. });
  46007. });
  46008. }
  46009. /**
  46010. * @alias module:echarts/component/helper/MapDraw
  46011. * @param {module:echarts/ExtensionAPI} api
  46012. * @param {boolean} updateGroup
  46013. */
  46014. function MapDraw(api, updateGroup) {
  46015. var group = new Group();
  46016. /**
  46017. * @type {string}
  46018. * @private
  46019. */
  46020. this.uid = getUID('ec_map_draw');
  46021. /**
  46022. * @type {module:echarts/component/helper/RoamController}
  46023. * @private
  46024. */
  46025. this._controller = new RoamController(api.getZr());
  46026. /**
  46027. * @type {Object} {target, zoom, zoomLimit}
  46028. * @private
  46029. */
  46030. this._controllerHost = {
  46031. target: updateGroup ? group : null
  46032. };
  46033. /**
  46034. * @type {module:zrender/container/Group}
  46035. * @readOnly
  46036. */
  46037. this.group = group;
  46038. /**
  46039. * @type {boolean}
  46040. * @private
  46041. */
  46042. this._updateGroup = updateGroup;
  46043. /**
  46044. * This flag is used to make sure that only one among
  46045. * `pan`, `zoom`, `click` can occurs, otherwise 'selected'
  46046. * action may be triggered when `pan`, which is unexpected.
  46047. * @type {booelan}
  46048. */
  46049. this._mouseDownFlag;
  46050. /**
  46051. * @type {string}
  46052. */
  46053. this._mapName;
  46054. /**
  46055. * @type {boolean}
  46056. */
  46057. this._initialized;
  46058. /**
  46059. * @type {module:zrender/container/Group}
  46060. */
  46061. group.add(this._regionsGroup = new Group());
  46062. /**
  46063. * @type {module:zrender/container/Group}
  46064. */
  46065. group.add(this._backgroundGroup = new Group());
  46066. }
  46067. MapDraw.prototype = {
  46068. constructor: MapDraw,
  46069. draw: function (mapOrGeoModel, ecModel, api, fromView, payload) {
  46070. var isGeo = mapOrGeoModel.mainType === 'geo'; // Map series has data. GEO model that controlled by map series
  46071. // will be assigned with map data. Other GEO model has no data.
  46072. var data = mapOrGeoModel.getData && mapOrGeoModel.getData();
  46073. isGeo && ecModel.eachComponent({
  46074. mainType: 'series',
  46075. subType: 'map'
  46076. }, function (mapSeries) {
  46077. if (!data && mapSeries.getHostGeoModel() === mapOrGeoModel) {
  46078. data = mapSeries.getData();
  46079. }
  46080. });
  46081. var geo = mapOrGeoModel.coordinateSystem;
  46082. this._updateBackground(geo);
  46083. var regionsGroup = this._regionsGroup;
  46084. var group = this.group;
  46085. var transformInfo = geo.getTransformInfo(); // No animation when first draw or in action
  46086. var isFirstDraw = !regionsGroup.childAt(0) || payload;
  46087. var targetScale;
  46088. if (isFirstDraw) {
  46089. group.transform = transformInfo.roamTransform;
  46090. group.decomposeTransform();
  46091. group.dirty();
  46092. } else {
  46093. var target = new Transformable();
  46094. target.transform = transformInfo.roamTransform;
  46095. target.decomposeTransform();
  46096. var props = {
  46097. scale: target.scale,
  46098. position: target.position
  46099. };
  46100. targetScale = target.scale;
  46101. updateProps(group, props, mapOrGeoModel);
  46102. }
  46103. var scale = transformInfo.rawScale;
  46104. var position = transformInfo.rawPosition;
  46105. regionsGroup.removeAll();
  46106. var itemStyleAccessPath = ['itemStyle'];
  46107. var hoverItemStyleAccessPath = ['emphasis', 'itemStyle'];
  46108. var labelAccessPath = ['label'];
  46109. var hoverLabelAccessPath = ['emphasis', 'label'];
  46110. var nameMap = createHashMap();
  46111. each$1(geo.regions, function (region) {
  46112. // Consider in GeoJson properties.name may be duplicated, for example,
  46113. // there is multiple region named "United Kindom" or "France" (so many
  46114. // colonies). And it is not appropriate to merge them in geo, which
  46115. // will make them share the same label and bring trouble in label
  46116. // location calculation.
  46117. var regionGroup = nameMap.get(region.name) || nameMap.set(region.name, new Group());
  46118. var compoundPath = new CompoundPath({
  46119. segmentIgnoreThreshold: 1,
  46120. shape: {
  46121. paths: []
  46122. }
  46123. });
  46124. regionGroup.add(compoundPath);
  46125. var regionModel = mapOrGeoModel.getRegionModel(region.name) || mapOrGeoModel;
  46126. var itemStyleModel = regionModel.getModel(itemStyleAccessPath);
  46127. var hoverItemStyleModel = regionModel.getModel(hoverItemStyleAccessPath);
  46128. var itemStyle = getFixedItemStyle(itemStyleModel);
  46129. var hoverItemStyle = getFixedItemStyle(hoverItemStyleModel);
  46130. var labelModel = regionModel.getModel(labelAccessPath);
  46131. var hoverLabelModel = regionModel.getModel(hoverLabelAccessPath);
  46132. var dataIdx; // Use the itemStyle in data if has data
  46133. if (data) {
  46134. dataIdx = data.indexOfName(region.name); // Only visual color of each item will be used. It can be encoded by dataRange
  46135. // But visual color of series is used in symbol drawing
  46136. //
  46137. // Visual color for each series is for the symbol draw
  46138. var visualColor = data.getItemVisual(dataIdx, 'color', true);
  46139. if (visualColor) {
  46140. itemStyle.fill = visualColor;
  46141. }
  46142. }
  46143. var transformPoint = function (point) {
  46144. return [point[0] * scale[0] + position[0], point[1] * scale[1] + position[1]];
  46145. };
  46146. each$1(region.geometries, function (geometry) {
  46147. if (geometry.type !== 'polygon') {
  46148. return;
  46149. }
  46150. var points = [];
  46151. for (var i = 0; i < geometry.exterior.length; ++i) {
  46152. points.push(transformPoint(geometry.exterior[i]));
  46153. }
  46154. compoundPath.shape.paths.push(new Polygon({
  46155. segmentIgnoreThreshold: 1,
  46156. shape: {
  46157. points: points
  46158. }
  46159. }));
  46160. for (var i = 0; i < (geometry.interiors ? geometry.interiors.length : 0); ++i) {
  46161. var interior = geometry.interiors[i];
  46162. var points = [];
  46163. for (var j = 0; j < interior.length; ++j) {
  46164. points.push(transformPoint(interior[j]));
  46165. }
  46166. compoundPath.shape.paths.push(new Polygon({
  46167. segmentIgnoreThreshold: 1,
  46168. shape: {
  46169. points: points
  46170. }
  46171. }));
  46172. }
  46173. });
  46174. compoundPath.setStyle(itemStyle);
  46175. compoundPath.style.strokeNoScale = true;
  46176. compoundPath.culling = true; // Label
  46177. var showLabel = labelModel.get('show');
  46178. var hoverShowLabel = hoverLabelModel.get('show');
  46179. var isDataNaN = data && isNaN(data.get(data.mapDimension('value'), dataIdx));
  46180. var itemLayout = data && data.getItemLayout(dataIdx); // In the following cases label will be drawn
  46181. // 1. In map series and data value is NaN
  46182. // 2. In geo component
  46183. // 4. Region has no series legendSymbol, which will be add a showLabel flag in mapSymbolLayout
  46184. if (isGeo || isDataNaN && (showLabel || hoverShowLabel) || itemLayout && itemLayout.showLabel) {
  46185. var query = !isGeo ? dataIdx : region.name;
  46186. var labelFetcher; // Consider dataIdx not found.
  46187. if (!data || dataIdx >= 0) {
  46188. labelFetcher = mapOrGeoModel;
  46189. }
  46190. var textEl = new Text({
  46191. position: transformPoint(region.center.slice()),
  46192. // FIXME
  46193. // label rotation is not support yet in geo or regions of series-map
  46194. // that has no data. The rotation will be effected by this `scale`.
  46195. // So needed to change to RectText?
  46196. scale: [1 / group.scale[0], 1 / group.scale[1]],
  46197. z2: 10,
  46198. silent: true
  46199. });
  46200. setLabelStyle(textEl.style, textEl.hoverStyle = {}, labelModel, hoverLabelModel, {
  46201. labelFetcher: labelFetcher,
  46202. labelDataIndex: query,
  46203. defaultText: region.name,
  46204. useInsideStyle: false
  46205. }, {
  46206. textAlign: 'center',
  46207. textVerticalAlign: 'middle'
  46208. });
  46209. if (!isFirstDraw) {
  46210. // Text animation
  46211. var textScale = [1 / targetScale[0], 1 / targetScale[1]];
  46212. updateProps(textEl, {
  46213. scale: textScale
  46214. }, mapOrGeoModel);
  46215. }
  46216. regionGroup.add(textEl);
  46217. } // setItemGraphicEl, setHoverStyle after all polygons and labels
  46218. // are added to the rigionGroup
  46219. if (data) {
  46220. data.setItemGraphicEl(dataIdx, regionGroup);
  46221. } else {
  46222. var regionModel = mapOrGeoModel.getRegionModel(region.name); // Package custom mouse event for geo component
  46223. compoundPath.eventData = {
  46224. componentType: 'geo',
  46225. componentIndex: mapOrGeoModel.componentIndex,
  46226. geoIndex: mapOrGeoModel.componentIndex,
  46227. name: region.name,
  46228. region: regionModel && regionModel.option || {}
  46229. };
  46230. }
  46231. var groupRegions = regionGroup.__regions || (regionGroup.__regions = []);
  46232. groupRegions.push(region);
  46233. regionGroup.highDownSilentOnTouch = !!mapOrGeoModel.get('selectedMode');
  46234. setHoverStyle(regionGroup, hoverItemStyle);
  46235. regionsGroup.add(regionGroup);
  46236. });
  46237. this._updateController(mapOrGeoModel, ecModel, api);
  46238. updateMapSelectHandler(this, mapOrGeoModel, regionsGroup, api, fromView);
  46239. updateMapSelected(mapOrGeoModel, regionsGroup);
  46240. },
  46241. remove: function () {
  46242. this._regionsGroup.removeAll();
  46243. this._backgroundGroup.removeAll();
  46244. this._controller.dispose();
  46245. this._mapName && geoSourceManager.removeGraphic(this._mapName, this.uid);
  46246. this._mapName = null;
  46247. this._controllerHost = {};
  46248. },
  46249. _updateBackground: function (geo) {
  46250. var mapName = geo.map;
  46251. if (this._mapName !== mapName) {
  46252. each$1(geoSourceManager.makeGraphic(mapName, this.uid), function (root) {
  46253. this._backgroundGroup.add(root);
  46254. }, this);
  46255. }
  46256. this._mapName = mapName;
  46257. },
  46258. _updateController: function (mapOrGeoModel, ecModel, api) {
  46259. var geo = mapOrGeoModel.coordinateSystem;
  46260. var controller = this._controller;
  46261. var controllerHost = this._controllerHost;
  46262. controllerHost.zoomLimit = mapOrGeoModel.get('scaleLimit');
  46263. controllerHost.zoom = geo.getZoom(); // roamType is will be set default true if it is null
  46264. controller.enable(mapOrGeoModel.get('roam') || false);
  46265. var mainType = mapOrGeoModel.mainType;
  46266. function makeActionBase() {
  46267. var action = {
  46268. type: 'geoRoam',
  46269. componentType: mainType
  46270. };
  46271. action[mainType + 'Id'] = mapOrGeoModel.id;
  46272. return action;
  46273. }
  46274. controller.off('pan').on('pan', function (e) {
  46275. this._mouseDownFlag = false;
  46276. updateViewOnPan(controllerHost, e.dx, e.dy);
  46277. api.dispatchAction(extend(makeActionBase(), {
  46278. dx: e.dx,
  46279. dy: e.dy
  46280. }));
  46281. }, this);
  46282. controller.off('zoom').on('zoom', function (e) {
  46283. this._mouseDownFlag = false;
  46284. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  46285. api.dispatchAction(extend(makeActionBase(), {
  46286. zoom: e.scale,
  46287. originX: e.originX,
  46288. originY: e.originY
  46289. }));
  46290. if (this._updateGroup) {
  46291. var scale = this.group.scale;
  46292. this._regionsGroup.traverse(function (el) {
  46293. if (el.type === 'text') {
  46294. el.attr('scale', [1 / scale[0], 1 / scale[1]]);
  46295. }
  46296. });
  46297. }
  46298. }, this);
  46299. controller.setPointerChecker(function (e, x, y) {
  46300. return geo.getViewRectAfterRoam().contain(x, y) && !onIrrelevantElement(e, api, mapOrGeoModel);
  46301. });
  46302. }
  46303. };
  46304. /*
  46305. * Licensed to the Apache Software Foundation (ASF) under one
  46306. * or more contributor license agreements. See the NOTICE file
  46307. * distributed with this work for additional information
  46308. * regarding copyright ownership. The ASF licenses this file
  46309. * to you under the Apache License, Version 2.0 (the
  46310. * "License"); you may not use this file except in compliance
  46311. * with the License. You may obtain a copy of the License at
  46312. *
  46313. * http://www.apache.org/licenses/LICENSE-2.0
  46314. *
  46315. * Unless required by applicable law or agreed to in writing,
  46316. * software distributed under the License is distributed on an
  46317. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46318. * KIND, either express or implied. See the License for the
  46319. * specific language governing permissions and limitations
  46320. * under the License.
  46321. */
  46322. var HIGH_DOWN_PROP = '__seriesMapHighDown';
  46323. var RECORD_VERSION_PROP = '__seriesMapCallKey';
  46324. extendChartView({
  46325. type: 'map',
  46326. render: function (mapModel, ecModel, api, payload) {
  46327. // Not render if it is an toggleSelect action from self
  46328. if (payload && payload.type === 'mapToggleSelect' && payload.from === this.uid) {
  46329. return;
  46330. }
  46331. var group = this.group;
  46332. group.removeAll();
  46333. if (mapModel.getHostGeoModel()) {
  46334. return;
  46335. } // Not update map if it is an roam action from self
  46336. if (!(payload && payload.type === 'geoRoam' && payload.componentType === 'series' && payload.seriesId === mapModel.id)) {
  46337. if (mapModel.needsDrawMap) {
  46338. var mapDraw = this._mapDraw || new MapDraw(api, true);
  46339. group.add(mapDraw.group);
  46340. mapDraw.draw(mapModel, ecModel, api, this, payload);
  46341. this._mapDraw = mapDraw;
  46342. } else {
  46343. // Remove drawed map
  46344. this._mapDraw && this._mapDraw.remove();
  46345. this._mapDraw = null;
  46346. }
  46347. } else {
  46348. var mapDraw = this._mapDraw;
  46349. mapDraw && group.add(mapDraw.group);
  46350. }
  46351. mapModel.get('showLegendSymbol') && ecModel.getComponent('legend') && this._renderSymbols(mapModel, ecModel, api);
  46352. },
  46353. remove: function () {
  46354. this._mapDraw && this._mapDraw.remove();
  46355. this._mapDraw = null;
  46356. this.group.removeAll();
  46357. },
  46358. dispose: function () {
  46359. this._mapDraw && this._mapDraw.remove();
  46360. this._mapDraw = null;
  46361. },
  46362. _renderSymbols: function (mapModel, ecModel, api) {
  46363. var originalData = mapModel.originalData;
  46364. var group = this.group;
  46365. originalData.each(originalData.mapDimension('value'), function (value, originalDataIndex) {
  46366. if (isNaN(value)) {
  46367. return;
  46368. }
  46369. var layout = originalData.getItemLayout(originalDataIndex);
  46370. if (!layout || !layout.point) {
  46371. // Not exists in map
  46372. return;
  46373. }
  46374. var point = layout.point;
  46375. var offset = layout.offset;
  46376. var circle = new Circle({
  46377. style: {
  46378. // Because the special of map draw.
  46379. // Which needs statistic of multiple series and draw on one map.
  46380. // And each series also need a symbol with legend color
  46381. //
  46382. // Layout and visual are put one the different data
  46383. fill: mapModel.getData().getVisual('color')
  46384. },
  46385. shape: {
  46386. cx: point[0] + offset * 9,
  46387. cy: point[1],
  46388. r: 3
  46389. },
  46390. silent: true,
  46391. // Do not overlap the first series, on which labels are displayed.
  46392. z2: 8 + (!offset ? Z2_EMPHASIS_LIFT + 1 : 0)
  46393. }); // Only the series that has the first value on the same region is in charge of rendering the label.
  46394. // But consider the case:
  46395. // series: [
  46396. // {id: 'X', type: 'map', map: 'm', {data: [{name: 'A', value: 11}, {name: 'B', {value: 22}]},
  46397. // {id: 'Y', type: 'map', map: 'm', {data: [{name: 'A', value: 21}, {name: 'C', {value: 33}]}
  46398. // ]
  46399. // The offset `0` of item `A` is at series `X`, but of item `C` is at series `Y`.
  46400. // For backward compatibility, we follow the rule that render label `A` by the
  46401. // settings on series `X` but render label `C` by the settings on series `Y`.
  46402. if (!offset) {
  46403. var fullData = mapModel.mainSeries.getData();
  46404. var name = originalData.getName(originalDataIndex);
  46405. var fullIndex = fullData.indexOfName(name);
  46406. var itemModel = originalData.getItemModel(originalDataIndex);
  46407. var labelModel = itemModel.getModel('label');
  46408. var hoverLabelModel = itemModel.getModel('emphasis.label');
  46409. var regionGroup = fullData.getItemGraphicEl(fullIndex); // `getFormattedLabel` needs to use `getData` inside. Here
  46410. // `mapModel.getData()` is shallow cloned from `mainSeries.getData()`.
  46411. // FIXME
  46412. // If this is not the `mainSeries`, the item model (like label formatter)
  46413. // set on original data item will never get. But it has been working
  46414. // like that from the begining, and this scenario is rarely encountered.
  46415. // So it won't be fixed until have to.
  46416. var normalText = retrieve2(mapModel.getFormattedLabel(fullIndex, 'normal'), name);
  46417. var emphasisText = retrieve2(mapModel.getFormattedLabel(fullIndex, 'emphasis'), normalText);
  46418. var highDownRecord = regionGroup[HIGH_DOWN_PROP];
  46419. var recordVersion = Math.random(); // Prevent from register listeners duplicatedly when roaming.
  46420. if (!highDownRecord) {
  46421. highDownRecord = regionGroup[HIGH_DOWN_PROP] = {};
  46422. var onEmphasis = curry(onRegionHighDown, true);
  46423. var onNormal = curry(onRegionHighDown, false);
  46424. regionGroup.on('mouseover', onEmphasis).on('mouseout', onNormal).on('emphasis', onEmphasis).on('normal', onNormal);
  46425. } // Prevent removed regions effect current grapics.
  46426. regionGroup[RECORD_VERSION_PROP] = recordVersion;
  46427. extend(highDownRecord, {
  46428. recordVersion: recordVersion,
  46429. circle: circle,
  46430. labelModel: labelModel,
  46431. hoverLabelModel: hoverLabelModel,
  46432. emphasisText: emphasisText,
  46433. normalText: normalText
  46434. }); // FIXME
  46435. // Consider set option when emphasis.
  46436. enterRegionHighDown(highDownRecord, false);
  46437. }
  46438. group.add(circle);
  46439. });
  46440. }
  46441. });
  46442. function onRegionHighDown(toHighOrDown) {
  46443. var highDownRecord = this[HIGH_DOWN_PROP];
  46444. if (highDownRecord && highDownRecord.recordVersion === this[RECORD_VERSION_PROP]) {
  46445. enterRegionHighDown(highDownRecord, toHighOrDown);
  46446. }
  46447. }
  46448. function enterRegionHighDown(highDownRecord, toHighOrDown) {
  46449. var circle = highDownRecord.circle;
  46450. var labelModel = highDownRecord.labelModel;
  46451. var hoverLabelModel = highDownRecord.hoverLabelModel;
  46452. var emphasisText = highDownRecord.emphasisText;
  46453. var normalText = highDownRecord.normalText;
  46454. if (toHighOrDown) {
  46455. circle.style.extendFrom(setTextStyle({}, hoverLabelModel, {
  46456. text: hoverLabelModel.get('show') ? emphasisText : null
  46457. }, {
  46458. isRectText: true,
  46459. useInsideStyle: false
  46460. }, true)); // Make label upper than others if overlaps.
  46461. circle.__mapOriginalZ2 = circle.z2;
  46462. circle.z2 += Z2_EMPHASIS_LIFT;
  46463. } else {
  46464. setTextStyle(circle.style, labelModel, {
  46465. text: labelModel.get('show') ? normalText : null,
  46466. textPosition: labelModel.getShallow('position') || 'bottom'
  46467. }, {
  46468. isRectText: true,
  46469. useInsideStyle: false
  46470. }); // Trigger normalize style like padding.
  46471. circle.dirty(false);
  46472. if (circle.__mapOriginalZ2 != null) {
  46473. circle.z2 = circle.__mapOriginalZ2;
  46474. circle.__mapOriginalZ2 = null;
  46475. }
  46476. }
  46477. }
  46478. /*
  46479. * Licensed to the Apache Software Foundation (ASF) under one
  46480. * or more contributor license agreements. See the NOTICE file
  46481. * distributed with this work for additional information
  46482. * regarding copyright ownership. The ASF licenses this file
  46483. * to you under the Apache License, Version 2.0 (the
  46484. * "License"); you may not use this file except in compliance
  46485. * with the License. You may obtain a copy of the License at
  46486. *
  46487. * http://www.apache.org/licenses/LICENSE-2.0
  46488. *
  46489. * Unless required by applicable law or agreed to in writing,
  46490. * software distributed under the License is distributed on an
  46491. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46492. * KIND, either express or implied. See the License for the
  46493. * specific language governing permissions and limitations
  46494. * under the License.
  46495. */
  46496. /**
  46497. * @payload
  46498. * @property {string} [componentType=series]
  46499. * @property {number} [dx]
  46500. * @property {number} [dy]
  46501. * @property {number} [zoom]
  46502. * @property {number} [originX]
  46503. * @property {number} [originY]
  46504. */
  46505. registerAction({
  46506. type: 'geoRoam',
  46507. event: 'geoRoam',
  46508. update: 'updateTransform'
  46509. }, function (payload, ecModel) {
  46510. var componentType = payload.componentType || 'series';
  46511. ecModel.eachComponent({
  46512. mainType: componentType,
  46513. query: payload
  46514. }, function (componentModel) {
  46515. var geo = componentModel.coordinateSystem;
  46516. if (geo.type !== 'geo') {
  46517. return;
  46518. }
  46519. var res = updateCenterAndZoom(geo, payload, componentModel.get('scaleLimit'));
  46520. componentModel.setCenter && componentModel.setCenter(res.center);
  46521. componentModel.setZoom && componentModel.setZoom(res.zoom); // All map series with same `map` use the same geo coordinate system
  46522. // So the center and zoom must be in sync. Include the series not selected by legend
  46523. if (componentType === 'series') {
  46524. each$1(componentModel.seriesGroup, function (seriesModel) {
  46525. seriesModel.setCenter(res.center);
  46526. seriesModel.setZoom(res.zoom);
  46527. });
  46528. }
  46529. });
  46530. });
  46531. /*
  46532. * Licensed to the Apache Software Foundation (ASF) under one
  46533. * or more contributor license agreements. See the NOTICE file
  46534. * distributed with this work for additional information
  46535. * regarding copyright ownership. The ASF licenses this file
  46536. * to you under the Apache License, Version 2.0 (the
  46537. * "License"); you may not use this file except in compliance
  46538. * with the License. You may obtain a copy of the License at
  46539. *
  46540. * http://www.apache.org/licenses/LICENSE-2.0
  46541. *
  46542. * Unless required by applicable law or agreed to in writing,
  46543. * software distributed under the License is distributed on an
  46544. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46545. * KIND, either express or implied. See the License for the
  46546. * specific language governing permissions and limitations
  46547. * under the License.
  46548. */
  46549. /**
  46550. * [Geo description]
  46551. * For backward compatibility, the orginal interface:
  46552. * `name, map, geoJson, specialAreas, nameMap` is kept.
  46553. *
  46554. * @param {string|Object} name
  46555. * @param {string} map Map type
  46556. * Specify the positioned areas by left, top, width, height
  46557. * @param {Object.<string, string>} [nameMap]
  46558. * Specify name alias
  46559. * @param {boolean} [invertLongitute=true]
  46560. */
  46561. function Geo(name, map$$1, nameMap, invertLongitute) {
  46562. View.call(this, name);
  46563. /**
  46564. * Map type
  46565. * @type {string}
  46566. */
  46567. this.map = map$$1;
  46568. var source = geoSourceManager.load(map$$1, nameMap);
  46569. this._nameCoordMap = source.nameCoordMap;
  46570. this._regionsMap = source.regionsMap;
  46571. this._invertLongitute = invertLongitute == null ? true : invertLongitute;
  46572. /**
  46573. * @readOnly
  46574. */
  46575. this.regions = source.regions;
  46576. /**
  46577. * @type {module:zrender/src/core/BoundingRect}
  46578. */
  46579. this._rect = source.boundingRect;
  46580. }
  46581. Geo.prototype = {
  46582. constructor: Geo,
  46583. type: 'geo',
  46584. /**
  46585. * @param {Array.<string>}
  46586. * @readOnly
  46587. */
  46588. dimensions: ['lng', 'lat'],
  46589. /**
  46590. * If contain given lng,lat coord
  46591. * @param {Array.<number>}
  46592. * @readOnly
  46593. */
  46594. containCoord: function (coord) {
  46595. var regions = this.regions;
  46596. for (var i = 0; i < regions.length; i++) {
  46597. if (regions[i].contain(coord)) {
  46598. return true;
  46599. }
  46600. }
  46601. return false;
  46602. },
  46603. /**
  46604. * @override
  46605. */
  46606. transformTo: function (x, y, width, height) {
  46607. var rect = this.getBoundingRect();
  46608. var invertLongitute = this._invertLongitute;
  46609. rect = rect.clone();
  46610. if (invertLongitute) {
  46611. // Longitute is inverted
  46612. rect.y = -rect.y - rect.height;
  46613. }
  46614. var rawTransformable = this._rawTransformable;
  46615. rawTransformable.transform = rect.calculateTransform(new BoundingRect(x, y, width, height));
  46616. rawTransformable.decomposeTransform();
  46617. if (invertLongitute) {
  46618. var scale = rawTransformable.scale;
  46619. scale[1] = -scale[1];
  46620. }
  46621. rawTransformable.updateTransform();
  46622. this._updateTransform();
  46623. },
  46624. /**
  46625. * @param {string} name
  46626. * @return {module:echarts/coord/geo/Region}
  46627. */
  46628. getRegion: function (name) {
  46629. return this._regionsMap.get(name);
  46630. },
  46631. getRegionByCoord: function (coord) {
  46632. var regions = this.regions;
  46633. for (var i = 0; i < regions.length; i++) {
  46634. if (regions[i].contain(coord)) {
  46635. return regions[i];
  46636. }
  46637. }
  46638. },
  46639. /**
  46640. * Add geoCoord for indexing by name
  46641. * @param {string} name
  46642. * @param {Array.<number>} geoCoord
  46643. */
  46644. addGeoCoord: function (name, geoCoord) {
  46645. this._nameCoordMap.set(name, geoCoord);
  46646. },
  46647. /**
  46648. * Get geoCoord by name
  46649. * @param {string} name
  46650. * @return {Array.<number>}
  46651. */
  46652. getGeoCoord: function (name) {
  46653. return this._nameCoordMap.get(name);
  46654. },
  46655. /**
  46656. * @override
  46657. */
  46658. getBoundingRect: function () {
  46659. return this._rect;
  46660. },
  46661. /**
  46662. * @param {string|Array.<number>} data
  46663. * @param {boolean} noRoam
  46664. * @param {Array.<number>} [out]
  46665. * @return {Array.<number>}
  46666. */
  46667. dataToPoint: function (data, noRoam, out) {
  46668. if (typeof data === 'string') {
  46669. // Map area name to geoCoord
  46670. data = this.getGeoCoord(data);
  46671. }
  46672. if (data) {
  46673. return View.prototype.dataToPoint.call(this, data, noRoam, out);
  46674. }
  46675. },
  46676. /**
  46677. * @override
  46678. */
  46679. convertToPixel: curry(doConvert$1, 'dataToPoint'),
  46680. /**
  46681. * @override
  46682. */
  46683. convertFromPixel: curry(doConvert$1, 'pointToData')
  46684. };
  46685. mixin(Geo, View);
  46686. function doConvert$1(methodName, ecModel, finder, value) {
  46687. var geoModel = finder.geoModel;
  46688. var seriesModel = finder.seriesModel;
  46689. var coordSys = geoModel ? geoModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem // For map.
  46690. || (seriesModel.getReferringComponents('geo')[0] || {}).coordinateSystem : null;
  46691. return coordSys === this ? coordSys[methodName](value) : null;
  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. * Resize method bound to the geo
  46713. * @param {module:echarts/coord/geo/GeoModel|module:echarts/chart/map/MapModel} geoModel
  46714. * @param {module:echarts/ExtensionAPI} api
  46715. */
  46716. function resizeGeo(geoModel, api) {
  46717. var boundingCoords = geoModel.get('boundingCoords');
  46718. if (boundingCoords != null) {
  46719. var leftTop = boundingCoords[0];
  46720. var rightBottom = boundingCoords[1];
  46721. if (isNaN(leftTop[0]) || isNaN(leftTop[1]) || isNaN(rightBottom[0]) || isNaN(rightBottom[1])) {} else {
  46722. this.setBoundingRect(leftTop[0], leftTop[1], rightBottom[0] - leftTop[0], rightBottom[1] - leftTop[1]);
  46723. }
  46724. }
  46725. var rect = this.getBoundingRect();
  46726. var boxLayoutOption;
  46727. var center = geoModel.get('layoutCenter');
  46728. var size = geoModel.get('layoutSize');
  46729. var viewWidth = api.getWidth();
  46730. var viewHeight = api.getHeight();
  46731. var aspect = rect.width / rect.height * this.aspectScale;
  46732. var useCenterAndSize = false;
  46733. if (center && size) {
  46734. center = [parsePercent$1(center[0], viewWidth), parsePercent$1(center[1], viewHeight)];
  46735. size = parsePercent$1(size, Math.min(viewWidth, viewHeight));
  46736. if (!isNaN(center[0]) && !isNaN(center[1]) && !isNaN(size)) {
  46737. useCenterAndSize = true;
  46738. } else {}
  46739. }
  46740. var viewRect;
  46741. if (useCenterAndSize) {
  46742. var viewRect = {};
  46743. if (aspect > 1) {
  46744. // Width is same with size
  46745. viewRect.width = size;
  46746. viewRect.height = size / aspect;
  46747. } else {
  46748. viewRect.height = size;
  46749. viewRect.width = size * aspect;
  46750. }
  46751. viewRect.y = center[1] - viewRect.height / 2;
  46752. viewRect.x = center[0] - viewRect.width / 2;
  46753. } else {
  46754. // Use left/top/width/height
  46755. boxLayoutOption = geoModel.getBoxLayoutParams(); // 0.75 rate
  46756. boxLayoutOption.aspect = aspect;
  46757. viewRect = getLayoutRect(boxLayoutOption, {
  46758. width: viewWidth,
  46759. height: viewHeight
  46760. });
  46761. }
  46762. this.setViewRect(viewRect.x, viewRect.y, viewRect.width, viewRect.height);
  46763. this.setCenter(geoModel.get('center'));
  46764. this.setZoom(geoModel.get('zoom'));
  46765. }
  46766. /**
  46767. * @param {module:echarts/coord/Geo} geo
  46768. * @param {module:echarts/model/Model} model
  46769. * @inner
  46770. */
  46771. function setGeoCoords(geo, model) {
  46772. each$1(model.get('geoCoord'), function (geoCoord, name) {
  46773. geo.addGeoCoord(name, geoCoord);
  46774. });
  46775. }
  46776. var geoCreator = {
  46777. // For deciding which dimensions to use when creating list data
  46778. dimensions: Geo.prototype.dimensions,
  46779. create: function (ecModel, api) {
  46780. var geoList = []; // FIXME Create each time may be slow
  46781. ecModel.eachComponent('geo', function (geoModel, idx) {
  46782. var name = geoModel.get('map');
  46783. var aspectScale = geoModel.get('aspectScale');
  46784. var invertLongitute = true;
  46785. var mapRecords = mapDataStorage.retrieveMap(name);
  46786. if (mapRecords && mapRecords[0] && mapRecords[0].type === 'svg') {
  46787. aspectScale == null && (aspectScale = 1);
  46788. invertLongitute = false;
  46789. } else {
  46790. aspectScale == null && (aspectScale = 0.75);
  46791. }
  46792. var geo = new Geo(name + idx, name, geoModel.get('nameMap'), invertLongitute);
  46793. geo.aspectScale = aspectScale;
  46794. geo.zoomLimit = geoModel.get('scaleLimit');
  46795. geoList.push(geo);
  46796. setGeoCoords(geo, geoModel);
  46797. geoModel.coordinateSystem = geo;
  46798. geo.model = geoModel; // Inject resize method
  46799. geo.resize = resizeGeo;
  46800. geo.resize(geoModel, api);
  46801. });
  46802. ecModel.eachSeries(function (seriesModel) {
  46803. var coordSys = seriesModel.get('coordinateSystem');
  46804. if (coordSys === 'geo') {
  46805. var geoIndex = seriesModel.get('geoIndex') || 0;
  46806. seriesModel.coordinateSystem = geoList[geoIndex];
  46807. }
  46808. }); // If has map series
  46809. var mapModelGroupBySeries = {};
  46810. ecModel.eachSeriesByType('map', function (seriesModel) {
  46811. if (!seriesModel.getHostGeoModel()) {
  46812. var mapType = seriesModel.getMapType();
  46813. mapModelGroupBySeries[mapType] = mapModelGroupBySeries[mapType] || [];
  46814. mapModelGroupBySeries[mapType].push(seriesModel);
  46815. }
  46816. });
  46817. each$1(mapModelGroupBySeries, function (mapSeries, mapType) {
  46818. var nameMapList = map(mapSeries, function (singleMapSeries) {
  46819. return singleMapSeries.get('nameMap');
  46820. });
  46821. var geo = new Geo(mapType, mapType, mergeAll(nameMapList));
  46822. geo.zoomLimit = retrieve.apply(null, map(mapSeries, function (singleMapSeries) {
  46823. return singleMapSeries.get('scaleLimit');
  46824. }));
  46825. geoList.push(geo); // Inject resize method
  46826. geo.resize = resizeGeo;
  46827. geo.aspectScale = mapSeries[0].get('aspectScale');
  46828. geo.resize(mapSeries[0], api);
  46829. each$1(mapSeries, function (singleMapSeries) {
  46830. singleMapSeries.coordinateSystem = geo;
  46831. setGeoCoords(geo, singleMapSeries);
  46832. });
  46833. });
  46834. return geoList;
  46835. },
  46836. /**
  46837. * Fill given regions array
  46838. * @param {Array.<Object>} originRegionArr
  46839. * @param {string} mapName
  46840. * @param {Object} [nameMap]
  46841. * @return {Array}
  46842. */
  46843. getFilledRegions: function (originRegionArr, mapName, nameMap) {
  46844. // Not use the original
  46845. var regionsArr = (originRegionArr || []).slice();
  46846. var dataNameMap = createHashMap();
  46847. for (var i = 0; i < regionsArr.length; i++) {
  46848. dataNameMap.set(regionsArr[i].name, regionsArr[i]);
  46849. }
  46850. var source = geoSourceManager.load(mapName, nameMap);
  46851. each$1(source.regions, function (region) {
  46852. var name = region.name;
  46853. !dataNameMap.get(name) && regionsArr.push({
  46854. name: name
  46855. });
  46856. });
  46857. return regionsArr;
  46858. }
  46859. };
  46860. registerCoordinateSystem('geo', geoCreator);
  46861. /*
  46862. * Licensed to the Apache Software Foundation (ASF) under one
  46863. * or more contributor license agreements. See the NOTICE file
  46864. * distributed with this work for additional information
  46865. * regarding copyright ownership. The ASF licenses this file
  46866. * to you under the Apache License, Version 2.0 (the
  46867. * "License"); you may not use this file except in compliance
  46868. * with the License. You may obtain a copy of the License at
  46869. *
  46870. * http://www.apache.org/licenses/LICENSE-2.0
  46871. *
  46872. * Unless required by applicable law or agreed to in writing,
  46873. * software distributed under the License is distributed on an
  46874. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46875. * KIND, either express or implied. See the License for the
  46876. * specific language governing permissions and limitations
  46877. * under the License.
  46878. */
  46879. var mapSymbolLayout = function (ecModel) {
  46880. var processedMapType = {};
  46881. ecModel.eachSeriesByType('map', function (mapSeries) {
  46882. var mapType = mapSeries.getMapType();
  46883. if (mapSeries.getHostGeoModel() || processedMapType[mapType]) {
  46884. return;
  46885. }
  46886. var mapSymbolOffsets = {};
  46887. each$1(mapSeries.seriesGroup, function (subMapSeries) {
  46888. var geo = subMapSeries.coordinateSystem;
  46889. var data = subMapSeries.originalData;
  46890. if (subMapSeries.get('showLegendSymbol') && ecModel.getComponent('legend')) {
  46891. data.each(data.mapDimension('value'), function (value, idx) {
  46892. var name = data.getName(idx);
  46893. var region = geo.getRegion(name); // If input series.data is [11, 22, '-'/null/undefined, 44],
  46894. // it will be filled with NaN: [11, 22, NaN, 44] and NaN will
  46895. // not be drawn. So here must validate if value is NaN.
  46896. if (!region || isNaN(value)) {
  46897. return;
  46898. }
  46899. var offset = mapSymbolOffsets[name] || 0;
  46900. var point = geo.dataToPoint(region.center);
  46901. mapSymbolOffsets[name] = offset + 1;
  46902. data.setItemLayout(idx, {
  46903. point: point,
  46904. offset: offset
  46905. });
  46906. });
  46907. }
  46908. }); // Show label of those region not has legendSymbol(which is offset 0)
  46909. var data = mapSeries.getData();
  46910. data.each(function (idx) {
  46911. var name = data.getName(idx);
  46912. var layout = data.getItemLayout(idx) || {};
  46913. layout.showLabel = !mapSymbolOffsets[name];
  46914. data.setItemLayout(idx, layout);
  46915. });
  46916. processedMapType[mapType] = true;
  46917. });
  46918. };
  46919. /*
  46920. * Licensed to the Apache Software Foundation (ASF) under one
  46921. * or more contributor license agreements. See the NOTICE file
  46922. * distributed with this work for additional information
  46923. * regarding copyright ownership. The ASF licenses this file
  46924. * to you under the Apache License, Version 2.0 (the
  46925. * "License"); you may not use this file except in compliance
  46926. * with the License. You may obtain a copy of the License at
  46927. *
  46928. * http://www.apache.org/licenses/LICENSE-2.0
  46929. *
  46930. * Unless required by applicable law or agreed to in writing,
  46931. * software distributed under the License is distributed on an
  46932. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46933. * KIND, either express or implied. See the License for the
  46934. * specific language governing permissions and limitations
  46935. * under the License.
  46936. */
  46937. var mapVisual$1 = function (ecModel) {
  46938. ecModel.eachSeriesByType('map', function (seriesModel) {
  46939. var colorList = seriesModel.get('color');
  46940. var itemStyleModel = seriesModel.getModel('itemStyle');
  46941. var areaColor = itemStyleModel.get('areaColor');
  46942. var color = itemStyleModel.get('color') || colorList[seriesModel.seriesIndex % colorList.length];
  46943. seriesModel.getData().setVisual({
  46944. 'areaColor': areaColor,
  46945. 'color': color
  46946. });
  46947. });
  46948. };
  46949. /*
  46950. * Licensed to the Apache Software Foundation (ASF) under one
  46951. * or more contributor license agreements. See the NOTICE file
  46952. * distributed with this work for additional information
  46953. * regarding copyright ownership. The ASF licenses this file
  46954. * to you under the Apache License, Version 2.0 (the
  46955. * "License"); you may not use this file except in compliance
  46956. * with the License. You may obtain a copy of the License at
  46957. *
  46958. * http://www.apache.org/licenses/LICENSE-2.0
  46959. *
  46960. * Unless required by applicable law or agreed to in writing,
  46961. * software distributed under the License is distributed on an
  46962. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  46963. * KIND, either express or implied. See the License for the
  46964. * specific language governing permissions and limitations
  46965. * under the License.
  46966. */
  46967. /**
  46968. * @param {Array.<module:echarts/data/List>} datas
  46969. * @param {string} statisticType 'average' 'sum'
  46970. * @inner
  46971. */
  46972. function dataStatistics(datas, statisticType) {
  46973. var dataNameMap = {};
  46974. each$1(datas, function (data) {
  46975. data.each(data.mapDimension('value'), function (value, idx) {
  46976. // Add prefix to avoid conflict with Object.prototype.
  46977. var mapKey = 'ec-' + data.getName(idx);
  46978. dataNameMap[mapKey] = dataNameMap[mapKey] || [];
  46979. if (!isNaN(value)) {
  46980. dataNameMap[mapKey].push(value);
  46981. }
  46982. });
  46983. });
  46984. return datas[0].map(datas[0].mapDimension('value'), function (value, idx) {
  46985. var mapKey = 'ec-' + datas[0].getName(idx);
  46986. var sum = 0;
  46987. var min = Infinity;
  46988. var max = -Infinity;
  46989. var len = dataNameMap[mapKey].length;
  46990. for (var i = 0; i < len; i++) {
  46991. min = Math.min(min, dataNameMap[mapKey][i]);
  46992. max = Math.max(max, dataNameMap[mapKey][i]);
  46993. sum += dataNameMap[mapKey][i];
  46994. }
  46995. var result;
  46996. if (statisticType === 'min') {
  46997. result = min;
  46998. } else if (statisticType === 'max') {
  46999. result = max;
  47000. } else if (statisticType === 'average') {
  47001. result = sum / len;
  47002. } else {
  47003. result = sum;
  47004. }
  47005. return len === 0 ? NaN : result;
  47006. });
  47007. }
  47008. var mapDataStatistic = function (ecModel) {
  47009. var seriesGroups = {};
  47010. ecModel.eachSeriesByType('map', function (seriesModel) {
  47011. var hostGeoModel = seriesModel.getHostGeoModel();
  47012. var key = hostGeoModel ? 'o' + hostGeoModel.id : 'i' + seriesModel.getMapType();
  47013. (seriesGroups[key] = seriesGroups[key] || []).push(seriesModel);
  47014. });
  47015. each$1(seriesGroups, function (seriesList, key) {
  47016. var data = dataStatistics(map(seriesList, function (seriesModel) {
  47017. return seriesModel.getData();
  47018. }), seriesList[0].get('mapValueCalculation'));
  47019. for (var i = 0; i < seriesList.length; i++) {
  47020. seriesList[i].originalData = seriesList[i].getData();
  47021. } // FIXME Put where?
  47022. for (var i = 0; i < seriesList.length; i++) {
  47023. seriesList[i].seriesGroup = seriesList;
  47024. seriesList[i].needsDrawMap = i === 0 && !seriesList[i].getHostGeoModel();
  47025. seriesList[i].setData(data.cloneShallow());
  47026. seriesList[i].mainSeries = seriesList[0];
  47027. }
  47028. });
  47029. };
  47030. /*
  47031. * Licensed to the Apache Software Foundation (ASF) under one
  47032. * or more contributor license agreements. See the NOTICE file
  47033. * distributed with this work for additional information
  47034. * regarding copyright ownership. The ASF licenses this file
  47035. * to you under the Apache License, Version 2.0 (the
  47036. * "License"); you may not use this file except in compliance
  47037. * with the License. You may obtain a copy of the License at
  47038. *
  47039. * http://www.apache.org/licenses/LICENSE-2.0
  47040. *
  47041. * Unless required by applicable law or agreed to in writing,
  47042. * software distributed under the License is distributed on an
  47043. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47044. * KIND, either express or implied. See the License for the
  47045. * specific language governing permissions and limitations
  47046. * under the License.
  47047. */
  47048. var backwardCompat$2 = function (option) {
  47049. // Save geoCoord
  47050. var mapSeries = [];
  47051. each$1(option.series, function (seriesOpt) {
  47052. if (seriesOpt && seriesOpt.type === 'map') {
  47053. mapSeries.push(seriesOpt);
  47054. seriesOpt.map = seriesOpt.map || seriesOpt.mapType; // Put x, y, width, height, x2, y2 in the top level
  47055. defaults(seriesOpt, seriesOpt.mapLocation);
  47056. }
  47057. });
  47058. };
  47059. /*
  47060. * Licensed to the Apache Software Foundation (ASF) under one
  47061. * or more contributor license agreements. See the NOTICE file
  47062. * distributed with this work for additional information
  47063. * regarding copyright ownership. The ASF licenses this file
  47064. * to you under the Apache License, Version 2.0 (the
  47065. * "License"); you may not use this file except in compliance
  47066. * with the License. You may obtain a copy of the License at
  47067. *
  47068. * http://www.apache.org/licenses/LICENSE-2.0
  47069. *
  47070. * Unless required by applicable law or agreed to in writing,
  47071. * software distributed under the License is distributed on an
  47072. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47073. * KIND, either express or implied. See the License for the
  47074. * specific language governing permissions and limitations
  47075. * under the License.
  47076. */
  47077. registerLayout(mapSymbolLayout);
  47078. registerVisual(mapVisual$1);
  47079. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, mapDataStatistic);
  47080. registerPreprocessor(backwardCompat$2);
  47081. createDataSelectAction('map', [{
  47082. type: 'mapToggleSelect',
  47083. event: 'mapselectchanged',
  47084. method: 'toggleSelected'
  47085. }, {
  47086. type: 'mapSelect',
  47087. event: 'mapselected',
  47088. method: 'select'
  47089. }, {
  47090. type: 'mapUnSelect',
  47091. event: 'mapunselected',
  47092. method: 'unSelect'
  47093. }]);
  47094. /*
  47095. * Licensed to the Apache Software Foundation (ASF) under one
  47096. * or more contributor license agreements. See the NOTICE file
  47097. * distributed with this work for additional information
  47098. * regarding copyright ownership. The ASF licenses this file
  47099. * to you under the Apache License, Version 2.0 (the
  47100. * "License"); you may not use this file except in compliance
  47101. * with the License. You may obtain a copy of the License at
  47102. *
  47103. * http://www.apache.org/licenses/LICENSE-2.0
  47104. *
  47105. * Unless required by applicable law or agreed to in writing,
  47106. * software distributed under the License is distributed on an
  47107. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47108. * KIND, either express or implied. See the License for the
  47109. * specific language governing permissions and limitations
  47110. * under the License.
  47111. */
  47112. /* global Uint32Array, Float64Array, Float32Array */
  47113. var Uint32Arr = typeof Uint32Array === 'undefined' ? Array : Uint32Array;
  47114. var Float64Arr = typeof Float64Array === 'undefined' ? Array : Float64Array;
  47115. function compatEc2(seriesOpt) {
  47116. var data = seriesOpt.data;
  47117. if (data && data[0] && data[0][0] && data[0][0].coord) {
  47118. seriesOpt.data = map(data, function (itemOpt) {
  47119. var coords = [itemOpt[0].coord, itemOpt[1].coord];
  47120. var target = {
  47121. coords: coords
  47122. };
  47123. if (itemOpt[0].name) {
  47124. target.fromName = itemOpt[0].name;
  47125. }
  47126. if (itemOpt[1].name) {
  47127. target.toName = itemOpt[1].name;
  47128. }
  47129. return mergeAll([target, itemOpt[0], itemOpt[1]]);
  47130. });
  47131. }
  47132. }
  47133. var LinesSeries = SeriesModel.extend({
  47134. type: 'series.lines',
  47135. dependencies: ['grid', 'polar'],
  47136. visualColorAccessPath: 'lineStyle.color',
  47137. init: function (option) {
  47138. // The input data may be null/undefined.
  47139. option.data = option.data || []; // Not using preprocessor because mergeOption may not have series.type
  47140. compatEc2(option);
  47141. var result = this._processFlatCoordsArray(option.data);
  47142. this._flatCoords = result.flatCoords;
  47143. this._flatCoordsOffset = result.flatCoordsOffset;
  47144. if (result.flatCoords) {
  47145. option.data = new Float32Array(result.count);
  47146. }
  47147. LinesSeries.superApply(this, 'init', arguments);
  47148. },
  47149. mergeOption: function (option) {
  47150. // The input data may be null/undefined.
  47151. option.data = option.data || [];
  47152. compatEc2(option);
  47153. if (option.data) {
  47154. // Only update when have option data to merge.
  47155. var result = this._processFlatCoordsArray(option.data);
  47156. this._flatCoords = result.flatCoords;
  47157. this._flatCoordsOffset = result.flatCoordsOffset;
  47158. if (result.flatCoords) {
  47159. option.data = new Float32Array(result.count);
  47160. }
  47161. }
  47162. LinesSeries.superApply(this, 'mergeOption', arguments);
  47163. },
  47164. appendData: function (params) {
  47165. var result = this._processFlatCoordsArray(params.data);
  47166. if (result.flatCoords) {
  47167. if (!this._flatCoords) {
  47168. this._flatCoords = result.flatCoords;
  47169. this._flatCoordsOffset = result.flatCoordsOffset;
  47170. } else {
  47171. this._flatCoords = concatArray(this._flatCoords, result.flatCoords);
  47172. this._flatCoordsOffset = concatArray(this._flatCoordsOffset, result.flatCoordsOffset);
  47173. }
  47174. params.data = new Float32Array(result.count);
  47175. }
  47176. this.getRawData().appendData(params.data);
  47177. },
  47178. _getCoordsFromItemModel: function (idx) {
  47179. var itemModel = this.getData().getItemModel(idx);
  47180. var coords = itemModel.option instanceof Array ? itemModel.option : itemModel.getShallow('coords');
  47181. return coords;
  47182. },
  47183. getLineCoordsCount: function (idx) {
  47184. if (this._flatCoordsOffset) {
  47185. return this._flatCoordsOffset[idx * 2 + 1];
  47186. } else {
  47187. return this._getCoordsFromItemModel(idx).length;
  47188. }
  47189. },
  47190. getLineCoords: function (idx, out) {
  47191. if (this._flatCoordsOffset) {
  47192. var offset = this._flatCoordsOffset[idx * 2];
  47193. var len = this._flatCoordsOffset[idx * 2 + 1];
  47194. for (var i = 0; i < len; i++) {
  47195. out[i] = out[i] || [];
  47196. out[i][0] = this._flatCoords[offset + i * 2];
  47197. out[i][1] = this._flatCoords[offset + i * 2 + 1];
  47198. }
  47199. return len;
  47200. } else {
  47201. var coords = this._getCoordsFromItemModel(idx);
  47202. for (var i = 0; i < coords.length; i++) {
  47203. out[i] = out[i] || [];
  47204. out[i][0] = coords[i][0];
  47205. out[i][1] = coords[i][1];
  47206. }
  47207. return coords.length;
  47208. }
  47209. },
  47210. _processFlatCoordsArray: function (data) {
  47211. var startOffset = 0;
  47212. if (this._flatCoords) {
  47213. startOffset = this._flatCoords.length;
  47214. } // Stored as a typed array. In format
  47215. // Points Count(2) | x | y | x | y | Points Count(3) | x | y | x | y | x | y |
  47216. if (typeof data[0] === 'number') {
  47217. var len = data.length; // Store offset and len of each segment
  47218. var coordsOffsetAndLenStorage = new Uint32Arr(len);
  47219. var coordsStorage = new Float64Arr(len);
  47220. var coordsCursor = 0;
  47221. var offsetCursor = 0;
  47222. var dataCount = 0;
  47223. for (var i = 0; i < len;) {
  47224. dataCount++;
  47225. var count = data[i++]; // Offset
  47226. coordsOffsetAndLenStorage[offsetCursor++] = coordsCursor + startOffset; // Len
  47227. coordsOffsetAndLenStorage[offsetCursor++] = count;
  47228. for (var k = 0; k < count; k++) {
  47229. var x = data[i++];
  47230. var y = data[i++];
  47231. coordsStorage[coordsCursor++] = x;
  47232. coordsStorage[coordsCursor++] = y;
  47233. }
  47234. }
  47235. return {
  47236. flatCoordsOffset: new Uint32Array(coordsOffsetAndLenStorage.buffer, 0, offsetCursor),
  47237. flatCoords: coordsStorage,
  47238. count: dataCount
  47239. };
  47240. }
  47241. return {
  47242. flatCoordsOffset: null,
  47243. flatCoords: null,
  47244. count: data.length
  47245. };
  47246. },
  47247. getInitialData: function (option, ecModel) {
  47248. var lineData = new List(['value'], this);
  47249. lineData.hasItemOption = false;
  47250. lineData.initData(option.data, [], function (dataItem, dimName, dataIndex, dimIndex) {
  47251. // dataItem is simply coords
  47252. if (dataItem instanceof Array) {
  47253. return NaN;
  47254. } else {
  47255. lineData.hasItemOption = true;
  47256. var value = dataItem.value;
  47257. if (value != null) {
  47258. return value instanceof Array ? value[dimIndex] : value;
  47259. }
  47260. }
  47261. });
  47262. return lineData;
  47263. },
  47264. formatTooltip: function (dataIndex) {
  47265. var data = this.getData();
  47266. var itemModel = data.getItemModel(dataIndex);
  47267. var name = itemModel.get('name');
  47268. if (name) {
  47269. return name;
  47270. }
  47271. var fromName = itemModel.get('fromName');
  47272. var toName = itemModel.get('toName');
  47273. var html = [];
  47274. fromName != null && html.push(fromName);
  47275. toName != null && html.push(toName);
  47276. return encodeHTML(html.join(' > '));
  47277. },
  47278. preventIncremental: function () {
  47279. return !!this.get('effect.show');
  47280. },
  47281. getProgressive: function () {
  47282. var progressive = this.option.progressive;
  47283. if (progressive == null) {
  47284. return this.option.large ? 1e4 : this.get('progressive');
  47285. }
  47286. return progressive;
  47287. },
  47288. getProgressiveThreshold: function () {
  47289. var progressiveThreshold = this.option.progressiveThreshold;
  47290. if (progressiveThreshold == null) {
  47291. return this.option.large ? 2e4 : this.get('progressiveThreshold');
  47292. }
  47293. return progressiveThreshold;
  47294. },
  47295. defaultOption: {
  47296. coordinateSystem: 'geo',
  47297. zlevel: 0,
  47298. z: 2,
  47299. legendHoverLink: true,
  47300. hoverAnimation: true,
  47301. // Cartesian coordinate system
  47302. xAxisIndex: 0,
  47303. yAxisIndex: 0,
  47304. symbol: ['none', 'none'],
  47305. symbolSize: [10, 10],
  47306. // Geo coordinate system
  47307. geoIndex: 0,
  47308. effect: {
  47309. show: false,
  47310. period: 4,
  47311. // Animation delay. support callback
  47312. // delay: 0,
  47313. // If move with constant speed px/sec
  47314. // period will be ignored if this property is > 0,
  47315. constantSpeed: 0,
  47316. symbol: 'circle',
  47317. symbolSize: 3,
  47318. loop: true,
  47319. // Length of trail, 0 - 1
  47320. trailLength: 0.2 // Same with lineStyle.color
  47321. // color
  47322. },
  47323. large: false,
  47324. // Available when large is true
  47325. largeThreshold: 2000,
  47326. // If lines are polyline
  47327. // polyline not support curveness, label, animation
  47328. polyline: false,
  47329. // If clip the overflow.
  47330. // Available when coordinateSystem is cartesian or polar.
  47331. clip: true,
  47332. label: {
  47333. show: false,
  47334. position: 'end' // distance: 5,
  47335. // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  47336. },
  47337. lineStyle: {
  47338. opacity: 0.5
  47339. }
  47340. }
  47341. });
  47342. /*
  47343. * Licensed to the Apache Software Foundation (ASF) under one
  47344. * or more contributor license agreements. See the NOTICE file
  47345. * distributed with this work for additional information
  47346. * regarding copyright ownership. The ASF licenses this file
  47347. * to you under the Apache License, Version 2.0 (the
  47348. * "License"); you may not use this file except in compliance
  47349. * with the License. You may obtain a copy of the License at
  47350. *
  47351. * http://www.apache.org/licenses/LICENSE-2.0
  47352. *
  47353. * Unless required by applicable law or agreed to in writing,
  47354. * software distributed under the License is distributed on an
  47355. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47356. * KIND, either express or implied. See the License for the
  47357. * specific language governing permissions and limitations
  47358. * under the License.
  47359. */
  47360. /**
  47361. * Line path for bezier and straight line draw
  47362. */
  47363. var straightLineProto = Line.prototype;
  47364. var bezierCurveProto = BezierCurve.prototype;
  47365. function isLine(shape) {
  47366. return isNaN(+shape.cpx1) || isNaN(+shape.cpy1);
  47367. }
  47368. var LinePath = extendShape({
  47369. type: 'ec-line',
  47370. style: {
  47371. stroke: '#000',
  47372. fill: null
  47373. },
  47374. shape: {
  47375. x1: 0,
  47376. y1: 0,
  47377. x2: 0,
  47378. y2: 0,
  47379. percent: 1,
  47380. cpx1: null,
  47381. cpy1: null
  47382. },
  47383. buildPath: function (ctx, shape) {
  47384. this[isLine(shape) ? '_buildPathLine' : '_buildPathCurve'](ctx, shape);
  47385. },
  47386. _buildPathLine: straightLineProto.buildPath,
  47387. _buildPathCurve: bezierCurveProto.buildPath,
  47388. pointAt: function (t) {
  47389. return this[isLine(this.shape) ? '_pointAtLine' : '_pointAtCurve'](t);
  47390. },
  47391. _pointAtLine: straightLineProto.pointAt,
  47392. _pointAtCurve: bezierCurveProto.pointAt,
  47393. tangentAt: function (t) {
  47394. var shape = this.shape;
  47395. var p = isLine(shape) ? [shape.x2 - shape.x1, shape.y2 - shape.y1] : this._tangentAtCurve(t);
  47396. return normalize(p, p);
  47397. },
  47398. _tangentAtCurve: bezierCurveProto.tangentAt
  47399. });
  47400. /*
  47401. * Licensed to the Apache Software Foundation (ASF) under one
  47402. * or more contributor license agreements. See the NOTICE file
  47403. * distributed with this work for additional information
  47404. * regarding copyright ownership. The ASF licenses this file
  47405. * to you under the Apache License, Version 2.0 (the
  47406. * "License"); you may not use this file except in compliance
  47407. * with the License. You may obtain a copy of the License at
  47408. *
  47409. * http://www.apache.org/licenses/LICENSE-2.0
  47410. *
  47411. * Unless required by applicable law or agreed to in writing,
  47412. * software distributed under the License is distributed on an
  47413. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47414. * KIND, either express or implied. See the License for the
  47415. * specific language governing permissions and limitations
  47416. * under the License.
  47417. */
  47418. /**
  47419. * @module echarts/chart/helper/Line
  47420. */
  47421. var SYMBOL_CATEGORIES = ['fromSymbol', 'toSymbol'];
  47422. function makeSymbolTypeKey(symbolCategory) {
  47423. return '_' + symbolCategory + 'Type';
  47424. }
  47425. /**
  47426. * @inner
  47427. */
  47428. function createSymbol$1(name, lineData, idx) {
  47429. var color = lineData.getItemVisual(idx, 'color');
  47430. var symbolType = lineData.getItemVisual(idx, name);
  47431. var symbolSize = lineData.getItemVisual(idx, name + 'Size');
  47432. if (!symbolType || symbolType === 'none') {
  47433. return;
  47434. }
  47435. if (!isArray(symbolSize)) {
  47436. symbolSize = [symbolSize, symbolSize];
  47437. }
  47438. var symbolPath = createSymbol(symbolType, -symbolSize[0] / 2, -symbolSize[1] / 2, symbolSize[0], symbolSize[1], color);
  47439. symbolPath.name = name;
  47440. return symbolPath;
  47441. }
  47442. function createLine(points) {
  47443. var line = new LinePath({
  47444. name: 'line',
  47445. subPixelOptimize: true
  47446. });
  47447. setLinePoints(line.shape, points);
  47448. return line;
  47449. }
  47450. function setLinePoints(targetShape, points) {
  47451. targetShape.x1 = points[0][0];
  47452. targetShape.y1 = points[0][1];
  47453. targetShape.x2 = points[1][0];
  47454. targetShape.y2 = points[1][1];
  47455. targetShape.percent = 1;
  47456. var cp1 = points[2];
  47457. if (cp1) {
  47458. targetShape.cpx1 = cp1[0];
  47459. targetShape.cpy1 = cp1[1];
  47460. } else {
  47461. targetShape.cpx1 = NaN;
  47462. targetShape.cpy1 = NaN;
  47463. }
  47464. }
  47465. function updateSymbolAndLabelBeforeLineUpdate() {
  47466. var lineGroup = this;
  47467. var symbolFrom = lineGroup.childOfName('fromSymbol');
  47468. var symbolTo = lineGroup.childOfName('toSymbol');
  47469. var label = lineGroup.childOfName('label'); // Quick reject
  47470. if (!symbolFrom && !symbolTo && label.ignore) {
  47471. return;
  47472. }
  47473. var invScale = 1;
  47474. var parentNode = this.parent;
  47475. while (parentNode) {
  47476. if (parentNode.scale) {
  47477. invScale /= parentNode.scale[0];
  47478. }
  47479. parentNode = parentNode.parent;
  47480. }
  47481. var line = lineGroup.childOfName('line'); // If line not changed
  47482. // FIXME Parent scale changed
  47483. if (!this.__dirty && !line.__dirty) {
  47484. return;
  47485. }
  47486. var percent = line.shape.percent;
  47487. var fromPos = line.pointAt(0);
  47488. var toPos = line.pointAt(percent);
  47489. var d = sub([], toPos, fromPos);
  47490. normalize(d, d);
  47491. if (symbolFrom) {
  47492. symbolFrom.attr('position', fromPos);
  47493. var tangent = line.tangentAt(0);
  47494. symbolFrom.attr('rotation', Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  47495. symbolFrom.attr('scale', [invScale * percent, invScale * percent]);
  47496. }
  47497. if (symbolTo) {
  47498. symbolTo.attr('position', toPos);
  47499. var tangent = line.tangentAt(1);
  47500. symbolTo.attr('rotation', -Math.PI / 2 - Math.atan2(tangent[1], tangent[0]));
  47501. symbolTo.attr('scale', [invScale * percent, invScale * percent]);
  47502. }
  47503. if (!label.ignore) {
  47504. label.attr('position', toPos);
  47505. var textPosition;
  47506. var textAlign;
  47507. var textVerticalAlign;
  47508. var textOrigin;
  47509. var distance$$1 = label.__labelDistance;
  47510. var distanceX = distance$$1[0] * invScale;
  47511. var distanceY = distance$$1[1] * invScale;
  47512. var halfPercent = percent / 2;
  47513. var tangent = line.tangentAt(halfPercent);
  47514. var n = [tangent[1], -tangent[0]];
  47515. var cp = line.pointAt(halfPercent);
  47516. if (n[1] > 0) {
  47517. n[0] = -n[0];
  47518. n[1] = -n[1];
  47519. }
  47520. var dir = tangent[0] < 0 ? -1 : 1;
  47521. if (label.__position !== 'start' && label.__position !== 'end') {
  47522. var rotation = -Math.atan2(tangent[1], tangent[0]);
  47523. if (toPos[0] < fromPos[0]) {
  47524. rotation = Math.PI + rotation;
  47525. }
  47526. label.attr('rotation', rotation);
  47527. }
  47528. var dy;
  47529. switch (label.__position) {
  47530. case 'insideStartTop':
  47531. case 'insideMiddleTop':
  47532. case 'insideEndTop':
  47533. case 'middle':
  47534. dy = -distanceY;
  47535. textVerticalAlign = 'bottom';
  47536. break;
  47537. case 'insideStartBottom':
  47538. case 'insideMiddleBottom':
  47539. case 'insideEndBottom':
  47540. dy = distanceY;
  47541. textVerticalAlign = 'top';
  47542. break;
  47543. default:
  47544. dy = 0;
  47545. textVerticalAlign = 'middle';
  47546. }
  47547. switch (label.__position) {
  47548. case 'end':
  47549. textPosition = [d[0] * distanceX + toPos[0], d[1] * distanceY + toPos[1]];
  47550. textAlign = d[0] > 0.8 ? 'left' : d[0] < -0.8 ? 'right' : 'center';
  47551. textVerticalAlign = d[1] > 0.8 ? 'top' : d[1] < -0.8 ? 'bottom' : 'middle';
  47552. break;
  47553. case 'start':
  47554. textPosition = [-d[0] * distanceX + fromPos[0], -d[1] * distanceY + fromPos[1]];
  47555. textAlign = d[0] > 0.8 ? 'right' : d[0] < -0.8 ? 'left' : 'center';
  47556. textVerticalAlign = d[1] > 0.8 ? 'bottom' : d[1] < -0.8 ? 'top' : 'middle';
  47557. break;
  47558. case 'insideStartTop':
  47559. case 'insideStart':
  47560. case 'insideStartBottom':
  47561. textPosition = [distanceX * dir + fromPos[0], fromPos[1] + dy];
  47562. textAlign = tangent[0] < 0 ? 'right' : 'left';
  47563. textOrigin = [-distanceX * dir, -dy];
  47564. break;
  47565. case 'insideMiddleTop':
  47566. case 'insideMiddle':
  47567. case 'insideMiddleBottom':
  47568. case 'middle':
  47569. textPosition = [cp[0], cp[1] + dy];
  47570. textAlign = 'center';
  47571. textOrigin = [0, -dy];
  47572. break;
  47573. case 'insideEndTop':
  47574. case 'insideEnd':
  47575. case 'insideEndBottom':
  47576. textPosition = [-distanceX * dir + toPos[0], toPos[1] + dy];
  47577. textAlign = tangent[0] >= 0 ? 'right' : 'left';
  47578. textOrigin = [distanceX * dir, -dy];
  47579. break;
  47580. }
  47581. label.attr({
  47582. style: {
  47583. // Use the user specified text align and baseline first
  47584. textVerticalAlign: label.__verticalAlign || textVerticalAlign,
  47585. textAlign: label.__textAlign || textAlign
  47586. },
  47587. position: textPosition,
  47588. scale: [invScale, invScale],
  47589. origin: textOrigin
  47590. });
  47591. }
  47592. }
  47593. /**
  47594. * @constructor
  47595. * @extends {module:zrender/graphic/Group}
  47596. * @alias {module:echarts/chart/helper/Line}
  47597. */
  47598. function Line$1(lineData, idx, seriesScope) {
  47599. Group.call(this);
  47600. this._createLine(lineData, idx, seriesScope);
  47601. }
  47602. var lineProto = Line$1.prototype; // Update symbol position and rotation
  47603. lineProto.beforeUpdate = updateSymbolAndLabelBeforeLineUpdate;
  47604. lineProto._createLine = function (lineData, idx, seriesScope) {
  47605. var seriesModel = lineData.hostModel;
  47606. var linePoints = lineData.getItemLayout(idx);
  47607. var line = createLine(linePoints);
  47608. line.shape.percent = 0;
  47609. initProps(line, {
  47610. shape: {
  47611. percent: 1
  47612. }
  47613. }, seriesModel, idx);
  47614. this.add(line);
  47615. var label = new Text({
  47616. name: 'label',
  47617. // FIXME
  47618. // Temporary solution for `focusNodeAdjacency`.
  47619. // line label do not use the opacity of lineStyle.
  47620. lineLabelOriginalOpacity: 1
  47621. });
  47622. this.add(label);
  47623. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  47624. var symbol = createSymbol$1(symbolCategory, lineData, idx); // symbols must added after line to make sure
  47625. // it will be updated after line#update.
  47626. // Or symbol position and rotation update in line#beforeUpdate will be one frame slow
  47627. this.add(symbol);
  47628. this[makeSymbolTypeKey(symbolCategory)] = lineData.getItemVisual(idx, symbolCategory);
  47629. }, this);
  47630. this._updateCommonStl(lineData, idx, seriesScope);
  47631. };
  47632. lineProto.updateData = function (lineData, idx, seriesScope) {
  47633. var seriesModel = lineData.hostModel;
  47634. var line = this.childOfName('line');
  47635. var linePoints = lineData.getItemLayout(idx);
  47636. var target = {
  47637. shape: {}
  47638. };
  47639. setLinePoints(target.shape, linePoints);
  47640. updateProps(line, target, seriesModel, idx);
  47641. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  47642. var symbolType = lineData.getItemVisual(idx, symbolCategory);
  47643. var key = makeSymbolTypeKey(symbolCategory); // Symbol changed
  47644. if (this[key] !== symbolType) {
  47645. this.remove(this.childOfName(symbolCategory));
  47646. var symbol = createSymbol$1(symbolCategory, lineData, idx);
  47647. this.add(symbol);
  47648. }
  47649. this[key] = symbolType;
  47650. }, this);
  47651. this._updateCommonStl(lineData, idx, seriesScope);
  47652. };
  47653. lineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  47654. var seriesModel = lineData.hostModel;
  47655. var line = this.childOfName('line');
  47656. var lineStyle = seriesScope && seriesScope.lineStyle;
  47657. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  47658. var labelModel = seriesScope && seriesScope.labelModel;
  47659. var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel; // Optimization for large dataset
  47660. if (!seriesScope || lineData.hasItemOption) {
  47661. var itemModel = lineData.getItemModel(idx);
  47662. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  47663. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  47664. labelModel = itemModel.getModel('label');
  47665. hoverLabelModel = itemModel.getModel('emphasis.label');
  47666. }
  47667. var visualColor = lineData.getItemVisual(idx, 'color');
  47668. var visualOpacity = retrieve3(lineData.getItemVisual(idx, 'opacity'), lineStyle.opacity, 1);
  47669. line.useStyle(defaults({
  47670. strokeNoScale: true,
  47671. fill: 'none',
  47672. stroke: visualColor,
  47673. opacity: visualOpacity
  47674. }, lineStyle));
  47675. line.hoverStyle = hoverLineStyle; // Update symbol
  47676. each$1(SYMBOL_CATEGORIES, function (symbolCategory) {
  47677. var symbol = this.childOfName(symbolCategory);
  47678. if (symbol) {
  47679. symbol.setColor(visualColor);
  47680. symbol.setStyle({
  47681. opacity: visualOpacity
  47682. });
  47683. }
  47684. }, this);
  47685. var showLabel = labelModel.getShallow('show');
  47686. var hoverShowLabel = hoverLabelModel.getShallow('show');
  47687. var label = this.childOfName('label');
  47688. var defaultLabelColor;
  47689. var baseText; // FIXME: the logic below probably should be merged to `graphic.setLabelStyle`.
  47690. if (showLabel || hoverShowLabel) {
  47691. defaultLabelColor = visualColor || '#000';
  47692. baseText = seriesModel.getFormattedLabel(idx, 'normal', lineData.dataType);
  47693. if (baseText == null) {
  47694. var rawVal = seriesModel.getRawValue(idx);
  47695. baseText = rawVal == null ? lineData.getName(idx) : isFinite(rawVal) ? round$1(rawVal) : rawVal;
  47696. }
  47697. }
  47698. var normalText = showLabel ? baseText : null;
  47699. var emphasisText = hoverShowLabel ? retrieve2(seriesModel.getFormattedLabel(idx, 'emphasis', lineData.dataType), baseText) : null;
  47700. var labelStyle = label.style; // Always set `textStyle` even if `normalStyle.text` is null, because default
  47701. // values have to be set on `normalStyle`.
  47702. if (normalText != null || emphasisText != null) {
  47703. setTextStyle(label.style, labelModel, {
  47704. text: normalText
  47705. }, {
  47706. autoColor: defaultLabelColor
  47707. });
  47708. label.__textAlign = labelStyle.textAlign;
  47709. label.__verticalAlign = labelStyle.textVerticalAlign; // 'start', 'middle', 'end'
  47710. label.__position = labelModel.get('position') || 'middle';
  47711. var distance$$1 = labelModel.get('distance');
  47712. if (!isArray(distance$$1)) {
  47713. distance$$1 = [distance$$1, distance$$1];
  47714. }
  47715. label.__labelDistance = distance$$1;
  47716. }
  47717. if (emphasisText != null) {
  47718. // Only these properties supported in this emphasis style here.
  47719. label.hoverStyle = {
  47720. text: emphasisText,
  47721. textFill: hoverLabelModel.getTextColor(true),
  47722. // For merging hover style to normal style, do not use
  47723. // `hoverLabelModel.getFont()` here.
  47724. fontStyle: hoverLabelModel.getShallow('fontStyle'),
  47725. fontWeight: hoverLabelModel.getShallow('fontWeight'),
  47726. fontSize: hoverLabelModel.getShallow('fontSize'),
  47727. fontFamily: hoverLabelModel.getShallow('fontFamily')
  47728. };
  47729. } else {
  47730. label.hoverStyle = {
  47731. text: null
  47732. };
  47733. }
  47734. label.ignore = !showLabel && !hoverShowLabel;
  47735. setHoverStyle(this);
  47736. };
  47737. lineProto.highlight = function () {
  47738. this.trigger('emphasis');
  47739. };
  47740. lineProto.downplay = function () {
  47741. this.trigger('normal');
  47742. };
  47743. lineProto.updateLayout = function (lineData, idx) {
  47744. this.setLinePoints(lineData.getItemLayout(idx));
  47745. };
  47746. lineProto.setLinePoints = function (points) {
  47747. var linePath = this.childOfName('line');
  47748. setLinePoints(linePath.shape, points);
  47749. linePath.dirty();
  47750. };
  47751. inherits(Line$1, Group);
  47752. /*
  47753. * Licensed to the Apache Software Foundation (ASF) under one
  47754. * or more contributor license agreements. See the NOTICE file
  47755. * distributed with this work for additional information
  47756. * regarding copyright ownership. The ASF licenses this file
  47757. * to you under the Apache License, Version 2.0 (the
  47758. * "License"); you may not use this file except in compliance
  47759. * with the License. You may obtain a copy of the License at
  47760. *
  47761. * http://www.apache.org/licenses/LICENSE-2.0
  47762. *
  47763. * Unless required by applicable law or agreed to in writing,
  47764. * software distributed under the License is distributed on an
  47765. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47766. * KIND, either express or implied. See the License for the
  47767. * specific language governing permissions and limitations
  47768. * under the License.
  47769. */
  47770. /**
  47771. * @module echarts/chart/helper/LineDraw
  47772. */
  47773. /**
  47774. * @alias module:echarts/component/marker/LineDraw
  47775. * @constructor
  47776. */
  47777. function LineDraw(ctor) {
  47778. this._ctor = ctor || Line$1;
  47779. this.group = new Group();
  47780. }
  47781. var lineDrawProto = LineDraw.prototype;
  47782. lineDrawProto.isPersistent = function () {
  47783. return true;
  47784. };
  47785. /**
  47786. * @param {module:echarts/data/List} lineData
  47787. */
  47788. lineDrawProto.updateData = function (lineData) {
  47789. var lineDraw = this;
  47790. var group = lineDraw.group;
  47791. var oldLineData = lineDraw._lineData;
  47792. lineDraw._lineData = lineData; // There is no oldLineData only when first rendering or switching from
  47793. // stream mode to normal mode, where previous elements should be removed.
  47794. if (!oldLineData) {
  47795. group.removeAll();
  47796. }
  47797. var seriesScope = makeSeriesScope$1(lineData);
  47798. lineData.diff(oldLineData).add(function (idx) {
  47799. doAdd(lineDraw, lineData, idx, seriesScope);
  47800. }).update(function (newIdx, oldIdx) {
  47801. doUpdate(lineDraw, oldLineData, lineData, oldIdx, newIdx, seriesScope);
  47802. }).remove(function (idx) {
  47803. group.remove(oldLineData.getItemGraphicEl(idx));
  47804. }).execute();
  47805. };
  47806. function doAdd(lineDraw, lineData, idx, seriesScope) {
  47807. var itemLayout = lineData.getItemLayout(idx);
  47808. if (!lineNeedsDraw(itemLayout)) {
  47809. return;
  47810. }
  47811. var el = new lineDraw._ctor(lineData, idx, seriesScope);
  47812. lineData.setItemGraphicEl(idx, el);
  47813. lineDraw.group.add(el);
  47814. }
  47815. function doUpdate(lineDraw, oldLineData, newLineData, oldIdx, newIdx, seriesScope) {
  47816. var itemEl = oldLineData.getItemGraphicEl(oldIdx);
  47817. if (!lineNeedsDraw(newLineData.getItemLayout(newIdx))) {
  47818. lineDraw.group.remove(itemEl);
  47819. return;
  47820. }
  47821. if (!itemEl) {
  47822. itemEl = new lineDraw._ctor(newLineData, newIdx, seriesScope);
  47823. } else {
  47824. itemEl.updateData(newLineData, newIdx, seriesScope);
  47825. }
  47826. newLineData.setItemGraphicEl(newIdx, itemEl);
  47827. lineDraw.group.add(itemEl);
  47828. }
  47829. lineDrawProto.updateLayout = function () {
  47830. var lineData = this._lineData; // Do not support update layout in incremental mode.
  47831. if (!lineData) {
  47832. return;
  47833. }
  47834. lineData.eachItemGraphicEl(function (el, idx) {
  47835. el.updateLayout(lineData, idx);
  47836. }, this);
  47837. };
  47838. lineDrawProto.incrementalPrepareUpdate = function (lineData) {
  47839. this._seriesScope = makeSeriesScope$1(lineData);
  47840. this._lineData = null;
  47841. this.group.removeAll();
  47842. };
  47843. function isEffectObject(el) {
  47844. return el.animators && el.animators.length > 0;
  47845. }
  47846. lineDrawProto.incrementalUpdate = function (taskParams, lineData) {
  47847. function updateIncrementalAndHover(el) {
  47848. if (!el.isGroup && !isEffectObject(el)) {
  47849. el.incremental = el.useHoverLayer = true;
  47850. }
  47851. }
  47852. for (var idx = taskParams.start; idx < taskParams.end; idx++) {
  47853. var itemLayout = lineData.getItemLayout(idx);
  47854. if (lineNeedsDraw(itemLayout)) {
  47855. var el = new this._ctor(lineData, idx, this._seriesScope);
  47856. el.traverse(updateIncrementalAndHover);
  47857. this.group.add(el);
  47858. lineData.setItemGraphicEl(idx, el);
  47859. }
  47860. }
  47861. };
  47862. function makeSeriesScope$1(lineData) {
  47863. var hostModel = lineData.hostModel;
  47864. return {
  47865. lineStyle: hostModel.getModel('lineStyle').getLineStyle(),
  47866. hoverLineStyle: hostModel.getModel('emphasis.lineStyle').getLineStyle(),
  47867. labelModel: hostModel.getModel('label'),
  47868. hoverLabelModel: hostModel.getModel('emphasis.label')
  47869. };
  47870. }
  47871. lineDrawProto.remove = function () {
  47872. this._clearIncremental();
  47873. this._incremental = null;
  47874. this.group.removeAll();
  47875. };
  47876. lineDrawProto._clearIncremental = function () {
  47877. var incremental = this._incremental;
  47878. if (incremental) {
  47879. incremental.clearDisplaybles();
  47880. }
  47881. };
  47882. function isPointNaN(pt) {
  47883. return isNaN(pt[0]) || isNaN(pt[1]);
  47884. }
  47885. function lineNeedsDraw(pts) {
  47886. return !isPointNaN(pts[0]) && !isPointNaN(pts[1]);
  47887. }
  47888. /*
  47889. * Licensed to the Apache Software Foundation (ASF) under one
  47890. * or more contributor license agreements. See the NOTICE file
  47891. * distributed with this work for additional information
  47892. * regarding copyright ownership. The ASF licenses this file
  47893. * to you under the Apache License, Version 2.0 (the
  47894. * "License"); you may not use this file except in compliance
  47895. * with the License. You may obtain a copy of the License at
  47896. *
  47897. * http://www.apache.org/licenses/LICENSE-2.0
  47898. *
  47899. * Unless required by applicable law or agreed to in writing,
  47900. * software distributed under the License is distributed on an
  47901. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  47902. * KIND, either express or implied. See the License for the
  47903. * specific language governing permissions and limitations
  47904. * under the License.
  47905. */
  47906. /**
  47907. * Provide effect for line
  47908. * @module echarts/chart/helper/EffectLine
  47909. */
  47910. /**
  47911. * @constructor
  47912. * @extends {module:zrender/graphic/Group}
  47913. * @alias {module:echarts/chart/helper/Line}
  47914. */
  47915. function EffectLine(lineData, idx, seriesScope) {
  47916. Group.call(this);
  47917. this.add(this.createLine(lineData, idx, seriesScope));
  47918. this._updateEffectSymbol(lineData, idx);
  47919. }
  47920. var effectLineProto = EffectLine.prototype;
  47921. effectLineProto.createLine = function (lineData, idx, seriesScope) {
  47922. return new Line$1(lineData, idx, seriesScope);
  47923. };
  47924. effectLineProto._updateEffectSymbol = function (lineData, idx) {
  47925. var itemModel = lineData.getItemModel(idx);
  47926. var effectModel = itemModel.getModel('effect');
  47927. var size = effectModel.get('symbolSize');
  47928. var symbolType = effectModel.get('symbol');
  47929. if (!isArray(size)) {
  47930. size = [size, size];
  47931. }
  47932. var color = effectModel.get('color') || lineData.getItemVisual(idx, 'color');
  47933. var symbol = this.childAt(1);
  47934. if (this._symbolType !== symbolType) {
  47935. // Remove previous
  47936. this.remove(symbol);
  47937. symbol = createSymbol(symbolType, -0.5, -0.5, 1, 1, color);
  47938. symbol.z2 = 100;
  47939. symbol.culling = true;
  47940. this.add(symbol);
  47941. } // Symbol may be removed if loop is false
  47942. if (!symbol) {
  47943. return;
  47944. } // Shadow color is same with color in default
  47945. symbol.setStyle('shadowColor', color);
  47946. symbol.setStyle(effectModel.getItemStyle(['color']));
  47947. symbol.attr('scale', size);
  47948. symbol.setColor(color);
  47949. symbol.attr('scale', size);
  47950. this._symbolType = symbolType;
  47951. this._symbolScale = size;
  47952. this._updateEffectAnimation(lineData, effectModel, idx);
  47953. };
  47954. effectLineProto._updateEffectAnimation = function (lineData, effectModel, idx) {
  47955. var symbol = this.childAt(1);
  47956. if (!symbol) {
  47957. return;
  47958. }
  47959. var self = this;
  47960. var points = lineData.getItemLayout(idx);
  47961. var period = effectModel.get('period') * 1000;
  47962. var loop = effectModel.get('loop');
  47963. var constantSpeed = effectModel.get('constantSpeed');
  47964. var delayExpr = retrieve(effectModel.get('delay'), function (idx) {
  47965. return idx / lineData.count() * period / 3;
  47966. });
  47967. var isDelayFunc = typeof delayExpr === 'function'; // Ignore when updating
  47968. symbol.ignore = true;
  47969. this.updateAnimationPoints(symbol, points);
  47970. if (constantSpeed > 0) {
  47971. period = this.getLineLength(symbol) / constantSpeed * 1000;
  47972. }
  47973. if (period !== this._period || loop !== this._loop) {
  47974. symbol.stopAnimation();
  47975. var delay = delayExpr;
  47976. if (isDelayFunc) {
  47977. delay = delayExpr(idx);
  47978. }
  47979. if (symbol.__t > 0) {
  47980. delay = -period * symbol.__t;
  47981. }
  47982. symbol.__t = 0;
  47983. var animator = symbol.animate('', loop).when(period, {
  47984. __t: 1
  47985. }).delay(delay).during(function () {
  47986. self.updateSymbolPosition(symbol);
  47987. });
  47988. if (!loop) {
  47989. animator.done(function () {
  47990. self.remove(symbol);
  47991. });
  47992. }
  47993. animator.start();
  47994. }
  47995. this._period = period;
  47996. this._loop = loop;
  47997. };
  47998. effectLineProto.getLineLength = function (symbol) {
  47999. // Not so accurate
  48000. return dist(symbol.__p1, symbol.__cp1) + dist(symbol.__cp1, symbol.__p2);
  48001. };
  48002. effectLineProto.updateAnimationPoints = function (symbol, points) {
  48003. symbol.__p1 = points[0];
  48004. symbol.__p2 = points[1];
  48005. symbol.__cp1 = points[2] || [(points[0][0] + points[1][0]) / 2, (points[0][1] + points[1][1]) / 2];
  48006. };
  48007. effectLineProto.updateData = function (lineData, idx, seriesScope) {
  48008. this.childAt(0).updateData(lineData, idx, seriesScope);
  48009. this._updateEffectSymbol(lineData, idx);
  48010. };
  48011. effectLineProto.updateSymbolPosition = function (symbol) {
  48012. var p1 = symbol.__p1;
  48013. var p2 = symbol.__p2;
  48014. var cp1 = symbol.__cp1;
  48015. var t = symbol.__t;
  48016. var pos = symbol.position;
  48017. var lastPos = [pos[0], pos[1]];
  48018. var quadraticAt$$1 = quadraticAt;
  48019. var quadraticDerivativeAt$$1 = quadraticDerivativeAt;
  48020. pos[0] = quadraticAt$$1(p1[0], cp1[0], p2[0], t);
  48021. pos[1] = quadraticAt$$1(p1[1], cp1[1], p2[1], t); // Tangent
  48022. var tx = quadraticDerivativeAt$$1(p1[0], cp1[0], p2[0], t);
  48023. var ty = quadraticDerivativeAt$$1(p1[1], cp1[1], p2[1], t);
  48024. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2; // enable continuity trail for 'line', 'rect', 'roundRect' symbolType
  48025. if (this._symbolType === 'line' || this._symbolType === 'rect' || this._symbolType === 'roundRect') {
  48026. if (symbol.__lastT !== undefined && symbol.__lastT < symbol.__t) {
  48027. var scaleY = dist(lastPos, pos) * 1.05;
  48028. symbol.attr('scale', [symbol.scale[0], scaleY]); // make sure the last segment render within endPoint
  48029. if (t === 1) {
  48030. pos[0] = lastPos[0] + (pos[0] - lastPos[0]) / 2;
  48031. pos[1] = lastPos[1] + (pos[1] - lastPos[1]) / 2;
  48032. }
  48033. } else if (symbol.__lastT === 1) {
  48034. // After first loop, symbol.__t does NOT start with 0, so connect p1 to pos directly.
  48035. var scaleY = 2 * dist(p1, pos);
  48036. symbol.attr('scale', [symbol.scale[0], scaleY]);
  48037. } else {
  48038. symbol.attr('scale', this._symbolScale);
  48039. }
  48040. }
  48041. symbol.__lastT = symbol.__t;
  48042. symbol.ignore = false;
  48043. };
  48044. effectLineProto.updateLayout = function (lineData, idx) {
  48045. this.childAt(0).updateLayout(lineData, idx);
  48046. var effectModel = lineData.getItemModel(idx).getModel('effect');
  48047. this._updateEffectAnimation(lineData, effectModel, idx);
  48048. };
  48049. inherits(EffectLine, Group);
  48050. /*
  48051. * Licensed to the Apache Software Foundation (ASF) under one
  48052. * or more contributor license agreements. See the NOTICE file
  48053. * distributed with this work for additional information
  48054. * regarding copyright ownership. The ASF licenses this file
  48055. * to you under the Apache License, Version 2.0 (the
  48056. * "License"); you may not use this file except in compliance
  48057. * with the License. You may obtain a copy of the License at
  48058. *
  48059. * http://www.apache.org/licenses/LICENSE-2.0
  48060. *
  48061. * Unless required by applicable law or agreed to in writing,
  48062. * software distributed under the License is distributed on an
  48063. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48064. * KIND, either express or implied. See the License for the
  48065. * specific language governing permissions and limitations
  48066. * under the License.
  48067. */
  48068. /**
  48069. * @module echarts/chart/helper/Line
  48070. */
  48071. /**
  48072. * @constructor
  48073. * @extends {module:zrender/graphic/Group}
  48074. * @alias {module:echarts/chart/helper/Polyline}
  48075. */
  48076. function Polyline$2(lineData, idx, seriesScope) {
  48077. Group.call(this);
  48078. this._createPolyline(lineData, idx, seriesScope);
  48079. }
  48080. var polylineProto = Polyline$2.prototype;
  48081. polylineProto._createPolyline = function (lineData, idx, seriesScope) {
  48082. // var seriesModel = lineData.hostModel;
  48083. var points = lineData.getItemLayout(idx);
  48084. var line = new Polyline({
  48085. shape: {
  48086. points: points
  48087. }
  48088. });
  48089. this.add(line);
  48090. this._updateCommonStl(lineData, idx, seriesScope);
  48091. };
  48092. polylineProto.updateData = function (lineData, idx, seriesScope) {
  48093. var seriesModel = lineData.hostModel;
  48094. var line = this.childAt(0);
  48095. var target = {
  48096. shape: {
  48097. points: lineData.getItemLayout(idx)
  48098. }
  48099. };
  48100. updateProps(line, target, seriesModel, idx);
  48101. this._updateCommonStl(lineData, idx, seriesScope);
  48102. };
  48103. polylineProto._updateCommonStl = function (lineData, idx, seriesScope) {
  48104. var line = this.childAt(0);
  48105. var itemModel = lineData.getItemModel(idx);
  48106. var visualColor = lineData.getItemVisual(idx, 'color');
  48107. var lineStyle = seriesScope && seriesScope.lineStyle;
  48108. var hoverLineStyle = seriesScope && seriesScope.hoverLineStyle;
  48109. if (!seriesScope || lineData.hasItemOption) {
  48110. lineStyle = itemModel.getModel('lineStyle').getLineStyle();
  48111. hoverLineStyle = itemModel.getModel('emphasis.lineStyle').getLineStyle();
  48112. }
  48113. line.useStyle(defaults({
  48114. strokeNoScale: true,
  48115. fill: 'none',
  48116. stroke: visualColor
  48117. }, lineStyle));
  48118. line.hoverStyle = hoverLineStyle;
  48119. setHoverStyle(this);
  48120. };
  48121. polylineProto.updateLayout = function (lineData, idx) {
  48122. var polyline = this.childAt(0);
  48123. polyline.setShape('points', lineData.getItemLayout(idx));
  48124. };
  48125. inherits(Polyline$2, Group);
  48126. /*
  48127. * Licensed to the Apache Software Foundation (ASF) under one
  48128. * or more contributor license agreements. See the NOTICE file
  48129. * distributed with this work for additional information
  48130. * regarding copyright ownership. The ASF licenses this file
  48131. * to you under the Apache License, Version 2.0 (the
  48132. * "License"); you may not use this file except in compliance
  48133. * with the License. You may obtain a copy of the License at
  48134. *
  48135. * http://www.apache.org/licenses/LICENSE-2.0
  48136. *
  48137. * Unless required by applicable law or agreed to in writing,
  48138. * software distributed under the License is distributed on an
  48139. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48140. * KIND, either express or implied. See the License for the
  48141. * specific language governing permissions and limitations
  48142. * under the License.
  48143. */
  48144. /**
  48145. * Provide effect for line
  48146. * @module echarts/chart/helper/EffectLine
  48147. */
  48148. /**
  48149. * @constructor
  48150. * @extends {module:echarts/chart/helper/EffectLine}
  48151. * @alias {module:echarts/chart/helper/Polyline}
  48152. */
  48153. function EffectPolyline(lineData, idx, seriesScope) {
  48154. EffectLine.call(this, lineData, idx, seriesScope);
  48155. this._lastFrame = 0;
  48156. this._lastFramePercent = 0;
  48157. }
  48158. var effectPolylineProto = EffectPolyline.prototype; // Overwrite
  48159. effectPolylineProto.createLine = function (lineData, idx, seriesScope) {
  48160. return new Polyline$2(lineData, idx, seriesScope);
  48161. }; // Overwrite
  48162. effectPolylineProto.updateAnimationPoints = function (symbol, points) {
  48163. this._points = points;
  48164. var accLenArr = [0];
  48165. var len$$1 = 0;
  48166. for (var i = 1; i < points.length; i++) {
  48167. var p1 = points[i - 1];
  48168. var p2 = points[i];
  48169. len$$1 += dist(p1, p2);
  48170. accLenArr.push(len$$1);
  48171. }
  48172. if (len$$1 === 0) {
  48173. return;
  48174. }
  48175. for (var i = 0; i < accLenArr.length; i++) {
  48176. accLenArr[i] /= len$$1;
  48177. }
  48178. this._offsets = accLenArr;
  48179. this._length = len$$1;
  48180. }; // Overwrite
  48181. effectPolylineProto.getLineLength = function (symbol) {
  48182. return this._length;
  48183. }; // Overwrite
  48184. effectPolylineProto.updateSymbolPosition = function (symbol) {
  48185. var t = symbol.__t;
  48186. var points = this._points;
  48187. var offsets = this._offsets;
  48188. var len$$1 = points.length;
  48189. if (!offsets) {
  48190. // Has length 0
  48191. return;
  48192. }
  48193. var lastFrame = this._lastFrame;
  48194. var frame;
  48195. if (t < this._lastFramePercent) {
  48196. // Start from the next frame
  48197. // PENDING start from lastFrame ?
  48198. var start = Math.min(lastFrame + 1, len$$1 - 1);
  48199. for (frame = start; frame >= 0; frame--) {
  48200. if (offsets[frame] <= t) {
  48201. break;
  48202. }
  48203. } // PENDING really need to do this ?
  48204. frame = Math.min(frame, len$$1 - 2);
  48205. } else {
  48206. for (var frame = lastFrame; frame < len$$1; frame++) {
  48207. if (offsets[frame] > t) {
  48208. break;
  48209. }
  48210. }
  48211. frame = Math.min(frame - 1, len$$1 - 2);
  48212. }
  48213. lerp(symbol.position, points[frame], points[frame + 1], (t - offsets[frame]) / (offsets[frame + 1] - offsets[frame]));
  48214. var tx = points[frame + 1][0] - points[frame][0];
  48215. var ty = points[frame + 1][1] - points[frame][1];
  48216. symbol.rotation = -Math.atan2(ty, tx) - Math.PI / 2;
  48217. this._lastFrame = frame;
  48218. this._lastFramePercent = t;
  48219. symbol.ignore = false;
  48220. };
  48221. inherits(EffectPolyline, EffectLine);
  48222. /*
  48223. * Licensed to the Apache Software Foundation (ASF) under one
  48224. * or more contributor license agreements. See the NOTICE file
  48225. * distributed with this work for additional information
  48226. * regarding copyright ownership. The ASF licenses this file
  48227. * to you under the Apache License, Version 2.0 (the
  48228. * "License"); you may not use this file except in compliance
  48229. * with the License. You may obtain a copy of the License at
  48230. *
  48231. * http://www.apache.org/licenses/LICENSE-2.0
  48232. *
  48233. * Unless required by applicable law or agreed to in writing,
  48234. * software distributed under the License is distributed on an
  48235. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48236. * KIND, either express or implied. See the License for the
  48237. * specific language governing permissions and limitations
  48238. * under the License.
  48239. */
  48240. // TODO Batch by color
  48241. var LargeLineShape = extendShape({
  48242. shape: {
  48243. polyline: false,
  48244. curveness: 0,
  48245. segs: []
  48246. },
  48247. buildPath: function (path, shape) {
  48248. var segs = shape.segs;
  48249. var curveness = shape.curveness;
  48250. if (shape.polyline) {
  48251. for (var i = 0; i < segs.length;) {
  48252. var count = segs[i++];
  48253. if (count > 0) {
  48254. path.moveTo(segs[i++], segs[i++]);
  48255. for (var k = 1; k < count; k++) {
  48256. path.lineTo(segs[i++], segs[i++]);
  48257. }
  48258. }
  48259. }
  48260. } else {
  48261. for (var i = 0; i < segs.length;) {
  48262. var x0 = segs[i++];
  48263. var y0 = segs[i++];
  48264. var x1 = segs[i++];
  48265. var y1 = segs[i++];
  48266. path.moveTo(x0, y0);
  48267. if (curveness > 0) {
  48268. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  48269. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  48270. path.quadraticCurveTo(x2, y2, x1, y1);
  48271. } else {
  48272. path.lineTo(x1, y1);
  48273. }
  48274. }
  48275. }
  48276. },
  48277. findDataIndex: function (x, y) {
  48278. var shape = this.shape;
  48279. var segs = shape.segs;
  48280. var curveness = shape.curveness;
  48281. if (shape.polyline) {
  48282. var dataIndex = 0;
  48283. for (var i = 0; i < segs.length;) {
  48284. var count = segs[i++];
  48285. if (count > 0) {
  48286. var x0 = segs[i++];
  48287. var y0 = segs[i++];
  48288. for (var k = 1; k < count; k++) {
  48289. var x1 = segs[i++];
  48290. var y1 = segs[i++];
  48291. if (containStroke$1(x0, y0, x1, y1)) {
  48292. return dataIndex;
  48293. }
  48294. }
  48295. }
  48296. dataIndex++;
  48297. }
  48298. } else {
  48299. var dataIndex = 0;
  48300. for (var i = 0; i < segs.length;) {
  48301. var x0 = segs[i++];
  48302. var y0 = segs[i++];
  48303. var x1 = segs[i++];
  48304. var y1 = segs[i++];
  48305. if (curveness > 0) {
  48306. var x2 = (x0 + x1) / 2 - (y0 - y1) * curveness;
  48307. var y2 = (y0 + y1) / 2 - (x1 - x0) * curveness;
  48308. if (containStroke$3(x0, y0, x2, y2, x1, y1)) {
  48309. return dataIndex;
  48310. }
  48311. } else {
  48312. if (containStroke$1(x0, y0, x1, y1)) {
  48313. return dataIndex;
  48314. }
  48315. }
  48316. dataIndex++;
  48317. }
  48318. }
  48319. return -1;
  48320. }
  48321. });
  48322. function LargeLineDraw() {
  48323. this.group = new Group();
  48324. }
  48325. var largeLineProto = LargeLineDraw.prototype;
  48326. largeLineProto.isPersistent = function () {
  48327. return !this._incremental;
  48328. };
  48329. /**
  48330. * Update symbols draw by new data
  48331. * @param {module:echarts/data/List} data
  48332. */
  48333. largeLineProto.updateData = function (data) {
  48334. this.group.removeAll();
  48335. var lineEl = new LargeLineShape({
  48336. rectHover: true,
  48337. cursor: 'default'
  48338. });
  48339. lineEl.setShape({
  48340. segs: data.getLayout('linesPoints')
  48341. });
  48342. this._setCommon(lineEl, data); // Add back
  48343. this.group.add(lineEl);
  48344. this._incremental = null;
  48345. };
  48346. /**
  48347. * @override
  48348. */
  48349. largeLineProto.incrementalPrepareUpdate = function (data) {
  48350. this.group.removeAll();
  48351. this._clearIncremental();
  48352. if (data.count() > 5e5) {
  48353. if (!this._incremental) {
  48354. this._incremental = new IncrementalDisplayble({
  48355. silent: true
  48356. });
  48357. }
  48358. this.group.add(this._incremental);
  48359. } else {
  48360. this._incremental = null;
  48361. }
  48362. };
  48363. /**
  48364. * @override
  48365. */
  48366. largeLineProto.incrementalUpdate = function (taskParams, data) {
  48367. var lineEl = new LargeLineShape();
  48368. lineEl.setShape({
  48369. segs: data.getLayout('linesPoints')
  48370. });
  48371. this._setCommon(lineEl, data, !!this._incremental);
  48372. if (!this._incremental) {
  48373. lineEl.rectHover = true;
  48374. lineEl.cursor = 'default';
  48375. lineEl.__startIndex = taskParams.start;
  48376. this.group.add(lineEl);
  48377. } else {
  48378. this._incremental.addDisplayable(lineEl, true);
  48379. }
  48380. };
  48381. /**
  48382. * @override
  48383. */
  48384. largeLineProto.remove = function () {
  48385. this._clearIncremental();
  48386. this._incremental = null;
  48387. this.group.removeAll();
  48388. };
  48389. largeLineProto._setCommon = function (lineEl, data, isIncremental) {
  48390. var hostModel = data.hostModel;
  48391. lineEl.setShape({
  48392. polyline: hostModel.get('polyline'),
  48393. curveness: hostModel.get('lineStyle.curveness')
  48394. });
  48395. lineEl.useStyle(hostModel.getModel('lineStyle').getLineStyle());
  48396. lineEl.style.strokeNoScale = true;
  48397. var visualColor = data.getVisual('color');
  48398. if (visualColor) {
  48399. lineEl.setStyle('stroke', visualColor);
  48400. }
  48401. lineEl.setStyle('fill');
  48402. if (!isIncremental) {
  48403. // Enable tooltip
  48404. // PENDING May have performance issue when path is extremely large
  48405. lineEl.seriesIndex = hostModel.seriesIndex;
  48406. lineEl.on('mousemove', function (e) {
  48407. lineEl.dataIndex = null;
  48408. var dataIndex = lineEl.findDataIndex(e.offsetX, e.offsetY);
  48409. if (dataIndex > 0) {
  48410. // Provide dataIndex for tooltip
  48411. lineEl.dataIndex = dataIndex + lineEl.__startIndex;
  48412. }
  48413. });
  48414. }
  48415. };
  48416. largeLineProto._clearIncremental = function () {
  48417. var incremental = this._incremental;
  48418. if (incremental) {
  48419. incremental.clearDisplaybles();
  48420. }
  48421. };
  48422. /*
  48423. * Licensed to the Apache Software Foundation (ASF) under one
  48424. * or more contributor license agreements. See the NOTICE file
  48425. * distributed with this work for additional information
  48426. * regarding copyright ownership. The ASF licenses this file
  48427. * to you under the Apache License, Version 2.0 (the
  48428. * "License"); you may not use this file except in compliance
  48429. * with the License. You may obtain a copy of the License at
  48430. *
  48431. * http://www.apache.org/licenses/LICENSE-2.0
  48432. *
  48433. * Unless required by applicable law or agreed to in writing,
  48434. * software distributed under the License is distributed on an
  48435. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48436. * KIND, either express or implied. See the License for the
  48437. * specific language governing permissions and limitations
  48438. * under the License.
  48439. */
  48440. /* global Float32Array */
  48441. var linesLayout = {
  48442. seriesType: 'lines',
  48443. plan: createRenderPlanner(),
  48444. reset: function (seriesModel) {
  48445. var coordSys = seriesModel.coordinateSystem;
  48446. var isPolyline = seriesModel.get('polyline');
  48447. var isLarge = seriesModel.pipelineContext.large;
  48448. function progress(params, lineData) {
  48449. var lineCoords = [];
  48450. if (isLarge) {
  48451. var points;
  48452. var segCount = params.end - params.start;
  48453. if (isPolyline) {
  48454. var totalCoordsCount = 0;
  48455. for (var i = params.start; i < params.end; i++) {
  48456. totalCoordsCount += seriesModel.getLineCoordsCount(i);
  48457. }
  48458. points = new Float32Array(segCount + totalCoordsCount * 2);
  48459. } else {
  48460. points = new Float32Array(segCount * 4);
  48461. }
  48462. var offset = 0;
  48463. var pt = [];
  48464. for (var i = params.start; i < params.end; i++) {
  48465. var len = seriesModel.getLineCoords(i, lineCoords);
  48466. if (isPolyline) {
  48467. points[offset++] = len;
  48468. }
  48469. for (var k = 0; k < len; k++) {
  48470. pt = coordSys.dataToPoint(lineCoords[k], false, pt);
  48471. points[offset++] = pt[0];
  48472. points[offset++] = pt[1];
  48473. }
  48474. }
  48475. lineData.setLayout('linesPoints', points);
  48476. } else {
  48477. for (var i = params.start; i < params.end; i++) {
  48478. var itemModel = lineData.getItemModel(i);
  48479. var len = seriesModel.getLineCoords(i, lineCoords);
  48480. var pts = [];
  48481. if (isPolyline) {
  48482. for (var j = 0; j < len; j++) {
  48483. pts.push(coordSys.dataToPoint(lineCoords[j]));
  48484. }
  48485. } else {
  48486. pts[0] = coordSys.dataToPoint(lineCoords[0]);
  48487. pts[1] = coordSys.dataToPoint(lineCoords[1]);
  48488. var curveness = itemModel.get('lineStyle.curveness');
  48489. if (+curveness) {
  48490. pts[2] = [(pts[0][0] + pts[1][0]) / 2 - (pts[0][1] - pts[1][1]) * curveness, (pts[0][1] + pts[1][1]) / 2 - (pts[1][0] - pts[0][0]) * curveness];
  48491. }
  48492. }
  48493. lineData.setItemLayout(i, pts);
  48494. }
  48495. }
  48496. }
  48497. return {
  48498. progress: progress
  48499. };
  48500. }
  48501. };
  48502. /*
  48503. * Licensed to the Apache Software Foundation (ASF) under one
  48504. * or more contributor license agreements. See the NOTICE file
  48505. * distributed with this work for additional information
  48506. * regarding copyright ownership. The ASF licenses this file
  48507. * to you under the Apache License, Version 2.0 (the
  48508. * "License"); you may not use this file except in compliance
  48509. * with the License. You may obtain a copy of the License at
  48510. *
  48511. * http://www.apache.org/licenses/LICENSE-2.0
  48512. *
  48513. * Unless required by applicable law or agreed to in writing,
  48514. * software distributed under the License is distributed on an
  48515. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48516. * KIND, either express or implied. See the License for the
  48517. * specific language governing permissions and limitations
  48518. * under the License.
  48519. */
  48520. extendChartView({
  48521. type: 'lines',
  48522. init: function () {},
  48523. render: function (seriesModel, ecModel, api) {
  48524. var data = seriesModel.getData();
  48525. var lineDraw = this._updateLineDraw(data, seriesModel);
  48526. var zlevel = seriesModel.get('zlevel');
  48527. var trailLength = seriesModel.get('effect.trailLength');
  48528. var zr = api.getZr(); // Avoid the drag cause ghost shadow
  48529. // FIXME Better way ?
  48530. // SVG doesn't support
  48531. var isSvg = zr.painter.getType() === 'svg';
  48532. if (!isSvg) {
  48533. zr.painter.getLayer(zlevel).clear(true);
  48534. } // Config layer with motion blur
  48535. if (this._lastZlevel != null && !isSvg) {
  48536. zr.configLayer(this._lastZlevel, {
  48537. motionBlur: false
  48538. });
  48539. }
  48540. if (this._showEffect(seriesModel) && trailLength) {
  48541. if (!isSvg) {
  48542. zr.configLayer(zlevel, {
  48543. motionBlur: true,
  48544. lastFrameAlpha: Math.max(Math.min(trailLength / 10 + 0.9, 1), 0)
  48545. });
  48546. }
  48547. }
  48548. lineDraw.updateData(data);
  48549. var clipPath = seriesModel.get('clip', true) && createClipPath(seriesModel.coordinateSystem, false, seriesModel);
  48550. if (clipPath) {
  48551. this.group.setClipPath(clipPath);
  48552. } else {
  48553. this.group.removeClipPath();
  48554. }
  48555. this._lastZlevel = zlevel;
  48556. this._finished = true;
  48557. },
  48558. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  48559. var data = seriesModel.getData();
  48560. var lineDraw = this._updateLineDraw(data, seriesModel);
  48561. lineDraw.incrementalPrepareUpdate(data);
  48562. this._clearLayer(api);
  48563. this._finished = false;
  48564. },
  48565. incrementalRender: function (taskParams, seriesModel, ecModel) {
  48566. this._lineDraw.incrementalUpdate(taskParams, seriesModel.getData());
  48567. this._finished = taskParams.end === seriesModel.getData().count();
  48568. },
  48569. updateTransform: function (seriesModel, ecModel, api) {
  48570. var data = seriesModel.getData();
  48571. var pipelineContext = seriesModel.pipelineContext;
  48572. if (!this._finished || pipelineContext.large || pipelineContext.progressiveRender) {
  48573. // TODO Don't have to do update in large mode. Only do it when there are millions of data.
  48574. return {
  48575. update: true
  48576. };
  48577. } else {
  48578. // TODO Use same logic with ScatterView.
  48579. // Manually update layout
  48580. var res = linesLayout.reset(seriesModel);
  48581. if (res.progress) {
  48582. res.progress({
  48583. start: 0,
  48584. end: data.count()
  48585. }, data);
  48586. }
  48587. this._lineDraw.updateLayout();
  48588. this._clearLayer(api);
  48589. }
  48590. },
  48591. _updateLineDraw: function (data, seriesModel) {
  48592. var lineDraw = this._lineDraw;
  48593. var hasEffect = this._showEffect(seriesModel);
  48594. var isPolyline = !!seriesModel.get('polyline');
  48595. var pipelineContext = seriesModel.pipelineContext;
  48596. var isLargeDraw = pipelineContext.large;
  48597. if (!lineDraw || hasEffect !== this._hasEffet || isPolyline !== this._isPolyline || isLargeDraw !== this._isLargeDraw) {
  48598. if (lineDraw) {
  48599. lineDraw.remove();
  48600. }
  48601. lineDraw = this._lineDraw = isLargeDraw ? new LargeLineDraw() : new LineDraw(isPolyline ? hasEffect ? EffectPolyline : Polyline$2 : hasEffect ? EffectLine : Line$1);
  48602. this._hasEffet = hasEffect;
  48603. this._isPolyline = isPolyline;
  48604. this._isLargeDraw = isLargeDraw;
  48605. this.group.removeAll();
  48606. }
  48607. this.group.add(lineDraw.group);
  48608. return lineDraw;
  48609. },
  48610. _showEffect: function (seriesModel) {
  48611. return !!seriesModel.get('effect.show');
  48612. },
  48613. _clearLayer: function (api) {
  48614. // Not use motion when dragging or zooming
  48615. var zr = api.getZr();
  48616. var isSvg = zr.painter.getType() === 'svg';
  48617. if (!isSvg && this._lastZlevel != null) {
  48618. zr.painter.getLayer(this._lastZlevel).clear(true);
  48619. }
  48620. },
  48621. remove: function (ecModel, api) {
  48622. this._lineDraw && this._lineDraw.remove();
  48623. this._lineDraw = null; // Clear motion when lineDraw is removed
  48624. this._clearLayer(api);
  48625. },
  48626. dispose: function () {}
  48627. });
  48628. /*
  48629. * Licensed to the Apache Software Foundation (ASF) under one
  48630. * or more contributor license agreements. See the NOTICE file
  48631. * distributed with this work for additional information
  48632. * regarding copyright ownership. The ASF licenses this file
  48633. * to you under the Apache License, Version 2.0 (the
  48634. * "License"); you may not use this file except in compliance
  48635. * with the License. You may obtain a copy of the License at
  48636. *
  48637. * http://www.apache.org/licenses/LICENSE-2.0
  48638. *
  48639. * Unless required by applicable law or agreed to in writing,
  48640. * software distributed under the License is distributed on an
  48641. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48642. * KIND, either express or implied. See the License for the
  48643. * specific language governing permissions and limitations
  48644. * under the License.
  48645. */
  48646. function normalize$1(a) {
  48647. if (!(a instanceof Array)) {
  48648. a = [a, a];
  48649. }
  48650. return a;
  48651. }
  48652. var opacityQuery = 'lineStyle.opacity'.split('.');
  48653. var linesVisual = {
  48654. seriesType: 'lines',
  48655. reset: function (seriesModel, ecModel, api) {
  48656. var symbolType = normalize$1(seriesModel.get('symbol'));
  48657. var symbolSize = normalize$1(seriesModel.get('symbolSize'));
  48658. var data = seriesModel.getData();
  48659. data.setVisual('fromSymbol', symbolType && symbolType[0]);
  48660. data.setVisual('toSymbol', symbolType && symbolType[1]);
  48661. data.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  48662. data.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  48663. data.setVisual('opacity', seriesModel.get(opacityQuery));
  48664. function dataEach(data, idx) {
  48665. var itemModel = data.getItemModel(idx);
  48666. var symbolType = normalize$1(itemModel.getShallow('symbol', true));
  48667. var symbolSize = normalize$1(itemModel.getShallow('symbolSize', true));
  48668. var opacity = itemModel.get(opacityQuery);
  48669. symbolType[0] && data.setItemVisual(idx, 'fromSymbol', symbolType[0]);
  48670. symbolType[1] && data.setItemVisual(idx, 'toSymbol', symbolType[1]);
  48671. symbolSize[0] && data.setItemVisual(idx, 'fromSymbolSize', symbolSize[0]);
  48672. symbolSize[1] && data.setItemVisual(idx, 'toSymbolSize', symbolSize[1]);
  48673. data.setItemVisual(idx, 'opacity', opacity);
  48674. }
  48675. return {
  48676. dataEach: data.hasItemOption ? dataEach : null
  48677. };
  48678. }
  48679. };
  48680. /*
  48681. * Licensed to the Apache Software Foundation (ASF) under one
  48682. * or more contributor license agreements. See the NOTICE file
  48683. * distributed with this work for additional information
  48684. * regarding copyright ownership. The ASF licenses this file
  48685. * to you under the Apache License, Version 2.0 (the
  48686. * "License"); you may not use this file except in compliance
  48687. * with the License. You may obtain a copy of the License at
  48688. *
  48689. * http://www.apache.org/licenses/LICENSE-2.0
  48690. *
  48691. * Unless required by applicable law or agreed to in writing,
  48692. * software distributed under the License is distributed on an
  48693. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48694. * KIND, either express or implied. See the License for the
  48695. * specific language governing permissions and limitations
  48696. * under the License.
  48697. */
  48698. registerLayout(linesLayout);
  48699. registerVisual(linesVisual);
  48700. /*
  48701. * Licensed to the Apache Software Foundation (ASF) under one
  48702. * or more contributor license agreements. See the NOTICE file
  48703. * distributed with this work for additional information
  48704. * regarding copyright ownership. The ASF licenses this file
  48705. * to you under the Apache License, Version 2.0 (the
  48706. * "License"); you may not use this file except in compliance
  48707. * with the License. You may obtain a copy of the License at
  48708. *
  48709. * http://www.apache.org/licenses/LICENSE-2.0
  48710. *
  48711. * Unless required by applicable law or agreed to in writing,
  48712. * software distributed under the License is distributed on an
  48713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  48714. * KIND, either express or implied. See the License for the
  48715. * specific language governing permissions and limitations
  48716. * under the License.
  48717. */
  48718. function generateNodeKey(id) {
  48719. return '_EC_' + id;
  48720. }
  48721. /**
  48722. * @alias module:echarts/data/Graph
  48723. * @constructor
  48724. * @param {boolean} directed
  48725. */
  48726. var Graph = function (directed) {
  48727. /**
  48728. * 是否是有向图
  48729. * @type {boolean}
  48730. * @private
  48731. */
  48732. this._directed = directed || false;
  48733. /**
  48734. * @type {Array.<module:echarts/data/Graph.Node>}
  48735. * @readOnly
  48736. */
  48737. this.nodes = [];
  48738. /**
  48739. * @type {Array.<module:echarts/data/Graph.Edge>}
  48740. * @readOnly
  48741. */
  48742. this.edges = [];
  48743. /**
  48744. * @type {Object.<string, module:echarts/data/Graph.Node>}
  48745. * @private
  48746. */
  48747. this._nodesMap = {};
  48748. /**
  48749. * @type {Object.<string, module:echarts/data/Graph.Edge>}
  48750. * @private
  48751. */
  48752. this._edgesMap = {};
  48753. /**
  48754. * @type {module:echarts/data/List}
  48755. * @readOnly
  48756. */
  48757. this.data;
  48758. /**
  48759. * @type {module:echarts/data/List}
  48760. * @readOnly
  48761. */
  48762. this.edgeData;
  48763. };
  48764. var graphProto = Graph.prototype;
  48765. /**
  48766. * @type {string}
  48767. */
  48768. graphProto.type = 'graph';
  48769. /**
  48770. * If is directed graph
  48771. * @return {boolean}
  48772. */
  48773. graphProto.isDirected = function () {
  48774. return this._directed;
  48775. };
  48776. /**
  48777. * Add a new node
  48778. * @param {string} id
  48779. * @param {number} [dataIndex]
  48780. */
  48781. graphProto.addNode = function (id, dataIndex) {
  48782. id = id == null ? '' + dataIndex : '' + id;
  48783. var nodesMap = this._nodesMap;
  48784. if (nodesMap[generateNodeKey(id)]) {
  48785. return;
  48786. }
  48787. var node = new Node(id, dataIndex);
  48788. node.hostGraph = this;
  48789. this.nodes.push(node);
  48790. nodesMap[generateNodeKey(id)] = node;
  48791. return node;
  48792. };
  48793. /**
  48794. * Get node by data index
  48795. * @param {number} dataIndex
  48796. * @return {module:echarts/data/Graph~Node}
  48797. */
  48798. graphProto.getNodeByIndex = function (dataIndex) {
  48799. var rawIdx = this.data.getRawIndex(dataIndex);
  48800. return this.nodes[rawIdx];
  48801. };
  48802. /**
  48803. * Get node by id
  48804. * @param {string} id
  48805. * @return {module:echarts/data/Graph.Node}
  48806. */
  48807. graphProto.getNodeById = function (id) {
  48808. return this._nodesMap[generateNodeKey(id)];
  48809. };
  48810. /**
  48811. * Add a new edge
  48812. * @param {number|string|module:echarts/data/Graph.Node} n1
  48813. * @param {number|string|module:echarts/data/Graph.Node} n2
  48814. * @param {number} [dataIndex=-1]
  48815. * @return {module:echarts/data/Graph.Edge}
  48816. */
  48817. graphProto.addEdge = function (n1, n2, dataIndex) {
  48818. var nodesMap = this._nodesMap;
  48819. var edgesMap = this._edgesMap; // PNEDING
  48820. if (typeof n1 === 'number') {
  48821. n1 = this.nodes[n1];
  48822. }
  48823. if (typeof n2 === 'number') {
  48824. n2 = this.nodes[n2];
  48825. }
  48826. if (!Node.isInstance(n1)) {
  48827. n1 = nodesMap[generateNodeKey(n1)];
  48828. }
  48829. if (!Node.isInstance(n2)) {
  48830. n2 = nodesMap[generateNodeKey(n2)];
  48831. }
  48832. if (!n1 || !n2) {
  48833. return;
  48834. }
  48835. var key = n1.id + '-' + n2.id; // PENDING
  48836. if (edgesMap[key]) {
  48837. return;
  48838. }
  48839. var edge = new Edge(n1, n2, dataIndex);
  48840. edge.hostGraph = this;
  48841. if (this._directed) {
  48842. n1.outEdges.push(edge);
  48843. n2.inEdges.push(edge);
  48844. }
  48845. n1.edges.push(edge);
  48846. if (n1 !== n2) {
  48847. n2.edges.push(edge);
  48848. }
  48849. this.edges.push(edge);
  48850. edgesMap[key] = edge;
  48851. return edge;
  48852. };
  48853. /**
  48854. * Get edge by data index
  48855. * @param {number} dataIndex
  48856. * @return {module:echarts/data/Graph~Node}
  48857. */
  48858. graphProto.getEdgeByIndex = function (dataIndex) {
  48859. var rawIdx = this.edgeData.getRawIndex(dataIndex);
  48860. return this.edges[rawIdx];
  48861. };
  48862. /**
  48863. * Get edge by two linked nodes
  48864. * @param {module:echarts/data/Graph.Node|string} n1
  48865. * @param {module:echarts/data/Graph.Node|string} n2
  48866. * @return {module:echarts/data/Graph.Edge}
  48867. */
  48868. graphProto.getEdge = function (n1, n2) {
  48869. if (Node.isInstance(n1)) {
  48870. n1 = n1.id;
  48871. }
  48872. if (Node.isInstance(n2)) {
  48873. n2 = n2.id;
  48874. }
  48875. var edgesMap = this._edgesMap;
  48876. if (this._directed) {
  48877. return edgesMap[n1 + '-' + n2];
  48878. } else {
  48879. return edgesMap[n1 + '-' + n2] || edgesMap[n2 + '-' + n1];
  48880. }
  48881. };
  48882. /**
  48883. * Iterate all nodes
  48884. * @param {Function} cb
  48885. * @param {*} [context]
  48886. */
  48887. graphProto.eachNode = function (cb, context) {
  48888. var nodes = this.nodes;
  48889. var len = nodes.length;
  48890. for (var i = 0; i < len; i++) {
  48891. if (nodes[i].dataIndex >= 0) {
  48892. cb.call(context, nodes[i], i);
  48893. }
  48894. }
  48895. };
  48896. /**
  48897. * Iterate all edges
  48898. * @param {Function} cb
  48899. * @param {*} [context]
  48900. */
  48901. graphProto.eachEdge = function (cb, context) {
  48902. var edges = this.edges;
  48903. var len = edges.length;
  48904. for (var i = 0; i < len; i++) {
  48905. if (edges[i].dataIndex >= 0 && edges[i].node1.dataIndex >= 0 && edges[i].node2.dataIndex >= 0) {
  48906. cb.call(context, edges[i], i);
  48907. }
  48908. }
  48909. };
  48910. /**
  48911. * Breadth first traverse
  48912. * @param {Function} cb
  48913. * @param {module:echarts/data/Graph.Node} startNode
  48914. * @param {string} [direction='none'] 'none'|'in'|'out'
  48915. * @param {*} [context]
  48916. */
  48917. graphProto.breadthFirstTraverse = function (cb, startNode, direction, context) {
  48918. if (!Node.isInstance(startNode)) {
  48919. startNode = this._nodesMap[generateNodeKey(startNode)];
  48920. }
  48921. if (!startNode) {
  48922. return;
  48923. }
  48924. var edgeType = direction === 'out' ? 'outEdges' : direction === 'in' ? 'inEdges' : 'edges';
  48925. for (var i = 0; i < this.nodes.length; i++) {
  48926. this.nodes[i].__visited = false;
  48927. }
  48928. if (cb.call(context, startNode, null)) {
  48929. return;
  48930. }
  48931. var queue = [startNode];
  48932. while (queue.length) {
  48933. var currentNode = queue.shift();
  48934. var edges = currentNode[edgeType];
  48935. for (var i = 0; i < edges.length; i++) {
  48936. var e = edges[i];
  48937. var otherNode = e.node1 === currentNode ? e.node2 : e.node1;
  48938. if (!otherNode.__visited) {
  48939. if (cb.call(context, otherNode, currentNode)) {
  48940. // Stop traversing
  48941. return;
  48942. }
  48943. queue.push(otherNode);
  48944. otherNode.__visited = true;
  48945. }
  48946. }
  48947. }
  48948. }; // TODO
  48949. // graphProto.depthFirstTraverse = function (
  48950. // cb, startNode, direction, context
  48951. // ) {
  48952. // };
  48953. // Filter update
  48954. graphProto.update = function () {
  48955. var data = this.data;
  48956. var edgeData = this.edgeData;
  48957. var nodes = this.nodes;
  48958. var edges = this.edges;
  48959. for (var i = 0, len = nodes.length; i < len; i++) {
  48960. nodes[i].dataIndex = -1;
  48961. }
  48962. for (var i = 0, len = data.count(); i < len; i++) {
  48963. nodes[data.getRawIndex(i)].dataIndex = i;
  48964. }
  48965. edgeData.filterSelf(function (idx) {
  48966. var edge = edges[edgeData.getRawIndex(idx)];
  48967. return edge.node1.dataIndex >= 0 && edge.node2.dataIndex >= 0;
  48968. }); // Update edge
  48969. for (var i = 0, len = edges.length; i < len; i++) {
  48970. edges[i].dataIndex = -1;
  48971. }
  48972. for (var i = 0, len = edgeData.count(); i < len; i++) {
  48973. edges[edgeData.getRawIndex(i)].dataIndex = i;
  48974. }
  48975. };
  48976. /**
  48977. * @return {module:echarts/data/Graph}
  48978. */
  48979. graphProto.clone = function () {
  48980. var graph = new Graph(this._directed);
  48981. var nodes = this.nodes;
  48982. var edges = this.edges;
  48983. for (var i = 0; i < nodes.length; i++) {
  48984. graph.addNode(nodes[i].id, nodes[i].dataIndex);
  48985. }
  48986. for (var i = 0; i < edges.length; i++) {
  48987. var e = edges[i];
  48988. graph.addEdge(e.node1.id, e.node2.id, e.dataIndex);
  48989. }
  48990. return graph;
  48991. };
  48992. /**
  48993. * @alias module:echarts/data/Graph.Node
  48994. */
  48995. function Node(id, dataIndex) {
  48996. /**
  48997. * @type {string}
  48998. */
  48999. this.id = id == null ? '' : id;
  49000. /**
  49001. * @type {Array.<module:echarts/data/Graph.Edge>}
  49002. */
  49003. this.inEdges = [];
  49004. /**
  49005. * @type {Array.<module:echarts/data/Graph.Edge>}
  49006. */
  49007. this.outEdges = [];
  49008. /**
  49009. * @type {Array.<module:echarts/data/Graph.Edge>}
  49010. */
  49011. this.edges = [];
  49012. /**
  49013. * @type {module:echarts/data/Graph}
  49014. */
  49015. this.hostGraph;
  49016. /**
  49017. * @type {number}
  49018. */
  49019. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  49020. }
  49021. Node.prototype = {
  49022. constructor: Node,
  49023. /**
  49024. * @return {number}
  49025. */
  49026. degree: function () {
  49027. return this.edges.length;
  49028. },
  49029. /**
  49030. * @return {number}
  49031. */
  49032. inDegree: function () {
  49033. return this.inEdges.length;
  49034. },
  49035. /**
  49036. * @return {number}
  49037. */
  49038. outDegree: function () {
  49039. return this.outEdges.length;
  49040. },
  49041. /**
  49042. * @param {string} [path]
  49043. * @return {module:echarts/model/Model}
  49044. */
  49045. getModel: function (path) {
  49046. if (this.dataIndex < 0) {
  49047. return;
  49048. }
  49049. var graph = this.hostGraph;
  49050. var itemModel = graph.data.getItemModel(this.dataIndex);
  49051. return itemModel.getModel(path);
  49052. }
  49053. };
  49054. /**
  49055. * 图边
  49056. * @alias module:echarts/data/Graph.Edge
  49057. * @param {module:echarts/data/Graph.Node} n1
  49058. * @param {module:echarts/data/Graph.Node} n2
  49059. * @param {number} [dataIndex=-1]
  49060. */
  49061. function Edge(n1, n2, dataIndex) {
  49062. /**
  49063. * 节点1,如果是有向图则为源节点
  49064. * @type {module:echarts/data/Graph.Node}
  49065. */
  49066. this.node1 = n1;
  49067. /**
  49068. * 节点2,如果是有向图则为目标节点
  49069. * @type {module:echarts/data/Graph.Node}
  49070. */
  49071. this.node2 = n2;
  49072. this.dataIndex = dataIndex == null ? -1 : dataIndex;
  49073. }
  49074. /**
  49075. * @param {string} [path]
  49076. * @return {module:echarts/model/Model}
  49077. */
  49078. Edge.prototype.getModel = function (path) {
  49079. if (this.dataIndex < 0) {
  49080. return;
  49081. }
  49082. var graph = this.hostGraph;
  49083. var itemModel = graph.edgeData.getItemModel(this.dataIndex);
  49084. return itemModel.getModel(path);
  49085. };
  49086. var createGraphDataProxyMixin = function (hostName, dataName) {
  49087. return {
  49088. /**
  49089. * @param {string=} [dimension='value'] Default 'value'. can be 'a', 'b', 'c', 'd', 'e'.
  49090. * @return {number}
  49091. */
  49092. getValue: function (dimension) {
  49093. var data = this[hostName][dataName];
  49094. return data.get(data.getDimension(dimension || 'value'), this.dataIndex);
  49095. },
  49096. /**
  49097. * @param {Object|string} key
  49098. * @param {*} [value]
  49099. */
  49100. setVisual: function (key, value) {
  49101. this.dataIndex >= 0 && this[hostName][dataName].setItemVisual(this.dataIndex, key, value);
  49102. },
  49103. /**
  49104. * @param {string} key
  49105. * @return {boolean}
  49106. */
  49107. getVisual: function (key, ignoreParent) {
  49108. return this[hostName][dataName].getItemVisual(this.dataIndex, key, ignoreParent);
  49109. },
  49110. /**
  49111. * @param {Object} layout
  49112. * @return {boolean} [merge=false]
  49113. */
  49114. setLayout: function (layout, merge$$1) {
  49115. this.dataIndex >= 0 && this[hostName][dataName].setItemLayout(this.dataIndex, layout, merge$$1);
  49116. },
  49117. /**
  49118. * @return {Object}
  49119. */
  49120. getLayout: function () {
  49121. return this[hostName][dataName].getItemLayout(this.dataIndex);
  49122. },
  49123. /**
  49124. * @return {module:zrender/Element}
  49125. */
  49126. getGraphicEl: function () {
  49127. return this[hostName][dataName].getItemGraphicEl(this.dataIndex);
  49128. },
  49129. /**
  49130. * @return {number}
  49131. */
  49132. getRawIndex: function () {
  49133. return this[hostName][dataName].getRawIndex(this.dataIndex);
  49134. }
  49135. };
  49136. };
  49137. mixin(Node, createGraphDataProxyMixin('hostGraph', 'data'));
  49138. mixin(Edge, createGraphDataProxyMixin('hostGraph', 'edgeData'));
  49139. Graph.Node = Node;
  49140. Graph.Edge = Edge;
  49141. enableClassCheck(Node);
  49142. enableClassCheck(Edge);
  49143. /*
  49144. * Licensed to the Apache Software Foundation (ASF) under one
  49145. * or more contributor license agreements. See the NOTICE file
  49146. * distributed with this work for additional information
  49147. * regarding copyright ownership. The ASF licenses this file
  49148. * to you under the Apache License, Version 2.0 (the
  49149. * "License"); you may not use this file except in compliance
  49150. * with the License. You may obtain a copy of the License at
  49151. *
  49152. * http://www.apache.org/licenses/LICENSE-2.0
  49153. *
  49154. * Unless required by applicable law or agreed to in writing,
  49155. * software distributed under the License is distributed on an
  49156. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49157. * KIND, either express or implied. See the License for the
  49158. * specific language governing permissions and limitations
  49159. * under the License.
  49160. */
  49161. var createGraphFromNodeEdge = function (nodes, edges, seriesModel, directed, beforeLink) {
  49162. // ??? TODO
  49163. // support dataset?
  49164. var graph = new Graph(directed);
  49165. for (var i = 0; i < nodes.length; i++) {
  49166. graph.addNode(retrieve( // Id, name, dataIndex
  49167. nodes[i].id, nodes[i].name, i), i);
  49168. }
  49169. var linkNameList = [];
  49170. var validEdges = [];
  49171. var linkCount = 0;
  49172. for (var i = 0; i < edges.length; i++) {
  49173. var link = edges[i];
  49174. var source = link.source;
  49175. var target = link.target; // addEdge may fail when source or target not exists
  49176. if (graph.addEdge(source, target, linkCount)) {
  49177. validEdges.push(link);
  49178. linkNameList.push(retrieve(link.id, source + ' > ' + target));
  49179. linkCount++;
  49180. }
  49181. }
  49182. var coordSys = seriesModel.get('coordinateSystem');
  49183. var nodeData;
  49184. if (coordSys === 'cartesian2d' || coordSys === 'polar') {
  49185. nodeData = createListFromArray(nodes, seriesModel);
  49186. } else {
  49187. var coordSysCtor = CoordinateSystemManager.get(coordSys);
  49188. var coordDimensions = coordSysCtor && coordSysCtor.type !== 'view' ? coordSysCtor.dimensions || [] : []; // FIXME: Some geo do not need `value` dimenson, whereas `calendar` needs
  49189. // `value` dimension, but graph need `value` dimension. It's better to
  49190. // uniform this behavior.
  49191. if (indexOf(coordDimensions, 'value') < 0) {
  49192. coordDimensions.concat(['value']);
  49193. }
  49194. var dimensionNames = createDimensions(nodes, {
  49195. coordDimensions: coordDimensions
  49196. });
  49197. nodeData = new List(dimensionNames, seriesModel);
  49198. nodeData.initData(nodes);
  49199. }
  49200. var edgeData = new List(['value'], seriesModel);
  49201. edgeData.initData(validEdges, linkNameList);
  49202. beforeLink && beforeLink(nodeData, edgeData);
  49203. linkList({
  49204. mainData: nodeData,
  49205. struct: graph,
  49206. structAttr: 'graph',
  49207. datas: {
  49208. node: nodeData,
  49209. edge: edgeData
  49210. },
  49211. datasAttr: {
  49212. node: 'data',
  49213. edge: 'edgeData'
  49214. }
  49215. }); // Update dataIndex of nodes and edges because invalid edge may be removed
  49216. graph.update();
  49217. return graph;
  49218. };
  49219. /*
  49220. * Licensed to the Apache Software Foundation (ASF) under one
  49221. * or more contributor license agreements. See the NOTICE file
  49222. * distributed with this work for additional information
  49223. * regarding copyright ownership. The ASF licenses this file
  49224. * to you under the Apache License, Version 2.0 (the
  49225. * "License"); you may not use this file except in compliance
  49226. * with the License. You may obtain a copy of the License at
  49227. *
  49228. * http://www.apache.org/licenses/LICENSE-2.0
  49229. *
  49230. * Unless required by applicable law or agreed to in writing,
  49231. * software distributed under the License is distributed on an
  49232. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49233. * KIND, either express or implied. See the License for the
  49234. * specific language governing permissions and limitations
  49235. * under the License.
  49236. */
  49237. var GraphSeries = extendSeriesModel({
  49238. type: 'series.graph',
  49239. init: function (option) {
  49240. GraphSeries.superApply(this, 'init', arguments);
  49241. var self = this;
  49242. function getCategoriesData() {
  49243. return self._categoriesData;
  49244. } // Provide data for legend select
  49245. this.legendVisualProvider = new LegendVisualProvider(getCategoriesData, getCategoriesData);
  49246. this.fillDataTextStyle(option.edges || option.links);
  49247. this._updateCategoriesData();
  49248. },
  49249. mergeOption: function (option) {
  49250. GraphSeries.superApply(this, 'mergeOption', arguments);
  49251. this.fillDataTextStyle(option.edges || option.links);
  49252. this._updateCategoriesData();
  49253. },
  49254. mergeDefaultAndTheme: function (option) {
  49255. GraphSeries.superApply(this, 'mergeDefaultAndTheme', arguments);
  49256. defaultEmphasis(option, ['edgeLabel'], ['show']);
  49257. },
  49258. getInitialData: function (option, ecModel) {
  49259. var edges = option.edges || option.links || [];
  49260. var nodes = option.data || option.nodes || [];
  49261. var self = this;
  49262. if (nodes && edges) {
  49263. return createGraphFromNodeEdge(nodes, edges, this, true, beforeLink).data;
  49264. }
  49265. function beforeLink(nodeData, edgeData) {
  49266. // Overwrite nodeData.getItemModel to
  49267. nodeData.wrapMethod('getItemModel', function (model) {
  49268. var categoriesModels = self._categoriesModels;
  49269. var categoryIdx = model.getShallow('category');
  49270. var categoryModel = categoriesModels[categoryIdx];
  49271. if (categoryModel) {
  49272. categoryModel.parentModel = model.parentModel;
  49273. model.parentModel = categoryModel;
  49274. }
  49275. return model;
  49276. });
  49277. var edgeLabelModel = self.getModel('edgeLabel'); // For option `edgeLabel` can be found by label.xxx.xxx on item mode.
  49278. var fakeSeriesModel = new Model({
  49279. label: edgeLabelModel.option
  49280. }, edgeLabelModel.parentModel, ecModel);
  49281. var emphasisEdgeLabelModel = self.getModel('emphasis.edgeLabel');
  49282. var emphasisFakeSeriesModel = new Model({
  49283. emphasis: {
  49284. label: emphasisEdgeLabelModel.option
  49285. }
  49286. }, emphasisEdgeLabelModel.parentModel, ecModel);
  49287. edgeData.wrapMethod('getItemModel', function (model) {
  49288. model.customizeGetParent(edgeGetParent);
  49289. return model;
  49290. });
  49291. function edgeGetParent(path) {
  49292. path = this.parsePath(path);
  49293. return path && path[0] === 'label' ? fakeSeriesModel : path && path[0] === 'emphasis' && path[1] === 'label' ? emphasisFakeSeriesModel : this.parentModel;
  49294. }
  49295. }
  49296. },
  49297. /**
  49298. * @return {module:echarts/data/Graph}
  49299. */
  49300. getGraph: function () {
  49301. return this.getData().graph;
  49302. },
  49303. /**
  49304. * @return {module:echarts/data/List}
  49305. */
  49306. getEdgeData: function () {
  49307. return this.getGraph().edgeData;
  49308. },
  49309. /**
  49310. * @return {module:echarts/data/List}
  49311. */
  49312. getCategoriesData: function () {
  49313. return this._categoriesData;
  49314. },
  49315. /**
  49316. * @override
  49317. */
  49318. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  49319. if (dataType === 'edge') {
  49320. var nodeData = this.getData();
  49321. var params = this.getDataParams(dataIndex, dataType);
  49322. var edge = nodeData.graph.getEdgeByIndex(dataIndex);
  49323. var sourceName = nodeData.getName(edge.node1.dataIndex);
  49324. var targetName = nodeData.getName(edge.node2.dataIndex);
  49325. var html = [];
  49326. sourceName != null && html.push(sourceName);
  49327. targetName != null && html.push(targetName);
  49328. html = encodeHTML(html.join(' > '));
  49329. if (params.value) {
  49330. html += ' : ' + encodeHTML(params.value);
  49331. }
  49332. return html;
  49333. } else {
  49334. // dataType === 'node' or empty
  49335. return GraphSeries.superApply(this, 'formatTooltip', arguments);
  49336. }
  49337. },
  49338. _updateCategoriesData: function () {
  49339. var categories = map(this.option.categories || [], function (category) {
  49340. // Data must has value
  49341. return category.value != null ? category : extend({
  49342. value: 0
  49343. }, category);
  49344. });
  49345. var categoriesData = new List(['value'], this);
  49346. categoriesData.initData(categories);
  49347. this._categoriesData = categoriesData;
  49348. this._categoriesModels = categoriesData.mapArray(function (idx) {
  49349. return categoriesData.getItemModel(idx, true);
  49350. });
  49351. },
  49352. setZoom: function (zoom) {
  49353. this.option.zoom = zoom;
  49354. },
  49355. setCenter: function (center) {
  49356. this.option.center = center;
  49357. },
  49358. isAnimationEnabled: function () {
  49359. return GraphSeries.superCall(this, 'isAnimationEnabled') // Not enable animation when do force layout
  49360. && !(this.get('layout') === 'force' && this.get('force.layoutAnimation'));
  49361. },
  49362. defaultOption: {
  49363. zlevel: 0,
  49364. z: 2,
  49365. coordinateSystem: 'view',
  49366. // Default option for all coordinate systems
  49367. // xAxisIndex: 0,
  49368. // yAxisIndex: 0,
  49369. // polarIndex: 0,
  49370. // geoIndex: 0,
  49371. legendHoverLink: true,
  49372. hoverAnimation: true,
  49373. layout: null,
  49374. focusNodeAdjacency: false,
  49375. // Configuration of circular layout
  49376. circular: {
  49377. rotateLabel: false
  49378. },
  49379. // Configuration of force directed layout
  49380. force: {
  49381. initLayout: null,
  49382. // Node repulsion. Can be an array to represent range.
  49383. repulsion: [0, 50],
  49384. gravity: 0.1,
  49385. // Initial friction
  49386. friction: 0.6,
  49387. // Edge length. Can be an array to represent range.
  49388. edgeLength: 30,
  49389. layoutAnimation: true
  49390. },
  49391. left: 'center',
  49392. top: 'center',
  49393. // right: null,
  49394. // bottom: null,
  49395. // width: '80%',
  49396. // height: '80%',
  49397. symbol: 'circle',
  49398. symbolSize: 10,
  49399. edgeSymbol: ['none', 'none'],
  49400. edgeSymbolSize: 10,
  49401. edgeLabel: {
  49402. position: 'middle',
  49403. distance: 5
  49404. },
  49405. draggable: false,
  49406. roam: false,
  49407. // Default on center of graph
  49408. center: null,
  49409. zoom: 1,
  49410. // Symbol size scale ratio in roam
  49411. nodeScaleRatio: 0.6,
  49412. // cursor: null,
  49413. // categories: [],
  49414. // data: []
  49415. // Or
  49416. // nodes: []
  49417. //
  49418. // links: []
  49419. // Or
  49420. // edges: []
  49421. label: {
  49422. show: false,
  49423. formatter: '{b}'
  49424. },
  49425. itemStyle: {},
  49426. lineStyle: {
  49427. color: '#aaa',
  49428. width: 1,
  49429. curveness: 0,
  49430. opacity: 0.5
  49431. },
  49432. emphasis: {
  49433. label: {
  49434. show: true
  49435. }
  49436. }
  49437. }
  49438. });
  49439. /*
  49440. * Licensed to the Apache Software Foundation (ASF) under one
  49441. * or more contributor license agreements. See the NOTICE file
  49442. * distributed with this work for additional information
  49443. * regarding copyright ownership. The ASF licenses this file
  49444. * to you under the Apache License, Version 2.0 (the
  49445. * "License"); you may not use this file except in compliance
  49446. * with the License. You may obtain a copy of the License at
  49447. *
  49448. * http://www.apache.org/licenses/LICENSE-2.0
  49449. *
  49450. * Unless required by applicable law or agreed to in writing,
  49451. * software distributed under the License is distributed on an
  49452. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49453. * KIND, either express or implied. See the License for the
  49454. * specific language governing permissions and limitations
  49455. * under the License.
  49456. */
  49457. function getNodeGlobalScale(seriesModel) {
  49458. var coordSys = seriesModel.coordinateSystem;
  49459. if (coordSys.type !== 'view') {
  49460. return 1;
  49461. }
  49462. var nodeScaleRatio = seriesModel.option.nodeScaleRatio;
  49463. var groupScale = coordSys.scale;
  49464. var groupZoom = groupScale && groupScale[0] || 1; // Scale node when zoom changes
  49465. var roamZoom = coordSys.getZoom();
  49466. var nodeScale = (roamZoom - 1) * nodeScaleRatio + 1;
  49467. return nodeScale / groupZoom;
  49468. }
  49469. function getSymbolSize$1(node) {
  49470. var symbolSize = node.getVisual('symbolSize');
  49471. if (symbolSize instanceof Array) {
  49472. symbolSize = (symbolSize[0] + symbolSize[1]) / 2;
  49473. }
  49474. return +symbolSize;
  49475. }
  49476. /*
  49477. * Licensed to the Apache Software Foundation (ASF) under one
  49478. * or more contributor license agreements. See the NOTICE file
  49479. * distributed with this work for additional information
  49480. * regarding copyright ownership. The ASF licenses this file
  49481. * to you under the Apache License, Version 2.0 (the
  49482. * "License"); you may not use this file except in compliance
  49483. * with the License. You may obtain a copy of the License at
  49484. *
  49485. * http://www.apache.org/licenses/LICENSE-2.0
  49486. *
  49487. * Unless required by applicable law or agreed to in writing,
  49488. * software distributed under the License is distributed on an
  49489. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49490. * KIND, either express or implied. See the License for the
  49491. * specific language governing permissions and limitations
  49492. * under the License.
  49493. */
  49494. var v1 = [];
  49495. var v2 = [];
  49496. var v3 = [];
  49497. var quadraticAt$1 = quadraticAt;
  49498. var v2DistSquare = distSquare;
  49499. var mathAbs$1 = Math.abs;
  49500. function intersectCurveCircle(curvePoints, center, radius) {
  49501. var p0 = curvePoints[0];
  49502. var p1 = curvePoints[1];
  49503. var p2 = curvePoints[2];
  49504. var d = Infinity;
  49505. var t;
  49506. var radiusSquare = radius * radius;
  49507. var interval = 0.1;
  49508. for (var _t = 0.1; _t <= 0.9; _t += 0.1) {
  49509. v1[0] = quadraticAt$1(p0[0], p1[0], p2[0], _t);
  49510. v1[1] = quadraticAt$1(p0[1], p1[1], p2[1], _t);
  49511. var diff = mathAbs$1(v2DistSquare(v1, center) - radiusSquare);
  49512. if (diff < d) {
  49513. d = diff;
  49514. t = _t;
  49515. }
  49516. } // Assume the segment is monotone,Find root through Bisection method
  49517. // At most 32 iteration
  49518. for (var i = 0; i < 32; i++) {
  49519. // var prev = t - interval;
  49520. var next = t + interval; // v1[0] = quadraticAt(p0[0], p1[0], p2[0], prev);
  49521. // v1[1] = quadraticAt(p0[1], p1[1], p2[1], prev);
  49522. v2[0] = quadraticAt$1(p0[0], p1[0], p2[0], t);
  49523. v2[1] = quadraticAt$1(p0[1], p1[1], p2[1], t);
  49524. v3[0] = quadraticAt$1(p0[0], p1[0], p2[0], next);
  49525. v3[1] = quadraticAt$1(p0[1], p1[1], p2[1], next);
  49526. var diff = v2DistSquare(v2, center) - radiusSquare;
  49527. if (mathAbs$1(diff) < 1e-2) {
  49528. break;
  49529. } // var prevDiff = v2DistSquare(v1, center) - radiusSquare;
  49530. var nextDiff = v2DistSquare(v3, center) - radiusSquare;
  49531. interval /= 2;
  49532. if (diff < 0) {
  49533. if (nextDiff >= 0) {
  49534. t = t + interval;
  49535. } else {
  49536. t = t - interval;
  49537. }
  49538. } else {
  49539. if (nextDiff >= 0) {
  49540. t = t - interval;
  49541. } else {
  49542. t = t + interval;
  49543. }
  49544. }
  49545. }
  49546. return t;
  49547. } // Adjust edge to avoid
  49548. var adjustEdge = function (graph, scale$$1) {
  49549. var tmp0 = [];
  49550. var quadraticSubdivide$$1 = quadraticSubdivide;
  49551. var pts = [[], [], []];
  49552. var pts2 = [[], []];
  49553. var v = [];
  49554. scale$$1 /= 2;
  49555. graph.eachEdge(function (edge, idx) {
  49556. var linePoints = edge.getLayout();
  49557. var fromSymbol = edge.getVisual('fromSymbol');
  49558. var toSymbol = edge.getVisual('toSymbol');
  49559. if (!linePoints.__original) {
  49560. linePoints.__original = [clone$1(linePoints[0]), clone$1(linePoints[1])];
  49561. if (linePoints[2]) {
  49562. linePoints.__original.push(clone$1(linePoints[2]));
  49563. }
  49564. }
  49565. var originalPoints = linePoints.__original; // Quadratic curve
  49566. if (linePoints[2] != null) {
  49567. copy(pts[0], originalPoints[0]);
  49568. copy(pts[1], originalPoints[2]);
  49569. copy(pts[2], originalPoints[1]);
  49570. if (fromSymbol && fromSymbol !== 'none') {
  49571. var symbolSize = getSymbolSize$1(edge.node1);
  49572. var t = intersectCurveCircle(pts, originalPoints[0], symbolSize * scale$$1); // Subdivide and get the second
  49573. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  49574. pts[0][0] = tmp0[3];
  49575. pts[1][0] = tmp0[4];
  49576. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  49577. pts[0][1] = tmp0[3];
  49578. pts[1][1] = tmp0[4];
  49579. }
  49580. if (toSymbol && toSymbol !== 'none') {
  49581. var symbolSize = getSymbolSize$1(edge.node2);
  49582. var t = intersectCurveCircle(pts, originalPoints[1], symbolSize * scale$$1); // Subdivide and get the first
  49583. quadraticSubdivide$$1(pts[0][0], pts[1][0], pts[2][0], t, tmp0);
  49584. pts[1][0] = tmp0[1];
  49585. pts[2][0] = tmp0[2];
  49586. quadraticSubdivide$$1(pts[0][1], pts[1][1], pts[2][1], t, tmp0);
  49587. pts[1][1] = tmp0[1];
  49588. pts[2][1] = tmp0[2];
  49589. } // Copy back to layout
  49590. copy(linePoints[0], pts[0]);
  49591. copy(linePoints[1], pts[2]);
  49592. copy(linePoints[2], pts[1]);
  49593. } // Line
  49594. else {
  49595. copy(pts2[0], originalPoints[0]);
  49596. copy(pts2[1], originalPoints[1]);
  49597. sub(v, pts2[1], pts2[0]);
  49598. normalize(v, v);
  49599. if (fromSymbol && fromSymbol !== 'none') {
  49600. var symbolSize = getSymbolSize$1(edge.node1);
  49601. scaleAndAdd(pts2[0], pts2[0], v, symbolSize * scale$$1);
  49602. }
  49603. if (toSymbol && toSymbol !== 'none') {
  49604. var symbolSize = getSymbolSize$1(edge.node2);
  49605. scaleAndAdd(pts2[1], pts2[1], v, -symbolSize * scale$$1);
  49606. }
  49607. copy(linePoints[0], pts2[0]);
  49608. copy(linePoints[1], pts2[1]);
  49609. }
  49610. });
  49611. };
  49612. /*
  49613. * Licensed to the Apache Software Foundation (ASF) under one
  49614. * or more contributor license agreements. See the NOTICE file
  49615. * distributed with this work for additional information
  49616. * regarding copyright ownership. The ASF licenses this file
  49617. * to you under the Apache License, Version 2.0 (the
  49618. * "License"); you may not use this file except in compliance
  49619. * with the License. You may obtain a copy of the License at
  49620. *
  49621. * http://www.apache.org/licenses/LICENSE-2.0
  49622. *
  49623. * Unless required by applicable law or agreed to in writing,
  49624. * software distributed under the License is distributed on an
  49625. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49626. * KIND, either express or implied. See the License for the
  49627. * specific language governing permissions and limitations
  49628. * under the License.
  49629. */
  49630. var FOCUS_ADJACENCY = '__focusNodeAdjacency';
  49631. var UNFOCUS_ADJACENCY = '__unfocusNodeAdjacency';
  49632. var nodeOpacityPath = ['itemStyle', 'opacity'];
  49633. var lineOpacityPath = ['lineStyle', 'opacity'];
  49634. function getItemOpacity(item, opacityPath) {
  49635. var opacity = item.getVisual('opacity');
  49636. return opacity != null ? opacity : item.getModel().get(opacityPath);
  49637. }
  49638. function fadeOutItem(item, opacityPath, opacityRatio) {
  49639. var el = item.getGraphicEl();
  49640. var opacity = getItemOpacity(item, opacityPath);
  49641. if (opacityRatio != null) {
  49642. opacity == null && (opacity = 1);
  49643. opacity *= opacityRatio;
  49644. }
  49645. el.downplay && el.downplay();
  49646. el.traverse(function (child) {
  49647. if (!child.isGroup) {
  49648. var opct = child.lineLabelOriginalOpacity;
  49649. if (opct == null || opacityRatio != null) {
  49650. opct = opacity;
  49651. }
  49652. child.setStyle('opacity', opct);
  49653. }
  49654. });
  49655. }
  49656. function fadeInItem(item, opacityPath) {
  49657. var opacity = getItemOpacity(item, opacityPath);
  49658. var el = item.getGraphicEl(); // Should go back to normal opacity first, consider hoverLayer,
  49659. // where current state is copied to elMirror, and support
  49660. // emphasis opacity here.
  49661. el.traverse(function (child) {
  49662. !child.isGroup && child.setStyle('opacity', opacity);
  49663. });
  49664. el.highlight && el.highlight();
  49665. }
  49666. extendChartView({
  49667. type: 'graph',
  49668. init: function (ecModel, api) {
  49669. var symbolDraw = new SymbolDraw();
  49670. var lineDraw = new LineDraw();
  49671. var group = this.group;
  49672. this._controller = new RoamController(api.getZr());
  49673. this._controllerHost = {
  49674. target: group
  49675. };
  49676. group.add(symbolDraw.group);
  49677. group.add(lineDraw.group);
  49678. this._symbolDraw = symbolDraw;
  49679. this._lineDraw = lineDraw;
  49680. this._firstRender = true;
  49681. },
  49682. render: function (seriesModel, ecModel, api) {
  49683. var graphView = this;
  49684. var coordSys = seriesModel.coordinateSystem;
  49685. this._model = seriesModel;
  49686. var symbolDraw = this._symbolDraw;
  49687. var lineDraw = this._lineDraw;
  49688. var group = this.group;
  49689. if (coordSys.type === 'view') {
  49690. var groupNewProp = {
  49691. position: coordSys.position,
  49692. scale: coordSys.scale
  49693. };
  49694. if (this._firstRender) {
  49695. group.attr(groupNewProp);
  49696. } else {
  49697. updateProps(group, groupNewProp, seriesModel);
  49698. }
  49699. } // Fix edge contact point with node
  49700. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49701. var data = seriesModel.getData();
  49702. symbolDraw.updateData(data);
  49703. var edgeData = seriesModel.getEdgeData();
  49704. lineDraw.updateData(edgeData);
  49705. this._updateNodeAndLinkScale();
  49706. this._updateController(seriesModel, ecModel, api);
  49707. clearTimeout(this._layoutTimeout);
  49708. var forceLayout = seriesModel.forceLayout;
  49709. var layoutAnimation = seriesModel.get('force.layoutAnimation');
  49710. if (forceLayout) {
  49711. this._startForceLayoutIteration(forceLayout, layoutAnimation);
  49712. }
  49713. data.eachItemGraphicEl(function (el, idx) {
  49714. var itemModel = data.getItemModel(idx); // Update draggable
  49715. el.off('drag').off('dragend');
  49716. var draggable = itemModel.get('draggable');
  49717. if (draggable) {
  49718. el.on('drag', function () {
  49719. if (forceLayout) {
  49720. forceLayout.warmUp();
  49721. !this._layouting && this._startForceLayoutIteration(forceLayout, layoutAnimation);
  49722. forceLayout.setFixed(idx); // Write position back to layout
  49723. data.setItemLayout(idx, el.position);
  49724. }
  49725. }, this).on('dragend', function () {
  49726. if (forceLayout) {
  49727. forceLayout.setUnfixed(idx);
  49728. }
  49729. }, this);
  49730. }
  49731. el.setDraggable(draggable && forceLayout);
  49732. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  49733. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  49734. if (itemModel.get('focusNodeAdjacency')) {
  49735. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  49736. graphView._clearTimer();
  49737. api.dispatchAction({
  49738. type: 'focusNodeAdjacency',
  49739. seriesId: seriesModel.id,
  49740. dataIndex: el.dataIndex
  49741. });
  49742. });
  49743. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  49744. graphView._dispatchUnfocus(api);
  49745. });
  49746. }
  49747. }, this);
  49748. data.graph.eachEdge(function (edge) {
  49749. var el = edge.getGraphicEl();
  49750. el[FOCUS_ADJACENCY] && el.off('mouseover', el[FOCUS_ADJACENCY]);
  49751. el[UNFOCUS_ADJACENCY] && el.off('mouseout', el[UNFOCUS_ADJACENCY]);
  49752. if (edge.getModel().get('focusNodeAdjacency')) {
  49753. el.on('mouseover', el[FOCUS_ADJACENCY] = function () {
  49754. graphView._clearTimer();
  49755. api.dispatchAction({
  49756. type: 'focusNodeAdjacency',
  49757. seriesId: seriesModel.id,
  49758. edgeDataIndex: edge.dataIndex
  49759. });
  49760. });
  49761. el.on('mouseout', el[UNFOCUS_ADJACENCY] = function () {
  49762. graphView._dispatchUnfocus(api);
  49763. });
  49764. }
  49765. });
  49766. var circularRotateLabel = seriesModel.get('layout') === 'circular' && seriesModel.get('circular.rotateLabel');
  49767. var cx = data.getLayout('cx');
  49768. var cy = data.getLayout('cy');
  49769. data.eachItemGraphicEl(function (el, idx) {
  49770. var itemModel = data.getItemModel(idx);
  49771. var labelRotate = itemModel.get('label.rotate') || 0;
  49772. var symbolPath = el.getSymbolPath();
  49773. if (circularRotateLabel) {
  49774. var pos = data.getItemLayout(idx);
  49775. var rad = Math.atan2(pos[1] - cy, pos[0] - cx);
  49776. if (rad < 0) {
  49777. rad = Math.PI * 2 + rad;
  49778. }
  49779. var isLeft = pos[0] < cx;
  49780. if (isLeft) {
  49781. rad = rad - Math.PI;
  49782. }
  49783. var textPosition = isLeft ? 'left' : 'right';
  49784. modifyLabelStyle(symbolPath, {
  49785. textRotation: -rad,
  49786. textPosition: textPosition,
  49787. textOrigin: 'center'
  49788. }, {
  49789. textPosition: textPosition
  49790. });
  49791. } else {
  49792. modifyLabelStyle(symbolPath, {
  49793. textRotation: labelRotate *= Math.PI / 180
  49794. });
  49795. }
  49796. });
  49797. this._firstRender = false;
  49798. },
  49799. dispose: function () {
  49800. this._controller && this._controller.dispose();
  49801. this._controllerHost = {};
  49802. this._clearTimer();
  49803. },
  49804. _dispatchUnfocus: function (api, opt) {
  49805. var self = this;
  49806. this._clearTimer();
  49807. this._unfocusDelayTimer = setTimeout(function () {
  49808. self._unfocusDelayTimer = null;
  49809. api.dispatchAction({
  49810. type: 'unfocusNodeAdjacency',
  49811. seriesId: self._model.id
  49812. });
  49813. }, 500);
  49814. },
  49815. _clearTimer: function () {
  49816. if (this._unfocusDelayTimer) {
  49817. clearTimeout(this._unfocusDelayTimer);
  49818. this._unfocusDelayTimer = null;
  49819. }
  49820. },
  49821. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  49822. var data = seriesModel.getData();
  49823. var graph = data.graph;
  49824. var dataIndex = payload.dataIndex;
  49825. var edgeDataIndex = payload.edgeDataIndex;
  49826. var node = graph.getNodeByIndex(dataIndex);
  49827. var edge = graph.getEdgeByIndex(edgeDataIndex);
  49828. if (!node && !edge) {
  49829. return;
  49830. }
  49831. graph.eachNode(function (node) {
  49832. fadeOutItem(node, nodeOpacityPath, 0.1);
  49833. });
  49834. graph.eachEdge(function (edge) {
  49835. fadeOutItem(edge, lineOpacityPath, 0.1);
  49836. });
  49837. if (node) {
  49838. fadeInItem(node, nodeOpacityPath);
  49839. each$1(node.edges, function (adjacentEdge) {
  49840. if (adjacentEdge.dataIndex < 0) {
  49841. return;
  49842. }
  49843. fadeInItem(adjacentEdge, lineOpacityPath);
  49844. fadeInItem(adjacentEdge.node1, nodeOpacityPath);
  49845. fadeInItem(adjacentEdge.node2, nodeOpacityPath);
  49846. });
  49847. }
  49848. if (edge) {
  49849. fadeInItem(edge, lineOpacityPath);
  49850. fadeInItem(edge.node1, nodeOpacityPath);
  49851. fadeInItem(edge.node2, nodeOpacityPath);
  49852. }
  49853. },
  49854. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  49855. var graph = seriesModel.getData().graph;
  49856. graph.eachNode(function (node) {
  49857. fadeOutItem(node, nodeOpacityPath);
  49858. });
  49859. graph.eachEdge(function (edge) {
  49860. fadeOutItem(edge, lineOpacityPath);
  49861. });
  49862. },
  49863. _startForceLayoutIteration: function (forceLayout, layoutAnimation) {
  49864. var self = this;
  49865. (function step() {
  49866. forceLayout.step(function (stopped) {
  49867. self.updateLayout(self._model);
  49868. (self._layouting = !stopped) && (layoutAnimation ? self._layoutTimeout = setTimeout(step, 16) : step());
  49869. });
  49870. })();
  49871. },
  49872. _updateController: function (seriesModel, ecModel, api) {
  49873. var controller = this._controller;
  49874. var controllerHost = this._controllerHost;
  49875. var group = this.group;
  49876. controller.setPointerChecker(function (e, x, y) {
  49877. var rect = group.getBoundingRect();
  49878. rect.applyTransform(group.transform);
  49879. return rect.contain(x, y) && !onIrrelevantElement(e, api, seriesModel);
  49880. });
  49881. if (seriesModel.coordinateSystem.type !== 'view') {
  49882. controller.disable();
  49883. return;
  49884. }
  49885. controller.enable(seriesModel.get('roam'));
  49886. controllerHost.zoomLimit = seriesModel.get('scaleLimit');
  49887. controllerHost.zoom = seriesModel.coordinateSystem.getZoom();
  49888. controller.off('pan').off('zoom').on('pan', function (e) {
  49889. updateViewOnPan(controllerHost, e.dx, e.dy);
  49890. api.dispatchAction({
  49891. seriesId: seriesModel.id,
  49892. type: 'graphRoam',
  49893. dx: e.dx,
  49894. dy: e.dy
  49895. });
  49896. }).on('zoom', function (e) {
  49897. updateViewOnZoom(controllerHost, e.scale, e.originX, e.originY);
  49898. api.dispatchAction({
  49899. seriesId: seriesModel.id,
  49900. type: 'graphRoam',
  49901. zoom: e.scale,
  49902. originX: e.originX,
  49903. originY: e.originY
  49904. });
  49905. this._updateNodeAndLinkScale();
  49906. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49907. this._lineDraw.updateLayout();
  49908. }, this);
  49909. },
  49910. _updateNodeAndLinkScale: function () {
  49911. var seriesModel = this._model;
  49912. var data = seriesModel.getData();
  49913. var nodeScale = getNodeGlobalScale(seriesModel);
  49914. var invScale = [nodeScale, nodeScale];
  49915. data.eachItemGraphicEl(function (el, idx) {
  49916. el.attr('scale', invScale);
  49917. });
  49918. },
  49919. updateLayout: function (seriesModel) {
  49920. adjustEdge(seriesModel.getGraph(), getNodeGlobalScale(seriesModel));
  49921. this._symbolDraw.updateLayout();
  49922. this._lineDraw.updateLayout();
  49923. },
  49924. remove: function (ecModel, api) {
  49925. this._symbolDraw && this._symbolDraw.remove();
  49926. this._lineDraw && this._lineDraw.remove();
  49927. }
  49928. });
  49929. /*
  49930. * Licensed to the Apache Software Foundation (ASF) under one
  49931. * or more contributor license agreements. See the NOTICE file
  49932. * distributed with this work for additional information
  49933. * regarding copyright ownership. The ASF licenses this file
  49934. * to you under the Apache License, Version 2.0 (the
  49935. * "License"); you may not use this file except in compliance
  49936. * with the License. You may obtain a copy of the License at
  49937. *
  49938. * http://www.apache.org/licenses/LICENSE-2.0
  49939. *
  49940. * Unless required by applicable law or agreed to in writing,
  49941. * software distributed under the License is distributed on an
  49942. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49943. * KIND, either express or implied. See the License for the
  49944. * specific language governing permissions and limitations
  49945. * under the License.
  49946. */
  49947. /**
  49948. * @payload
  49949. * @property {number} [seriesIndex]
  49950. * @property {string} [seriesId]
  49951. * @property {string} [seriesName]
  49952. * @property {number} [dataIndex]
  49953. */
  49954. registerAction({
  49955. type: 'focusNodeAdjacency',
  49956. event: 'focusNodeAdjacency',
  49957. update: 'series:focusNodeAdjacency'
  49958. }, function () {});
  49959. /**
  49960. * @payload
  49961. * @property {number} [seriesIndex]
  49962. * @property {string} [seriesId]
  49963. * @property {string} [seriesName]
  49964. */
  49965. registerAction({
  49966. type: 'unfocusNodeAdjacency',
  49967. event: 'unfocusNodeAdjacency',
  49968. update: 'series:unfocusNodeAdjacency'
  49969. }, function () {});
  49970. /*
  49971. * Licensed to the Apache Software Foundation (ASF) under one
  49972. * or more contributor license agreements. See the NOTICE file
  49973. * distributed with this work for additional information
  49974. * regarding copyright ownership. The ASF licenses this file
  49975. * to you under the Apache License, Version 2.0 (the
  49976. * "License"); you may not use this file except in compliance
  49977. * with the License. You may obtain a copy of the License at
  49978. *
  49979. * http://www.apache.org/licenses/LICENSE-2.0
  49980. *
  49981. * Unless required by applicable law or agreed to in writing,
  49982. * software distributed under the License is distributed on an
  49983. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  49984. * KIND, either express or implied. See the License for the
  49985. * specific language governing permissions and limitations
  49986. * under the License.
  49987. */
  49988. var actionInfo = {
  49989. type: 'graphRoam',
  49990. event: 'graphRoam',
  49991. update: 'none'
  49992. };
  49993. /**
  49994. * @payload
  49995. * @property {string} name Series name
  49996. * @property {number} [dx]
  49997. * @property {number} [dy]
  49998. * @property {number} [zoom]
  49999. * @property {number} [originX]
  50000. * @property {number} [originY]
  50001. */
  50002. registerAction(actionInfo, function (payload, ecModel) {
  50003. ecModel.eachComponent({
  50004. mainType: 'series',
  50005. query: payload
  50006. }, function (seriesModel) {
  50007. var coordSys = seriesModel.coordinateSystem;
  50008. var res = updateCenterAndZoom(coordSys, payload);
  50009. seriesModel.setCenter && seriesModel.setCenter(res.center);
  50010. seriesModel.setZoom && seriesModel.setZoom(res.zoom);
  50011. });
  50012. });
  50013. /*
  50014. * Licensed to the Apache Software Foundation (ASF) under one
  50015. * or more contributor license agreements. See the NOTICE file
  50016. * distributed with this work for additional information
  50017. * regarding copyright ownership. The ASF licenses this file
  50018. * to you under the Apache License, Version 2.0 (the
  50019. * "License"); you may not use this file except in compliance
  50020. * with the License. You may obtain a copy of the License at
  50021. *
  50022. * http://www.apache.org/licenses/LICENSE-2.0
  50023. *
  50024. * Unless required by applicable law or agreed to in writing,
  50025. * software distributed under the License is distributed on an
  50026. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50027. * KIND, either express or implied. See the License for the
  50028. * specific language governing permissions and limitations
  50029. * under the License.
  50030. */
  50031. var categoryFilter = function (ecModel) {
  50032. var legendModels = ecModel.findComponents({
  50033. mainType: 'legend'
  50034. });
  50035. if (!legendModels || !legendModels.length) {
  50036. return;
  50037. }
  50038. ecModel.eachSeriesByType('graph', function (graphSeries) {
  50039. var categoriesData = graphSeries.getCategoriesData();
  50040. var graph = graphSeries.getGraph();
  50041. var data = graph.data;
  50042. var categoryNames = categoriesData.mapArray(categoriesData.getName);
  50043. data.filterSelf(function (idx) {
  50044. var model = data.getItemModel(idx);
  50045. var category = model.getShallow('category');
  50046. if (category != null) {
  50047. if (typeof category === 'number') {
  50048. category = categoryNames[category];
  50049. } // If in any legend component the status is not selected.
  50050. for (var i = 0; i < legendModels.length; i++) {
  50051. if (!legendModels[i].isSelected(category)) {
  50052. return false;
  50053. }
  50054. }
  50055. }
  50056. return true;
  50057. });
  50058. }, this);
  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. var categoryVisual = function (ecModel) {
  50079. var paletteScope = {};
  50080. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50081. var categoriesData = seriesModel.getCategoriesData();
  50082. var data = seriesModel.getData();
  50083. var categoryNameIdxMap = {};
  50084. categoriesData.each(function (idx) {
  50085. var name = categoriesData.getName(idx); // Add prefix to avoid conflict with Object.prototype.
  50086. categoryNameIdxMap['ec-' + name] = idx;
  50087. var itemModel = categoriesData.getItemModel(idx);
  50088. var color = itemModel.get('itemStyle.color') || seriesModel.getColorFromPalette(name, paletteScope);
  50089. categoriesData.setItemVisual(idx, 'color', color);
  50090. var itemStyleList = ['opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  50091. for (var i = 0; i < itemStyleList.length; i++) {
  50092. var itemStyle = itemModel.getShallow(itemStyleList[i], true);
  50093. if (itemStyle != null) {
  50094. categoriesData.setItemVisual(idx, itemStyleList[i], itemStyle);
  50095. }
  50096. }
  50097. }); // Assign category color to visual
  50098. if (categoriesData.count()) {
  50099. data.each(function (idx) {
  50100. var model = data.getItemModel(idx);
  50101. var category = model.getShallow('category');
  50102. if (category != null) {
  50103. if (typeof category === 'string') {
  50104. category = categoryNameIdxMap['ec-' + category];
  50105. }
  50106. var itemStyleList = ['color', 'opacity', 'symbol', 'symbolSize', 'symbolKeepAspect'];
  50107. for (var i = 0; i < itemStyleList.length; i++) {
  50108. if (data.getItemVisual(idx, itemStyleList[i], true) == null) {
  50109. data.setItemVisual(idx, itemStyleList[i], categoriesData.getItemVisual(category, itemStyleList[i]));
  50110. }
  50111. }
  50112. }
  50113. });
  50114. }
  50115. });
  50116. };
  50117. /*
  50118. * Licensed to the Apache Software Foundation (ASF) under one
  50119. * or more contributor license agreements. See the NOTICE file
  50120. * distributed with this work for additional information
  50121. * regarding copyright ownership. The ASF licenses this file
  50122. * to you under the Apache License, Version 2.0 (the
  50123. * "License"); you may not use this file except in compliance
  50124. * with the License. You may obtain a copy of the License at
  50125. *
  50126. * http://www.apache.org/licenses/LICENSE-2.0
  50127. *
  50128. * Unless required by applicable law or agreed to in writing,
  50129. * software distributed under the License is distributed on an
  50130. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50131. * KIND, either express or implied. See the License for the
  50132. * specific language governing permissions and limitations
  50133. * under the License.
  50134. */
  50135. function normalize$2(a) {
  50136. if (!(a instanceof Array)) {
  50137. a = [a, a];
  50138. }
  50139. return a;
  50140. }
  50141. var edgeVisual = function (ecModel) {
  50142. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50143. var graph = seriesModel.getGraph();
  50144. var edgeData = seriesModel.getEdgeData();
  50145. var symbolType = normalize$2(seriesModel.get('edgeSymbol'));
  50146. var symbolSize = normalize$2(seriesModel.get('edgeSymbolSize'));
  50147. var colorQuery = 'lineStyle.color'.split('.');
  50148. var opacityQuery = 'lineStyle.opacity'.split('.');
  50149. edgeData.setVisual('fromSymbol', symbolType && symbolType[0]);
  50150. edgeData.setVisual('toSymbol', symbolType && symbolType[1]);
  50151. edgeData.setVisual('fromSymbolSize', symbolSize && symbolSize[0]);
  50152. edgeData.setVisual('toSymbolSize', symbolSize && symbolSize[1]);
  50153. edgeData.setVisual('color', seriesModel.get(colorQuery));
  50154. edgeData.setVisual('opacity', seriesModel.get(opacityQuery));
  50155. edgeData.each(function (idx) {
  50156. var itemModel = edgeData.getItemModel(idx);
  50157. var edge = graph.getEdgeByIndex(idx);
  50158. var symbolType = normalize$2(itemModel.getShallow('symbol', true));
  50159. var symbolSize = normalize$2(itemModel.getShallow('symbolSize', true)); // Edge visual must after node visual
  50160. var color = itemModel.get(colorQuery);
  50161. var opacity = itemModel.get(opacityQuery);
  50162. switch (color) {
  50163. case 'source':
  50164. color = edge.node1.getVisual('color');
  50165. break;
  50166. case 'target':
  50167. color = edge.node2.getVisual('color');
  50168. break;
  50169. }
  50170. symbolType[0] && edge.setVisual('fromSymbol', symbolType[0]);
  50171. symbolType[1] && edge.setVisual('toSymbol', symbolType[1]);
  50172. symbolSize[0] && edge.setVisual('fromSymbolSize', symbolSize[0]);
  50173. symbolSize[1] && edge.setVisual('toSymbolSize', symbolSize[1]);
  50174. edge.setVisual('color', color);
  50175. edge.setVisual('opacity', opacity);
  50176. });
  50177. });
  50178. };
  50179. /*
  50180. * Licensed to the Apache Software Foundation (ASF) under one
  50181. * or more contributor license agreements. See the NOTICE file
  50182. * distributed with this work for additional information
  50183. * regarding copyright ownership. The ASF licenses this file
  50184. * to you under the Apache License, Version 2.0 (the
  50185. * "License"); you may not use this file except in compliance
  50186. * with the License. You may obtain a copy of the License at
  50187. *
  50188. * http://www.apache.org/licenses/LICENSE-2.0
  50189. *
  50190. * Unless required by applicable law or agreed to in writing,
  50191. * software distributed under the License is distributed on an
  50192. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50193. * KIND, either express or implied. See the License for the
  50194. * specific language governing permissions and limitations
  50195. * under the License.
  50196. */
  50197. function simpleLayout$1(seriesModel) {
  50198. var coordSys = seriesModel.coordinateSystem;
  50199. if (coordSys && coordSys.type !== 'view') {
  50200. return;
  50201. }
  50202. var graph = seriesModel.getGraph();
  50203. graph.eachNode(function (node) {
  50204. var model = node.getModel();
  50205. node.setLayout([+model.get('x'), +model.get('y')]);
  50206. });
  50207. simpleLayoutEdge(graph);
  50208. }
  50209. function simpleLayoutEdge(graph) {
  50210. graph.eachEdge(function (edge) {
  50211. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50212. var p1 = clone$1(edge.node1.getLayout());
  50213. var p2 = clone$1(edge.node2.getLayout());
  50214. var points = [p1, p2];
  50215. if (+curveness) {
  50216. points.push([(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * curveness]);
  50217. }
  50218. edge.setLayout(points);
  50219. });
  50220. }
  50221. /*
  50222. * Licensed to the Apache Software Foundation (ASF) under one
  50223. * or more contributor license agreements. See the NOTICE file
  50224. * distributed with this work for additional information
  50225. * regarding copyright ownership. The ASF licenses this file
  50226. * to you under the Apache License, Version 2.0 (the
  50227. * "License"); you may not use this file except in compliance
  50228. * with the License. You may obtain a copy of the License at
  50229. *
  50230. * http://www.apache.org/licenses/LICENSE-2.0
  50231. *
  50232. * Unless required by applicable law or agreed to in writing,
  50233. * software distributed under the License is distributed on an
  50234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50235. * KIND, either express or implied. See the License for the
  50236. * specific language governing permissions and limitations
  50237. * under the License.
  50238. */
  50239. var simpleLayout = function (ecModel, api) {
  50240. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50241. var layout = seriesModel.get('layout');
  50242. var coordSys = seriesModel.coordinateSystem;
  50243. if (coordSys && coordSys.type !== 'view') {
  50244. var data = seriesModel.getData();
  50245. var dimensions = [];
  50246. each$1(coordSys.dimensions, function (coordDim) {
  50247. dimensions = dimensions.concat(data.mapDimension(coordDim, true));
  50248. });
  50249. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  50250. var value = [];
  50251. var hasValue = false;
  50252. for (var i = 0; i < dimensions.length; i++) {
  50253. var val = data.get(dimensions[i], dataIndex);
  50254. if (!isNaN(val)) {
  50255. hasValue = true;
  50256. }
  50257. value.push(val);
  50258. }
  50259. if (hasValue) {
  50260. data.setItemLayout(dataIndex, coordSys.dataToPoint(value));
  50261. } else {
  50262. // Also {Array.<number>}, not undefined to avoid if...else... statement
  50263. data.setItemLayout(dataIndex, [NaN, NaN]);
  50264. }
  50265. }
  50266. simpleLayoutEdge(data.graph);
  50267. } else if (!layout || layout === 'none') {
  50268. simpleLayout$1(seriesModel);
  50269. }
  50270. });
  50271. };
  50272. /*
  50273. * Licensed to the Apache Software Foundation (ASF) under one
  50274. * or more contributor license agreements. See the NOTICE file
  50275. * distributed with this work for additional information
  50276. * regarding copyright ownership. The ASF licenses this file
  50277. * to you under the Apache License, Version 2.0 (the
  50278. * "License"); you may not use this file except in compliance
  50279. * with the License. You may obtain a copy of the License at
  50280. *
  50281. * http://www.apache.org/licenses/LICENSE-2.0
  50282. *
  50283. * Unless required by applicable law or agreed to in writing,
  50284. * software distributed under the License is distributed on an
  50285. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50286. * KIND, either express or implied. See the License for the
  50287. * specific language governing permissions and limitations
  50288. * under the License.
  50289. */
  50290. var PI$3 = Math.PI;
  50291. var _symbolRadiansHalf = [];
  50292. /**
  50293. * `basedOn` can be:
  50294. * 'value':
  50295. * This layout is not accurate and have same bad case. For example,
  50296. * if the min value is very smaller than the max value, the nodes
  50297. * with the min value probably overlap even though there is enough
  50298. * space to layout them. So we only use this approach in the as the
  50299. * init layout of the force layout.
  50300. * FIXME
  50301. * Probably we do not need this method any more but use
  50302. * `basedOn: 'symbolSize'` in force layout if
  50303. * delay its init operations to GraphView.
  50304. * 'symbolSize':
  50305. * This approach work only if all of the symbol size calculated.
  50306. * That is, the progressive rendering is not applied to graph.
  50307. * FIXME
  50308. * If progressive rendering is applied to graph some day,
  50309. * probably we have to use `basedOn: 'value'`.
  50310. *
  50311. * @param {module:echarts/src/model/Series} seriesModel
  50312. * @param {string} basedOn 'value' or 'symbolSize'
  50313. */
  50314. function circularLayout$1(seriesModel, basedOn) {
  50315. var coordSys = seriesModel.coordinateSystem;
  50316. if (coordSys && coordSys.type !== 'view') {
  50317. return;
  50318. }
  50319. var rect = coordSys.getBoundingRect();
  50320. var nodeData = seriesModel.getData();
  50321. var graph = nodeData.graph;
  50322. var cx = rect.width / 2 + rect.x;
  50323. var cy = rect.height / 2 + rect.y;
  50324. var r = Math.min(rect.width, rect.height) / 2;
  50325. var count = nodeData.count();
  50326. nodeData.setLayout({
  50327. cx: cx,
  50328. cy: cy
  50329. });
  50330. if (!count) {
  50331. return;
  50332. }
  50333. _layoutNodesBasedOn[basedOn](seriesModel, coordSys, graph, nodeData, r, cx, cy, count);
  50334. graph.eachEdge(function (edge) {
  50335. var curveness = edge.getModel().get('lineStyle.curveness') || 0;
  50336. var p1 = clone$1(edge.node1.getLayout());
  50337. var p2 = clone$1(edge.node2.getLayout());
  50338. var cp1;
  50339. var x12 = (p1[0] + p2[0]) / 2;
  50340. var y12 = (p1[1] + p2[1]) / 2;
  50341. if (+curveness) {
  50342. curveness *= 3;
  50343. cp1 = [cx * curveness + x12 * (1 - curveness), cy * curveness + y12 * (1 - curveness)];
  50344. }
  50345. edge.setLayout([p1, p2, cp1]);
  50346. });
  50347. }
  50348. var _layoutNodesBasedOn = {
  50349. value: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50350. var angle = 0;
  50351. var sum = nodeData.getSum('value');
  50352. var unitAngle = Math.PI * 2 / (sum || count);
  50353. graph.eachNode(function (node) {
  50354. var value = node.getValue('value');
  50355. var radianHalf = unitAngle * (sum ? value : 1) / 2;
  50356. angle += radianHalf;
  50357. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  50358. angle += radianHalf;
  50359. });
  50360. },
  50361. symbolSize: function (seriesModel, coordSys, graph, nodeData, r, cx, cy, count) {
  50362. var sumRadian = 0;
  50363. _symbolRadiansHalf.length = count;
  50364. var nodeScale = getNodeGlobalScale(seriesModel);
  50365. graph.eachNode(function (node) {
  50366. var symbolSize = getSymbolSize$1(node); // Normally this case will not happen, but we still add
  50367. // some the defensive code (2px is an arbitrary value).
  50368. isNaN(symbolSize) && (symbolSize = 2);
  50369. symbolSize < 0 && (symbolSize = 0);
  50370. symbolSize *= nodeScale;
  50371. var symbolRadianHalf = Math.asin(symbolSize / 2 / r); // when `symbolSize / 2` is bigger than `r`.
  50372. isNaN(symbolRadianHalf) && (symbolRadianHalf = PI$3 / 2);
  50373. _symbolRadiansHalf[node.dataIndex] = symbolRadianHalf;
  50374. sumRadian += symbolRadianHalf * 2;
  50375. });
  50376. var halfRemainRadian = (2 * PI$3 - sumRadian) / count / 2;
  50377. var angle = 0;
  50378. graph.eachNode(function (node) {
  50379. var radianHalf = halfRemainRadian + _symbolRadiansHalf[node.dataIndex];
  50380. angle += radianHalf;
  50381. node.setLayout([r * Math.cos(angle) + cx, r * Math.sin(angle) + cy]);
  50382. angle += radianHalf;
  50383. });
  50384. }
  50385. };
  50386. /*
  50387. * Licensed to the Apache Software Foundation (ASF) under one
  50388. * or more contributor license agreements. See the NOTICE file
  50389. * distributed with this work for additional information
  50390. * regarding copyright ownership. The ASF licenses this file
  50391. * to you under the Apache License, Version 2.0 (the
  50392. * "License"); you may not use this file except in compliance
  50393. * with the License. You may obtain a copy of the License at
  50394. *
  50395. * http://www.apache.org/licenses/LICENSE-2.0
  50396. *
  50397. * Unless required by applicable law or agreed to in writing,
  50398. * software distributed under the License is distributed on an
  50399. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50400. * KIND, either express or implied. See the License for the
  50401. * specific language governing permissions and limitations
  50402. * under the License.
  50403. */
  50404. var circularLayout = function (ecModel) {
  50405. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50406. if (seriesModel.get('layout') === 'circular') {
  50407. circularLayout$1(seriesModel, 'symbolSize');
  50408. }
  50409. });
  50410. };
  50411. /*
  50412. * Licensed to the Apache Software Foundation (ASF) under one
  50413. * or more contributor license agreements. See the NOTICE file
  50414. * distributed with this work for additional information
  50415. * regarding copyright ownership. The ASF licenses this file
  50416. * to you under the Apache License, Version 2.0 (the
  50417. * "License"); you may not use this file except in compliance
  50418. * with the License. You may obtain a copy of the License at
  50419. *
  50420. * http://www.apache.org/licenses/LICENSE-2.0
  50421. *
  50422. * Unless required by applicable law or agreed to in writing,
  50423. * software distributed under the License is distributed on an
  50424. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50425. * KIND, either express or implied. See the License for the
  50426. * specific language governing permissions and limitations
  50427. * under the License.
  50428. */
  50429. /*
  50430. * A third-party license is embeded for some of the code in this file:
  50431. * Some formulas were originally copied from "d3.js" with some
  50432. * modifications made for this project.
  50433. * (See more details in the comment of the method "step" below.)
  50434. * The use of the source code of this file is also subject to the terms
  50435. * and consitions of the license of "d3.js" (BSD-3Clause, see
  50436. * </licenses/LICENSE-d3>).
  50437. */
  50438. var scaleAndAdd$2 = scaleAndAdd; // function adjacentNode(n, e) {
  50439. // return e.n1 === n ? e.n2 : e.n1;
  50440. // }
  50441. function forceLayout$1(nodes, edges, opts) {
  50442. var rect = opts.rect;
  50443. var width = rect.width;
  50444. var height = rect.height;
  50445. var center = [rect.x + width / 2, rect.y + height / 2]; // var scale = opts.scale || 1;
  50446. var gravity = opts.gravity == null ? 0.1 : opts.gravity; // for (var i = 0; i < edges.length; i++) {
  50447. // var e = edges[i];
  50448. // var n1 = e.n1;
  50449. // var n2 = e.n2;
  50450. // n1.edges = n1.edges || [];
  50451. // n2.edges = n2.edges || [];
  50452. // n1.edges.push(e);
  50453. // n2.edges.push(e);
  50454. // }
  50455. // Init position
  50456. for (var i = 0; i < nodes.length; i++) {
  50457. var n = nodes[i];
  50458. if (!n.p) {
  50459. n.p = create(width * (Math.random() - 0.5) + center[0], height * (Math.random() - 0.5) + center[1]);
  50460. }
  50461. n.pp = clone$1(n.p);
  50462. n.edges = null;
  50463. } // Formula in 'Graph Drawing by Force-directed Placement'
  50464. // var k = scale * Math.sqrt(width * height / nodes.length);
  50465. // var k2 = k * k;
  50466. var initialFriction = opts.friction == null ? 0.6 : opts.friction;
  50467. var friction = initialFriction;
  50468. return {
  50469. warmUp: function () {
  50470. friction = initialFriction * 0.8;
  50471. },
  50472. setFixed: function (idx) {
  50473. nodes[idx].fixed = true;
  50474. },
  50475. setUnfixed: function (idx) {
  50476. nodes[idx].fixed = false;
  50477. },
  50478. /**
  50479. * Some formulas were originally copied from "d3.js"
  50480. * https://github.com/d3/d3/blob/b516d77fb8566b576088e73410437494717ada26/src/layout/force.js
  50481. * with some modifications made for this project.
  50482. * See the license statement at the head of this file.
  50483. */
  50484. step: function (cb) {
  50485. var v12 = [];
  50486. var nLen = nodes.length;
  50487. for (var i = 0; i < edges.length; i++) {
  50488. var e = edges[i];
  50489. if (e.ignoreForceLayout) {
  50490. continue;
  50491. }
  50492. var n1 = e.n1;
  50493. var n2 = e.n2;
  50494. sub(v12, n2.p, n1.p);
  50495. var d = len(v12) - e.d;
  50496. var w = n2.w / (n1.w + n2.w);
  50497. if (isNaN(w)) {
  50498. w = 0;
  50499. }
  50500. normalize(v12, v12);
  50501. !n1.fixed && scaleAndAdd$2(n1.p, n1.p, v12, w * d * friction);
  50502. !n2.fixed && scaleAndAdd$2(n2.p, n2.p, v12, -(1 - w) * d * friction);
  50503. } // Gravity
  50504. for (var i = 0; i < nLen; i++) {
  50505. var n = nodes[i];
  50506. if (!n.fixed) {
  50507. sub(v12, center, n.p); // var d = vec2.len(v12);
  50508. // vec2.scale(v12, v12, 1 / d);
  50509. // var gravityFactor = gravity;
  50510. scaleAndAdd$2(n.p, n.p, v12, gravity * friction);
  50511. }
  50512. } // Repulsive
  50513. // PENDING
  50514. for (var i = 0; i < nLen; i++) {
  50515. var n1 = nodes[i];
  50516. for (var j = i + 1; j < nLen; j++) {
  50517. var n2 = nodes[j];
  50518. sub(v12, n2.p, n1.p);
  50519. var d = len(v12);
  50520. if (d === 0) {
  50521. // Random repulse
  50522. set(v12, Math.random() - 0.5, Math.random() - 0.5);
  50523. d = 1;
  50524. }
  50525. var repFact = (n1.rep + n2.rep) / d / d;
  50526. !n1.fixed && scaleAndAdd$2(n1.pp, n1.pp, v12, repFact);
  50527. !n2.fixed && scaleAndAdd$2(n2.pp, n2.pp, v12, -repFact);
  50528. }
  50529. }
  50530. var v = [];
  50531. for (var i = 0; i < nLen; i++) {
  50532. var n = nodes[i];
  50533. if (!n.fixed) {
  50534. sub(v, n.p, n.pp);
  50535. scaleAndAdd$2(n.p, n.p, v, friction);
  50536. copy(n.pp, n.p);
  50537. }
  50538. }
  50539. friction = friction * 0.992;
  50540. cb && cb(nodes, edges, friction < 0.01);
  50541. }
  50542. };
  50543. }
  50544. /*
  50545. * Licensed to the Apache Software Foundation (ASF) under one
  50546. * or more contributor license agreements. See the NOTICE file
  50547. * distributed with this work for additional information
  50548. * regarding copyright ownership. The ASF licenses this file
  50549. * to you under the Apache License, Version 2.0 (the
  50550. * "License"); you may not use this file except in compliance
  50551. * with the License. You may obtain a copy of the License at
  50552. *
  50553. * http://www.apache.org/licenses/LICENSE-2.0
  50554. *
  50555. * Unless required by applicable law or agreed to in writing,
  50556. * software distributed under the License is distributed on an
  50557. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50558. * KIND, either express or implied. See the License for the
  50559. * specific language governing permissions and limitations
  50560. * under the License.
  50561. */
  50562. var forceLayout = function (ecModel) {
  50563. ecModel.eachSeriesByType('graph', function (graphSeries) {
  50564. var coordSys = graphSeries.coordinateSystem;
  50565. if (coordSys && coordSys.type !== 'view') {
  50566. return;
  50567. }
  50568. if (graphSeries.get('layout') === 'force') {
  50569. var preservedPoints = graphSeries.preservedPoints || {};
  50570. var graph = graphSeries.getGraph();
  50571. var nodeData = graph.data;
  50572. var edgeData = graph.edgeData;
  50573. var forceModel = graphSeries.getModel('force');
  50574. var initLayout = forceModel.get('initLayout');
  50575. if (graphSeries.preservedPoints) {
  50576. nodeData.each(function (idx) {
  50577. var id = nodeData.getId(idx);
  50578. nodeData.setItemLayout(idx, preservedPoints[id] || [NaN, NaN]);
  50579. });
  50580. } else if (!initLayout || initLayout === 'none') {
  50581. simpleLayout$1(graphSeries);
  50582. } else if (initLayout === 'circular') {
  50583. circularLayout$1(graphSeries, 'value');
  50584. }
  50585. var nodeDataExtent = nodeData.getDataExtent('value');
  50586. var edgeDataExtent = edgeData.getDataExtent('value'); // var edgeDataExtent = edgeData.getDataExtent('value');
  50587. var repulsion = forceModel.get('repulsion');
  50588. var edgeLength = forceModel.get('edgeLength');
  50589. if (!isArray(repulsion)) {
  50590. repulsion = [repulsion, repulsion];
  50591. }
  50592. if (!isArray(edgeLength)) {
  50593. edgeLength = [edgeLength, edgeLength];
  50594. } // Larger value has smaller length
  50595. edgeLength = [edgeLength[1], edgeLength[0]];
  50596. var nodes = nodeData.mapArray('value', function (value, idx) {
  50597. var point = nodeData.getItemLayout(idx);
  50598. var rep = linearMap(value, nodeDataExtent, repulsion);
  50599. if (isNaN(rep)) {
  50600. rep = (repulsion[0] + repulsion[1]) / 2;
  50601. }
  50602. return {
  50603. w: rep,
  50604. rep: rep,
  50605. fixed: nodeData.getItemModel(idx).get('fixed'),
  50606. p: !point || isNaN(point[0]) || isNaN(point[1]) ? null : point
  50607. };
  50608. });
  50609. var edges = edgeData.mapArray('value', function (value, idx) {
  50610. var edge = graph.getEdgeByIndex(idx);
  50611. var d = linearMap(value, edgeDataExtent, edgeLength);
  50612. if (isNaN(d)) {
  50613. d = (edgeLength[0] + edgeLength[1]) / 2;
  50614. }
  50615. var edgeModel = edge.getModel();
  50616. return {
  50617. n1: nodes[edge.node1.dataIndex],
  50618. n2: nodes[edge.node2.dataIndex],
  50619. d: d,
  50620. curveness: edgeModel.get('lineStyle.curveness') || 0,
  50621. ignoreForceLayout: edgeModel.get('ignoreForceLayout')
  50622. };
  50623. });
  50624. var coordSys = graphSeries.coordinateSystem;
  50625. var rect = coordSys.getBoundingRect();
  50626. var forceInstance = forceLayout$1(nodes, edges, {
  50627. rect: rect,
  50628. gravity: forceModel.get('gravity'),
  50629. friction: forceModel.get('friction')
  50630. });
  50631. var oldStep = forceInstance.step;
  50632. forceInstance.step = function (cb) {
  50633. for (var i = 0, l = nodes.length; i < l; i++) {
  50634. if (nodes[i].fixed) {
  50635. // Write back to layout instance
  50636. copy(nodes[i].p, graph.getNodeByIndex(i).getLayout());
  50637. }
  50638. }
  50639. oldStep(function (nodes, edges, stopped) {
  50640. for (var i = 0, l = nodes.length; i < l; i++) {
  50641. if (!nodes[i].fixed) {
  50642. graph.getNodeByIndex(i).setLayout(nodes[i].p);
  50643. }
  50644. preservedPoints[nodeData.getId(i)] = nodes[i].p;
  50645. }
  50646. for (var i = 0, l = edges.length; i < l; i++) {
  50647. var e = edges[i];
  50648. var edge = graph.getEdgeByIndex(i);
  50649. var p1 = e.n1.p;
  50650. var p2 = e.n2.p;
  50651. var points = edge.getLayout();
  50652. points = points ? points.slice() : [];
  50653. points[0] = points[0] || [];
  50654. points[1] = points[1] || [];
  50655. copy(points[0], p1);
  50656. copy(points[1], p2);
  50657. if (+e.curveness) {
  50658. points[2] = [(p1[0] + p2[0]) / 2 - (p1[1] - p2[1]) * e.curveness, (p1[1] + p2[1]) / 2 - (p2[0] - p1[0]) * e.curveness];
  50659. }
  50660. edge.setLayout(points);
  50661. } // Update layout
  50662. cb && cb(stopped);
  50663. });
  50664. };
  50665. graphSeries.forceLayout = forceInstance;
  50666. graphSeries.preservedPoints = preservedPoints; // Step to get the layout
  50667. forceInstance.step();
  50668. } else {
  50669. // Remove prev injected forceLayout instance
  50670. graphSeries.forceLayout = null;
  50671. }
  50672. });
  50673. };
  50674. /*
  50675. * Licensed to the Apache Software Foundation (ASF) under one
  50676. * or more contributor license agreements. See the NOTICE file
  50677. * distributed with this work for additional information
  50678. * regarding copyright ownership. The ASF licenses this file
  50679. * to you under the Apache License, Version 2.0 (the
  50680. * "License"); you may not use this file except in compliance
  50681. * with the License. You may obtain a copy of the License at
  50682. *
  50683. * http://www.apache.org/licenses/LICENSE-2.0
  50684. *
  50685. * Unless required by applicable law or agreed to in writing,
  50686. * software distributed under the License is distributed on an
  50687. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50688. * KIND, either express or implied. See the License for the
  50689. * specific language governing permissions and limitations
  50690. * under the License.
  50691. */
  50692. // FIXME Where to create the simple view coordinate system
  50693. function getViewRect$2(seriesModel, api, aspect) {
  50694. var option = seriesModel.getBoxLayoutParams();
  50695. option.aspect = aspect;
  50696. return getLayoutRect(option, {
  50697. width: api.getWidth(),
  50698. height: api.getHeight()
  50699. });
  50700. }
  50701. var createView = function (ecModel, api) {
  50702. var viewList = [];
  50703. ecModel.eachSeriesByType('graph', function (seriesModel) {
  50704. var coordSysType = seriesModel.get('coordinateSystem');
  50705. if (!coordSysType || coordSysType === 'view') {
  50706. var data = seriesModel.getData();
  50707. var positions = data.mapArray(function (idx) {
  50708. var itemModel = data.getItemModel(idx);
  50709. return [+itemModel.get('x'), +itemModel.get('y')];
  50710. });
  50711. var min = [];
  50712. var max = [];
  50713. fromPoints(positions, min, max); // If width or height is 0
  50714. if (max[0] - min[0] === 0) {
  50715. max[0] += 1;
  50716. min[0] -= 1;
  50717. }
  50718. if (max[1] - min[1] === 0) {
  50719. max[1] += 1;
  50720. min[1] -= 1;
  50721. }
  50722. var aspect = (max[0] - min[0]) / (max[1] - min[1]); // FIXME If get view rect after data processed?
  50723. var viewRect = getViewRect$2(seriesModel, api, aspect); // Position may be NaN, use view rect instead
  50724. if (isNaN(aspect)) {
  50725. min = [viewRect.x, viewRect.y];
  50726. max = [viewRect.x + viewRect.width, viewRect.y + viewRect.height];
  50727. }
  50728. var bbWidth = max[0] - min[0];
  50729. var bbHeight = max[1] - min[1];
  50730. var viewWidth = viewRect.width;
  50731. var viewHeight = viewRect.height;
  50732. var viewCoordSys = seriesModel.coordinateSystem = new View();
  50733. viewCoordSys.zoomLimit = seriesModel.get('scaleLimit');
  50734. viewCoordSys.setBoundingRect(min[0], min[1], bbWidth, bbHeight);
  50735. viewCoordSys.setViewRect(viewRect.x, viewRect.y, viewWidth, viewHeight); // Update roam info
  50736. viewCoordSys.setCenter(seriesModel.get('center'));
  50737. viewCoordSys.setZoom(seriesModel.get('zoom'));
  50738. viewList.push(viewCoordSys);
  50739. }
  50740. });
  50741. return viewList;
  50742. };
  50743. /*
  50744. * Licensed to the Apache Software Foundation (ASF) under one
  50745. * or more contributor license agreements. See the NOTICE file
  50746. * distributed with this work for additional information
  50747. * regarding copyright ownership. The ASF licenses this file
  50748. * to you under the Apache License, Version 2.0 (the
  50749. * "License"); you may not use this file except in compliance
  50750. * with the License. You may obtain a copy of the License at
  50751. *
  50752. * http://www.apache.org/licenses/LICENSE-2.0
  50753. *
  50754. * Unless required by applicable law or agreed to in writing,
  50755. * software distributed under the License is distributed on an
  50756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50757. * KIND, either express or implied. See the License for the
  50758. * specific language governing permissions and limitations
  50759. * under the License.
  50760. */
  50761. registerProcessor(categoryFilter);
  50762. registerVisual(visualSymbol('graph', 'circle', null));
  50763. registerVisual(categoryVisual);
  50764. registerVisual(edgeVisual);
  50765. registerLayout(simpleLayout);
  50766. registerLayout(PRIORITY.VISUAL.POST_CHART_LAYOUT, circularLayout);
  50767. registerLayout(forceLayout); // Graph view coordinate system
  50768. registerCoordinateSystem('graphView', {
  50769. create: createView
  50770. });
  50771. /*
  50772. * Licensed to the Apache Software Foundation (ASF) under one
  50773. * or more contributor license agreements. See the NOTICE file
  50774. * distributed with this work for additional information
  50775. * regarding copyright ownership. The ASF licenses this file
  50776. * to you under the Apache License, Version 2.0 (the
  50777. * "License"); you may not use this file except in compliance
  50778. * with the License. You may obtain a copy of the License at
  50779. *
  50780. * http://www.apache.org/licenses/LICENSE-2.0
  50781. *
  50782. * Unless required by applicable law or agreed to in writing,
  50783. * software distributed under the License is distributed on an
  50784. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50785. * KIND, either express or implied. See the License for the
  50786. * specific language governing permissions and limitations
  50787. * under the License.
  50788. */
  50789. var BoxplotSeries = SeriesModel.extend({
  50790. type: 'series.boxplot',
  50791. dependencies: ['xAxis', 'yAxis', 'grid'],
  50792. // TODO
  50793. // box width represents group size, so dimension should have 'size'.
  50794. /**
  50795. * @see <https://en.wikipedia.org/wiki/Box_plot>
  50796. * The meanings of 'min' and 'max' depend on user,
  50797. * and echarts do not need to know it.
  50798. * @readOnly
  50799. */
  50800. defaultValueDimensions: [{
  50801. name: 'min',
  50802. defaultTooltip: true
  50803. }, {
  50804. name: 'Q1',
  50805. defaultTooltip: true
  50806. }, {
  50807. name: 'median',
  50808. defaultTooltip: true
  50809. }, {
  50810. name: 'Q3',
  50811. defaultTooltip: true
  50812. }, {
  50813. name: 'max',
  50814. defaultTooltip: true
  50815. }],
  50816. /**
  50817. * @type {Array.<string>}
  50818. * @readOnly
  50819. */
  50820. dimensions: null,
  50821. /**
  50822. * @override
  50823. */
  50824. defaultOption: {
  50825. zlevel: 0,
  50826. // 一级层叠
  50827. z: 2,
  50828. // 二级层叠
  50829. coordinateSystem: 'cartesian2d',
  50830. legendHoverLink: true,
  50831. hoverAnimation: true,
  50832. // xAxisIndex: 0,
  50833. // yAxisIndex: 0,
  50834. layout: null,
  50835. // 'horizontal' or 'vertical'
  50836. boxWidth: [7, 50],
  50837. // [min, max] can be percent of band width.
  50838. itemStyle: {
  50839. color: '#fff',
  50840. borderWidth: 1
  50841. },
  50842. emphasis: {
  50843. itemStyle: {
  50844. borderWidth: 2,
  50845. shadowBlur: 5,
  50846. shadowOffsetX: 2,
  50847. shadowOffsetY: 2,
  50848. shadowColor: 'rgba(0,0,0,0.4)'
  50849. }
  50850. },
  50851. animationEasing: 'elasticOut',
  50852. animationDuration: 800
  50853. }
  50854. });
  50855. mixin(BoxplotSeries, seriesModelMixin, true);
  50856. /*
  50857. * Licensed to the Apache Software Foundation (ASF) under one
  50858. * or more contributor license agreements. See the NOTICE file
  50859. * distributed with this work for additional information
  50860. * regarding copyright ownership. The ASF licenses this file
  50861. * to you under the Apache License, Version 2.0 (the
  50862. * "License"); you may not use this file except in compliance
  50863. * with the License. You may obtain a copy of the License at
  50864. *
  50865. * http://www.apache.org/licenses/LICENSE-2.0
  50866. *
  50867. * Unless required by applicable law or agreed to in writing,
  50868. * software distributed under the License is distributed on an
  50869. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50870. * KIND, either express or implied. See the License for the
  50871. * specific language governing permissions and limitations
  50872. * under the License.
  50873. */
  50874. var NORMAL_ITEM_STYLE_PATH$1 = ['itemStyle'];
  50875. var EMPHASIS_ITEM_STYLE_PATH$1 = ['emphasis', 'itemStyle'];
  50876. var BoxplotView = Chart.extend({
  50877. type: 'boxplot',
  50878. render: function (seriesModel, ecModel, api) {
  50879. var data = seriesModel.getData();
  50880. var group = this.group;
  50881. var oldData = this._data; // There is no old data only when first rendering or switching from
  50882. // stream mode to normal mode, where previous elements should be removed.
  50883. if (!this._data) {
  50884. group.removeAll();
  50885. }
  50886. var constDim = seriesModel.get('layout') === 'horizontal' ? 1 : 0;
  50887. data.diff(oldData).add(function (newIdx) {
  50888. if (data.hasValue(newIdx)) {
  50889. var itemLayout = data.getItemLayout(newIdx);
  50890. var symbolEl = createNormalBox$1(itemLayout, data, newIdx, constDim, true);
  50891. data.setItemGraphicEl(newIdx, symbolEl);
  50892. group.add(symbolEl);
  50893. }
  50894. }).update(function (newIdx, oldIdx) {
  50895. var symbolEl = oldData.getItemGraphicEl(oldIdx); // Empty data
  50896. if (!data.hasValue(newIdx)) {
  50897. group.remove(symbolEl);
  50898. return;
  50899. }
  50900. var itemLayout = data.getItemLayout(newIdx);
  50901. if (!symbolEl) {
  50902. symbolEl = createNormalBox$1(itemLayout, data, newIdx, constDim);
  50903. } else {
  50904. updateNormalBoxData(itemLayout, symbolEl, data, newIdx);
  50905. }
  50906. group.add(symbolEl);
  50907. data.setItemGraphicEl(newIdx, symbolEl);
  50908. }).remove(function (oldIdx) {
  50909. var el = oldData.getItemGraphicEl(oldIdx);
  50910. el && group.remove(el);
  50911. }).execute();
  50912. this._data = data;
  50913. },
  50914. remove: function (ecModel) {
  50915. var group = this.group;
  50916. var data = this._data;
  50917. this._data = null;
  50918. data && data.eachItemGraphicEl(function (el) {
  50919. el && group.remove(el);
  50920. });
  50921. },
  50922. dispose: noop
  50923. });
  50924. var BoxPath = Path.extend({
  50925. type: 'boxplotBoxPath',
  50926. shape: {},
  50927. buildPath: function (ctx, shape) {
  50928. var ends = shape.points;
  50929. var i = 0;
  50930. ctx.moveTo(ends[i][0], ends[i][1]);
  50931. i++;
  50932. for (; i < 4; i++) {
  50933. ctx.lineTo(ends[i][0], ends[i][1]);
  50934. }
  50935. ctx.closePath();
  50936. for (; i < ends.length; i++) {
  50937. ctx.moveTo(ends[i][0], ends[i][1]);
  50938. i++;
  50939. ctx.lineTo(ends[i][0], ends[i][1]);
  50940. }
  50941. }
  50942. });
  50943. function createNormalBox$1(itemLayout, data, dataIndex, constDim, isInit) {
  50944. var ends = itemLayout.ends;
  50945. var el = new BoxPath({
  50946. shape: {
  50947. points: isInit ? transInit$1(ends, constDim, itemLayout) : ends
  50948. }
  50949. });
  50950. updateNormalBoxData(itemLayout, el, data, dataIndex, isInit);
  50951. return el;
  50952. }
  50953. function updateNormalBoxData(itemLayout, el, data, dataIndex, isInit) {
  50954. var seriesModel = data.hostModel;
  50955. var updateMethod = graphic[isInit ? 'initProps' : 'updateProps'];
  50956. updateMethod(el, {
  50957. shape: {
  50958. points: itemLayout.ends
  50959. }
  50960. }, seriesModel, dataIndex);
  50961. var itemModel = data.getItemModel(dataIndex);
  50962. var normalItemStyleModel = itemModel.getModel(NORMAL_ITEM_STYLE_PATH$1);
  50963. var borderColor = data.getItemVisual(dataIndex, 'color'); // Exclude borderColor.
  50964. var itemStyle = normalItemStyleModel.getItemStyle(['borderColor']);
  50965. itemStyle.stroke = borderColor;
  50966. itemStyle.strokeNoScale = true;
  50967. el.useStyle(itemStyle);
  50968. el.z2 = 100;
  50969. var hoverStyle = itemModel.getModel(EMPHASIS_ITEM_STYLE_PATH$1).getItemStyle();
  50970. setHoverStyle(el, hoverStyle);
  50971. }
  50972. function transInit$1(points, dim, itemLayout) {
  50973. return map(points, function (point) {
  50974. point = point.slice();
  50975. point[dim] = itemLayout.initBaseline;
  50976. return point;
  50977. });
  50978. }
  50979. /*
  50980. * Licensed to the Apache Software Foundation (ASF) under one
  50981. * or more contributor license agreements. See the NOTICE file
  50982. * distributed with this work for additional information
  50983. * regarding copyright ownership. The ASF licenses this file
  50984. * to you under the Apache License, Version 2.0 (the
  50985. * "License"); you may not use this file except in compliance
  50986. * with the License. You may obtain a copy of the License at
  50987. *
  50988. * http://www.apache.org/licenses/LICENSE-2.0
  50989. *
  50990. * Unless required by applicable law or agreed to in writing,
  50991. * software distributed under the License is distributed on an
  50992. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  50993. * KIND, either express or implied. See the License for the
  50994. * specific language governing permissions and limitations
  50995. * under the License.
  50996. */
  50997. var borderColorQuery = ['itemStyle', 'borderColor'];
  50998. var boxplotVisual = function (ecModel, api) {
  50999. var globalColors = ecModel.get('color');
  51000. ecModel.eachRawSeriesByType('boxplot', function (seriesModel) {
  51001. var defaulColor = globalColors[seriesModel.seriesIndex % globalColors.length];
  51002. var data = seriesModel.getData();
  51003. data.setVisual({
  51004. legendSymbol: 'roundRect',
  51005. // Use name 'color' but not 'borderColor' for legend usage and
  51006. // visual coding from other component like dataRange.
  51007. color: seriesModel.get(borderColorQuery) || defaulColor
  51008. }); // Only visible series has each data be visual encoded
  51009. if (!ecModel.isSeriesFiltered(seriesModel)) {
  51010. data.each(function (idx) {
  51011. var itemModel = data.getItemModel(idx);
  51012. data.setItemVisual(idx, {
  51013. color: itemModel.get(borderColorQuery, true)
  51014. });
  51015. });
  51016. }
  51017. });
  51018. };
  51019. /*
  51020. * Licensed to the Apache Software Foundation (ASF) under one
  51021. * or more contributor license agreements. See the NOTICE file
  51022. * distributed with this work for additional information
  51023. * regarding copyright ownership. The ASF licenses this file
  51024. * to you under the Apache License, Version 2.0 (the
  51025. * "License"); you may not use this file except in compliance
  51026. * with the License. You may obtain a copy of the License at
  51027. *
  51028. * http://www.apache.org/licenses/LICENSE-2.0
  51029. *
  51030. * Unless required by applicable law or agreed to in writing,
  51031. * software distributed under the License is distributed on an
  51032. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51033. * KIND, either express or implied. See the License for the
  51034. * specific language governing permissions and limitations
  51035. * under the License.
  51036. */
  51037. var each$11 = each$1;
  51038. var boxplotLayout = function (ecModel) {
  51039. var groupResult = groupSeriesByAxis(ecModel);
  51040. each$11(groupResult, function (groupItem) {
  51041. var seriesModels = groupItem.seriesModels;
  51042. if (!seriesModels.length) {
  51043. return;
  51044. }
  51045. calculateBase(groupItem);
  51046. each$11(seriesModels, function (seriesModel, idx) {
  51047. layoutSingleSeries(seriesModel, groupItem.boxOffsetList[idx], groupItem.boxWidthList[idx]);
  51048. });
  51049. });
  51050. };
  51051. /**
  51052. * Group series by axis.
  51053. */
  51054. function groupSeriesByAxis(ecModel) {
  51055. var result = [];
  51056. var axisList = [];
  51057. ecModel.eachSeriesByType('boxplot', function (seriesModel) {
  51058. var baseAxis = seriesModel.getBaseAxis();
  51059. var idx = indexOf(axisList, baseAxis);
  51060. if (idx < 0) {
  51061. idx = axisList.length;
  51062. axisList[idx] = baseAxis;
  51063. result[idx] = {
  51064. axis: baseAxis,
  51065. seriesModels: []
  51066. };
  51067. }
  51068. result[idx].seriesModels.push(seriesModel);
  51069. });
  51070. return result;
  51071. }
  51072. /**
  51073. * Calculate offset and box width for each series.
  51074. */
  51075. function calculateBase(groupItem) {
  51076. var extent;
  51077. var baseAxis = groupItem.axis;
  51078. var seriesModels = groupItem.seriesModels;
  51079. var seriesCount = seriesModels.length;
  51080. var boxWidthList = groupItem.boxWidthList = [];
  51081. var boxOffsetList = groupItem.boxOffsetList = [];
  51082. var boundList = [];
  51083. var bandWidth;
  51084. if (baseAxis.type === 'category') {
  51085. bandWidth = baseAxis.getBandWidth();
  51086. } else {
  51087. var maxDataCount = 0;
  51088. each$11(seriesModels, function (seriesModel) {
  51089. maxDataCount = Math.max(maxDataCount, seriesModel.getData().count());
  51090. });
  51091. extent = baseAxis.getExtent(), Math.abs(extent[1] - extent[0]) / maxDataCount;
  51092. }
  51093. each$11(seriesModels, function (seriesModel) {
  51094. var boxWidthBound = seriesModel.get('boxWidth');
  51095. if (!isArray(boxWidthBound)) {
  51096. boxWidthBound = [boxWidthBound, boxWidthBound];
  51097. }
  51098. boundList.push([parsePercent$1(boxWidthBound[0], bandWidth) || 0, parsePercent$1(boxWidthBound[1], bandWidth) || 0]);
  51099. });
  51100. var availableWidth = bandWidth * 0.8 - 2;
  51101. var boxGap = availableWidth / seriesCount * 0.3;
  51102. var boxWidth = (availableWidth - boxGap * (seriesCount - 1)) / seriesCount;
  51103. var base = boxWidth / 2 - availableWidth / 2;
  51104. each$11(seriesModels, function (seriesModel, idx) {
  51105. boxOffsetList.push(base);
  51106. base += boxGap + boxWidth;
  51107. boxWidthList.push(Math.min(Math.max(boxWidth, boundList[idx][0]), boundList[idx][1]));
  51108. });
  51109. }
  51110. /**
  51111. * Calculate points location for each series.
  51112. */
  51113. function layoutSingleSeries(seriesModel, offset, boxWidth) {
  51114. var coordSys = seriesModel.coordinateSystem;
  51115. var data = seriesModel.getData();
  51116. var halfWidth = boxWidth / 2;
  51117. var cDimIdx = seriesModel.get('layout') === 'horizontal' ? 0 : 1;
  51118. var vDimIdx = 1 - cDimIdx;
  51119. var coordDims = ['x', 'y'];
  51120. var cDim = data.mapDimension(coordDims[cDimIdx]);
  51121. var vDims = data.mapDimension(coordDims[vDimIdx], true);
  51122. if (cDim == null || vDims.length < 5) {
  51123. return;
  51124. }
  51125. for (var dataIndex = 0; dataIndex < data.count(); dataIndex++) {
  51126. var axisDimVal = data.get(cDim, dataIndex);
  51127. var median = getPoint(axisDimVal, vDims[2], dataIndex);
  51128. var end1 = getPoint(axisDimVal, vDims[0], dataIndex);
  51129. var end2 = getPoint(axisDimVal, vDims[1], dataIndex);
  51130. var end4 = getPoint(axisDimVal, vDims[3], dataIndex);
  51131. var end5 = getPoint(axisDimVal, vDims[4], dataIndex);
  51132. var ends = [];
  51133. addBodyEnd(ends, end2, 0);
  51134. addBodyEnd(ends, end4, 1);
  51135. ends.push(end1, end2, end5, end4);
  51136. layEndLine(ends, end1);
  51137. layEndLine(ends, end5);
  51138. layEndLine(ends, median);
  51139. data.setItemLayout(dataIndex, {
  51140. initBaseline: median[vDimIdx],
  51141. ends: ends
  51142. });
  51143. }
  51144. function getPoint(axisDimVal, dimIdx, dataIndex) {
  51145. var val = data.get(dimIdx, dataIndex);
  51146. var p = [];
  51147. p[cDimIdx] = axisDimVal;
  51148. p[vDimIdx] = val;
  51149. var point;
  51150. if (isNaN(axisDimVal) || isNaN(val)) {
  51151. point = [NaN, NaN];
  51152. } else {
  51153. point = coordSys.dataToPoint(p);
  51154. point[cDimIdx] += offset;
  51155. }
  51156. return point;
  51157. }
  51158. function addBodyEnd(ends, point, start) {
  51159. var point1 = point.slice();
  51160. var point2 = point.slice();
  51161. point1[cDimIdx] += halfWidth;
  51162. point2[cDimIdx] -= halfWidth;
  51163. start ? ends.push(point1, point2) : ends.push(point2, point1);
  51164. }
  51165. function layEndLine(ends, endCenter) {
  51166. var from = endCenter.slice();
  51167. var to = endCenter.slice();
  51168. from[cDimIdx] -= halfWidth;
  51169. to[cDimIdx] += halfWidth;
  51170. ends.push(from, to);
  51171. }
  51172. }
  51173. /*
  51174. * Licensed to the Apache Software Foundation (ASF) under one
  51175. * or more contributor license agreements. See the NOTICE file
  51176. * distributed with this work for additional information
  51177. * regarding copyright ownership. The ASF licenses this file
  51178. * to you under the Apache License, Version 2.0 (the
  51179. * "License"); you may not use this file except in compliance
  51180. * with the License. You may obtain a copy of the License at
  51181. *
  51182. * http://www.apache.org/licenses/LICENSE-2.0
  51183. *
  51184. * Unless required by applicable law or agreed to in writing,
  51185. * software distributed under the License is distributed on an
  51186. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51187. * KIND, either express or implied. See the License for the
  51188. * specific language governing permissions and limitations
  51189. * under the License.
  51190. */
  51191. registerVisual(boxplotVisual);
  51192. registerLayout(boxplotLayout);
  51193. /*
  51194. * Licensed to the Apache Software Foundation (ASF) under one
  51195. * or more contributor license agreements. See the NOTICE file
  51196. * distributed with this work for additional information
  51197. * regarding copyright ownership. The ASF licenses this file
  51198. * to you under the Apache License, Version 2.0 (the
  51199. * "License"); you may not use this file except in compliance
  51200. * with the License. You may obtain a copy of the License at
  51201. *
  51202. * http://www.apache.org/licenses/LICENSE-2.0
  51203. *
  51204. * Unless required by applicable law or agreed to in writing,
  51205. * software distributed under the License is distributed on an
  51206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51207. * KIND, either express or implied. See the License for the
  51208. * specific language governing permissions and limitations
  51209. * under the License.
  51210. */
  51211. var parallelPreprocessor = function (option) {
  51212. createParallelIfNeeded(option);
  51213. mergeAxisOptionFromParallel(option);
  51214. };
  51215. /**
  51216. * Create a parallel coordinate if not exists.
  51217. * @inner
  51218. */
  51219. function createParallelIfNeeded(option) {
  51220. if (option.parallel) {
  51221. return;
  51222. }
  51223. var hasParallelSeries = false;
  51224. each$1(option.series, function (seriesOpt) {
  51225. if (seriesOpt && seriesOpt.type === 'parallel') {
  51226. hasParallelSeries = true;
  51227. }
  51228. });
  51229. if (hasParallelSeries) {
  51230. option.parallel = [{}];
  51231. }
  51232. }
  51233. /**
  51234. * Merge aixs definition from parallel option (if exists) to axis option.
  51235. * @inner
  51236. */
  51237. function mergeAxisOptionFromParallel(option) {
  51238. var axes = normalizeToArray(option.parallelAxis);
  51239. each$1(axes, function (axisOption) {
  51240. if (!isObject$1(axisOption)) {
  51241. return;
  51242. }
  51243. var parallelIndex = axisOption.parallelIndex || 0;
  51244. var parallelOption = normalizeToArray(option.parallel)[parallelIndex];
  51245. if (parallelOption && parallelOption.parallelAxisDefault) {
  51246. merge(axisOption, parallelOption.parallelAxisDefault, false);
  51247. }
  51248. });
  51249. }
  51250. /*
  51251. * Licensed to the Apache Software Foundation (ASF) under one
  51252. * or more contributor license agreements. See the NOTICE file
  51253. * distributed with this work for additional information
  51254. * regarding copyright ownership. The ASF licenses this file
  51255. * to you under the Apache License, Version 2.0 (the
  51256. * "License"); you may not use this file except in compliance
  51257. * with the License. You may obtain a copy of the License at
  51258. *
  51259. * http://www.apache.org/licenses/LICENSE-2.0
  51260. *
  51261. * Unless required by applicable law or agreed to in writing,
  51262. * software distributed under the License is distributed on an
  51263. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51264. * KIND, either express or implied. See the License for the
  51265. * specific language governing permissions and limitations
  51266. * under the License.
  51267. */
  51268. /**
  51269. * @constructor module:echarts/coord/parallel/ParallelAxis
  51270. * @extends {module:echarts/coord/Axis}
  51271. * @param {string} dim
  51272. * @param {*} scale
  51273. * @param {Array.<number>} coordExtent
  51274. * @param {string} axisType
  51275. */
  51276. var ParallelAxis = function (dim, scale, coordExtent, axisType, axisIndex) {
  51277. Axis.call(this, dim, scale, coordExtent);
  51278. /**
  51279. * Axis type
  51280. * - 'category'
  51281. * - 'value'
  51282. * - 'time'
  51283. * - 'log'
  51284. * @type {string}
  51285. */
  51286. this.type = axisType || 'value';
  51287. /**
  51288. * @type {number}
  51289. * @readOnly
  51290. */
  51291. this.axisIndex = axisIndex;
  51292. };
  51293. ParallelAxis.prototype = {
  51294. constructor: ParallelAxis,
  51295. /**
  51296. * Axis model
  51297. * @param {module:echarts/coord/parallel/AxisModel}
  51298. */
  51299. model: null,
  51300. /**
  51301. * @override
  51302. */
  51303. isHorizontal: function () {
  51304. return this.coordinateSystem.getModel().get('layout') !== 'horizontal';
  51305. }
  51306. };
  51307. inherits(ParallelAxis, Axis);
  51308. /*
  51309. * Licensed to the Apache Software Foundation (ASF) under one
  51310. * or more contributor license agreements. See the NOTICE file
  51311. * distributed with this work for additional information
  51312. * regarding copyright ownership. The ASF licenses this file
  51313. * to you under the Apache License, Version 2.0 (the
  51314. * "License"); you may not use this file except in compliance
  51315. * with the License. You may obtain a copy of the License at
  51316. *
  51317. * http://www.apache.org/licenses/LICENSE-2.0
  51318. *
  51319. * Unless required by applicable law or agreed to in writing,
  51320. * software distributed under the License is distributed on an
  51321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51322. * KIND, either express or implied. See the License for the
  51323. * specific language governing permissions and limitations
  51324. * under the License.
  51325. */
  51326. /**
  51327. * Calculate slider move result.
  51328. * Usage:
  51329. * (1) If both handle0 and handle1 are needed to be moved, set minSpan the same as
  51330. * maxSpan and the same as `Math.abs(handleEnd[1] - handleEnds[0])`.
  51331. * (2) If handle0 is forbidden to cross handle1, set minSpan as `0`.
  51332. *
  51333. * @param {number} delta Move length.
  51334. * @param {Array.<number>} handleEnds handleEnds[0] can be bigger then handleEnds[1].
  51335. * handleEnds will be modified in this method.
  51336. * @param {Array.<number>} extent handleEnds is restricted by extent.
  51337. * extent[0] should less or equals than extent[1].
  51338. * @param {number|string} handleIndex Can be 'all', means that both move the two handleEnds.
  51339. * @param {number} [minSpan] The range of dataZoom can not be smaller than that.
  51340. * If not set, handle0 and cross handle1. If set as a non-negative
  51341. * number (including `0`), handles will push each other when reaching
  51342. * the minSpan.
  51343. * @param {number} [maxSpan] The range of dataZoom can not be larger than that.
  51344. * @return {Array.<number>} The input handleEnds.
  51345. */
  51346. var sliderMove = function (delta, handleEnds, extent, handleIndex, minSpan, maxSpan) {
  51347. delta = delta || 0;
  51348. var extentSpan = extent[1] - extent[0]; // Notice maxSpan and minSpan can be null/undefined.
  51349. if (minSpan != null) {
  51350. minSpan = restrict$1(minSpan, [0, extentSpan]);
  51351. }
  51352. if (maxSpan != null) {
  51353. maxSpan = Math.max(maxSpan, minSpan != null ? minSpan : 0);
  51354. }
  51355. if (handleIndex === 'all') {
  51356. var handleSpan = Math.abs(handleEnds[1] - handleEnds[0]);
  51357. handleSpan = restrict$1(handleSpan, [0, extentSpan]);
  51358. minSpan = maxSpan = restrict$1(handleSpan, [minSpan, maxSpan]);
  51359. handleIndex = 0;
  51360. }
  51361. handleEnds[0] = restrict$1(handleEnds[0], extent);
  51362. handleEnds[1] = restrict$1(handleEnds[1], extent);
  51363. var originalDistSign = getSpanSign(handleEnds, handleIndex);
  51364. handleEnds[handleIndex] += delta; // Restrict in extent.
  51365. var extentMinSpan = minSpan || 0;
  51366. var realExtent = extent.slice();
  51367. originalDistSign.sign < 0 ? realExtent[0] += extentMinSpan : realExtent[1] -= extentMinSpan;
  51368. handleEnds[handleIndex] = restrict$1(handleEnds[handleIndex], realExtent); // Expand span.
  51369. var currDistSign = getSpanSign(handleEnds, handleIndex);
  51370. if (minSpan != null && (currDistSign.sign !== originalDistSign.sign || currDistSign.span < minSpan)) {
  51371. // If minSpan exists, 'cross' is forbidden.
  51372. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + originalDistSign.sign * minSpan;
  51373. } // Shrink span.
  51374. var currDistSign = getSpanSign(handleEnds, handleIndex);
  51375. if (maxSpan != null && currDistSign.span > maxSpan) {
  51376. handleEnds[1 - handleIndex] = handleEnds[handleIndex] + currDistSign.sign * maxSpan;
  51377. }
  51378. return handleEnds;
  51379. };
  51380. function getSpanSign(handleEnds, handleIndex) {
  51381. var dist = handleEnds[handleIndex] - handleEnds[1 - handleIndex]; // If `handleEnds[0] === handleEnds[1]`, always believe that handleEnd[0]
  51382. // is at left of handleEnds[1] for non-cross case.
  51383. return {
  51384. span: Math.abs(dist),
  51385. sign: dist > 0 ? -1 : dist < 0 ? 1 : handleIndex ? -1 : 1
  51386. };
  51387. }
  51388. function restrict$1(value, extend) {
  51389. return Math.min(extend[1] != null ? extend[1] : Infinity, Math.max(extend[0] != null ? extend[0] : -Infinity, value));
  51390. }
  51391. /*
  51392. * Licensed to the Apache Software Foundation (ASF) under one
  51393. * or more contributor license agreements. See the NOTICE file
  51394. * distributed with this work for additional information
  51395. * regarding copyright ownership. The ASF licenses this file
  51396. * to you under the Apache License, Version 2.0 (the
  51397. * "License"); you may not use this file except in compliance
  51398. * with the License. You may obtain a copy of the License at
  51399. *
  51400. * http://www.apache.org/licenses/LICENSE-2.0
  51401. *
  51402. * Unless required by applicable law or agreed to in writing,
  51403. * software distributed under the License is distributed on an
  51404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51405. * KIND, either express or implied. See the License for the
  51406. * specific language governing permissions and limitations
  51407. * under the License.
  51408. */
  51409. /**
  51410. * Parallel Coordinates
  51411. * <https://en.wikipedia.org/wiki/Parallel_coordinates>
  51412. */
  51413. var each$12 = each$1;
  51414. var mathMin$6 = Math.min;
  51415. var mathMax$6 = Math.max;
  51416. var mathFloor$2 = Math.floor;
  51417. var mathCeil$2 = Math.ceil;
  51418. var round$2 = round$1;
  51419. var PI$4 = Math.PI;
  51420. function Parallel(parallelModel, ecModel, api) {
  51421. /**
  51422. * key: dimension
  51423. * @type {Object.<string, module:echarts/coord/parallel/Axis>}
  51424. * @private
  51425. */
  51426. this._axesMap = createHashMap();
  51427. /**
  51428. * key: dimension
  51429. * value: {position: [], rotation, }
  51430. * @type {Object.<string, Object>}
  51431. * @private
  51432. */
  51433. this._axesLayout = {};
  51434. /**
  51435. * Always follow axis order.
  51436. * @type {Array.<string>}
  51437. * @readOnly
  51438. */
  51439. this.dimensions = parallelModel.dimensions;
  51440. /**
  51441. * @type {module:zrender/core/BoundingRect}
  51442. */
  51443. this._rect;
  51444. /**
  51445. * @type {module:echarts/coord/parallel/ParallelModel}
  51446. */
  51447. this._model = parallelModel;
  51448. this._init(parallelModel, ecModel, api);
  51449. }
  51450. Parallel.prototype = {
  51451. type: 'parallel',
  51452. constructor: Parallel,
  51453. /**
  51454. * Initialize cartesian coordinate systems
  51455. * @private
  51456. */
  51457. _init: function (parallelModel, ecModel, api) {
  51458. var dimensions = parallelModel.dimensions;
  51459. var parallelAxisIndex = parallelModel.parallelAxisIndex;
  51460. each$12(dimensions, function (dim, idx) {
  51461. var axisIndex = parallelAxisIndex[idx];
  51462. var axisModel = ecModel.getComponent('parallelAxis', axisIndex);
  51463. var axis = this._axesMap.set(dim, new ParallelAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisIndex));
  51464. var isCategory = axis.type === 'category';
  51465. axis.onBand = isCategory && axisModel.get('boundaryGap');
  51466. axis.inverse = axisModel.get('inverse'); // Injection
  51467. axisModel.axis = axis;
  51468. axis.model = axisModel;
  51469. axis.coordinateSystem = axisModel.coordinateSystem = this;
  51470. }, this);
  51471. },
  51472. /**
  51473. * Update axis scale after data processed
  51474. * @param {module:echarts/model/Global} ecModel
  51475. * @param {module:echarts/ExtensionAPI} api
  51476. */
  51477. update: function (ecModel, api) {
  51478. this._updateAxesFromSeries(this._model, ecModel);
  51479. },
  51480. /**
  51481. * @override
  51482. */
  51483. containPoint: function (point) {
  51484. var layoutInfo = this._makeLayoutInfo();
  51485. var axisBase = layoutInfo.axisBase;
  51486. var layoutBase = layoutInfo.layoutBase;
  51487. var pixelDimIndex = layoutInfo.pixelDimIndex;
  51488. var pAxis = point[1 - pixelDimIndex];
  51489. var pLayout = point[pixelDimIndex];
  51490. return pAxis >= axisBase && pAxis <= axisBase + layoutInfo.axisLength && pLayout >= layoutBase && pLayout <= layoutBase + layoutInfo.layoutLength;
  51491. },
  51492. getModel: function () {
  51493. return this._model;
  51494. },
  51495. /**
  51496. * Update properties from series
  51497. * @private
  51498. */
  51499. _updateAxesFromSeries: function (parallelModel, ecModel) {
  51500. ecModel.eachSeries(function (seriesModel) {
  51501. if (!parallelModel.contains(seriesModel, ecModel)) {
  51502. return;
  51503. }
  51504. var data = seriesModel.getData();
  51505. each$12(this.dimensions, function (dim) {
  51506. var axis = this._axesMap.get(dim);
  51507. axis.scale.unionExtentFromData(data, data.mapDimension(dim));
  51508. niceScaleExtent(axis.scale, axis.model);
  51509. }, this);
  51510. }, this);
  51511. },
  51512. /**
  51513. * Resize the parallel coordinate system.
  51514. * @param {module:echarts/coord/parallel/ParallelModel} parallelModel
  51515. * @param {module:echarts/ExtensionAPI} api
  51516. */
  51517. resize: function (parallelModel, api) {
  51518. this._rect = getLayoutRect(parallelModel.getBoxLayoutParams(), {
  51519. width: api.getWidth(),
  51520. height: api.getHeight()
  51521. });
  51522. this._layoutAxes();
  51523. },
  51524. /**
  51525. * @return {module:zrender/core/BoundingRect}
  51526. */
  51527. getRect: function () {
  51528. return this._rect;
  51529. },
  51530. /**
  51531. * @private
  51532. */
  51533. _makeLayoutInfo: function () {
  51534. var parallelModel = this._model;
  51535. var rect = this._rect;
  51536. var xy = ['x', 'y'];
  51537. var wh = ['width', 'height'];
  51538. var layout = parallelModel.get('layout');
  51539. var pixelDimIndex = layout === 'horizontal' ? 0 : 1;
  51540. var layoutLength = rect[wh[pixelDimIndex]];
  51541. var layoutExtent = [0, layoutLength];
  51542. var axisCount = this.dimensions.length;
  51543. var axisExpandWidth = restrict(parallelModel.get('axisExpandWidth'), layoutExtent);
  51544. var axisExpandCount = restrict(parallelModel.get('axisExpandCount') || 0, [0, axisCount]);
  51545. var axisExpandable = parallelModel.get('axisExpandable') && axisCount > 3 && axisCount > axisExpandCount && axisExpandCount > 1 && axisExpandWidth > 0 && layoutLength > 0; // `axisExpandWindow` is According to the coordinates of [0, axisExpandLength],
  51546. // for sake of consider the case that axisCollapseWidth is 0 (when screen is narrow),
  51547. // where collapsed axes should be overlapped.
  51548. var axisExpandWindow = parallelModel.get('axisExpandWindow');
  51549. var winSize;
  51550. if (!axisExpandWindow) {
  51551. winSize = restrict(axisExpandWidth * (axisExpandCount - 1), layoutExtent);
  51552. var axisExpandCenter = parallelModel.get('axisExpandCenter') || mathFloor$2(axisCount / 2);
  51553. axisExpandWindow = [axisExpandWidth * axisExpandCenter - winSize / 2];
  51554. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  51555. } else {
  51556. winSize = restrict(axisExpandWindow[1] - axisExpandWindow[0], layoutExtent);
  51557. axisExpandWindow[1] = axisExpandWindow[0] + winSize;
  51558. }
  51559. var axisCollapseWidth = (layoutLength - winSize) / (axisCount - axisExpandCount); // Avoid axisCollapseWidth is too small.
  51560. axisCollapseWidth < 3 && (axisCollapseWidth = 0); // Find the first and last indices > ewin[0] and < ewin[1].
  51561. var winInnerIndices = [mathFloor$2(round$2(axisExpandWindow[0] / axisExpandWidth, 1)) + 1, mathCeil$2(round$2(axisExpandWindow[1] / axisExpandWidth, 1)) - 1]; // Pos in ec coordinates.
  51562. var axisExpandWindow0Pos = axisCollapseWidth / axisExpandWidth * axisExpandWindow[0];
  51563. return {
  51564. layout: layout,
  51565. pixelDimIndex: pixelDimIndex,
  51566. layoutBase: rect[xy[pixelDimIndex]],
  51567. layoutLength: layoutLength,
  51568. axisBase: rect[xy[1 - pixelDimIndex]],
  51569. axisLength: rect[wh[1 - pixelDimIndex]],
  51570. axisExpandable: axisExpandable,
  51571. axisExpandWidth: axisExpandWidth,
  51572. axisCollapseWidth: axisCollapseWidth,
  51573. axisExpandWindow: axisExpandWindow,
  51574. axisCount: axisCount,
  51575. winInnerIndices: winInnerIndices,
  51576. axisExpandWindow0Pos: axisExpandWindow0Pos
  51577. };
  51578. },
  51579. /**
  51580. * @private
  51581. */
  51582. _layoutAxes: function () {
  51583. var rect = this._rect;
  51584. var axes = this._axesMap;
  51585. var dimensions = this.dimensions;
  51586. var layoutInfo = this._makeLayoutInfo();
  51587. var layout = layoutInfo.layout;
  51588. axes.each(function (axis) {
  51589. var axisExtent = [0, layoutInfo.axisLength];
  51590. var idx = axis.inverse ? 1 : 0;
  51591. axis.setExtent(axisExtent[idx], axisExtent[1 - idx]);
  51592. });
  51593. each$12(dimensions, function (dim, idx) {
  51594. var posInfo = (layoutInfo.axisExpandable ? layoutAxisWithExpand : layoutAxisWithoutExpand)(idx, layoutInfo);
  51595. var positionTable = {
  51596. horizontal: {
  51597. x: posInfo.position,
  51598. y: layoutInfo.axisLength
  51599. },
  51600. vertical: {
  51601. x: 0,
  51602. y: posInfo.position
  51603. }
  51604. };
  51605. var rotationTable = {
  51606. horizontal: PI$4 / 2,
  51607. vertical: 0
  51608. };
  51609. var position = [positionTable[layout].x + rect.x, positionTable[layout].y + rect.y];
  51610. var rotation = rotationTable[layout];
  51611. var transform = create$1();
  51612. rotate(transform, transform, rotation);
  51613. translate(transform, transform, position); // TODO
  51614. // tick等排布信息。
  51615. // TODO
  51616. // 根据axis order 更新 dimensions顺序。
  51617. this._axesLayout[dim] = {
  51618. position: position,
  51619. rotation: rotation,
  51620. transform: transform,
  51621. axisNameAvailableWidth: posInfo.axisNameAvailableWidth,
  51622. axisLabelShow: posInfo.axisLabelShow,
  51623. nameTruncateMaxWidth: posInfo.nameTruncateMaxWidth,
  51624. tickDirection: 1,
  51625. labelDirection: 1
  51626. };
  51627. }, this);
  51628. },
  51629. /**
  51630. * Get axis by dim.
  51631. * @param {string} dim
  51632. * @return {module:echarts/coord/parallel/ParallelAxis} [description]
  51633. */
  51634. getAxis: function (dim) {
  51635. return this._axesMap.get(dim);
  51636. },
  51637. /**
  51638. * Convert a dim value of a single item of series data to Point.
  51639. * @param {*} value
  51640. * @param {string} dim
  51641. * @return {Array}
  51642. */
  51643. dataToPoint: function (value, dim) {
  51644. return this.axisCoordToPoint(this._axesMap.get(dim).dataToCoord(value), dim);
  51645. },
  51646. /**
  51647. * Travel data for one time, get activeState of each data item.
  51648. * @param {module:echarts/data/List} data
  51649. * @param {Functio} cb param: {string} activeState 'active' or 'inactive' or 'normal'
  51650. * {number} dataIndex
  51651. * @param {number} [start=0] the start dataIndex that travel from.
  51652. * @param {number} [end=data.count()] the next dataIndex of the last dataIndex will be travel.
  51653. */
  51654. eachActiveState: function (data, callback, start, end) {
  51655. start == null && (start = 0);
  51656. end == null && (end = data.count());
  51657. var axesMap = this._axesMap;
  51658. var dimensions = this.dimensions;
  51659. var dataDimensions = [];
  51660. var axisModels = [];
  51661. each$1(dimensions, function (axisDim) {
  51662. dataDimensions.push(data.mapDimension(axisDim));
  51663. axisModels.push(axesMap.get(axisDim).model);
  51664. });
  51665. var hasActiveSet = this.hasAxisBrushed();
  51666. for (var dataIndex = start; dataIndex < end; dataIndex++) {
  51667. var activeState;
  51668. if (!hasActiveSet) {
  51669. activeState = 'normal';
  51670. } else {
  51671. activeState = 'active';
  51672. var values = data.getValues(dataDimensions, dataIndex);
  51673. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  51674. var state = axisModels[j].getActiveState(values[j]);
  51675. if (state === 'inactive') {
  51676. activeState = 'inactive';
  51677. break;
  51678. }
  51679. }
  51680. }
  51681. callback(activeState, dataIndex);
  51682. }
  51683. },
  51684. /**
  51685. * Whether has any activeSet.
  51686. * @return {boolean}
  51687. */
  51688. hasAxisBrushed: function () {
  51689. var dimensions = this.dimensions;
  51690. var axesMap = this._axesMap;
  51691. var hasActiveSet = false;
  51692. for (var j = 0, lenj = dimensions.length; j < lenj; j++) {
  51693. if (axesMap.get(dimensions[j]).model.getActiveState() !== 'normal') {
  51694. hasActiveSet = true;
  51695. }
  51696. }
  51697. return hasActiveSet;
  51698. },
  51699. /**
  51700. * Convert coords of each axis to Point.
  51701. * Return point. For example: [10, 20]
  51702. * @param {Array.<number>} coords
  51703. * @param {string} dim
  51704. * @return {Array.<number>}
  51705. */
  51706. axisCoordToPoint: function (coord, dim) {
  51707. var axisLayout = this._axesLayout[dim];
  51708. return applyTransform$1([coord, 0], axisLayout.transform);
  51709. },
  51710. /**
  51711. * Get axis layout.
  51712. */
  51713. getAxisLayout: function (dim) {
  51714. return clone(this._axesLayout[dim]);
  51715. },
  51716. /**
  51717. * @param {Array.<number>} point
  51718. * @return {Object} {axisExpandWindow, delta, behavior: 'jump' | 'slide' | 'none'}.
  51719. */
  51720. getSlidedAxisExpandWindow: function (point) {
  51721. var layoutInfo = this._makeLayoutInfo();
  51722. var pixelDimIndex = layoutInfo.pixelDimIndex;
  51723. var axisExpandWindow = layoutInfo.axisExpandWindow.slice();
  51724. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  51725. var extent = [0, layoutInfo.axisExpandWidth * (layoutInfo.axisCount - 1)]; // Out of the area of coordinate system.
  51726. if (!this.containPoint(point)) {
  51727. return {
  51728. behavior: 'none',
  51729. axisExpandWindow: axisExpandWindow
  51730. };
  51731. } // Conver the point from global to expand coordinates.
  51732. var pointCoord = point[pixelDimIndex] - layoutInfo.layoutBase - layoutInfo.axisExpandWindow0Pos; // For dragging operation convenience, the window should not be
  51733. // slided when mouse is the center area of the window.
  51734. var delta;
  51735. var behavior = 'slide';
  51736. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  51737. var triggerArea = this._model.get('axisExpandSlideTriggerArea'); // But consider touch device, jump is necessary.
  51738. var useJump = triggerArea[0] != null;
  51739. if (axisCollapseWidth) {
  51740. if (useJump && axisCollapseWidth && pointCoord < winSize * triggerArea[0]) {
  51741. behavior = 'jump';
  51742. delta = pointCoord - winSize * triggerArea[2];
  51743. } else if (useJump && axisCollapseWidth && pointCoord > winSize * (1 - triggerArea[0])) {
  51744. behavior = 'jump';
  51745. delta = pointCoord - winSize * (1 - triggerArea[2]);
  51746. } else {
  51747. (delta = pointCoord - winSize * triggerArea[1]) >= 0 && (delta = pointCoord - winSize * (1 - triggerArea[1])) <= 0 && (delta = 0);
  51748. }
  51749. delta *= layoutInfo.axisExpandWidth / axisCollapseWidth;
  51750. delta ? sliderMove(delta, axisExpandWindow, extent, 'all') // Avoid nonsense triger on mousemove.
  51751. : behavior = 'none';
  51752. } // When screen is too narrow, make it visible and slidable, although it is hard to interact.
  51753. else {
  51754. var winSize = axisExpandWindow[1] - axisExpandWindow[0];
  51755. var pos = extent[1] * pointCoord / winSize;
  51756. axisExpandWindow = [mathMax$6(0, pos - winSize / 2)];
  51757. axisExpandWindow[1] = mathMin$6(extent[1], axisExpandWindow[0] + winSize);
  51758. axisExpandWindow[0] = axisExpandWindow[1] - winSize;
  51759. }
  51760. return {
  51761. axisExpandWindow: axisExpandWindow,
  51762. behavior: behavior
  51763. };
  51764. }
  51765. };
  51766. function restrict(len, extent) {
  51767. return mathMin$6(mathMax$6(len, extent[0]), extent[1]);
  51768. }
  51769. function layoutAxisWithoutExpand(axisIndex, layoutInfo) {
  51770. var step = layoutInfo.layoutLength / (layoutInfo.axisCount - 1);
  51771. return {
  51772. position: step * axisIndex,
  51773. axisNameAvailableWidth: step,
  51774. axisLabelShow: true
  51775. };
  51776. }
  51777. function layoutAxisWithExpand(axisIndex, layoutInfo) {
  51778. var layoutLength = layoutInfo.layoutLength;
  51779. var axisExpandWidth = layoutInfo.axisExpandWidth;
  51780. var axisCount = layoutInfo.axisCount;
  51781. var axisCollapseWidth = layoutInfo.axisCollapseWidth;
  51782. var winInnerIndices = layoutInfo.winInnerIndices;
  51783. var position;
  51784. var axisNameAvailableWidth = axisCollapseWidth;
  51785. var axisLabelShow = false;
  51786. var nameTruncateMaxWidth;
  51787. if (axisIndex < winInnerIndices[0]) {
  51788. position = axisIndex * axisCollapseWidth;
  51789. nameTruncateMaxWidth = axisCollapseWidth;
  51790. } else if (axisIndex <= winInnerIndices[1]) {
  51791. position = layoutInfo.axisExpandWindow0Pos + axisIndex * axisExpandWidth - layoutInfo.axisExpandWindow[0];
  51792. axisNameAvailableWidth = axisExpandWidth;
  51793. axisLabelShow = true;
  51794. } else {
  51795. position = layoutLength - (axisCount - 1 - axisIndex) * axisCollapseWidth;
  51796. nameTruncateMaxWidth = axisCollapseWidth;
  51797. }
  51798. return {
  51799. position: position,
  51800. axisNameAvailableWidth: axisNameAvailableWidth,
  51801. axisLabelShow: axisLabelShow,
  51802. nameTruncateMaxWidth: nameTruncateMaxWidth
  51803. };
  51804. }
  51805. /*
  51806. * Licensed to the Apache Software Foundation (ASF) under one
  51807. * or more contributor license agreements. See the NOTICE file
  51808. * distributed with this work for additional information
  51809. * regarding copyright ownership. The ASF licenses this file
  51810. * to you under the Apache License, Version 2.0 (the
  51811. * "License"); you may not use this file except in compliance
  51812. * with the License. You may obtain a copy of the License at
  51813. *
  51814. * http://www.apache.org/licenses/LICENSE-2.0
  51815. *
  51816. * Unless required by applicable law or agreed to in writing,
  51817. * software distributed under the License is distributed on an
  51818. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51819. * KIND, either express or implied. See the License for the
  51820. * specific language governing permissions and limitations
  51821. * under the License.
  51822. */
  51823. /**
  51824. * Parallel coordinate system creater.
  51825. */
  51826. function create$2(ecModel, api) {
  51827. var coordSysList = [];
  51828. ecModel.eachComponent('parallel', function (parallelModel, idx) {
  51829. var coordSys = new Parallel(parallelModel, ecModel, api);
  51830. coordSys.name = 'parallel_' + idx;
  51831. coordSys.resize(parallelModel, api);
  51832. parallelModel.coordinateSystem = coordSys;
  51833. coordSys.model = parallelModel;
  51834. coordSysList.push(coordSys);
  51835. }); // Inject the coordinateSystems into seriesModel
  51836. ecModel.eachSeries(function (seriesModel) {
  51837. if (seriesModel.get('coordinateSystem') === 'parallel') {
  51838. var parallelModel = ecModel.queryComponents({
  51839. mainType: 'parallel',
  51840. index: seriesModel.get('parallelIndex'),
  51841. id: seriesModel.get('parallelId')
  51842. })[0];
  51843. seriesModel.coordinateSystem = parallelModel.coordinateSystem;
  51844. }
  51845. });
  51846. return coordSysList;
  51847. }
  51848. CoordinateSystemManager.register('parallel', {
  51849. create: create$2
  51850. });
  51851. /*
  51852. * Licensed to the Apache Software Foundation (ASF) under one
  51853. * or more contributor license agreements. See the NOTICE file
  51854. * distributed with this work for additional information
  51855. * regarding copyright ownership. The ASF licenses this file
  51856. * to you under the Apache License, Version 2.0 (the
  51857. * "License"); you may not use this file except in compliance
  51858. * with the License. You may obtain a copy of the License at
  51859. *
  51860. * http://www.apache.org/licenses/LICENSE-2.0
  51861. *
  51862. * Unless required by applicable law or agreed to in writing,
  51863. * software distributed under the License is distributed on an
  51864. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51865. * KIND, either express or implied. See the License for the
  51866. * specific language governing permissions and limitations
  51867. * under the License.
  51868. */
  51869. var AxisModel$2 = ComponentModel.extend({
  51870. type: 'baseParallelAxis',
  51871. /**
  51872. * @type {module:echarts/coord/parallel/Axis}
  51873. */
  51874. axis: null,
  51875. /**
  51876. * @type {Array.<Array.<number>}
  51877. * @readOnly
  51878. */
  51879. activeIntervals: [],
  51880. /**
  51881. * @return {Object}
  51882. */
  51883. getAreaSelectStyle: function () {
  51884. return makeStyleMapper([['fill', 'color'], ['lineWidth', 'borderWidth'], ['stroke', 'borderColor'], ['width', 'width'], ['opacity', 'opacity']])(this.getModel('areaSelectStyle'));
  51885. },
  51886. /**
  51887. * The code of this feature is put on AxisModel but not ParallelAxis,
  51888. * because axisModel can be alive after echarts updating but instance of
  51889. * ParallelAxis having been disposed. this._activeInterval should be kept
  51890. * when action dispatched (i.e. legend click).
  51891. *
  51892. * @param {Array.<Array<number>>} intervals interval.length === 0
  51893. * means set all active.
  51894. * @public
  51895. */
  51896. setActiveIntervals: function (intervals) {
  51897. var activeIntervals = this.activeIntervals = clone(intervals); // Normalize
  51898. if (activeIntervals) {
  51899. for (var i = activeIntervals.length - 1; i >= 0; i--) {
  51900. asc(activeIntervals[i]);
  51901. }
  51902. }
  51903. },
  51904. /**
  51905. * @param {number|string} [value] When attempting to detect 'no activeIntervals set',
  51906. * value can not be input.
  51907. * @return {string} 'normal': no activeIntervals set,
  51908. * 'active',
  51909. * 'inactive'.
  51910. * @public
  51911. */
  51912. getActiveState: function (value) {
  51913. var activeIntervals = this.activeIntervals;
  51914. if (!activeIntervals.length) {
  51915. return 'normal';
  51916. }
  51917. if (value == null || isNaN(value)) {
  51918. return 'inactive';
  51919. } // Simple optimization
  51920. if (activeIntervals.length === 1) {
  51921. var interval = activeIntervals[0];
  51922. if (interval[0] <= value && value <= interval[1]) {
  51923. return 'active';
  51924. }
  51925. } else {
  51926. for (var i = 0, len = activeIntervals.length; i < len; i++) {
  51927. if (activeIntervals[i][0] <= value && value <= activeIntervals[i][1]) {
  51928. return 'active';
  51929. }
  51930. }
  51931. }
  51932. return 'inactive';
  51933. }
  51934. });
  51935. var defaultOption$1 = {
  51936. type: 'value',
  51937. /**
  51938. * @type {Array.<number>}
  51939. */
  51940. dim: null,
  51941. // 0, 1, 2, ...
  51942. // parallelIndex: null,
  51943. areaSelectStyle: {
  51944. width: 20,
  51945. borderWidth: 1,
  51946. borderColor: 'rgba(160,197,232)',
  51947. color: 'rgba(160,197,232)',
  51948. opacity: 0.3
  51949. },
  51950. realtime: true,
  51951. // Whether realtime update view when select.
  51952. z: 10
  51953. };
  51954. merge(AxisModel$2.prototype, axisModelCommonMixin);
  51955. function getAxisType$1(axisName, option) {
  51956. return option.type || (option.data ? 'category' : 'value');
  51957. }
  51958. axisModelCreator('parallel', AxisModel$2, getAxisType$1, defaultOption$1);
  51959. /*
  51960. * Licensed to the Apache Software Foundation (ASF) under one
  51961. * or more contributor license agreements. See the NOTICE file
  51962. * distributed with this work for additional information
  51963. * regarding copyright ownership. The ASF licenses this file
  51964. * to you under the Apache License, Version 2.0 (the
  51965. * "License"); you may not use this file except in compliance
  51966. * with the License. You may obtain a copy of the License at
  51967. *
  51968. * http://www.apache.org/licenses/LICENSE-2.0
  51969. *
  51970. * Unless required by applicable law or agreed to in writing,
  51971. * software distributed under the License is distributed on an
  51972. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  51973. * KIND, either express or implied. See the License for the
  51974. * specific language governing permissions and limitations
  51975. * under the License.
  51976. */
  51977. ComponentModel.extend({
  51978. type: 'parallel',
  51979. dependencies: ['parallelAxis'],
  51980. /**
  51981. * @type {module:echarts/coord/parallel/Parallel}
  51982. */
  51983. coordinateSystem: null,
  51984. /**
  51985. * Each item like: 'dim0', 'dim1', 'dim2', ...
  51986. * @type {Array.<string>}
  51987. * @readOnly
  51988. */
  51989. dimensions: null,
  51990. /**
  51991. * Coresponding to dimensions.
  51992. * @type {Array.<number>}
  51993. * @readOnly
  51994. */
  51995. parallelAxisIndex: null,
  51996. layoutMode: 'box',
  51997. defaultOption: {
  51998. zlevel: 0,
  51999. z: 0,
  52000. left: 80,
  52001. top: 60,
  52002. right: 80,
  52003. bottom: 60,
  52004. // width: {totalWidth} - left - right,
  52005. // height: {totalHeight} - top - bottom,
  52006. layout: 'horizontal',
  52007. // 'horizontal' or 'vertical'
  52008. // FIXME
  52009. // naming?
  52010. axisExpandable: false,
  52011. axisExpandCenter: null,
  52012. axisExpandCount: 0,
  52013. axisExpandWidth: 50,
  52014. // FIXME '10%' ?
  52015. axisExpandRate: 17,
  52016. axisExpandDebounce: 50,
  52017. // [out, in, jumpTarget]. In percentage. If use [null, 0.05], null means full.
  52018. // Do not doc to user until necessary.
  52019. axisExpandSlideTriggerArea: [-0.15, 0.05, 0.4],
  52020. axisExpandTriggerOn: 'click',
  52021. // 'mousemove' or 'click'
  52022. parallelAxisDefault: null
  52023. },
  52024. /**
  52025. * @override
  52026. */
  52027. init: function () {
  52028. ComponentModel.prototype.init.apply(this, arguments);
  52029. this.mergeOption({});
  52030. },
  52031. /**
  52032. * @override
  52033. */
  52034. mergeOption: function (newOption) {
  52035. var thisOption = this.option;
  52036. newOption && merge(thisOption, newOption, true);
  52037. this._initDimensions();
  52038. },
  52039. /**
  52040. * Whether series or axis is in this coordinate system.
  52041. * @param {module:echarts/model/Series|module:echarts/coord/parallel/AxisModel} model
  52042. * @param {module:echarts/model/Global} ecModel
  52043. */
  52044. contains: function (model, ecModel) {
  52045. var parallelIndex = model.get('parallelIndex');
  52046. return parallelIndex != null && ecModel.getComponent('parallel', parallelIndex) === this;
  52047. },
  52048. setAxisExpand: function (opt) {
  52049. each$1(['axisExpandable', 'axisExpandCenter', 'axisExpandCount', 'axisExpandWidth', 'axisExpandWindow'], function (name) {
  52050. if (opt.hasOwnProperty(name)) {
  52051. this.option[name] = opt[name];
  52052. }
  52053. }, this);
  52054. },
  52055. /**
  52056. * @private
  52057. */
  52058. _initDimensions: function () {
  52059. var dimensions = this.dimensions = [];
  52060. var parallelAxisIndex = this.parallelAxisIndex = [];
  52061. var axisModels = filter(this.dependentModels.parallelAxis, function (axisModel) {
  52062. // Can not use this.contains here, because
  52063. // initialization has not been completed yet.
  52064. return (axisModel.get('parallelIndex') || 0) === this.componentIndex;
  52065. }, this);
  52066. each$1(axisModels, function (axisModel) {
  52067. dimensions.push('dim' + axisModel.get('dim'));
  52068. parallelAxisIndex.push(axisModel.componentIndex);
  52069. });
  52070. }
  52071. });
  52072. /*
  52073. * Licensed to the Apache Software Foundation (ASF) under one
  52074. * or more contributor license agreements. See the NOTICE file
  52075. * distributed with this work for additional information
  52076. * regarding copyright ownership. The ASF licenses this file
  52077. * to you under the Apache License, Version 2.0 (the
  52078. * "License"); you may not use this file except in compliance
  52079. * with the License. You may obtain a copy of the License at
  52080. *
  52081. * http://www.apache.org/licenses/LICENSE-2.0
  52082. *
  52083. * Unless required by applicable law or agreed to in writing,
  52084. * software distributed under the License is distributed on an
  52085. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52086. * KIND, either express or implied. See the License for the
  52087. * specific language governing permissions and limitations
  52088. * under the License.
  52089. */
  52090. /**
  52091. * @payload
  52092. * @property {string} parallelAxisId
  52093. * @property {Array.<Array.<number>>} intervals
  52094. */
  52095. var actionInfo$1 = {
  52096. type: 'axisAreaSelect',
  52097. event: 'axisAreaSelected' // update: 'updateVisual'
  52098. };
  52099. registerAction(actionInfo$1, function (payload, ecModel) {
  52100. ecModel.eachComponent({
  52101. mainType: 'parallelAxis',
  52102. query: payload
  52103. }, function (parallelAxisModel) {
  52104. parallelAxisModel.axis.model.setActiveIntervals(payload.intervals);
  52105. });
  52106. });
  52107. /**
  52108. * @payload
  52109. */
  52110. registerAction('parallelAxisExpand', function (payload, ecModel) {
  52111. ecModel.eachComponent({
  52112. mainType: 'parallel',
  52113. query: payload
  52114. }, function (parallelModel) {
  52115. parallelModel.setAxisExpand(payload);
  52116. });
  52117. });
  52118. /*
  52119. * Licensed to the Apache Software Foundation (ASF) under one
  52120. * or more contributor license agreements. See the NOTICE file
  52121. * distributed with this work for additional information
  52122. * regarding copyright ownership. The ASF licenses this file
  52123. * to you under the Apache License, Version 2.0 (the
  52124. * "License"); you may not use this file except in compliance
  52125. * with the License. You may obtain a copy of the License at
  52126. *
  52127. * http://www.apache.org/licenses/LICENSE-2.0
  52128. *
  52129. * Unless required by applicable law or agreed to in writing,
  52130. * software distributed under the License is distributed on an
  52131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52132. * KIND, either express or implied. See the License for the
  52133. * specific language governing permissions and limitations
  52134. * under the License.
  52135. */
  52136. var curry$2 = curry;
  52137. var each$13 = each$1;
  52138. var map$2 = map;
  52139. var mathMin$7 = Math.min;
  52140. var mathMax$7 = Math.max;
  52141. var mathPow$2 = Math.pow;
  52142. var COVER_Z = 10000;
  52143. var UNSELECT_THRESHOLD = 6;
  52144. var MIN_RESIZE_LINE_WIDTH = 6;
  52145. var MUTEX_RESOURCE_KEY = 'globalPan';
  52146. var DIRECTION_MAP = {
  52147. w: [0, 0],
  52148. e: [0, 1],
  52149. n: [1, 0],
  52150. s: [1, 1]
  52151. };
  52152. var CURSOR_MAP = {
  52153. w: 'ew',
  52154. e: 'ew',
  52155. n: 'ns',
  52156. s: 'ns',
  52157. ne: 'nesw',
  52158. sw: 'nesw',
  52159. nw: 'nwse',
  52160. se: 'nwse'
  52161. };
  52162. var DEFAULT_BRUSH_OPT = {
  52163. brushStyle: {
  52164. lineWidth: 2,
  52165. stroke: 'rgba(0,0,0,0.3)',
  52166. fill: 'rgba(0,0,0,0.1)'
  52167. },
  52168. transformable: true,
  52169. brushMode: 'single',
  52170. removeOnClick: false
  52171. };
  52172. var baseUID = 0;
  52173. /**
  52174. * @alias module:echarts/component/helper/BrushController
  52175. * @constructor
  52176. * @mixin {module:zrender/mixin/Eventful}
  52177. * @event module:echarts/component/helper/BrushController#brush
  52178. * params:
  52179. * areas: Array.<Array>, coord relates to container group,
  52180. * If no container specified, to global.
  52181. * opt {
  52182. * isEnd: boolean,
  52183. * removeOnClick: boolean
  52184. * }
  52185. *
  52186. * @param {module:zrender/zrender~ZRender} zr
  52187. */
  52188. function BrushController(zr) {
  52189. Eventful.call(this);
  52190. /**
  52191. * @type {module:zrender/zrender~ZRender}
  52192. * @private
  52193. */
  52194. this._zr = zr;
  52195. /**
  52196. * @type {module:zrender/container/Group}
  52197. * @readOnly
  52198. */
  52199. this.group = new Group();
  52200. /**
  52201. * Only for drawing (after enabledBrush).
  52202. * 'line', 'rect', 'polygon' or false
  52203. * If passing false/null/undefined, disable brush.
  52204. * If passing 'auto', determined by panel.defaultBrushType
  52205. * @private
  52206. * @type {string}
  52207. */
  52208. this._brushType;
  52209. /**
  52210. * Only for drawing (after enabledBrush).
  52211. *
  52212. * @private
  52213. * @type {Object}
  52214. */
  52215. this._brushOption;
  52216. /**
  52217. * @private
  52218. * @type {Object}
  52219. */
  52220. this._panels;
  52221. /**
  52222. * @private
  52223. * @type {Array.<nubmer>}
  52224. */
  52225. this._track = [];
  52226. /**
  52227. * @private
  52228. * @type {boolean}
  52229. */
  52230. this._dragging;
  52231. /**
  52232. * @private
  52233. * @type {Array}
  52234. */
  52235. this._covers = [];
  52236. /**
  52237. * @private
  52238. * @type {moudule:zrender/container/Group}
  52239. */
  52240. this._creatingCover;
  52241. /**
  52242. * `true` means global panel
  52243. * @private
  52244. * @type {module:zrender/container/Group|boolean}
  52245. */
  52246. this._creatingPanel;
  52247. /**
  52248. * @private
  52249. * @type {boolean}
  52250. */
  52251. this._enableGlobalPan;
  52252. /**
  52253. * @private
  52254. * @type {boolean}
  52255. */
  52256. /**
  52257. * @private
  52258. * @type {string}
  52259. */
  52260. this._uid = 'brushController_' + baseUID++;
  52261. /**
  52262. * @private
  52263. * @type {Object}
  52264. */
  52265. this._handlers = {};
  52266. each$13(pointerHandlers, function (handler, eventName) {
  52267. this._handlers[eventName] = bind(handler, this);
  52268. }, this);
  52269. }
  52270. BrushController.prototype = {
  52271. constructor: BrushController,
  52272. /**
  52273. * If set to null/undefined/false, select disabled.
  52274. * @param {Object} brushOption
  52275. * @param {string|boolean} brushOption.brushType 'line', 'rect', 'polygon' or false
  52276. * If passing false/null/undefined, disable brush.
  52277. * If passing 'auto', determined by panel.defaultBrushType.
  52278. * ('auto' can not be used in global panel)
  52279. * @param {number} [brushOption.brushMode='single'] 'single' or 'multiple'
  52280. * @param {boolean} [brushOption.transformable=true]
  52281. * @param {boolean} [brushOption.removeOnClick=false]
  52282. * @param {Object} [brushOption.brushStyle]
  52283. * @param {number} [brushOption.brushStyle.width]
  52284. * @param {number} [brushOption.brushStyle.lineWidth]
  52285. * @param {string} [brushOption.brushStyle.stroke]
  52286. * @param {string} [brushOption.brushStyle.fill]
  52287. * @param {number} [brushOption.z]
  52288. */
  52289. enableBrush: function (brushOption) {
  52290. this._brushType && doDisableBrush(this);
  52291. brushOption.brushType && doEnableBrush(this, brushOption);
  52292. return this;
  52293. },
  52294. /**
  52295. * @param {Array.<Object>} panelOpts If not pass, it is global brush.
  52296. * Each items: {
  52297. * panelId, // mandatory.
  52298. * clipPath, // mandatory. function.
  52299. * isTargetByCursor, // mandatory. function.
  52300. * defaultBrushType, // optional, only used when brushType is 'auto'.
  52301. * getLinearBrushOtherExtent, // optional. function.
  52302. * }
  52303. */
  52304. setPanels: function (panelOpts) {
  52305. if (panelOpts && panelOpts.length) {
  52306. var panels = this._panels = {};
  52307. each$1(panelOpts, function (panelOpts) {
  52308. panels[panelOpts.panelId] = clone(panelOpts);
  52309. });
  52310. } else {
  52311. this._panels = null;
  52312. }
  52313. return this;
  52314. },
  52315. /**
  52316. * @param {Object} [opt]
  52317. * @return {boolean} [opt.enableGlobalPan=false]
  52318. */
  52319. mount: function (opt) {
  52320. opt = opt || {};
  52321. this._enableGlobalPan = opt.enableGlobalPan;
  52322. var thisGroup = this.group;
  52323. this._zr.add(thisGroup);
  52324. thisGroup.attr({
  52325. position: opt.position || [0, 0],
  52326. rotation: opt.rotation || 0,
  52327. scale: opt.scale || [1, 1]
  52328. });
  52329. this._transform = thisGroup.getLocalTransform();
  52330. return this;
  52331. },
  52332. eachCover: function (cb, context) {
  52333. each$13(this._covers, cb, context);
  52334. },
  52335. /**
  52336. * Update covers.
  52337. * @param {Array.<Object>} brushOptionList Like:
  52338. * [
  52339. * {id: 'xx', brushType: 'line', range: [23, 44], brushStyle, transformable},
  52340. * {id: 'yy', brushType: 'rect', range: [[23, 44], [23, 54]]},
  52341. * ...
  52342. * ]
  52343. * `brushType` is required in each cover info. (can not be 'auto')
  52344. * `id` is not mandatory.
  52345. * `brushStyle`, `transformable` is not mandatory, use DEFAULT_BRUSH_OPT by default.
  52346. * If brushOptionList is null/undefined, all covers removed.
  52347. */
  52348. updateCovers: function (brushOptionList) {
  52349. brushOptionList = map(brushOptionList, function (brushOption) {
  52350. return merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  52351. });
  52352. var tmpIdPrefix = '\0-brush-index-';
  52353. var oldCovers = this._covers;
  52354. var newCovers = this._covers = [];
  52355. var controller = this;
  52356. var creatingCover = this._creatingCover;
  52357. new DataDiffer(oldCovers, brushOptionList, oldGetKey, getKey).add(addOrUpdate).update(addOrUpdate).remove(remove).execute();
  52358. return this;
  52359. function getKey(brushOption, index) {
  52360. return (brushOption.id != null ? brushOption.id : tmpIdPrefix + index) + '-' + brushOption.brushType;
  52361. }
  52362. function oldGetKey(cover, index) {
  52363. return getKey(cover.__brushOption, index);
  52364. }
  52365. function addOrUpdate(newIndex, oldIndex) {
  52366. var newBrushOption = brushOptionList[newIndex]; // Consider setOption in event listener of brushSelect,
  52367. // where updating cover when creating should be forbiden.
  52368. if (oldIndex != null && oldCovers[oldIndex] === creatingCover) {
  52369. newCovers[newIndex] = oldCovers[oldIndex];
  52370. } else {
  52371. var cover = newCovers[newIndex] = oldIndex != null ? (oldCovers[oldIndex].__brushOption = newBrushOption, oldCovers[oldIndex]) : endCreating(controller, createCover(controller, newBrushOption));
  52372. updateCoverAfterCreation(controller, cover);
  52373. }
  52374. }
  52375. function remove(oldIndex) {
  52376. if (oldCovers[oldIndex] !== creatingCover) {
  52377. controller.group.remove(oldCovers[oldIndex]);
  52378. }
  52379. }
  52380. },
  52381. unmount: function () {
  52382. this.enableBrush(false); // container may 'removeAll' outside.
  52383. clearCovers(this);
  52384. this._zr.remove(this.group);
  52385. return this;
  52386. },
  52387. dispose: function () {
  52388. this.unmount();
  52389. this.off();
  52390. }
  52391. };
  52392. mixin(BrushController, Eventful);
  52393. function doEnableBrush(controller, brushOption) {
  52394. var zr = controller._zr; // Consider roam, which takes globalPan too.
  52395. if (!controller._enableGlobalPan) {
  52396. take(zr, MUTEX_RESOURCE_KEY, controller._uid);
  52397. }
  52398. mountHandlers(zr, controller._handlers);
  52399. controller._brushType = brushOption.brushType;
  52400. controller._brushOption = merge(clone(DEFAULT_BRUSH_OPT), brushOption, true);
  52401. }
  52402. function doDisableBrush(controller) {
  52403. var zr = controller._zr;
  52404. release(zr, MUTEX_RESOURCE_KEY, controller._uid);
  52405. unmountHandlers(zr, controller._handlers);
  52406. controller._brushType = controller._brushOption = null;
  52407. }
  52408. function mountHandlers(zr, handlers) {
  52409. each$13(handlers, function (handler, eventName) {
  52410. zr.on(eventName, handler);
  52411. });
  52412. }
  52413. function unmountHandlers(zr, handlers) {
  52414. each$13(handlers, function (handler, eventName) {
  52415. zr.off(eventName, handler);
  52416. });
  52417. }
  52418. function createCover(controller, brushOption) {
  52419. var cover = coverRenderers[brushOption.brushType].createCover(controller, brushOption);
  52420. cover.__brushOption = brushOption;
  52421. updateZ$1(cover, brushOption);
  52422. controller.group.add(cover);
  52423. return cover;
  52424. }
  52425. function endCreating(controller, creatingCover) {
  52426. var coverRenderer = getCoverRenderer(creatingCover);
  52427. if (coverRenderer.endCreating) {
  52428. coverRenderer.endCreating(controller, creatingCover);
  52429. updateZ$1(creatingCover, creatingCover.__brushOption);
  52430. }
  52431. return creatingCover;
  52432. }
  52433. function updateCoverShape(controller, cover) {
  52434. var brushOption = cover.__brushOption;
  52435. getCoverRenderer(cover).updateCoverShape(controller, cover, brushOption.range, brushOption);
  52436. }
  52437. function updateZ$1(cover, brushOption) {
  52438. var z = brushOption.z;
  52439. z == null && (z = COVER_Z);
  52440. cover.traverse(function (el) {
  52441. el.z = z;
  52442. el.z2 = z; // Consider in given container.
  52443. });
  52444. }
  52445. function updateCoverAfterCreation(controller, cover) {
  52446. getCoverRenderer(cover).updateCommon(controller, cover);
  52447. updateCoverShape(controller, cover);
  52448. }
  52449. function getCoverRenderer(cover) {
  52450. return coverRenderers[cover.__brushOption.brushType];
  52451. } // return target panel or `true` (means global panel)
  52452. function getPanelByPoint(controller, e, localCursorPoint) {
  52453. var panels = controller._panels;
  52454. if (!panels) {
  52455. return true; // Global panel
  52456. }
  52457. var panel;
  52458. var transform = controller._transform;
  52459. each$13(panels, function (pn) {
  52460. pn.isTargetByCursor(e, localCursorPoint, transform) && (panel = pn);
  52461. });
  52462. return panel;
  52463. } // Return a panel or true
  52464. function getPanelByCover(controller, cover) {
  52465. var panels = controller._panels;
  52466. if (!panels) {
  52467. return true; // Global panel
  52468. }
  52469. var panelId = cover.__brushOption.panelId; // User may give cover without coord sys info,
  52470. // which is then treated as global panel.
  52471. return panelId != null ? panels[panelId] : true;
  52472. }
  52473. function clearCovers(controller) {
  52474. var covers = controller._covers;
  52475. var originalLength = covers.length;
  52476. each$13(covers, function (cover) {
  52477. controller.group.remove(cover);
  52478. }, controller);
  52479. covers.length = 0;
  52480. return !!originalLength;
  52481. }
  52482. function trigger$1(controller, opt) {
  52483. var areas = map$2(controller._covers, function (cover) {
  52484. var brushOption = cover.__brushOption;
  52485. var range = clone(brushOption.range);
  52486. return {
  52487. brushType: brushOption.brushType,
  52488. panelId: brushOption.panelId,
  52489. range: range
  52490. };
  52491. });
  52492. controller.trigger('brush', areas, {
  52493. isEnd: !!opt.isEnd,
  52494. removeOnClick: !!opt.removeOnClick
  52495. });
  52496. }
  52497. function shouldShowCover(controller) {
  52498. var track = controller._track;
  52499. if (!track.length) {
  52500. return false;
  52501. }
  52502. var p2 = track[track.length - 1];
  52503. var p1 = track[0];
  52504. var dx = p2[0] - p1[0];
  52505. var dy = p2[1] - p1[1];
  52506. var dist = mathPow$2(dx * dx + dy * dy, 0.5);
  52507. return dist > UNSELECT_THRESHOLD;
  52508. }
  52509. function getTrackEnds(track) {
  52510. var tail = track.length - 1;
  52511. tail < 0 && (tail = 0);
  52512. return [track[0], track[tail]];
  52513. }
  52514. function createBaseRectCover(doDrift, controller, brushOption, edgeNames) {
  52515. var cover = new Group();
  52516. cover.add(new Rect({
  52517. name: 'main',
  52518. style: makeStyle(brushOption),
  52519. silent: true,
  52520. draggable: true,
  52521. cursor: 'move',
  52522. drift: curry$2(doDrift, controller, cover, 'nswe'),
  52523. ondragend: curry$2(trigger$1, controller, {
  52524. isEnd: true
  52525. })
  52526. }));
  52527. each$13(edgeNames, function (name) {
  52528. cover.add(new Rect({
  52529. name: name,
  52530. style: {
  52531. opacity: 0
  52532. },
  52533. draggable: true,
  52534. silent: true,
  52535. invisible: true,
  52536. drift: curry$2(doDrift, controller, cover, name),
  52537. ondragend: curry$2(trigger$1, controller, {
  52538. isEnd: true
  52539. })
  52540. }));
  52541. });
  52542. return cover;
  52543. }
  52544. function updateBaseRect(controller, cover, localRange, brushOption) {
  52545. var lineWidth = brushOption.brushStyle.lineWidth || 0;
  52546. var handleSize = mathMax$7(lineWidth, MIN_RESIZE_LINE_WIDTH);
  52547. var x = localRange[0][0];
  52548. var y = localRange[1][0];
  52549. var xa = x - lineWidth / 2;
  52550. var ya = y - lineWidth / 2;
  52551. var x2 = localRange[0][1];
  52552. var y2 = localRange[1][1];
  52553. var x2a = x2 - handleSize + lineWidth / 2;
  52554. var y2a = y2 - handleSize + lineWidth / 2;
  52555. var width = x2 - x;
  52556. var height = y2 - y;
  52557. var widtha = width + lineWidth;
  52558. var heighta = height + lineWidth;
  52559. updateRectShape(controller, cover, 'main', x, y, width, height);
  52560. if (brushOption.transformable) {
  52561. updateRectShape(controller, cover, 'w', xa, ya, handleSize, heighta);
  52562. updateRectShape(controller, cover, 'e', x2a, ya, handleSize, heighta);
  52563. updateRectShape(controller, cover, 'n', xa, ya, widtha, handleSize);
  52564. updateRectShape(controller, cover, 's', xa, y2a, widtha, handleSize);
  52565. updateRectShape(controller, cover, 'nw', xa, ya, handleSize, handleSize);
  52566. updateRectShape(controller, cover, 'ne', x2a, ya, handleSize, handleSize);
  52567. updateRectShape(controller, cover, 'sw', xa, y2a, handleSize, handleSize);
  52568. updateRectShape(controller, cover, 'se', x2a, y2a, handleSize, handleSize);
  52569. }
  52570. }
  52571. function updateCommon(controller, cover) {
  52572. var brushOption = cover.__brushOption;
  52573. var transformable = brushOption.transformable;
  52574. var mainEl = cover.childAt(0);
  52575. mainEl.useStyle(makeStyle(brushOption));
  52576. mainEl.attr({
  52577. silent: !transformable,
  52578. cursor: transformable ? 'move' : 'default'
  52579. });
  52580. each$13(['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw'], function (name) {
  52581. var el = cover.childOfName(name);
  52582. var globalDir = getGlobalDirection(controller, name);
  52583. el && el.attr({
  52584. silent: !transformable,
  52585. invisible: !transformable,
  52586. cursor: transformable ? CURSOR_MAP[globalDir] + '-resize' : null
  52587. });
  52588. });
  52589. }
  52590. function updateRectShape(controller, cover, name, x, y, w, h) {
  52591. var el = cover.childOfName(name);
  52592. el && el.setShape(pointsToRect(clipByPanel(controller, cover, [[x, y], [x + w, y + h]])));
  52593. }
  52594. function makeStyle(brushOption) {
  52595. return defaults({
  52596. strokeNoScale: true
  52597. }, brushOption.brushStyle);
  52598. }
  52599. function formatRectRange(x, y, x2, y2) {
  52600. var min = [mathMin$7(x, x2), mathMin$7(y, y2)];
  52601. var max = [mathMax$7(x, x2), mathMax$7(y, y2)];
  52602. return [[min[0], max[0]], // x range
  52603. [min[1], max[1]] // y range
  52604. ];
  52605. }
  52606. function getTransform$1(controller) {
  52607. return getTransform(controller.group);
  52608. }
  52609. function getGlobalDirection(controller, localDirection) {
  52610. if (localDirection.length > 1) {
  52611. localDirection = localDirection.split('');
  52612. var globalDir = [getGlobalDirection(controller, localDirection[0]), getGlobalDirection(controller, localDirection[1])];
  52613. (globalDir[0] === 'e' || globalDir[0] === 'w') && globalDir.reverse();
  52614. return globalDir.join('');
  52615. } else {
  52616. var map$$1 = {
  52617. w: 'left',
  52618. e: 'right',
  52619. n: 'top',
  52620. s: 'bottom'
  52621. };
  52622. var inverseMap = {
  52623. left: 'w',
  52624. right: 'e',
  52625. top: 'n',
  52626. bottom: 's'
  52627. };
  52628. var globalDir = transformDirection(map$$1[localDirection], getTransform$1(controller));
  52629. return inverseMap[globalDir];
  52630. }
  52631. }
  52632. function driftRect(toRectRange, fromRectRange, controller, cover, name, dx, dy, e) {
  52633. var brushOption = cover.__brushOption;
  52634. var rectRange = toRectRange(brushOption.range);
  52635. var localDelta = toLocalDelta(controller, dx, dy);
  52636. each$13(name.split(''), function (namePart) {
  52637. var ind = DIRECTION_MAP[namePart];
  52638. rectRange[ind[0]][ind[1]] += localDelta[ind[0]];
  52639. });
  52640. brushOption.range = fromRectRange(formatRectRange(rectRange[0][0], rectRange[1][0], rectRange[0][1], rectRange[1][1]));
  52641. updateCoverAfterCreation(controller, cover);
  52642. trigger$1(controller, {
  52643. isEnd: false
  52644. });
  52645. }
  52646. function driftPolygon(controller, cover, dx, dy, e) {
  52647. var range = cover.__brushOption.range;
  52648. var localDelta = toLocalDelta(controller, dx, dy);
  52649. each$13(range, function (point) {
  52650. point[0] += localDelta[0];
  52651. point[1] += localDelta[1];
  52652. });
  52653. updateCoverAfterCreation(controller, cover);
  52654. trigger$1(controller, {
  52655. isEnd: false
  52656. });
  52657. }
  52658. function toLocalDelta(controller, dx, dy) {
  52659. var thisGroup = controller.group;
  52660. var localD = thisGroup.transformCoordToLocal(dx, dy);
  52661. var localZero = thisGroup.transformCoordToLocal(0, 0);
  52662. return [localD[0] - localZero[0], localD[1] - localZero[1]];
  52663. }
  52664. function clipByPanel(controller, cover, data) {
  52665. var panel = getPanelByCover(controller, cover);
  52666. return panel && panel !== true ? panel.clipPath(data, controller._transform) : clone(data);
  52667. }
  52668. function pointsToRect(points) {
  52669. var xmin = mathMin$7(points[0][0], points[1][0]);
  52670. var ymin = mathMin$7(points[0][1], points[1][1]);
  52671. var xmax = mathMax$7(points[0][0], points[1][0]);
  52672. var ymax = mathMax$7(points[0][1], points[1][1]);
  52673. return {
  52674. x: xmin,
  52675. y: ymin,
  52676. width: xmax - xmin,
  52677. height: ymax - ymin
  52678. };
  52679. }
  52680. function resetCursor(controller, e, localCursorPoint) {
  52681. if ( // Check active
  52682. !controller._brushType // resetCursor should be always called when mouse is in zr area,
  52683. // but not called when mouse is out of zr area to avoid bad influence
  52684. // if `mousemove`, `mouseup` are triggered from `document` event.
  52685. || isOutsideZrArea(controller, e)) {
  52686. return;
  52687. }
  52688. var zr = controller._zr;
  52689. var covers = controller._covers;
  52690. var currPanel = getPanelByPoint(controller, e, localCursorPoint); // Check whether in covers.
  52691. if (!controller._dragging) {
  52692. for (var i = 0; i < covers.length; i++) {
  52693. var brushOption = covers[i].__brushOption;
  52694. if (currPanel && (currPanel === true || brushOption.panelId === currPanel.panelId) && coverRenderers[brushOption.brushType].contain(covers[i], localCursorPoint[0], localCursorPoint[1])) {
  52695. // Use cursor style set on cover.
  52696. return;
  52697. }
  52698. }
  52699. }
  52700. currPanel && zr.setCursorStyle('crosshair');
  52701. }
  52702. function preventDefault(e) {
  52703. var rawE = e.event;
  52704. rawE.preventDefault && rawE.preventDefault();
  52705. }
  52706. function mainShapeContain(cover, x, y) {
  52707. return cover.childOfName('main').contain(x, y);
  52708. }
  52709. function updateCoverByMouse(controller, e, localCursorPoint, isEnd) {
  52710. var creatingCover = controller._creatingCover;
  52711. var panel = controller._creatingPanel;
  52712. var thisBrushOption = controller._brushOption;
  52713. var eventParams;
  52714. controller._track.push(localCursorPoint.slice());
  52715. if (shouldShowCover(controller) || creatingCover) {
  52716. if (panel && !creatingCover) {
  52717. thisBrushOption.brushMode === 'single' && clearCovers(controller);
  52718. var brushOption = clone(thisBrushOption);
  52719. brushOption.brushType = determineBrushType(brushOption.brushType, panel);
  52720. brushOption.panelId = panel === true ? null : panel.panelId;
  52721. creatingCover = controller._creatingCover = createCover(controller, brushOption);
  52722. controller._covers.push(creatingCover);
  52723. }
  52724. if (creatingCover) {
  52725. var coverRenderer = coverRenderers[determineBrushType(controller._brushType, panel)];
  52726. var coverBrushOption = creatingCover.__brushOption;
  52727. coverBrushOption.range = coverRenderer.getCreatingRange(clipByPanel(controller, creatingCover, controller._track));
  52728. if (isEnd) {
  52729. endCreating(controller, creatingCover);
  52730. coverRenderer.updateCommon(controller, creatingCover);
  52731. }
  52732. updateCoverShape(controller, creatingCover);
  52733. eventParams = {
  52734. isEnd: isEnd
  52735. };
  52736. }
  52737. } else if (isEnd && thisBrushOption.brushMode === 'single' && thisBrushOption.removeOnClick) {
  52738. // Help user to remove covers easily, only by a tiny drag, in 'single' mode.
  52739. // But a single click do not clear covers, because user may have casual
  52740. // clicks (for example, click on other component and do not expect covers
  52741. // disappear).
  52742. // Only some cover removed, trigger action, but not every click trigger action.
  52743. if (getPanelByPoint(controller, e, localCursorPoint) && clearCovers(controller)) {
  52744. eventParams = {
  52745. isEnd: isEnd,
  52746. removeOnClick: true
  52747. };
  52748. }
  52749. }
  52750. return eventParams;
  52751. }
  52752. function determineBrushType(brushType, panel) {
  52753. if (brushType === 'auto') {
  52754. return panel.defaultBrushType;
  52755. }
  52756. return brushType;
  52757. }
  52758. var pointerHandlers = {
  52759. mousedown: function (e) {
  52760. if (this._dragging) {
  52761. // In case some browser do not support globalOut,
  52762. // and release mose out side the browser.
  52763. handleDragEnd(this, e);
  52764. } else if (!e.target || !e.target.draggable) {
  52765. preventDefault(e);
  52766. var localCursorPoint = this.group.transformCoordToLocal(e.offsetX, e.offsetY);
  52767. this._creatingCover = null;
  52768. var panel = this._creatingPanel = getPanelByPoint(this, e, localCursorPoint);
  52769. if (panel) {
  52770. this._dragging = true;
  52771. this._track = [localCursorPoint.slice()];
  52772. }
  52773. }
  52774. },
  52775. mousemove: function (e) {
  52776. var x = e.offsetX;
  52777. var y = e.offsetY;
  52778. var localCursorPoint = this.group.transformCoordToLocal(x, y);
  52779. resetCursor(this, e, localCursorPoint);
  52780. if (this._dragging) {
  52781. preventDefault(e);
  52782. var eventParams = updateCoverByMouse(this, e, localCursorPoint, false);
  52783. eventParams && trigger$1(this, eventParams);
  52784. }
  52785. },
  52786. mouseup: function (e) {
  52787. handleDragEnd(this, e);
  52788. }
  52789. };
  52790. function handleDragEnd(controller, e) {
  52791. if (controller._dragging) {
  52792. preventDefault(e);
  52793. var x = e.offsetX;
  52794. var y = e.offsetY;
  52795. var localCursorPoint = controller.group.transformCoordToLocal(x, y);
  52796. var eventParams = updateCoverByMouse(controller, e, localCursorPoint, true);
  52797. controller._dragging = false;
  52798. controller._track = [];
  52799. controller._creatingCover = null; // trigger event shoule be at final, after procedure will be nested.
  52800. eventParams && trigger$1(controller, eventParams);
  52801. }
  52802. }
  52803. function isOutsideZrArea(controller, x, y) {
  52804. var zr = controller._zr;
  52805. return x < 0 || x > zr.getWidth() || y < 0 || y > zr.getHeight();
  52806. }
  52807. /**
  52808. * key: brushType
  52809. * @type {Object}
  52810. */
  52811. var coverRenderers = {
  52812. lineX: getLineRenderer(0),
  52813. lineY: getLineRenderer(1),
  52814. rect: {
  52815. createCover: function (controller, brushOption) {
  52816. return createBaseRectCover(curry$2(driftRect, function (range) {
  52817. return range;
  52818. }, function (range) {
  52819. return range;
  52820. }), controller, brushOption, ['w', 'e', 'n', 's', 'se', 'sw', 'ne', 'nw']);
  52821. },
  52822. getCreatingRange: function (localTrack) {
  52823. var ends = getTrackEnds(localTrack);
  52824. return formatRectRange(ends[1][0], ends[1][1], ends[0][0], ends[0][1]);
  52825. },
  52826. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52827. updateBaseRect(controller, cover, localRange, brushOption);
  52828. },
  52829. updateCommon: updateCommon,
  52830. contain: mainShapeContain
  52831. },
  52832. polygon: {
  52833. createCover: function (controller, brushOption) {
  52834. var cover = new Group(); // Do not use graphic.Polygon because graphic.Polyline do not close the
  52835. // border of the shape when drawing, which is a better experience for user.
  52836. cover.add(new Polyline({
  52837. name: 'main',
  52838. style: makeStyle(brushOption),
  52839. silent: true
  52840. }));
  52841. return cover;
  52842. },
  52843. getCreatingRange: function (localTrack) {
  52844. return localTrack;
  52845. },
  52846. endCreating: function (controller, cover) {
  52847. cover.remove(cover.childAt(0)); // Use graphic.Polygon close the shape.
  52848. cover.add(new Polygon({
  52849. name: 'main',
  52850. draggable: true,
  52851. drift: curry$2(driftPolygon, controller, cover),
  52852. ondragend: curry$2(trigger$1, controller, {
  52853. isEnd: true
  52854. })
  52855. }));
  52856. },
  52857. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52858. cover.childAt(0).setShape({
  52859. points: clipByPanel(controller, cover, localRange)
  52860. });
  52861. },
  52862. updateCommon: updateCommon,
  52863. contain: mainShapeContain
  52864. }
  52865. };
  52866. function getLineRenderer(xyIndex) {
  52867. return {
  52868. createCover: function (controller, brushOption) {
  52869. return createBaseRectCover(curry$2(driftRect, function (range) {
  52870. var rectRange = [range, [0, 100]];
  52871. xyIndex && rectRange.reverse();
  52872. return rectRange;
  52873. }, function (rectRange) {
  52874. return rectRange[xyIndex];
  52875. }), controller, brushOption, [['w', 'e'], ['n', 's']][xyIndex]);
  52876. },
  52877. getCreatingRange: function (localTrack) {
  52878. var ends = getTrackEnds(localTrack);
  52879. var min = mathMin$7(ends[0][xyIndex], ends[1][xyIndex]);
  52880. var max = mathMax$7(ends[0][xyIndex], ends[1][xyIndex]);
  52881. return [min, max];
  52882. },
  52883. updateCoverShape: function (controller, cover, localRange, brushOption) {
  52884. var otherExtent; // If brushWidth not specified, fit the panel.
  52885. var panel = getPanelByCover(controller, cover);
  52886. if (panel !== true && panel.getLinearBrushOtherExtent) {
  52887. otherExtent = panel.getLinearBrushOtherExtent(xyIndex, controller._transform);
  52888. } else {
  52889. var zr = controller._zr;
  52890. otherExtent = [0, [zr.getWidth(), zr.getHeight()][1 - xyIndex]];
  52891. }
  52892. var rectRange = [localRange, otherExtent];
  52893. xyIndex && rectRange.reverse();
  52894. updateBaseRect(controller, cover, rectRange, brushOption);
  52895. },
  52896. updateCommon: updateCommon,
  52897. contain: mainShapeContain
  52898. };
  52899. }
  52900. /*
  52901. * Licensed to the Apache Software Foundation (ASF) under one
  52902. * or more contributor license agreements. See the NOTICE file
  52903. * distributed with this work for additional information
  52904. * regarding copyright ownership. The ASF licenses this file
  52905. * to you under the Apache License, Version 2.0 (the
  52906. * "License"); you may not use this file except in compliance
  52907. * with the License. You may obtain a copy of the License at
  52908. *
  52909. * http://www.apache.org/licenses/LICENSE-2.0
  52910. *
  52911. * Unless required by applicable law or agreed to in writing,
  52912. * software distributed under the License is distributed on an
  52913. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52914. * KIND, either express or implied. See the License for the
  52915. * specific language governing permissions and limitations
  52916. * under the License.
  52917. */
  52918. function makeRectPanelClipPath(rect) {
  52919. rect = normalizeRect(rect);
  52920. return function (localPoints, transform) {
  52921. return clipPointsByRect(localPoints, rect);
  52922. };
  52923. }
  52924. function makeLinearBrushOtherExtent(rect, specifiedXYIndex) {
  52925. rect = normalizeRect(rect);
  52926. return function (xyIndex) {
  52927. var idx = specifiedXYIndex != null ? specifiedXYIndex : xyIndex;
  52928. var brushWidth = idx ? rect.width : rect.height;
  52929. var base = idx ? rect.x : rect.y;
  52930. return [base, base + (brushWidth || 0)];
  52931. };
  52932. }
  52933. function makeRectIsTargetByCursor(rect, api, targetModel) {
  52934. rect = normalizeRect(rect);
  52935. return function (e, localCursorPoint, transform) {
  52936. return rect.contain(localCursorPoint[0], localCursorPoint[1]) && !onIrrelevantElement(e, api, targetModel);
  52937. };
  52938. } // Consider width/height is negative.
  52939. function normalizeRect(rect) {
  52940. return BoundingRect.create(rect);
  52941. }
  52942. /*
  52943. * Licensed to the Apache Software Foundation (ASF) under one
  52944. * or more contributor license agreements. See the NOTICE file
  52945. * distributed with this work for additional information
  52946. * regarding copyright ownership. The ASF licenses this file
  52947. * to you under the Apache License, Version 2.0 (the
  52948. * "License"); you may not use this file except in compliance
  52949. * with the License. You may obtain a copy of the License at
  52950. *
  52951. * http://www.apache.org/licenses/LICENSE-2.0
  52952. *
  52953. * Unless required by applicable law or agreed to in writing,
  52954. * software distributed under the License is distributed on an
  52955. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  52956. * KIND, either express or implied. See the License for the
  52957. * specific language governing permissions and limitations
  52958. * under the License.
  52959. */
  52960. var elementList = ['axisLine', 'axisTickLabel', 'axisName'];
  52961. var AxisView$2 = extendComponentView({
  52962. type: 'parallelAxis',
  52963. /**
  52964. * @override
  52965. */
  52966. init: function (ecModel, api) {
  52967. AxisView$2.superApply(this, 'init', arguments);
  52968. /**
  52969. * @type {module:echarts/component/helper/BrushController}
  52970. */
  52971. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this));
  52972. },
  52973. /**
  52974. * @override
  52975. */
  52976. render: function (axisModel, ecModel, api, payload) {
  52977. if (fromAxisAreaSelect(axisModel, ecModel, payload)) {
  52978. return;
  52979. }
  52980. this.axisModel = axisModel;
  52981. this.api = api;
  52982. this.group.removeAll();
  52983. var oldAxisGroup = this._axisGroup;
  52984. this._axisGroup = new Group();
  52985. this.group.add(this._axisGroup);
  52986. if (!axisModel.get('show')) {
  52987. return;
  52988. }
  52989. var coordSysModel = getCoordSysModel(axisModel, ecModel);
  52990. var coordSys = coordSysModel.coordinateSystem;
  52991. var areaSelectStyle = axisModel.getAreaSelectStyle();
  52992. var areaWidth = areaSelectStyle.width;
  52993. var dim = axisModel.axis.dim;
  52994. var axisLayout = coordSys.getAxisLayout(dim);
  52995. var builderOpt = extend({
  52996. strokeContainThreshold: areaWidth
  52997. }, axisLayout);
  52998. var axisBuilder = new AxisBuilder(axisModel, builderOpt);
  52999. each$1(elementList, axisBuilder.add, axisBuilder);
  53000. this._axisGroup.add(axisBuilder.getGroup());
  53001. this._refreshBrushController(builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api);
  53002. var animationModel = payload && payload.animation === false ? null : axisModel;
  53003. groupTransition(oldAxisGroup, this._axisGroup, animationModel);
  53004. },
  53005. // /**
  53006. // * @override
  53007. // */
  53008. // updateVisual: function (axisModel, ecModel, api, payload) {
  53009. // this._brushController && this._brushController
  53010. // .updateCovers(getCoverInfoList(axisModel));
  53011. // },
  53012. _refreshBrushController: function (builderOpt, areaSelectStyle, axisModel, coordSysModel, areaWidth, api) {
  53013. // After filtering, axis may change, select area needs to be update.
  53014. var extent = axisModel.axis.getExtent();
  53015. var extentLen = extent[1] - extent[0];
  53016. var extra = Math.min(30, Math.abs(extentLen) * 0.1); // Arbitrary value.
  53017. // width/height might be negative, which will be
  53018. // normalized in BoundingRect.
  53019. var rect = BoundingRect.create({
  53020. x: extent[0],
  53021. y: -areaWidth / 2,
  53022. width: extentLen,
  53023. height: areaWidth
  53024. });
  53025. rect.x -= extra;
  53026. rect.width += 2 * extra;
  53027. this._brushController.mount({
  53028. enableGlobalPan: true,
  53029. rotation: builderOpt.rotation,
  53030. position: builderOpt.position
  53031. }).setPanels([{
  53032. panelId: 'pl',
  53033. clipPath: makeRectPanelClipPath(rect),
  53034. isTargetByCursor: makeRectIsTargetByCursor(rect, api, coordSysModel),
  53035. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect, 0)
  53036. }]).enableBrush({
  53037. brushType: 'lineX',
  53038. brushStyle: areaSelectStyle,
  53039. removeOnClick: true
  53040. }).updateCovers(getCoverInfoList(axisModel));
  53041. },
  53042. _onBrush: function (coverInfoList, opt) {
  53043. // Do not cache these object, because the mey be changed.
  53044. var axisModel = this.axisModel;
  53045. var axis = axisModel.axis;
  53046. var intervals = map(coverInfoList, function (coverInfo) {
  53047. return [axis.coordToData(coverInfo.range[0], true), axis.coordToData(coverInfo.range[1], true)];
  53048. }); // If realtime is true, action is not dispatched on drag end, because
  53049. // the drag end emits the same params with the last drag move event,
  53050. // and may have some delay when using touch pad.
  53051. if (!axisModel.option.realtime === opt.isEnd || opt.removeOnClick) {
  53052. // jshint ignore:line
  53053. this.api.dispatchAction({
  53054. type: 'axisAreaSelect',
  53055. parallelAxisId: axisModel.id,
  53056. intervals: intervals
  53057. });
  53058. }
  53059. },
  53060. /**
  53061. * @override
  53062. */
  53063. dispose: function () {
  53064. this._brushController.dispose();
  53065. }
  53066. });
  53067. function fromAxisAreaSelect(axisModel, ecModel, payload) {
  53068. return payload && payload.type === 'axisAreaSelect' && ecModel.findComponents({
  53069. mainType: 'parallelAxis',
  53070. query: payload
  53071. })[0] === axisModel;
  53072. }
  53073. function getCoverInfoList(axisModel) {
  53074. var axis = axisModel.axis;
  53075. return map(axisModel.activeIntervals, function (interval) {
  53076. return {
  53077. brushType: 'lineX',
  53078. panelId: 'pl',
  53079. range: [axis.dataToCoord(interval[0], true), axis.dataToCoord(interval[1], true)]
  53080. };
  53081. });
  53082. }
  53083. function getCoordSysModel(axisModel, ecModel) {
  53084. return ecModel.getComponent('parallel', axisModel.get('parallelIndex'));
  53085. }
  53086. /*
  53087. * Licensed to the Apache Software Foundation (ASF) under one
  53088. * or more contributor license agreements. See the NOTICE file
  53089. * distributed with this work for additional information
  53090. * regarding copyright ownership. The ASF licenses this file
  53091. * to you under the Apache License, Version 2.0 (the
  53092. * "License"); you may not use this file except in compliance
  53093. * with the License. You may obtain a copy of the License at
  53094. *
  53095. * http://www.apache.org/licenses/LICENSE-2.0
  53096. *
  53097. * Unless required by applicable law or agreed to in writing,
  53098. * software distributed under the License is distributed on an
  53099. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53100. * KIND, either express or implied. See the License for the
  53101. * specific language governing permissions and limitations
  53102. * under the License.
  53103. */
  53104. /*
  53105. * Licensed to the Apache Software Foundation (ASF) under one
  53106. * or more contributor license agreements. See the NOTICE file
  53107. * distributed with this work for additional information
  53108. * regarding copyright ownership. The ASF licenses this file
  53109. * to you under the Apache License, Version 2.0 (the
  53110. * "License"); you may not use this file except in compliance
  53111. * with the License. You may obtain a copy of the License at
  53112. *
  53113. * http://www.apache.org/licenses/LICENSE-2.0
  53114. *
  53115. * Unless required by applicable law or agreed to in writing,
  53116. * software distributed under the License is distributed on an
  53117. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53118. * KIND, either express or implied. See the License for the
  53119. * specific language governing permissions and limitations
  53120. * under the License.
  53121. */
  53122. var CLICK_THRESHOLD = 5; // > 4
  53123. // Parallel view
  53124. extendComponentView({
  53125. type: 'parallel',
  53126. render: function (parallelModel, ecModel, api) {
  53127. this._model = parallelModel;
  53128. this._api = api;
  53129. if (!this._handlers) {
  53130. this._handlers = {};
  53131. each$1(handlers, function (handler, eventName) {
  53132. api.getZr().on(eventName, this._handlers[eventName] = bind(handler, this));
  53133. }, this);
  53134. }
  53135. createOrUpdate(this, '_throttledDispatchExpand', parallelModel.get('axisExpandRate'), 'fixRate');
  53136. },
  53137. dispose: function (ecModel, api) {
  53138. each$1(this._handlers, function (handler, eventName) {
  53139. api.getZr().off(eventName, handler);
  53140. });
  53141. this._handlers = null;
  53142. },
  53143. /**
  53144. * @param {Object} [opt] If null, cancle the last action triggering for debounce.
  53145. */
  53146. _throttledDispatchExpand: function (opt) {
  53147. this._dispatchExpand(opt);
  53148. },
  53149. _dispatchExpand: function (opt) {
  53150. opt && this._api.dispatchAction(extend({
  53151. type: 'parallelAxisExpand'
  53152. }, opt));
  53153. }
  53154. });
  53155. var handlers = {
  53156. mousedown: function (e) {
  53157. if (checkTrigger(this, 'click')) {
  53158. this._mouseDownPoint = [e.offsetX, e.offsetY];
  53159. }
  53160. },
  53161. mouseup: function (e) {
  53162. var mouseDownPoint = this._mouseDownPoint;
  53163. if (checkTrigger(this, 'click') && mouseDownPoint) {
  53164. var point = [e.offsetX, e.offsetY];
  53165. var dist = Math.pow(mouseDownPoint[0] - point[0], 2) + Math.pow(mouseDownPoint[1] - point[1], 2);
  53166. if (dist > CLICK_THRESHOLD) {
  53167. return;
  53168. }
  53169. var result = this._model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  53170. result.behavior !== 'none' && this._dispatchExpand({
  53171. axisExpandWindow: result.axisExpandWindow
  53172. });
  53173. }
  53174. this._mouseDownPoint = null;
  53175. },
  53176. mousemove: function (e) {
  53177. // Should do nothing when brushing.
  53178. if (this._mouseDownPoint || !checkTrigger(this, 'mousemove')) {
  53179. return;
  53180. }
  53181. var model = this._model;
  53182. var result = model.coordinateSystem.getSlidedAxisExpandWindow([e.offsetX, e.offsetY]);
  53183. var behavior = result.behavior;
  53184. behavior === 'jump' && this._throttledDispatchExpand.debounceNextCall(model.get('axisExpandDebounce'));
  53185. this._throttledDispatchExpand(behavior === 'none' ? null // Cancle the last trigger, in case that mouse slide out of the area quickly.
  53186. : {
  53187. axisExpandWindow: result.axisExpandWindow,
  53188. // Jumping uses animation, and sliding suppresses animation.
  53189. animation: behavior === 'jump' ? null : false
  53190. });
  53191. }
  53192. };
  53193. function checkTrigger(view, triggerOn) {
  53194. var model = view._model;
  53195. return model.get('axisExpandable') && model.get('axisExpandTriggerOn') === triggerOn;
  53196. }
  53197. registerPreprocessor(parallelPreprocessor);
  53198. /*
  53199. * Licensed to the Apache Software Foundation (ASF) under one
  53200. * or more contributor license agreements. See the NOTICE file
  53201. * distributed with this work for additional information
  53202. * regarding copyright ownership. The ASF licenses this file
  53203. * to you under the Apache License, Version 2.0 (the
  53204. * "License"); you may not use this file except in compliance
  53205. * with the License. You may obtain a copy of the License at
  53206. *
  53207. * http://www.apache.org/licenses/LICENSE-2.0
  53208. *
  53209. * Unless required by applicable law or agreed to in writing,
  53210. * software distributed under the License is distributed on an
  53211. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53212. * KIND, either express or implied. See the License for the
  53213. * specific language governing permissions and limitations
  53214. * under the License.
  53215. */
  53216. SeriesModel.extend({
  53217. type: 'series.parallel',
  53218. dependencies: ['parallel'],
  53219. visualColorAccessPath: 'lineStyle.color',
  53220. getInitialData: function (option, ecModel) {
  53221. var source = this.getSource();
  53222. setEncodeAndDimensions(source, this);
  53223. return createListFromArray(source, this);
  53224. },
  53225. /**
  53226. * User can get data raw indices on 'axisAreaSelected' event received.
  53227. *
  53228. * @public
  53229. * @param {string} activeState 'active' or 'inactive' or 'normal'
  53230. * @return {Array.<number>} Raw indices
  53231. */
  53232. getRawIndicesByActiveState: function (activeState) {
  53233. var coordSys = this.coordinateSystem;
  53234. var data = this.getData();
  53235. var indices = [];
  53236. coordSys.eachActiveState(data, function (theActiveState, dataIndex) {
  53237. if (activeState === theActiveState) {
  53238. indices.push(data.getRawIndex(dataIndex));
  53239. }
  53240. });
  53241. return indices;
  53242. },
  53243. defaultOption: {
  53244. zlevel: 0,
  53245. // 一级层叠
  53246. z: 2,
  53247. // 二级层叠
  53248. coordinateSystem: 'parallel',
  53249. parallelIndex: 0,
  53250. label: {
  53251. show: false
  53252. },
  53253. inactiveOpacity: 0.05,
  53254. activeOpacity: 1,
  53255. lineStyle: {
  53256. width: 1,
  53257. opacity: 0.45,
  53258. type: 'solid'
  53259. },
  53260. emphasis: {
  53261. label: {
  53262. show: false
  53263. }
  53264. },
  53265. progressive: 500,
  53266. smooth: false,
  53267. // true | false | number
  53268. animationEasing: 'linear'
  53269. }
  53270. });
  53271. function setEncodeAndDimensions(source, seriesModel) {
  53272. // The mapping of parallelAxis dimension to data dimension can
  53273. // be specified in parallelAxis.option.dim. For example, if
  53274. // parallelAxis.option.dim is 'dim3', it mapping to the third
  53275. // dimension of data. But `data.encode` has higher priority.
  53276. // Moreover, parallelModel.dimension should not be regarded as data
  53277. // dimensions. Consider dimensions = ['dim4', 'dim2', 'dim6'];
  53278. if (source.encodeDefine) {
  53279. return;
  53280. }
  53281. var parallelModel = seriesModel.ecModel.getComponent('parallel', seriesModel.get('parallelIndex'));
  53282. if (!parallelModel) {
  53283. return;
  53284. }
  53285. var encodeDefine = source.encodeDefine = createHashMap();
  53286. each$1(parallelModel.dimensions, function (axisDim) {
  53287. var dataDimIndex = convertDimNameToNumber(axisDim);
  53288. encodeDefine.set(axisDim, dataDimIndex);
  53289. });
  53290. }
  53291. function convertDimNameToNumber(dimName) {
  53292. return +dimName.replace('dim', '');
  53293. }
  53294. /*
  53295. * Licensed to the Apache Software Foundation (ASF) under one
  53296. * or more contributor license agreements. See the NOTICE file
  53297. * distributed with this work for additional information
  53298. * regarding copyright ownership. The ASF licenses this file
  53299. * to you under the Apache License, Version 2.0 (the
  53300. * "License"); you may not use this file except in compliance
  53301. * with the License. You may obtain a copy of the License at
  53302. *
  53303. * http://www.apache.org/licenses/LICENSE-2.0
  53304. *
  53305. * Unless required by applicable law or agreed to in writing,
  53306. * software distributed under the License is distributed on an
  53307. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53308. * KIND, either express or implied. See the License for the
  53309. * specific language governing permissions and limitations
  53310. * under the License.
  53311. */
  53312. var DEFAULT_SMOOTH = 0.3;
  53313. var ParallelView = Chart.extend({
  53314. type: 'parallel',
  53315. init: function () {
  53316. /**
  53317. * @type {module:zrender/container/Group}
  53318. * @private
  53319. */
  53320. this._dataGroup = new Group();
  53321. this.group.add(this._dataGroup);
  53322. /**
  53323. * @type {module:echarts/data/List}
  53324. */
  53325. this._data;
  53326. /**
  53327. * @type {boolean}
  53328. */
  53329. this._initialized;
  53330. },
  53331. /**
  53332. * @override
  53333. */
  53334. render: function (seriesModel, ecModel, api, payload) {
  53335. var dataGroup = this._dataGroup;
  53336. var data = seriesModel.getData();
  53337. var oldData = this._data;
  53338. var coordSys = seriesModel.coordinateSystem;
  53339. var dimensions = coordSys.dimensions;
  53340. var seriesScope = makeSeriesScope$2(seriesModel);
  53341. data.diff(oldData).add(add).update(update).remove(remove).execute();
  53342. function add(newDataIndex) {
  53343. var line = addEl(data, dataGroup, newDataIndex, dimensions, coordSys);
  53344. updateElCommon(line, data, newDataIndex, seriesScope);
  53345. }
  53346. function update(newDataIndex, oldDataIndex) {
  53347. var line = oldData.getItemGraphicEl(oldDataIndex);
  53348. var points = createLinePoints(data, newDataIndex, dimensions, coordSys);
  53349. data.setItemGraphicEl(newDataIndex, line);
  53350. var animationModel = payload && payload.animation === false ? null : seriesModel;
  53351. updateProps(line, {
  53352. shape: {
  53353. points: points
  53354. }
  53355. }, animationModel, newDataIndex);
  53356. updateElCommon(line, data, newDataIndex, seriesScope);
  53357. }
  53358. function remove(oldDataIndex) {
  53359. var line = oldData.getItemGraphicEl(oldDataIndex);
  53360. dataGroup.remove(line);
  53361. } // First create
  53362. if (!this._initialized) {
  53363. this._initialized = true;
  53364. var clipPath = createGridClipShape(coordSys, seriesModel, function () {
  53365. // Callback will be invoked immediately if there is no animation
  53366. setTimeout(function () {
  53367. dataGroup.removeClipPath();
  53368. });
  53369. });
  53370. dataGroup.setClipPath(clipPath);
  53371. }
  53372. this._data = data;
  53373. },
  53374. incrementalPrepareRender: function (seriesModel, ecModel, api) {
  53375. this._initialized = true;
  53376. this._data = null;
  53377. this._dataGroup.removeAll();
  53378. },
  53379. incrementalRender: function (taskParams, seriesModel, ecModel) {
  53380. var data = seriesModel.getData();
  53381. var coordSys = seriesModel.coordinateSystem;
  53382. var dimensions = coordSys.dimensions;
  53383. var seriesScope = makeSeriesScope$2(seriesModel);
  53384. for (var dataIndex = taskParams.start; dataIndex < taskParams.end; dataIndex++) {
  53385. var line = addEl(data, this._dataGroup, dataIndex, dimensions, coordSys);
  53386. line.incremental = true;
  53387. updateElCommon(line, data, dataIndex, seriesScope);
  53388. }
  53389. },
  53390. dispose: function () {},
  53391. // _renderForProgressive: function (seriesModel) {
  53392. // var dataGroup = this._dataGroup;
  53393. // var data = seriesModel.getData();
  53394. // var oldData = this._data;
  53395. // var coordSys = seriesModel.coordinateSystem;
  53396. // var dimensions = coordSys.dimensions;
  53397. // var option = seriesModel.option;
  53398. // var progressive = option.progressive;
  53399. // var smooth = option.smooth ? SMOOTH : null;
  53400. // // In progressive animation is disabled, so use simple data diff,
  53401. // // which effects performance less.
  53402. // // (Typically performance for data with length 7000+ like:
  53403. // // simpleDiff: 60ms, addEl: 184ms,
  53404. // // in RMBP 2.4GHz intel i7, OSX 10.9 chrome 50.0.2661.102 (64-bit))
  53405. // if (simpleDiff(oldData, data, dimensions)) {
  53406. // dataGroup.removeAll();
  53407. // data.each(function (dataIndex) {
  53408. // addEl(data, dataGroup, dataIndex, dimensions, coordSys);
  53409. // });
  53410. // }
  53411. // updateElCommon(data, progressive, smooth);
  53412. // // Consider switch between progressive and not.
  53413. // data.__plProgressive = true;
  53414. // this._data = data;
  53415. // },
  53416. /**
  53417. * @override
  53418. */
  53419. remove: function () {
  53420. this._dataGroup && this._dataGroup.removeAll();
  53421. this._data = null;
  53422. }
  53423. });
  53424. function createGridClipShape(coordSys, seriesModel, cb) {
  53425. var parallelModel = coordSys.model;
  53426. var rect = coordSys.getRect();
  53427. var rectEl = new Rect({
  53428. shape: {
  53429. x: rect.x,
  53430. y: rect.y,
  53431. width: rect.width,
  53432. height: rect.height
  53433. }
  53434. });
  53435. var dim = parallelModel.get('layout') === 'horizontal' ? 'width' : 'height';
  53436. rectEl.setShape(dim, 0);
  53437. initProps(rectEl, {
  53438. shape: {
  53439. width: rect.width,
  53440. height: rect.height
  53441. }
  53442. }, seriesModel, cb);
  53443. return rectEl;
  53444. }
  53445. function createLinePoints(data, dataIndex, dimensions, coordSys) {
  53446. var points = [];
  53447. for (var i = 0; i < dimensions.length; i++) {
  53448. var dimName = dimensions[i];
  53449. var value = data.get(data.mapDimension(dimName), dataIndex);
  53450. if (!isEmptyValue(value, coordSys.getAxis(dimName).type)) {
  53451. points.push(coordSys.dataToPoint(value, dimName));
  53452. }
  53453. }
  53454. return points;
  53455. }
  53456. function addEl(data, dataGroup, dataIndex, dimensions, coordSys) {
  53457. var points = createLinePoints(data, dataIndex, dimensions, coordSys);
  53458. var line = new Polyline({
  53459. shape: {
  53460. points: points
  53461. },
  53462. silent: true,
  53463. z2: 10
  53464. });
  53465. dataGroup.add(line);
  53466. data.setItemGraphicEl(dataIndex, line);
  53467. return line;
  53468. }
  53469. function makeSeriesScope$2(seriesModel) {
  53470. var smooth = seriesModel.get('smooth', true);
  53471. smooth === true && (smooth = DEFAULT_SMOOTH);
  53472. return {
  53473. lineStyle: seriesModel.getModel('lineStyle').getLineStyle(),
  53474. smooth: smooth != null ? smooth : DEFAULT_SMOOTH
  53475. };
  53476. }
  53477. function updateElCommon(el, data, dataIndex, seriesScope) {
  53478. var lineStyle = seriesScope.lineStyle;
  53479. if (data.hasItemOption) {
  53480. var lineStyleModel = data.getItemModel(dataIndex).getModel('lineStyle');
  53481. lineStyle = lineStyleModel.getLineStyle();
  53482. }
  53483. el.useStyle(lineStyle);
  53484. var elStyle = el.style;
  53485. elStyle.fill = null; // lineStyle.color have been set to itemVisual in module:echarts/visual/seriesColor.
  53486. elStyle.stroke = data.getItemVisual(dataIndex, 'color'); // lineStyle.opacity have been set to itemVisual in parallelVisual.
  53487. elStyle.opacity = data.getItemVisual(dataIndex, 'opacity');
  53488. seriesScope.smooth && (el.shape.smooth = seriesScope.smooth);
  53489. } // function simpleDiff(oldData, newData, dimensions) {
  53490. // var oldLen;
  53491. // if (!oldData
  53492. // || !oldData.__plProgressive
  53493. // || (oldLen = oldData.count()) !== newData.count()
  53494. // ) {
  53495. // return true;
  53496. // }
  53497. // var dimLen = dimensions.length;
  53498. // for (var i = 0; i < oldLen; i++) {
  53499. // for (var j = 0; j < dimLen; j++) {
  53500. // if (oldData.get(dimensions[j], i) !== newData.get(dimensions[j], i)) {
  53501. // return true;
  53502. // }
  53503. // }
  53504. // }
  53505. // return false;
  53506. // }
  53507. // FIXME
  53508. // 公用方法?
  53509. function isEmptyValue(val, axisType) {
  53510. return axisType === 'category' ? val == null : val == null || isNaN(val); // axisType === 'value'
  53511. }
  53512. /*
  53513. * Licensed to the Apache Software Foundation (ASF) under one
  53514. * or more contributor license agreements. See the NOTICE file
  53515. * distributed with this work for additional information
  53516. * regarding copyright ownership. The ASF licenses this file
  53517. * to you under the Apache License, Version 2.0 (the
  53518. * "License"); you may not use this file except in compliance
  53519. * with the License. You may obtain a copy of the License at
  53520. *
  53521. * http://www.apache.org/licenses/LICENSE-2.0
  53522. *
  53523. * Unless required by applicable law or agreed to in writing,
  53524. * software distributed under the License is distributed on an
  53525. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53526. * KIND, either express or implied. See the License for the
  53527. * specific language governing permissions and limitations
  53528. * under the License.
  53529. */
  53530. var opacityAccessPath = ['lineStyle', 'normal', 'opacity'];
  53531. var parallelVisual = {
  53532. seriesType: 'parallel',
  53533. reset: function (seriesModel, ecModel, api) {
  53534. var itemStyleModel = seriesModel.getModel('itemStyle');
  53535. var lineStyleModel = seriesModel.getModel('lineStyle');
  53536. var globalColors = ecModel.get('color');
  53537. var color = lineStyleModel.get('color') || itemStyleModel.get('color') || globalColors[seriesModel.seriesIndex % globalColors.length];
  53538. var inactiveOpacity = seriesModel.get('inactiveOpacity');
  53539. var activeOpacity = seriesModel.get('activeOpacity');
  53540. var lineStyle = seriesModel.getModel('lineStyle').getLineStyle();
  53541. var coordSys = seriesModel.coordinateSystem;
  53542. var data = seriesModel.getData();
  53543. var opacityMap = {
  53544. normal: lineStyle.opacity,
  53545. active: activeOpacity,
  53546. inactive: inactiveOpacity
  53547. };
  53548. data.setVisual('color', color);
  53549. function progress(params, data) {
  53550. coordSys.eachActiveState(data, function (activeState, dataIndex) {
  53551. var opacity = opacityMap[activeState];
  53552. if (activeState === 'normal' && data.hasItemOption) {
  53553. var itemOpacity = data.getItemModel(dataIndex).get(opacityAccessPath, true);
  53554. itemOpacity != null && (opacity = itemOpacity);
  53555. }
  53556. data.setItemVisual(dataIndex, 'opacity', opacity);
  53557. }, params.start, params.end);
  53558. }
  53559. return {
  53560. progress: progress
  53561. };
  53562. }
  53563. };
  53564. /*
  53565. * Licensed to the Apache Software Foundation (ASF) under one
  53566. * or more contributor license agreements. See the NOTICE file
  53567. * distributed with this work for additional information
  53568. * regarding copyright ownership. The ASF licenses this file
  53569. * to you under the Apache License, Version 2.0 (the
  53570. * "License"); you may not use this file except in compliance
  53571. * with the License. You may obtain a copy of the License at
  53572. *
  53573. * http://www.apache.org/licenses/LICENSE-2.0
  53574. *
  53575. * Unless required by applicable law or agreed to in writing,
  53576. * software distributed under the License is distributed on an
  53577. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53578. * KIND, either express or implied. See the License for the
  53579. * specific language governing permissions and limitations
  53580. * under the License.
  53581. */
  53582. registerVisual(parallelVisual);
  53583. /*
  53584. * Licensed to the Apache Software Foundation (ASF) under one
  53585. * or more contributor license agreements. See the NOTICE file
  53586. * distributed with this work for additional information
  53587. * regarding copyright ownership. The ASF licenses this file
  53588. * to you under the Apache License, Version 2.0 (the
  53589. * "License"); you may not use this file except in compliance
  53590. * with the License. You may obtain a copy of the License at
  53591. *
  53592. * http://www.apache.org/licenses/LICENSE-2.0
  53593. *
  53594. * Unless required by applicable law or agreed to in writing,
  53595. * software distributed under the License is distributed on an
  53596. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53597. * KIND, either express or implied. See the License for the
  53598. * specific language governing permissions and limitations
  53599. * under the License.
  53600. */
  53601. var GaugeSeries = SeriesModel.extend({
  53602. type: 'series.gauge',
  53603. getInitialData: function (option, ecModel) {
  53604. return createListSimply(this, ['value']);
  53605. },
  53606. defaultOption: {
  53607. zlevel: 0,
  53608. z: 2,
  53609. // 默认全局居中
  53610. center: ['50%', '50%'],
  53611. legendHoverLink: true,
  53612. radius: '75%',
  53613. startAngle: 225,
  53614. endAngle: -45,
  53615. clockwise: true,
  53616. // 最小值
  53617. min: 0,
  53618. // 最大值
  53619. max: 100,
  53620. // 分割段数,默认为10
  53621. splitNumber: 10,
  53622. // 坐标轴线
  53623. axisLine: {
  53624. // 默认显示,属性show控制显示与否
  53625. show: true,
  53626. lineStyle: {
  53627. // 属性lineStyle控制线条样式
  53628. color: [[0.2, '#91c7ae'], [0.8, '#63869e'], [1, '#c23531']],
  53629. width: 30
  53630. }
  53631. },
  53632. // 分隔线
  53633. splitLine: {
  53634. // 默认显示,属性show控制显示与否
  53635. show: true,
  53636. // 属性length控制线长
  53637. length: 30,
  53638. // 属性lineStyle(详见lineStyle)控制线条样式
  53639. lineStyle: {
  53640. color: '#eee',
  53641. width: 2,
  53642. type: 'solid'
  53643. }
  53644. },
  53645. // 坐标轴小标记
  53646. axisTick: {
  53647. // 属性show控制显示与否,默认不显示
  53648. show: true,
  53649. // 每份split细分多少段
  53650. splitNumber: 5,
  53651. // 属性length控制线长
  53652. length: 8,
  53653. // 属性lineStyle控制线条样式
  53654. lineStyle: {
  53655. color: '#eee',
  53656. width: 1,
  53657. type: 'solid'
  53658. }
  53659. },
  53660. axisLabel: {
  53661. show: true,
  53662. distance: 5,
  53663. // formatter: null,
  53664. color: 'auto'
  53665. },
  53666. pointer: {
  53667. show: true,
  53668. length: '80%',
  53669. width: 8
  53670. },
  53671. itemStyle: {
  53672. color: 'auto'
  53673. },
  53674. title: {
  53675. show: true,
  53676. // x, y,单位px
  53677. offsetCenter: [0, '-40%'],
  53678. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  53679. color: '#333',
  53680. fontSize: 15
  53681. },
  53682. detail: {
  53683. show: true,
  53684. backgroundColor: 'rgba(0,0,0,0)',
  53685. borderWidth: 0,
  53686. borderColor: '#ccc',
  53687. width: 100,
  53688. height: null,
  53689. // self-adaption
  53690. padding: [5, 10],
  53691. // x, y,单位px
  53692. offsetCenter: [0, '40%'],
  53693. // formatter: null,
  53694. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  53695. color: 'auto',
  53696. fontSize: 30
  53697. }
  53698. }
  53699. });
  53700. /*
  53701. * Licensed to the Apache Software Foundation (ASF) under one
  53702. * or more contributor license agreements. See the NOTICE file
  53703. * distributed with this work for additional information
  53704. * regarding copyright ownership. The ASF licenses this file
  53705. * to you under the Apache License, Version 2.0 (the
  53706. * "License"); you may not use this file except in compliance
  53707. * with the License. You may obtain a copy of the License at
  53708. *
  53709. * http://www.apache.org/licenses/LICENSE-2.0
  53710. *
  53711. * Unless required by applicable law or agreed to in writing,
  53712. * software distributed under the License is distributed on an
  53713. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  53714. * KIND, either express or implied. See the License for the
  53715. * specific language governing permissions and limitations
  53716. * under the License.
  53717. */
  53718. var PointerPath = Path.extend({
  53719. type: 'echartsGaugePointer',
  53720. shape: {
  53721. angle: 0,
  53722. width: 10,
  53723. r: 10,
  53724. x: 0,
  53725. y: 0
  53726. },
  53727. buildPath: function (ctx, shape) {
  53728. var mathCos = Math.cos;
  53729. var mathSin = Math.sin;
  53730. var r = shape.r;
  53731. var width = shape.width;
  53732. var angle = shape.angle;
  53733. var x = shape.x - mathCos(angle) * width * (width >= r / 3 ? 1 : 2);
  53734. var y = shape.y - mathSin(angle) * width * (width >= r / 3 ? 1 : 2);
  53735. angle = shape.angle - Math.PI / 2;
  53736. ctx.moveTo(x, y);
  53737. ctx.lineTo(shape.x + mathCos(angle) * width, shape.y + mathSin(angle) * width);
  53738. ctx.lineTo(shape.x + mathCos(shape.angle) * r, shape.y + mathSin(shape.angle) * r);
  53739. ctx.lineTo(shape.x - mathCos(angle) * width, shape.y - mathSin(angle) * width);
  53740. ctx.lineTo(x, y);
  53741. return;
  53742. }
  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. function parsePosition(seriesModel, api) {
  53763. var center = seriesModel.get('center');
  53764. var width = api.getWidth();
  53765. var height = api.getHeight();
  53766. var size = Math.min(width, height);
  53767. var cx = parsePercent$1(center[0], api.getWidth());
  53768. var cy = parsePercent$1(center[1], api.getHeight());
  53769. var r = parsePercent$1(seriesModel.get('radius'), size / 2);
  53770. return {
  53771. cx: cx,
  53772. cy: cy,
  53773. r: r
  53774. };
  53775. }
  53776. function formatLabel(label, labelFormatter) {
  53777. if (labelFormatter) {
  53778. if (typeof labelFormatter === 'string') {
  53779. label = labelFormatter.replace('{value}', label != null ? label : '');
  53780. } else if (typeof labelFormatter === 'function') {
  53781. label = labelFormatter(label);
  53782. }
  53783. }
  53784. return label;
  53785. }
  53786. var PI2$5 = Math.PI * 2;
  53787. var GaugeView = Chart.extend({
  53788. type: 'gauge',
  53789. render: function (seriesModel, ecModel, api) {
  53790. this.group.removeAll();
  53791. var colorList = seriesModel.get('axisLine.lineStyle.color');
  53792. var posInfo = parsePosition(seriesModel, api);
  53793. this._renderMain(seriesModel, ecModel, api, colorList, posInfo);
  53794. },
  53795. dispose: function () {},
  53796. _renderMain: function (seriesModel, ecModel, api, colorList, posInfo) {
  53797. var group = this.group;
  53798. var axisLineModel = seriesModel.getModel('axisLine');
  53799. var lineStyleModel = axisLineModel.getModel('lineStyle');
  53800. var clockwise = seriesModel.get('clockwise');
  53801. var startAngle = -seriesModel.get('startAngle') / 180 * Math.PI;
  53802. var endAngle = -seriesModel.get('endAngle') / 180 * Math.PI;
  53803. var angleRangeSpan = (endAngle - startAngle) % PI2$5;
  53804. var prevEndAngle = startAngle;
  53805. var axisLineWidth = lineStyleModel.get('width');
  53806. var showAxis = axisLineModel.get('show');
  53807. for (var i = 0; showAxis && i < colorList.length; i++) {
  53808. // Clamp
  53809. var percent = Math.min(Math.max(colorList[i][0], 0), 1);
  53810. var endAngle = startAngle + angleRangeSpan * percent;
  53811. var sector = new Sector({
  53812. shape: {
  53813. startAngle: prevEndAngle,
  53814. endAngle: endAngle,
  53815. cx: posInfo.cx,
  53816. cy: posInfo.cy,
  53817. clockwise: clockwise,
  53818. r0: posInfo.r - axisLineWidth,
  53819. r: posInfo.r
  53820. },
  53821. silent: true
  53822. });
  53823. sector.setStyle({
  53824. fill: colorList[i][1]
  53825. });
  53826. sector.setStyle(lineStyleModel.getLineStyle( // Because we use sector to simulate arc
  53827. // so the properties for stroking are useless
  53828. ['color', 'borderWidth', 'borderColor']));
  53829. group.add(sector);
  53830. prevEndAngle = endAngle;
  53831. }
  53832. var getColor = function (percent) {
  53833. // Less than 0
  53834. if (percent <= 0) {
  53835. return colorList[0][1];
  53836. }
  53837. for (var i = 0; i < colorList.length; i++) {
  53838. if (colorList[i][0] >= percent && (i === 0 ? 0 : colorList[i - 1][0]) < percent) {
  53839. return colorList[i][1];
  53840. }
  53841. } // More than 1
  53842. return colorList[i - 1][1];
  53843. };
  53844. if (!clockwise) {
  53845. var tmp = startAngle;
  53846. startAngle = endAngle;
  53847. endAngle = tmp;
  53848. }
  53849. this._renderTicks(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise);
  53850. this._renderPointer(seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise);
  53851. this._renderTitle(seriesModel, ecModel, api, getColor, posInfo);
  53852. this._renderDetail(seriesModel, ecModel, api, getColor, posInfo);
  53853. },
  53854. _renderTicks: function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise) {
  53855. var group = this.group;
  53856. var cx = posInfo.cx;
  53857. var cy = posInfo.cy;
  53858. var r = posInfo.r;
  53859. var minVal = +seriesModel.get('min');
  53860. var maxVal = +seriesModel.get('max');
  53861. var splitLineModel = seriesModel.getModel('splitLine');
  53862. var tickModel = seriesModel.getModel('axisTick');
  53863. var labelModel = seriesModel.getModel('axisLabel');
  53864. var splitNumber = seriesModel.get('splitNumber');
  53865. var subSplitNumber = tickModel.get('splitNumber');
  53866. var splitLineLen = parsePercent$1(splitLineModel.get('length'), r);
  53867. var tickLen = parsePercent$1(tickModel.get('length'), r);
  53868. var angle = startAngle;
  53869. var step = (endAngle - startAngle) / splitNumber;
  53870. var subStep = step / subSplitNumber;
  53871. var splitLineStyle = splitLineModel.getModel('lineStyle').getLineStyle();
  53872. var tickLineStyle = tickModel.getModel('lineStyle').getLineStyle();
  53873. for (var i = 0; i <= splitNumber; i++) {
  53874. var unitX = Math.cos(angle);
  53875. var unitY = Math.sin(angle); // Split line
  53876. if (splitLineModel.get('show')) {
  53877. var splitLine = new Line({
  53878. shape: {
  53879. x1: unitX * r + cx,
  53880. y1: unitY * r + cy,
  53881. x2: unitX * (r - splitLineLen) + cx,
  53882. y2: unitY * (r - splitLineLen) + cy
  53883. },
  53884. style: splitLineStyle,
  53885. silent: true
  53886. });
  53887. if (splitLineStyle.stroke === 'auto') {
  53888. splitLine.setStyle({
  53889. stroke: getColor(i / splitNumber)
  53890. });
  53891. }
  53892. group.add(splitLine);
  53893. } // Label
  53894. if (labelModel.get('show')) {
  53895. var label = formatLabel(round$1(i / splitNumber * (maxVal - minVal) + minVal), labelModel.get('formatter'));
  53896. var distance = labelModel.get('distance');
  53897. var autoColor = getColor(i / splitNumber);
  53898. group.add(new Text({
  53899. style: setTextStyle({}, labelModel, {
  53900. text: label,
  53901. x: unitX * (r - splitLineLen - distance) + cx,
  53902. y: unitY * (r - splitLineLen - distance) + cy,
  53903. textVerticalAlign: unitY < -0.4 ? 'top' : unitY > 0.4 ? 'bottom' : 'middle',
  53904. textAlign: unitX < -0.4 ? 'left' : unitX > 0.4 ? 'right' : 'center'
  53905. }, {
  53906. autoColor: autoColor
  53907. }),
  53908. silent: true
  53909. }));
  53910. } // Axis tick
  53911. if (tickModel.get('show') && i !== splitNumber) {
  53912. for (var j = 0; j <= subSplitNumber; j++) {
  53913. var unitX = Math.cos(angle);
  53914. var unitY = Math.sin(angle);
  53915. var tickLine = new Line({
  53916. shape: {
  53917. x1: unitX * r + cx,
  53918. y1: unitY * r + cy,
  53919. x2: unitX * (r - tickLen) + cx,
  53920. y2: unitY * (r - tickLen) + cy
  53921. },
  53922. silent: true,
  53923. style: tickLineStyle
  53924. });
  53925. if (tickLineStyle.stroke === 'auto') {
  53926. tickLine.setStyle({
  53927. stroke: getColor((i + j / subSplitNumber) / splitNumber)
  53928. });
  53929. }
  53930. group.add(tickLine);
  53931. angle += subStep;
  53932. }
  53933. angle -= subStep;
  53934. } else {
  53935. angle += step;
  53936. }
  53937. }
  53938. },
  53939. _renderPointer: function (seriesModel, ecModel, api, getColor, posInfo, startAngle, endAngle, clockwise) {
  53940. var group = this.group;
  53941. var oldData = this._data;
  53942. if (!seriesModel.get('pointer.show')) {
  53943. // Remove old element
  53944. oldData && oldData.eachItemGraphicEl(function (el) {
  53945. group.remove(el);
  53946. });
  53947. return;
  53948. }
  53949. var valueExtent = [+seriesModel.get('min'), +seriesModel.get('max')];
  53950. var angleExtent = [startAngle, endAngle];
  53951. var data = seriesModel.getData();
  53952. var valueDim = data.mapDimension('value');
  53953. data.diff(oldData).add(function (idx) {
  53954. var pointer = new PointerPath({
  53955. shape: {
  53956. angle: startAngle
  53957. }
  53958. });
  53959. initProps(pointer, {
  53960. shape: {
  53961. angle: linearMap(data.get(valueDim, idx), valueExtent, angleExtent, true)
  53962. }
  53963. }, seriesModel);
  53964. group.add(pointer);
  53965. data.setItemGraphicEl(idx, pointer);
  53966. }).update(function (newIdx, oldIdx) {
  53967. var pointer = oldData.getItemGraphicEl(oldIdx);
  53968. updateProps(pointer, {
  53969. shape: {
  53970. angle: linearMap(data.get(valueDim, newIdx), valueExtent, angleExtent, true)
  53971. }
  53972. }, seriesModel);
  53973. group.add(pointer);
  53974. data.setItemGraphicEl(newIdx, pointer);
  53975. }).remove(function (idx) {
  53976. var pointer = oldData.getItemGraphicEl(idx);
  53977. group.remove(pointer);
  53978. }).execute();
  53979. data.eachItemGraphicEl(function (pointer, idx) {
  53980. var itemModel = data.getItemModel(idx);
  53981. var pointerModel = itemModel.getModel('pointer');
  53982. pointer.setShape({
  53983. x: posInfo.cx,
  53984. y: posInfo.cy,
  53985. width: parsePercent$1(pointerModel.get('width'), posInfo.r),
  53986. r: parsePercent$1(pointerModel.get('length'), posInfo.r)
  53987. });
  53988. pointer.useStyle(itemModel.getModel('itemStyle').getItemStyle());
  53989. if (pointer.style.fill === 'auto') {
  53990. pointer.setStyle('fill', getColor(linearMap(data.get(valueDim, idx), valueExtent, [0, 1], true)));
  53991. }
  53992. setHoverStyle(pointer, itemModel.getModel('emphasis.itemStyle').getItemStyle());
  53993. });
  53994. this._data = data;
  53995. },
  53996. _renderTitle: function (seriesModel, ecModel, api, getColor, posInfo) {
  53997. var data = seriesModel.getData();
  53998. var valueDim = data.mapDimension('value');
  53999. var titleModel = seriesModel.getModel('title');
  54000. if (titleModel.get('show')) {
  54001. var offsetCenter = titleModel.get('offsetCenter');
  54002. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  54003. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  54004. var minVal = +seriesModel.get('min');
  54005. var maxVal = +seriesModel.get('max');
  54006. var value = seriesModel.getData().get(valueDim, 0);
  54007. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  54008. this.group.add(new Text({
  54009. silent: true,
  54010. style: setTextStyle({}, titleModel, {
  54011. x: x,
  54012. y: y,
  54013. // FIXME First data name ?
  54014. text: data.getName(0),
  54015. textAlign: 'center',
  54016. textVerticalAlign: 'middle'
  54017. }, {
  54018. autoColor: autoColor,
  54019. forceRich: true
  54020. })
  54021. }));
  54022. }
  54023. },
  54024. _renderDetail: function (seriesModel, ecModel, api, getColor, posInfo) {
  54025. var detailModel = seriesModel.getModel('detail');
  54026. var minVal = +seriesModel.get('min');
  54027. var maxVal = +seriesModel.get('max');
  54028. if (detailModel.get('show')) {
  54029. var offsetCenter = detailModel.get('offsetCenter');
  54030. var x = posInfo.cx + parsePercent$1(offsetCenter[0], posInfo.r);
  54031. var y = posInfo.cy + parsePercent$1(offsetCenter[1], posInfo.r);
  54032. var width = parsePercent$1(detailModel.get('width'), posInfo.r);
  54033. var height = parsePercent$1(detailModel.get('height'), posInfo.r);
  54034. var data = seriesModel.getData();
  54035. var value = data.get(data.mapDimension('value'), 0);
  54036. var autoColor = getColor(linearMap(value, [minVal, maxVal], [0, 1], true));
  54037. this.group.add(new Text({
  54038. silent: true,
  54039. style: setTextStyle({}, detailModel, {
  54040. x: x,
  54041. y: y,
  54042. text: formatLabel( // FIXME First data name ?
  54043. value, detailModel.get('formatter')),
  54044. textWidth: isNaN(width) ? null : width,
  54045. textHeight: isNaN(height) ? null : height,
  54046. textAlign: 'center',
  54047. textVerticalAlign: 'middle'
  54048. }, {
  54049. autoColor: autoColor,
  54050. forceRich: true
  54051. })
  54052. }));
  54053. }
  54054. }
  54055. });
  54056. /*
  54057. * Licensed to the Apache Software Foundation (ASF) under one
  54058. * or more contributor license agreements. See the NOTICE file
  54059. * distributed with this work for additional information
  54060. * regarding copyright ownership. The ASF licenses this file
  54061. * to you under the Apache License, Version 2.0 (the
  54062. * "License"); you may not use this file except in compliance
  54063. * with the License. You may obtain a copy of the License at
  54064. *
  54065. * http://www.apache.org/licenses/LICENSE-2.0
  54066. *
  54067. * Unless required by applicable law or agreed to in writing,
  54068. * software distributed under the License is distributed on an
  54069. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54070. * KIND, either express or implied. See the License for the
  54071. * specific language governing permissions and limitations
  54072. * under the License.
  54073. */
  54074. /*
  54075. * Licensed to the Apache Software Foundation (ASF) under one
  54076. * or more contributor license agreements. See the NOTICE file
  54077. * distributed with this work for additional information
  54078. * regarding copyright ownership. The ASF licenses this file
  54079. * to you under the Apache License, Version 2.0 (the
  54080. * "License"); you may not use this file except in compliance
  54081. * with the License. You may obtain a copy of the License at
  54082. *
  54083. * http://www.apache.org/licenses/LICENSE-2.0
  54084. *
  54085. * Unless required by applicable law or agreed to in writing,
  54086. * software distributed under the License is distributed on an
  54087. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54088. * KIND, either express or implied. See the License for the
  54089. * specific language governing permissions and limitations
  54090. * under the License.
  54091. */
  54092. var FunnelSeries = extendSeriesModel({
  54093. type: 'series.funnel',
  54094. init: function (option) {
  54095. FunnelSeries.superApply(this, 'init', arguments); // Enable legend selection for each data item
  54096. // Use a function instead of direct access because data reference may changed
  54097. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this)); // Extend labelLine emphasis
  54098. this._defaultLabelLine(option);
  54099. },
  54100. getInitialData: function (option, ecModel) {
  54101. return createListSimply(this, {
  54102. coordDimensions: ['value'],
  54103. encodeDefaulter: curry(makeSeriesEncodeForNameBased, this)
  54104. });
  54105. },
  54106. _defaultLabelLine: function (option) {
  54107. // Extend labelLine emphasis
  54108. defaultEmphasis(option, 'labelLine', ['show']);
  54109. var labelLineNormalOpt = option.labelLine;
  54110. var labelLineEmphasisOpt = option.emphasis.labelLine; // Not show label line if `label.normal.show = false`
  54111. labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.show;
  54112. labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.emphasis.label.show;
  54113. },
  54114. // Overwrite
  54115. getDataParams: function (dataIndex) {
  54116. var data = this.getData();
  54117. var params = FunnelSeries.superCall(this, 'getDataParams', dataIndex);
  54118. var valueDim = data.mapDimension('value');
  54119. var sum = data.getSum(valueDim); // Percent is 0 if sum is 0
  54120. params.percent = !sum ? 0 : +(data.get(valueDim, dataIndex) / sum * 100).toFixed(2);
  54121. params.$vars.push('percent');
  54122. return params;
  54123. },
  54124. defaultOption: {
  54125. zlevel: 0,
  54126. // 一级层叠
  54127. z: 2,
  54128. // 二级层叠
  54129. legendHoverLink: true,
  54130. left: 80,
  54131. top: 60,
  54132. right: 80,
  54133. bottom: 60,
  54134. // width: {totalWidth} - left - right,
  54135. // height: {totalHeight} - top - bottom,
  54136. // 默认取数据最小最大值
  54137. // min: 0,
  54138. // max: 100,
  54139. minSize: '0%',
  54140. maxSize: '100%',
  54141. sort: 'descending',
  54142. // 'ascending', 'descending'
  54143. gap: 0,
  54144. funnelAlign: 'center',
  54145. label: {
  54146. show: true,
  54147. position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调
  54148. },
  54149. labelLine: {
  54150. show: true,
  54151. length: 20,
  54152. lineStyle: {
  54153. // color: 各异,
  54154. width: 1,
  54155. type: 'solid'
  54156. }
  54157. },
  54158. itemStyle: {
  54159. // color: 各异,
  54160. borderColor: '#fff',
  54161. borderWidth: 1
  54162. },
  54163. emphasis: {
  54164. label: {
  54165. show: true
  54166. }
  54167. }
  54168. }
  54169. });
  54170. /*
  54171. * Licensed to the Apache Software Foundation (ASF) under one
  54172. * or more contributor license agreements. See the NOTICE file
  54173. * distributed with this work for additional information
  54174. * regarding copyright ownership. The ASF licenses this file
  54175. * to you under the Apache License, Version 2.0 (the
  54176. * "License"); you may not use this file except in compliance
  54177. * with the License. You may obtain a copy of the License at
  54178. *
  54179. * http://www.apache.org/licenses/LICENSE-2.0
  54180. *
  54181. * Unless required by applicable law or agreed to in writing,
  54182. * software distributed under the License is distributed on an
  54183. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54184. * KIND, either express or implied. See the License for the
  54185. * specific language governing permissions and limitations
  54186. * under the License.
  54187. */
  54188. /**
  54189. * Piece of pie including Sector, Label, LabelLine
  54190. * @constructor
  54191. * @extends {module:zrender/graphic/Group}
  54192. */
  54193. function FunnelPiece(data, idx) {
  54194. Group.call(this);
  54195. var polygon = new Polygon();
  54196. var labelLine = new Polyline();
  54197. var text = new Text();
  54198. this.add(polygon);
  54199. this.add(labelLine);
  54200. this.add(text);
  54201. this.highDownOnUpdate = function (fromState, toState) {
  54202. if (toState === 'emphasis') {
  54203. labelLine.ignore = labelLine.hoverIgnore;
  54204. text.ignore = text.hoverIgnore;
  54205. } else {
  54206. labelLine.ignore = labelLine.normalIgnore;
  54207. text.ignore = text.normalIgnore;
  54208. }
  54209. };
  54210. this.updateData(data, idx, true);
  54211. }
  54212. var funnelPieceProto = FunnelPiece.prototype;
  54213. var opacityAccessPath$1 = ['itemStyle', 'opacity'];
  54214. funnelPieceProto.updateData = function (data, idx, firstCreate) {
  54215. var polygon = this.childAt(0);
  54216. var seriesModel = data.hostModel;
  54217. var itemModel = data.getItemModel(idx);
  54218. var layout = data.getItemLayout(idx);
  54219. var opacity = data.getItemModel(idx).get(opacityAccessPath$1);
  54220. opacity = opacity == null ? 1 : opacity; // Reset style
  54221. polygon.useStyle({});
  54222. if (firstCreate) {
  54223. polygon.setShape({
  54224. points: layout.points
  54225. });
  54226. polygon.setStyle({
  54227. opacity: 0
  54228. });
  54229. initProps(polygon, {
  54230. style: {
  54231. opacity: opacity
  54232. }
  54233. }, seriesModel, idx);
  54234. } else {
  54235. updateProps(polygon, {
  54236. style: {
  54237. opacity: opacity
  54238. },
  54239. shape: {
  54240. points: layout.points
  54241. }
  54242. }, seriesModel, idx);
  54243. } // Update common style
  54244. var itemStyleModel = itemModel.getModel('itemStyle');
  54245. var visualColor = data.getItemVisual(idx, 'color');
  54246. polygon.setStyle(defaults({
  54247. lineJoin: 'round',
  54248. fill: visualColor
  54249. }, itemStyleModel.getItemStyle(['opacity'])));
  54250. polygon.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle();
  54251. this._updateLabel(data, idx);
  54252. setHoverStyle(this);
  54253. };
  54254. funnelPieceProto._updateLabel = function (data, idx) {
  54255. var labelLine = this.childAt(1);
  54256. var labelText = this.childAt(2);
  54257. var seriesModel = data.hostModel;
  54258. var itemModel = data.getItemModel(idx);
  54259. var layout = data.getItemLayout(idx);
  54260. var labelLayout = layout.label;
  54261. var visualColor = data.getItemVisual(idx, 'color');
  54262. updateProps(labelLine, {
  54263. shape: {
  54264. points: labelLayout.linePoints || labelLayout.linePoints
  54265. }
  54266. }, seriesModel, idx);
  54267. updateProps(labelText, {
  54268. style: {
  54269. x: labelLayout.x,
  54270. y: labelLayout.y
  54271. }
  54272. }, seriesModel, idx);
  54273. labelText.attr({
  54274. rotation: labelLayout.rotation,
  54275. origin: [labelLayout.x, labelLayout.y],
  54276. z2: 10
  54277. });
  54278. var labelModel = itemModel.getModel('label');
  54279. var labelHoverModel = itemModel.getModel('emphasis.label');
  54280. var labelLineModel = itemModel.getModel('labelLine');
  54281. var labelLineHoverModel = itemModel.getModel('emphasis.labelLine');
  54282. var visualColor = data.getItemVisual(idx, 'color');
  54283. setLabelStyle(labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel, {
  54284. labelFetcher: data.hostModel,
  54285. labelDataIndex: idx,
  54286. defaultText: data.getName(idx),
  54287. autoColor: visualColor,
  54288. useInsideStyle: !!labelLayout.inside
  54289. }, {
  54290. textAlign: labelLayout.textAlign,
  54291. textVerticalAlign: labelLayout.verticalAlign
  54292. });
  54293. labelText.ignore = labelText.normalIgnore = !labelModel.get('show');
  54294. labelText.hoverIgnore = !labelHoverModel.get('show');
  54295. labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show');
  54296. labelLine.hoverIgnore = !labelLineHoverModel.get('show'); // Default use item visual color
  54297. labelLine.setStyle({
  54298. stroke: visualColor
  54299. });
  54300. labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle());
  54301. labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle();
  54302. };
  54303. inherits(FunnelPiece, Group);
  54304. var FunnelView = Chart.extend({
  54305. type: 'funnel',
  54306. render: function (seriesModel, ecModel, api) {
  54307. var data = seriesModel.getData();
  54308. var oldData = this._data;
  54309. var group = this.group;
  54310. data.diff(oldData).add(function (idx) {
  54311. var funnelPiece = new FunnelPiece(data, idx);
  54312. data.setItemGraphicEl(idx, funnelPiece);
  54313. group.add(funnelPiece);
  54314. }).update(function (newIdx, oldIdx) {
  54315. var piePiece = oldData.getItemGraphicEl(oldIdx);
  54316. piePiece.updateData(data, newIdx);
  54317. group.add(piePiece);
  54318. data.setItemGraphicEl(newIdx, piePiece);
  54319. }).remove(function (idx) {
  54320. var piePiece = oldData.getItemGraphicEl(idx);
  54321. group.remove(piePiece);
  54322. }).execute();
  54323. this._data = data;
  54324. },
  54325. remove: function () {
  54326. this.group.removeAll();
  54327. this._data = null;
  54328. },
  54329. dispose: function () {}
  54330. });
  54331. /*
  54332. * Licensed to the Apache Software Foundation (ASF) under one
  54333. * or more contributor license agreements. See the NOTICE file
  54334. * distributed with this work for additional information
  54335. * regarding copyright ownership. The ASF licenses this file
  54336. * to you under the Apache License, Version 2.0 (the
  54337. * "License"); you may not use this file except in compliance
  54338. * with the License. You may obtain a copy of the License at
  54339. *
  54340. * http://www.apache.org/licenses/LICENSE-2.0
  54341. *
  54342. * Unless required by applicable law or agreed to in writing,
  54343. * software distributed under the License is distributed on an
  54344. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54345. * KIND, either express or implied. See the License for the
  54346. * specific language governing permissions and limitations
  54347. * under the License.
  54348. */
  54349. function getViewRect$3(seriesModel, api) {
  54350. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  54351. width: api.getWidth(),
  54352. height: api.getHeight()
  54353. });
  54354. }
  54355. function getSortedIndices(data, sort) {
  54356. var valueDim = data.mapDimension('value');
  54357. var valueArr = data.mapArray(valueDim, function (val) {
  54358. return val;
  54359. });
  54360. var indices = [];
  54361. var isAscending = sort === 'ascending';
  54362. for (var i = 0, len = data.count(); i < len; i++) {
  54363. indices[i] = i;
  54364. } // Add custom sortable function & none sortable opetion by "options.sort"
  54365. if (typeof sort === 'function') {
  54366. indices.sort(sort);
  54367. } else if (sort !== 'none') {
  54368. indices.sort(function (a, b) {
  54369. return isAscending ? valueArr[a] - valueArr[b] : valueArr[b] - valueArr[a];
  54370. });
  54371. }
  54372. return indices;
  54373. }
  54374. function labelLayout$1(data) {
  54375. data.each(function (idx) {
  54376. var itemModel = data.getItemModel(idx);
  54377. var labelModel = itemModel.getModel('label');
  54378. var labelPosition = labelModel.get('position');
  54379. var labelLineModel = itemModel.getModel('labelLine');
  54380. var layout = data.getItemLayout(idx);
  54381. var points = layout.points;
  54382. var isLabelInside = labelPosition === 'inner' || labelPosition === 'inside' || labelPosition === 'center' || labelPosition === 'insideLeft' || labelPosition === 'insideRight';
  54383. var textAlign;
  54384. var textX;
  54385. var textY;
  54386. var linePoints;
  54387. if (isLabelInside) {
  54388. if (labelPosition === 'insideLeft') {
  54389. textX = (points[0][0] + points[3][0]) / 2 + 5;
  54390. textY = (points[0][1] + points[3][1]) / 2;
  54391. textAlign = 'left';
  54392. } else if (labelPosition === 'insideRight') {
  54393. textX = (points[1][0] + points[2][0]) / 2 - 5;
  54394. textY = (points[1][1] + points[2][1]) / 2;
  54395. textAlign = 'right';
  54396. } else {
  54397. textX = (points[0][0] + points[1][0] + points[2][0] + points[3][0]) / 4;
  54398. textY = (points[0][1] + points[1][1] + points[2][1] + points[3][1]) / 4;
  54399. textAlign = 'center';
  54400. }
  54401. linePoints = [[textX, textY], [textX, textY]];
  54402. } else {
  54403. var x1;
  54404. var y1;
  54405. var x2;
  54406. var labelLineLen = labelLineModel.get('length');
  54407. if (labelPosition === 'left') {
  54408. // Left side
  54409. x1 = (points[3][0] + points[0][0]) / 2;
  54410. y1 = (points[3][1] + points[0][1]) / 2;
  54411. x2 = x1 - labelLineLen;
  54412. textX = x2 - 5;
  54413. textAlign = 'right';
  54414. } else if (labelPosition === 'right') {
  54415. // Right side
  54416. x1 = (points[1][0] + points[2][0]) / 2;
  54417. y1 = (points[1][1] + points[2][1]) / 2;
  54418. x2 = x1 + labelLineLen;
  54419. textX = x2 + 5;
  54420. textAlign = 'left';
  54421. } else if (labelPosition === 'rightTop') {
  54422. // RightTop side
  54423. x1 = points[1][0];
  54424. y1 = points[1][1];
  54425. x2 = x1 + labelLineLen;
  54426. textX = x2 + 5;
  54427. textAlign = 'top';
  54428. } else if (labelPosition === 'rightBottom') {
  54429. // RightBottom side
  54430. x1 = points[2][0];
  54431. y1 = points[2][1];
  54432. x2 = x1 + labelLineLen;
  54433. textX = x2 + 5;
  54434. textAlign = 'bottom';
  54435. } else if (labelPosition === 'leftTop') {
  54436. // LeftTop side
  54437. x1 = points[0][0];
  54438. y1 = points[1][1];
  54439. x2 = x1 - labelLineLen;
  54440. textX = x2 - 5;
  54441. textAlign = 'right';
  54442. } else if (labelPosition === 'leftBottom') {
  54443. // LeftBottom side
  54444. x1 = points[3][0];
  54445. y1 = points[2][1];
  54446. x2 = x1 - labelLineLen;
  54447. textX = x2 - 5;
  54448. textAlign = 'right';
  54449. } else {
  54450. // Right side
  54451. x1 = (points[1][0] + points[2][0]) / 2;
  54452. y1 = (points[1][1] + points[2][1]) / 2;
  54453. x2 = x1 + labelLineLen;
  54454. textX = x2 + 5;
  54455. textAlign = 'left';
  54456. }
  54457. var y2 = y1;
  54458. linePoints = [[x1, y1], [x2, y2]];
  54459. textY = y2;
  54460. }
  54461. layout.label = {
  54462. linePoints: linePoints,
  54463. x: textX,
  54464. y: textY,
  54465. verticalAlign: 'middle',
  54466. textAlign: textAlign,
  54467. inside: isLabelInside
  54468. };
  54469. });
  54470. }
  54471. var funnelLayout = function (ecModel, api, payload) {
  54472. ecModel.eachSeriesByType('funnel', function (seriesModel) {
  54473. var data = seriesModel.getData();
  54474. var valueDim = data.mapDimension('value');
  54475. var sort = seriesModel.get('sort');
  54476. var viewRect = getViewRect$3(seriesModel, api);
  54477. var indices = getSortedIndices(data, sort);
  54478. var sizeExtent = [parsePercent$1(seriesModel.get('minSize'), viewRect.width), parsePercent$1(seriesModel.get('maxSize'), viewRect.width)];
  54479. var dataExtent = data.getDataExtent(valueDim);
  54480. var min = seriesModel.get('min');
  54481. var max = seriesModel.get('max');
  54482. if (min == null) {
  54483. min = Math.min(dataExtent[0], 0);
  54484. }
  54485. if (max == null) {
  54486. max = dataExtent[1];
  54487. }
  54488. var funnelAlign = seriesModel.get('funnelAlign');
  54489. var gap = seriesModel.get('gap');
  54490. var itemHeight = (viewRect.height - gap * (data.count() - 1)) / data.count();
  54491. var y = viewRect.y;
  54492. var getLinePoints = function (idx, offY) {
  54493. // End point index is data.count() and we assign it 0
  54494. var val = data.get(valueDim, idx) || 0;
  54495. var itemWidth = linearMap(val, [min, max], sizeExtent, true);
  54496. var x0;
  54497. switch (funnelAlign) {
  54498. case 'left':
  54499. x0 = viewRect.x;
  54500. break;
  54501. case 'center':
  54502. x0 = viewRect.x + (viewRect.width - itemWidth) / 2;
  54503. break;
  54504. case 'right':
  54505. x0 = viewRect.x + viewRect.width - itemWidth;
  54506. break;
  54507. }
  54508. return [[x0, offY], [x0 + itemWidth, offY]];
  54509. };
  54510. if (sort === 'ascending') {
  54511. // From bottom to top
  54512. itemHeight = -itemHeight;
  54513. gap = -gap;
  54514. y += viewRect.height;
  54515. indices = indices.reverse();
  54516. }
  54517. for (var i = 0; i < indices.length; i++) {
  54518. var idx = indices[i];
  54519. var nextIdx = indices[i + 1];
  54520. var itemModel = data.getItemModel(idx);
  54521. var height = itemModel.get('itemStyle.height');
  54522. if (height == null) {
  54523. height = itemHeight;
  54524. } else {
  54525. height = parsePercent$1(height, viewRect.height);
  54526. if (sort === 'ascending') {
  54527. height = -height;
  54528. }
  54529. }
  54530. var start = getLinePoints(idx, y);
  54531. var end = getLinePoints(nextIdx, y + height);
  54532. y += height + gap;
  54533. data.setItemLayout(idx, {
  54534. points: start.concat(end.slice().reverse())
  54535. });
  54536. }
  54537. labelLayout$1(data);
  54538. });
  54539. };
  54540. /*
  54541. * Licensed to the Apache Software Foundation (ASF) under one
  54542. * or more contributor license agreements. See the NOTICE file
  54543. * distributed with this work for additional information
  54544. * regarding copyright ownership. The ASF licenses this file
  54545. * to you under the Apache License, Version 2.0 (the
  54546. * "License"); you may not use this file except in compliance
  54547. * with the License. You may obtain a copy of the License at
  54548. *
  54549. * http://www.apache.org/licenses/LICENSE-2.0
  54550. *
  54551. * Unless required by applicable law or agreed to in writing,
  54552. * software distributed under the License is distributed on an
  54553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54554. * KIND, either express or implied. See the License for the
  54555. * specific language governing permissions and limitations
  54556. * under the License.
  54557. */
  54558. registerVisual(dataColor('funnel'));
  54559. registerLayout(funnelLayout);
  54560. registerProcessor(dataFilter('funnel'));
  54561. /*
  54562. * Licensed to the Apache Software Foundation (ASF) under one
  54563. * or more contributor license agreements. See the NOTICE file
  54564. * distributed with this work for additional information
  54565. * regarding copyright ownership. The ASF licenses this file
  54566. * to you under the Apache License, Version 2.0 (the
  54567. * "License"); you may not use this file except in compliance
  54568. * with the License. You may obtain a copy of the License at
  54569. *
  54570. * http://www.apache.org/licenses/LICENSE-2.0
  54571. *
  54572. * Unless required by applicable law or agreed to in writing,
  54573. * software distributed under the License is distributed on an
  54574. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54575. * KIND, either express or implied. See the License for the
  54576. * specific language governing permissions and limitations
  54577. * under the License.
  54578. */
  54579. var SankeySeries = SeriesModel.extend({
  54580. type: 'series.sankey',
  54581. layoutInfo: null,
  54582. levelModels: null,
  54583. /**
  54584. * Init a graph data structure from data in option series
  54585. *
  54586. * @param {Object} option the object used to config echarts view
  54587. * @return {module:echarts/data/List} storage initial data
  54588. */
  54589. getInitialData: function (option, ecModel) {
  54590. var links = option.edges || option.links;
  54591. var nodes = option.data || option.nodes;
  54592. var levels = option.levels;
  54593. var levelModels = this.levelModels = {};
  54594. for (var i = 0; i < levels.length; i++) {
  54595. if (levels[i].depth != null && levels[i].depth >= 0) {
  54596. levelModels[levels[i].depth] = new Model(levels[i], this, ecModel);
  54597. } else {}
  54598. }
  54599. if (nodes && links) {
  54600. var graph = createGraphFromNodeEdge(nodes, links, this, true, beforeLink);
  54601. return graph.data;
  54602. }
  54603. function beforeLink(nodeData, edgeData) {
  54604. nodeData.wrapMethod('getItemModel', function (model, idx) {
  54605. model.customizeGetParent(function (path) {
  54606. var parentModel = this.parentModel;
  54607. var nodeDepth = parentModel.getData().getItemLayout(idx).depth;
  54608. var levelModel = parentModel.levelModels[nodeDepth];
  54609. return levelModel || this.parentModel;
  54610. });
  54611. return model;
  54612. });
  54613. edgeData.wrapMethod('getItemModel', function (model, idx) {
  54614. model.customizeGetParent(function (path) {
  54615. var parentModel = this.parentModel;
  54616. var edge = parentModel.getGraph().getEdgeByIndex(idx);
  54617. var depth = edge.node1.getLayout().depth;
  54618. var levelModel = parentModel.levelModels[depth];
  54619. return levelModel || this.parentModel;
  54620. });
  54621. return model;
  54622. });
  54623. }
  54624. },
  54625. setNodePosition: function (dataIndex, localPosition) {
  54626. var dataItem = this.option.data[dataIndex];
  54627. dataItem.localX = localPosition[0];
  54628. dataItem.localY = localPosition[1];
  54629. },
  54630. /**
  54631. * Return the graphic data structure
  54632. *
  54633. * @return {module:echarts/data/Graph} graphic data structure
  54634. */
  54635. getGraph: function () {
  54636. return this.getData().graph;
  54637. },
  54638. /**
  54639. * Get edge data of graphic data structure
  54640. *
  54641. * @return {module:echarts/data/List} data structure of list
  54642. */
  54643. getEdgeData: function () {
  54644. return this.getGraph().edgeData;
  54645. },
  54646. /**
  54647. * @override
  54648. */
  54649. formatTooltip: function (dataIndex, multipleSeries, dataType) {
  54650. // dataType === 'node' or empty do not show tooltip by default
  54651. if (dataType === 'edge') {
  54652. var params = this.getDataParams(dataIndex, dataType);
  54653. var rawDataOpt = params.data;
  54654. var html = rawDataOpt.source + ' -- ' + rawDataOpt.target;
  54655. if (params.value) {
  54656. html += ' : ' + params.value;
  54657. }
  54658. return encodeHTML(html);
  54659. } else if (dataType === 'node') {
  54660. var node = this.getGraph().getNodeByIndex(dataIndex);
  54661. var value = node.getLayout().value;
  54662. var name = this.getDataParams(dataIndex, dataType).data.name;
  54663. if (value) {
  54664. var html = name + ' : ' + value;
  54665. }
  54666. return encodeHTML(html);
  54667. }
  54668. return SankeySeries.superCall(this, 'formatTooltip', dataIndex, multipleSeries);
  54669. },
  54670. optionUpdated: function () {
  54671. var option = this.option;
  54672. if (option.focusNodeAdjacency === true) {
  54673. option.focusNodeAdjacency = 'allEdges';
  54674. }
  54675. },
  54676. // Override Series.getDataParams()
  54677. getDataParams: function (dataIndex, dataType) {
  54678. var params = SankeySeries.superCall(this, 'getDataParams', dataIndex, dataType);
  54679. if (params.value == null && dataType === 'node') {
  54680. var node = this.getGraph().getNodeByIndex(dataIndex);
  54681. var nodeValue = node.getLayout().value;
  54682. params.value = nodeValue;
  54683. }
  54684. return params;
  54685. },
  54686. defaultOption: {
  54687. zlevel: 0,
  54688. z: 2,
  54689. coordinateSystem: 'view',
  54690. layout: null,
  54691. // The position of the whole view
  54692. left: '5%',
  54693. top: '5%',
  54694. right: '20%',
  54695. bottom: '5%',
  54696. // Value can be 'vertical'
  54697. orient: 'horizontal',
  54698. // The dx of the node
  54699. nodeWidth: 20,
  54700. // The vertical distance between two nodes
  54701. nodeGap: 8,
  54702. // Control if the node can move or not
  54703. draggable: true,
  54704. // Value can be 'inEdges', 'outEdges', 'allEdges', true (the same as 'allEdges').
  54705. focusNodeAdjacency: false,
  54706. // The number of iterations to change the position of the node
  54707. layoutIterations: 32,
  54708. label: {
  54709. show: true,
  54710. position: 'right',
  54711. color: '#000',
  54712. fontSize: 12
  54713. },
  54714. levels: [],
  54715. // Value can be 'left' or 'right'
  54716. nodeAlign: 'justify',
  54717. itemStyle: {
  54718. borderWidth: 1,
  54719. borderColor: '#333'
  54720. },
  54721. lineStyle: {
  54722. color: '#314656',
  54723. opacity: 0.2,
  54724. curveness: 0.5
  54725. },
  54726. emphasis: {
  54727. label: {
  54728. show: true
  54729. },
  54730. lineStyle: {
  54731. opacity: 0.5
  54732. }
  54733. },
  54734. animationEasing: 'linear',
  54735. animationDuration: 1000
  54736. }
  54737. });
  54738. /*
  54739. * Licensed to the Apache Software Foundation (ASF) under one
  54740. * or more contributor license agreements. See the NOTICE file
  54741. * distributed with this work for additional information
  54742. * regarding copyright ownership. The ASF licenses this file
  54743. * to you under the Apache License, Version 2.0 (the
  54744. * "License"); you may not use this file except in compliance
  54745. * with the License. You may obtain a copy of the License at
  54746. *
  54747. * http://www.apache.org/licenses/LICENSE-2.0
  54748. *
  54749. * Unless required by applicable law or agreed to in writing,
  54750. * software distributed under the License is distributed on an
  54751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  54752. * KIND, either express or implied. See the License for the
  54753. * specific language governing permissions and limitations
  54754. * under the License.
  54755. */
  54756. var nodeOpacityPath$1 = ['itemStyle', 'opacity'];
  54757. var hoverNodeOpacityPath = ['emphasis', 'itemStyle', 'opacity'];
  54758. var lineOpacityPath$1 = ['lineStyle', 'opacity'];
  54759. var hoverLineOpacityPath = ['emphasis', 'lineStyle', 'opacity'];
  54760. function getItemOpacity$1(item, opacityPath) {
  54761. return item.getVisual('opacity') || item.getModel().get(opacityPath);
  54762. }
  54763. function fadeOutItem$1(item, opacityPath, opacityRatio) {
  54764. var el = item.getGraphicEl();
  54765. var opacity = getItemOpacity$1(item, opacityPath);
  54766. if (opacityRatio != null) {
  54767. opacity == null && (opacity = 1);
  54768. opacity *= opacityRatio;
  54769. }
  54770. el.downplay && el.downplay();
  54771. el.traverse(function (child) {
  54772. if (child.type !== 'group') {
  54773. child.setStyle('opacity', opacity);
  54774. }
  54775. });
  54776. }
  54777. function fadeInItem$1(item, opacityPath) {
  54778. var opacity = getItemOpacity$1(item, opacityPath);
  54779. var el = item.getGraphicEl();
  54780. el.traverse(function (child) {
  54781. if (child.type !== 'group') {
  54782. child.setStyle('opacity', opacity);
  54783. }
  54784. }); // Support emphasis here.
  54785. el.highlight && el.highlight();
  54786. }
  54787. var SankeyShape = extendShape({
  54788. shape: {
  54789. x1: 0,
  54790. y1: 0,
  54791. x2: 0,
  54792. y2: 0,
  54793. cpx1: 0,
  54794. cpy1: 0,
  54795. cpx2: 0,
  54796. cpy2: 0,
  54797. extent: 0,
  54798. orient: ''
  54799. },
  54800. buildPath: function (ctx, shape) {
  54801. var extent = shape.extent;
  54802. ctx.moveTo(shape.x1, shape.y1);
  54803. ctx.bezierCurveTo(shape.cpx1, shape.cpy1, shape.cpx2, shape.cpy2, shape.x2, shape.y2);
  54804. if (shape.orient === 'vertical') {
  54805. ctx.lineTo(shape.x2 + extent, shape.y2);
  54806. ctx.bezierCurveTo(shape.cpx2 + extent, shape.cpy2, shape.cpx1 + extent, shape.cpy1, shape.x1 + extent, shape.y1);
  54807. } else {
  54808. ctx.lineTo(shape.x2, shape.y2 + extent);
  54809. ctx.bezierCurveTo(shape.cpx2, shape.cpy2 + extent, shape.cpx1, shape.cpy1 + extent, shape.x1, shape.y1 + extent);
  54810. }
  54811. ctx.closePath();
  54812. },
  54813. highlight: function () {
  54814. this.trigger('emphasis');
  54815. },
  54816. downplay: function () {
  54817. this.trigger('normal');
  54818. }
  54819. });
  54820. extendChartView({
  54821. type: 'sankey',
  54822. /**
  54823. * @private
  54824. * @type {module:echarts/chart/sankey/SankeySeries}
  54825. */
  54826. _model: null,
  54827. /**
  54828. * @private
  54829. * @type {boolean}
  54830. */
  54831. _focusAdjacencyDisabled: false,
  54832. render: function (seriesModel, ecModel, api) {
  54833. var sankeyView = this;
  54834. var graph = seriesModel.getGraph();
  54835. var group = this.group;
  54836. var layoutInfo = seriesModel.layoutInfo; // view width
  54837. var width = layoutInfo.width; // view height
  54838. var height = layoutInfo.height;
  54839. var nodeData = seriesModel.getData();
  54840. var edgeData = seriesModel.getData('edge');
  54841. var orient = seriesModel.get('orient');
  54842. this._model = seriesModel;
  54843. group.removeAll();
  54844. group.attr('position', [layoutInfo.x, layoutInfo.y]); // generate a bezire Curve for each edge
  54845. graph.eachEdge(function (edge) {
  54846. var curve = new SankeyShape();
  54847. curve.dataIndex = edge.dataIndex;
  54848. curve.seriesIndex = seriesModel.seriesIndex;
  54849. curve.dataType = 'edge';
  54850. var lineStyleModel = edge.getModel('lineStyle');
  54851. var curvature = lineStyleModel.get('curveness');
  54852. var n1Layout = edge.node1.getLayout();
  54853. var node1Model = edge.node1.getModel();
  54854. var dragX1 = node1Model.get('localX');
  54855. var dragY1 = node1Model.get('localY');
  54856. var n2Layout = edge.node2.getLayout();
  54857. var node2Model = edge.node2.getModel();
  54858. var dragX2 = node2Model.get('localX');
  54859. var dragY2 = node2Model.get('localY');
  54860. var edgeLayout = edge.getLayout();
  54861. var x1;
  54862. var y1;
  54863. var x2;
  54864. var y2;
  54865. var cpx1;
  54866. var cpy1;
  54867. var cpx2;
  54868. var cpy2;
  54869. curve.shape.extent = Math.max(1, edgeLayout.dy);
  54870. curve.shape.orient = orient;
  54871. if (orient === 'vertical') {
  54872. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + edgeLayout.sy;
  54873. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + n1Layout.dy;
  54874. x2 = (dragX2 != null ? dragX2 * width : n2Layout.x) + edgeLayout.ty;
  54875. y2 = dragY2 != null ? dragY2 * height : n2Layout.y;
  54876. cpx1 = x1;
  54877. cpy1 = y1 * (1 - curvature) + y2 * curvature;
  54878. cpx2 = x2;
  54879. cpy2 = y1 * curvature + y2 * (1 - curvature);
  54880. } else {
  54881. x1 = (dragX1 != null ? dragX1 * width : n1Layout.x) + n1Layout.dx;
  54882. y1 = (dragY1 != null ? dragY1 * height : n1Layout.y) + edgeLayout.sy;
  54883. x2 = dragX2 != null ? dragX2 * width : n2Layout.x;
  54884. y2 = (dragY2 != null ? dragY2 * height : n2Layout.y) + edgeLayout.ty;
  54885. cpx1 = x1 * (1 - curvature) + x2 * curvature;
  54886. cpy1 = y1;
  54887. cpx2 = x1 * curvature + x2 * (1 - curvature);
  54888. cpy2 = y2;
  54889. }
  54890. curve.setShape({
  54891. x1: x1,
  54892. y1: y1,
  54893. x2: x2,
  54894. y2: y2,
  54895. cpx1: cpx1,
  54896. cpy1: cpy1,
  54897. cpx2: cpx2,
  54898. cpy2: cpy2
  54899. });
  54900. curve.setStyle(lineStyleModel.getItemStyle()); // Special color, use source node color or target node color
  54901. switch (curve.style.fill) {
  54902. case 'source':
  54903. curve.style.fill = edge.node1.getVisual('color');
  54904. break;
  54905. case 'target':
  54906. curve.style.fill = edge.node2.getVisual('color');
  54907. break;
  54908. }
  54909. setHoverStyle(curve, edge.getModel('emphasis.lineStyle').getItemStyle());
  54910. group.add(curve);
  54911. edgeData.setItemGraphicEl(edge.dataIndex, curve);
  54912. }); // Generate a rect for each node
  54913. graph.eachNode(function (node) {
  54914. var layout = node.getLayout();
  54915. var itemModel = node.getModel();
  54916. var dragX = itemModel.get('localX');
  54917. var dragY = itemModel.get('localY');
  54918. var labelModel = itemModel.getModel('label');
  54919. var labelHoverModel = itemModel.getModel('emphasis.label');
  54920. var rect = new Rect({
  54921. shape: {
  54922. x: dragX != null ? dragX * width : layout.x,
  54923. y: dragY != null ? dragY * height : layout.y,
  54924. width: layout.dx,
  54925. height: layout.dy
  54926. },
  54927. style: itemModel.getModel('itemStyle').getItemStyle()
  54928. });
  54929. var hoverStyle = node.getModel('emphasis.itemStyle').getItemStyle();
  54930. setLabelStyle(rect.style, hoverStyle, labelModel, labelHoverModel, {
  54931. labelFetcher: seriesModel,
  54932. labelDataIndex: node.dataIndex,
  54933. defaultText: node.id,
  54934. isRectText: true
  54935. });
  54936. rect.setStyle('fill', node.getVisual('color'));
  54937. setHoverStyle(rect, hoverStyle);
  54938. group.add(rect);
  54939. nodeData.setItemGraphicEl(node.dataIndex, rect);
  54940. rect.dataType = 'node';
  54941. });
  54942. nodeData.eachItemGraphicEl(function (el, dataIndex) {
  54943. var itemModel = nodeData.getItemModel(dataIndex);
  54944. if (itemModel.get('draggable')) {
  54945. el.drift = function (dx, dy) {
  54946. sankeyView._focusAdjacencyDisabled = true;
  54947. this.shape.x += dx;
  54948. this.shape.y += dy;
  54949. this.dirty();
  54950. api.dispatchAction({
  54951. type: 'dragNode',
  54952. seriesId: seriesModel.id,
  54953. dataIndex: nodeData.getRawIndex(dataIndex),
  54954. localX: this.shape.x / width,
  54955. localY: this.shape.y / height
  54956. });
  54957. };
  54958. el.ondragend = function () {
  54959. sankeyView._focusAdjacencyDisabled = false;
  54960. };
  54961. el.draggable = true;
  54962. el.cursor = 'move';
  54963. }
  54964. el.highlight = function () {
  54965. this.trigger('emphasis');
  54966. };
  54967. el.downplay = function () {
  54968. this.trigger('normal');
  54969. };
  54970. el.focusNodeAdjHandler && el.off('mouseover', el.focusNodeAdjHandler);
  54971. el.unfocusNodeAdjHandler && el.off('mouseout', el.unfocusNodeAdjHandler);
  54972. if (itemModel.get('focusNodeAdjacency')) {
  54973. el.on('mouseover', el.focusNodeAdjHandler = function () {
  54974. if (!sankeyView._focusAdjacencyDisabled) {
  54975. sankeyView._clearTimer();
  54976. api.dispatchAction({
  54977. type: 'focusNodeAdjacency',
  54978. seriesId: seriesModel.id,
  54979. dataIndex: el.dataIndex
  54980. });
  54981. }
  54982. });
  54983. el.on('mouseout', el.unfocusNodeAdjHandler = function () {
  54984. if (!sankeyView._focusAdjacencyDisabled) {
  54985. sankeyView._dispatchUnfocus(api);
  54986. }
  54987. });
  54988. }
  54989. });
  54990. edgeData.eachItemGraphicEl(function (el, dataIndex) {
  54991. var edgeModel = edgeData.getItemModel(dataIndex);
  54992. el.focusNodeAdjHandler && el.off('mouseover', el.focusNodeAdjHandler);
  54993. el.unfocusNodeAdjHandler && el.off('mouseout', el.unfocusNodeAdjHandler);
  54994. if (edgeModel.get('focusNodeAdjacency')) {
  54995. el.on('mouseover', el.focusNodeAdjHandler = function () {
  54996. if (!sankeyView._focusAdjacencyDisabled) {
  54997. sankeyView._clearTimer();
  54998. api.dispatchAction({
  54999. type: 'focusNodeAdjacency',
  55000. seriesId: seriesModel.id,
  55001. edgeDataIndex: el.dataIndex
  55002. });
  55003. }
  55004. });
  55005. el.on('mouseout', el.unfocusNodeAdjHandler = function () {
  55006. if (!sankeyView._focusAdjacencyDisabled) {
  55007. sankeyView._dispatchUnfocus(api);
  55008. }
  55009. });
  55010. }
  55011. });
  55012. if (!this._data && seriesModel.get('animation')) {
  55013. group.setClipPath(createGridClipShape$1(group.getBoundingRect(), seriesModel, function () {
  55014. group.removeClipPath();
  55015. }));
  55016. }
  55017. this._data = seriesModel.getData();
  55018. },
  55019. dispose: function () {
  55020. this._clearTimer();
  55021. },
  55022. _dispatchUnfocus: function (api) {
  55023. var self = this;
  55024. this._clearTimer();
  55025. this._unfocusDelayTimer = setTimeout(function () {
  55026. self._unfocusDelayTimer = null;
  55027. api.dispatchAction({
  55028. type: 'unfocusNodeAdjacency',
  55029. seriesId: self._model.id
  55030. });
  55031. }, 500);
  55032. },
  55033. _clearTimer: function () {
  55034. if (this._unfocusDelayTimer) {
  55035. clearTimeout(this._unfocusDelayTimer);
  55036. this._unfocusDelayTimer = null;
  55037. }
  55038. },
  55039. focusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  55040. var data = seriesModel.getData();
  55041. var graph = data.graph;
  55042. var dataIndex = payload.dataIndex;
  55043. var itemModel = data.getItemModel(dataIndex);
  55044. var edgeDataIndex = payload.edgeDataIndex;
  55045. if (dataIndex == null && edgeDataIndex == null) {
  55046. return;
  55047. }
  55048. var node = graph.getNodeByIndex(dataIndex);
  55049. var edge = graph.getEdgeByIndex(edgeDataIndex);
  55050. graph.eachNode(function (node) {
  55051. fadeOutItem$1(node, nodeOpacityPath$1, 0.1);
  55052. });
  55053. graph.eachEdge(function (edge) {
  55054. fadeOutItem$1(edge, lineOpacityPath$1, 0.1);
  55055. });
  55056. if (node) {
  55057. fadeInItem$1(node, hoverNodeOpacityPath);
  55058. var focusNodeAdj = itemModel.get('focusNodeAdjacency');
  55059. if (focusNodeAdj === 'outEdges') {
  55060. each$1(node.outEdges, function (edge) {
  55061. if (edge.dataIndex < 0) {
  55062. return;
  55063. }
  55064. fadeInItem$1(edge, hoverLineOpacityPath);
  55065. fadeInItem$1(edge.node2, hoverNodeOpacityPath);
  55066. });
  55067. } else if (focusNodeAdj === 'inEdges') {
  55068. each$1(node.inEdges, function (edge) {
  55069. if (edge.dataIndex < 0) {
  55070. return;
  55071. }
  55072. fadeInItem$1(edge, hoverLineOpacityPath);
  55073. fadeInItem$1(edge.node1, hoverNodeOpacityPath);
  55074. });
  55075. } else if (focusNodeAdj === 'allEdges') {
  55076. each$1(node.edges, function (edge) {
  55077. if (edge.dataIndex < 0) {
  55078. return;
  55079. }
  55080. fadeInItem$1(edge, hoverLineOpacityPath);
  55081. edge.node1 !== node && fadeInItem$1(edge.node1, hoverNodeOpacityPath);
  55082. edge.node2 !== node && fadeInItem$1(edge.node2, hoverNodeOpacityPath);
  55083. });
  55084. }
  55085. }
  55086. if (edge) {
  55087. fadeInItem$1(edge, hoverLineOpacityPath);
  55088. fadeInItem$1(edge.node1, hoverNodeOpacityPath);
  55089. fadeInItem$1(edge.node2, hoverNodeOpacityPath);
  55090. }
  55091. },
  55092. unfocusNodeAdjacency: function (seriesModel, ecModel, api, payload) {
  55093. var graph = seriesModel.getGraph();
  55094. graph.eachNode(function (node) {
  55095. fadeOutItem$1(node, nodeOpacityPath$1);
  55096. });
  55097. graph.eachEdge(function (edge) {
  55098. fadeOutItem$1(edge, lineOpacityPath$1);
  55099. });
  55100. }
  55101. }); // Add animation to the view
  55102. function createGridClipShape$1(rect, seriesModel, cb) {
  55103. var rectEl = new Rect({
  55104. shape: {
  55105. x: rect.x - 10,
  55106. y: rect.y - 10,
  55107. width: 0,
  55108. height: rect.height + 20
  55109. }
  55110. });
  55111. initProps(rectEl, {
  55112. shape: {
  55113. width: rect.width + 20
  55114. }
  55115. }, seriesModel, cb);
  55116. return rectEl;
  55117. }
  55118. /*
  55119. * Licensed to the Apache Software Foundation (ASF) under one
  55120. * or more contributor license agreements. See the NOTICE file
  55121. * distributed with this work for additional information
  55122. * regarding copyright ownership. The ASF licenses this file
  55123. * to you under the Apache License, Version 2.0 (the
  55124. * "License"); you may not use this file except in compliance
  55125. * with the License. You may obtain a copy of the License at
  55126. *
  55127. * http://www.apache.org/licenses/LICENSE-2.0
  55128. *
  55129. * Unless required by applicable law or agreed to in writing,
  55130. * software distributed under the License is distributed on an
  55131. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55132. * KIND, either express or implied. See the License for the
  55133. * specific language governing permissions and limitations
  55134. * under the License.
  55135. */
  55136. registerAction({
  55137. type: 'dragNode',
  55138. event: 'dragnode',
  55139. // here can only use 'update' now, other value is not support in echarts.
  55140. update: 'update'
  55141. }, function (payload, ecModel) {
  55142. ecModel.eachComponent({
  55143. mainType: 'series',
  55144. subType: 'sankey',
  55145. query: payload
  55146. }, function (seriesModel) {
  55147. seriesModel.setNodePosition(payload.dataIndex, [payload.localX, payload.localY]);
  55148. });
  55149. });
  55150. /*
  55151. * Licensed to the Apache Software Foundation (ASF) under one
  55152. * or more contributor license agreements. See the NOTICE file
  55153. * distributed with this work for additional information
  55154. * regarding copyright ownership. The ASF licenses this file
  55155. * to you under the Apache License, Version 2.0 (the
  55156. * "License"); you may not use this file except in compliance
  55157. * with the License. You may obtain a copy of the License at
  55158. *
  55159. * http://www.apache.org/licenses/LICENSE-2.0
  55160. *
  55161. * Unless required by applicable law or agreed to in writing,
  55162. * software distributed under the License is distributed on an
  55163. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55164. * KIND, either express or implied. See the License for the
  55165. * specific language governing permissions and limitations
  55166. * under the License.
  55167. */
  55168. var sankeyLayout = function (ecModel, api, payload) {
  55169. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  55170. var nodeWidth = seriesModel.get('nodeWidth');
  55171. var nodeGap = seriesModel.get('nodeGap');
  55172. var layoutInfo = getViewRect$4(seriesModel, api);
  55173. seriesModel.layoutInfo = layoutInfo;
  55174. var width = layoutInfo.width;
  55175. var height = layoutInfo.height;
  55176. var graph = seriesModel.getGraph();
  55177. var nodes = graph.nodes;
  55178. var edges = graph.edges;
  55179. computeNodeValues(nodes);
  55180. var filteredNodes = filter(nodes, function (node) {
  55181. return node.getLayout().value === 0;
  55182. });
  55183. var iterations = filteredNodes.length !== 0 ? 0 : seriesModel.get('layoutIterations');
  55184. var orient = seriesModel.get('orient');
  55185. var nodeAlign = seriesModel.get('nodeAlign');
  55186. layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign);
  55187. });
  55188. };
  55189. /**
  55190. * Get the layout position of the whole view
  55191. *
  55192. * @param {module:echarts/model/Series} seriesModel the model object of sankey series
  55193. * @param {module:echarts/ExtensionAPI} api provide the API list that the developer can call
  55194. * @return {module:zrender/core/BoundingRect} size of rect to draw the sankey view
  55195. */
  55196. function getViewRect$4(seriesModel, api) {
  55197. return getLayoutRect(seriesModel.getBoxLayoutParams(), {
  55198. width: api.getWidth(),
  55199. height: api.getHeight()
  55200. });
  55201. }
  55202. function layoutSankey(nodes, edges, nodeWidth, nodeGap, width, height, iterations, orient, nodeAlign) {
  55203. computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign);
  55204. computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient);
  55205. computeEdgeDepths(nodes, orient);
  55206. }
  55207. /**
  55208. * Compute the value of each node by summing the associated edge's value
  55209. *
  55210. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55211. */
  55212. function computeNodeValues(nodes) {
  55213. each$1(nodes, function (node) {
  55214. var value1 = sum(node.outEdges, getEdgeValue);
  55215. var value2 = sum(node.inEdges, getEdgeValue);
  55216. var nodeRawValue = node.getValue() || 0;
  55217. var value = Math.max(value1, value2, nodeRawValue);
  55218. node.setLayout({
  55219. value: value
  55220. }, true);
  55221. });
  55222. }
  55223. /**
  55224. * Compute the x-position for each node.
  55225. *
  55226. * Here we use Kahn algorithm to detect cycle when we traverse
  55227. * the node to computer the initial x position.
  55228. *
  55229. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55230. * @param {number} nodeWidth the dx of the node
  55231. * @param {number} width the whole width of the area to draw the view
  55232. */
  55233. function computeNodeBreadths(nodes, edges, nodeWidth, width, height, orient, nodeAlign) {
  55234. // Used to mark whether the edge is deleted. if it is deleted,
  55235. // the value is 0, otherwise it is 1.
  55236. var remainEdges = []; // Storage each node's indegree.
  55237. var indegreeArr = []; //Used to storage the node with indegree is equal to 0.
  55238. var zeroIndegrees = [];
  55239. var nextTargetNode = [];
  55240. var x = 0;
  55241. var kx = 0;
  55242. for (var i = 0; i < edges.length; i++) {
  55243. remainEdges[i] = 1;
  55244. }
  55245. for (i = 0; i < nodes.length; i++) {
  55246. indegreeArr[i] = nodes[i].inEdges.length;
  55247. if (indegreeArr[i] === 0) {
  55248. zeroIndegrees.push(nodes[i]);
  55249. }
  55250. }
  55251. var maxNodeDepth = -1; // Traversing nodes using topological sorting to calculate the
  55252. // horizontal(if orient === 'horizontal') or vertical(if orient === 'vertical')
  55253. // position of the nodes.
  55254. while (zeroIndegrees.length) {
  55255. for (var idx = 0; idx < zeroIndegrees.length; idx++) {
  55256. var node = zeroIndegrees[idx];
  55257. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55258. var isItemDepth = item.depth != null && item.depth >= 0;
  55259. if (isItemDepth && item.depth > maxNodeDepth) {
  55260. maxNodeDepth = item.depth;
  55261. }
  55262. node.setLayout({
  55263. depth: isItemDepth ? item.depth : x
  55264. }, true);
  55265. orient === 'vertical' ? node.setLayout({
  55266. dy: nodeWidth
  55267. }, true) : node.setLayout({
  55268. dx: nodeWidth
  55269. }, true);
  55270. for (var edgeIdx = 0; edgeIdx < node.outEdges.length; edgeIdx++) {
  55271. var edge = node.outEdges[edgeIdx];
  55272. var indexEdge = edges.indexOf(edge);
  55273. remainEdges[indexEdge] = 0;
  55274. var targetNode = edge.node2;
  55275. var nodeIndex = nodes.indexOf(targetNode);
  55276. if (--indegreeArr[nodeIndex] === 0 && nextTargetNode.indexOf(targetNode) < 0) {
  55277. nextTargetNode.push(targetNode);
  55278. }
  55279. }
  55280. }
  55281. ++x;
  55282. zeroIndegrees = nextTargetNode;
  55283. nextTargetNode = [];
  55284. }
  55285. for (i = 0; i < remainEdges.length; i++) {
  55286. if (remainEdges[i] === 1) {
  55287. throw new Error('Sankey is a DAG, the original data has cycle!');
  55288. }
  55289. }
  55290. var maxDepth = maxNodeDepth > x - 1 ? maxNodeDepth : x - 1;
  55291. if (nodeAlign && nodeAlign !== 'left') {
  55292. adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth);
  55293. }
  55294. var kx = orient === 'vertical' ? (height - nodeWidth) / maxDepth : (width - nodeWidth) / maxDepth;
  55295. scaleNodeBreadths(nodes, kx, orient);
  55296. }
  55297. function isNodeDepth(node) {
  55298. var item = node.hostGraph.data.getRawDataItem(node.dataIndex);
  55299. return item.depth != null && item.depth >= 0;
  55300. }
  55301. function adjustNodeWithNodeAlign(nodes, nodeAlign, orient, maxDepth) {
  55302. if (nodeAlign === 'right') {
  55303. var nextSourceNode = [];
  55304. var remainNodes = nodes;
  55305. var nodeHeight = 0;
  55306. while (remainNodes.length) {
  55307. for (var i = 0; i < remainNodes.length; i++) {
  55308. var node = remainNodes[i];
  55309. node.setLayout({
  55310. skNodeHeight: nodeHeight
  55311. }, true);
  55312. for (var j = 0; j < node.inEdges.length; j++) {
  55313. var edge = node.inEdges[j];
  55314. if (nextSourceNode.indexOf(edge.node1) < 0) {
  55315. nextSourceNode.push(edge.node1);
  55316. }
  55317. }
  55318. }
  55319. remainNodes = nextSourceNode;
  55320. nextSourceNode = [];
  55321. ++nodeHeight;
  55322. }
  55323. each$1(nodes, function (node) {
  55324. if (!isNodeDepth(node)) {
  55325. node.setLayout({
  55326. depth: Math.max(0, maxDepth - node.getLayout().skNodeHeight)
  55327. }, true);
  55328. }
  55329. });
  55330. } else if (nodeAlign === 'justify') {
  55331. moveSinksRight(nodes, maxDepth);
  55332. }
  55333. }
  55334. /**
  55335. * All the node without outEgdes are assigned maximum x-position and
  55336. * be aligned in the last column.
  55337. *
  55338. * @param {module:echarts/data/Graph~Node} nodes. node of sankey view.
  55339. * @param {number} maxDepth. use to assign to node without outEdges as x-position.
  55340. */
  55341. function moveSinksRight(nodes, maxDepth) {
  55342. each$1(nodes, function (node) {
  55343. if (!isNodeDepth(node) && !node.outEdges.length) {
  55344. node.setLayout({
  55345. depth: maxDepth
  55346. }, true);
  55347. }
  55348. });
  55349. }
  55350. /**
  55351. * Scale node x-position to the width
  55352. *
  55353. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55354. * @param {number} kx multiple used to scale nodes
  55355. */
  55356. function scaleNodeBreadths(nodes, kx, orient) {
  55357. each$1(nodes, function (node) {
  55358. var nodeDepth = node.getLayout().depth * kx;
  55359. orient === 'vertical' ? node.setLayout({
  55360. y: nodeDepth
  55361. }, true) : node.setLayout({
  55362. x: nodeDepth
  55363. }, true);
  55364. });
  55365. }
  55366. /**
  55367. * Using Gauss-Seidel iterations method to compute the node depth(y-position)
  55368. *
  55369. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55370. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55371. * @param {number} height the whole height of the area to draw the view
  55372. * @param {number} nodeGap the vertical distance between two nodes
  55373. * in the same column.
  55374. * @param {number} iterations the number of iterations for the algorithm
  55375. */
  55376. function computeNodeDepths(nodes, edges, height, width, nodeGap, iterations, orient) {
  55377. var nodesByBreadth = prepareNodesByBreadth(nodes, orient);
  55378. initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient);
  55379. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55380. for (var alpha = 1; iterations > 0; iterations--) {
  55381. // 0.99 is a experience parameter, ensure that each iterations of
  55382. // changes as small as possible.
  55383. alpha *= 0.99;
  55384. relaxRightToLeft(nodesByBreadth, alpha, orient);
  55385. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55386. relaxLeftToRight(nodesByBreadth, alpha, orient);
  55387. resolveCollisions(nodesByBreadth, nodeGap, height, width, orient);
  55388. }
  55389. }
  55390. function prepareNodesByBreadth(nodes, orient) {
  55391. var nodesByBreadth = [];
  55392. var keyAttr = orient === 'vertical' ? 'y' : 'x';
  55393. var groupResult = groupData(nodes, function (node) {
  55394. return node.getLayout()[keyAttr];
  55395. });
  55396. groupResult.keys.sort(function (a, b) {
  55397. return a - b;
  55398. });
  55399. each$1(groupResult.keys, function (key) {
  55400. nodesByBreadth.push(groupResult.buckets.get(key));
  55401. });
  55402. return nodesByBreadth;
  55403. }
  55404. /**
  55405. * Compute the original y-position for each node
  55406. *
  55407. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55408. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55409. * group by the array of all sankey nodes based on the nodes x-position.
  55410. * @param {module:echarts/data/Graph~Edge} edges edge of sankey view
  55411. * @param {number} height the whole height of the area to draw the view
  55412. * @param {number} nodeGap the vertical distance between two nodes
  55413. */
  55414. function initializeNodeDepth(nodesByBreadth, edges, height, width, nodeGap, orient) {
  55415. var minKy = Infinity;
  55416. each$1(nodesByBreadth, function (nodes) {
  55417. var n = nodes.length;
  55418. var sum = 0;
  55419. each$1(nodes, function (node) {
  55420. sum += node.getLayout().value;
  55421. });
  55422. var ky = orient === 'vertical' ? (width - (n - 1) * nodeGap) / sum : (height - (n - 1) * nodeGap) / sum;
  55423. if (ky < minKy) {
  55424. minKy = ky;
  55425. }
  55426. });
  55427. each$1(nodesByBreadth, function (nodes) {
  55428. each$1(nodes, function (node, i) {
  55429. var nodeDy = node.getLayout().value * minKy;
  55430. if (orient === 'vertical') {
  55431. node.setLayout({
  55432. x: i
  55433. }, true);
  55434. node.setLayout({
  55435. dx: nodeDy
  55436. }, true);
  55437. } else {
  55438. node.setLayout({
  55439. y: i
  55440. }, true);
  55441. node.setLayout({
  55442. dy: nodeDy
  55443. }, true);
  55444. }
  55445. });
  55446. });
  55447. each$1(edges, function (edge) {
  55448. var edgeDy = +edge.getValue() * minKy;
  55449. edge.setLayout({
  55450. dy: edgeDy
  55451. }, true);
  55452. });
  55453. }
  55454. /**
  55455. * Resolve the collision of initialized depth (y-position)
  55456. *
  55457. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55458. * group by the array of all sankey nodes based on the nodes x-position.
  55459. * @param {number} nodeGap the vertical distance between two nodes
  55460. * @param {number} height the whole height of the area to draw the view
  55461. */
  55462. function resolveCollisions(nodesByBreadth, nodeGap, height, width, orient) {
  55463. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55464. each$1(nodesByBreadth, function (nodes) {
  55465. nodes.sort(function (a, b) {
  55466. return a.getLayout()[keyAttr] - b.getLayout()[keyAttr];
  55467. });
  55468. var nodeX;
  55469. var node;
  55470. var dy;
  55471. var y0 = 0;
  55472. var n = nodes.length;
  55473. var nodeDyAttr = orient === 'vertical' ? 'dx' : 'dy';
  55474. for (var i = 0; i < n; i++) {
  55475. node = nodes[i];
  55476. dy = y0 - node.getLayout()[keyAttr];
  55477. if (dy > 0) {
  55478. nodeX = node.getLayout()[keyAttr] + dy;
  55479. orient === 'vertical' ? node.setLayout({
  55480. x: nodeX
  55481. }, true) : node.setLayout({
  55482. y: nodeX
  55483. }, true);
  55484. }
  55485. y0 = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap;
  55486. }
  55487. var viewWidth = orient === 'vertical' ? width : height; // If the bottommost node goes outside the bounds, push it back up
  55488. dy = y0 - nodeGap - viewWidth;
  55489. if (dy > 0) {
  55490. nodeX = node.getLayout()[keyAttr] - dy;
  55491. orient === 'vertical' ? node.setLayout({
  55492. x: nodeX
  55493. }, true) : node.setLayout({
  55494. y: nodeX
  55495. }, true);
  55496. y0 = nodeX;
  55497. for (i = n - 2; i >= 0; --i) {
  55498. node = nodes[i];
  55499. dy = node.getLayout()[keyAttr] + node.getLayout()[nodeDyAttr] + nodeGap - y0;
  55500. if (dy > 0) {
  55501. nodeX = node.getLayout()[keyAttr] - dy;
  55502. orient === 'vertical' ? node.setLayout({
  55503. x: nodeX
  55504. }, true) : node.setLayout({
  55505. y: nodeX
  55506. }, true);
  55507. }
  55508. y0 = node.getLayout()[keyAttr];
  55509. }
  55510. }
  55511. });
  55512. }
  55513. /**
  55514. * Change the y-position of the nodes, except most the right side nodes
  55515. *
  55516. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55517. * group by the array of all sankey nodes based on the node x-position.
  55518. * @param {number} alpha parameter used to adjust the nodes y-position
  55519. */
  55520. function relaxRightToLeft(nodesByBreadth, alpha, orient) {
  55521. each$1(nodesByBreadth.slice().reverse(), function (nodes) {
  55522. each$1(nodes, function (node) {
  55523. if (node.outEdges.length) {
  55524. var y = sum(node.outEdges, weightedTarget, orient) / sum(node.outEdges, getEdgeValue, orient);
  55525. if (isNaN(y)) {
  55526. var len = node.outEdges.length;
  55527. y = len ? sum(node.outEdges, centerTarget, orient) / len : 0;
  55528. }
  55529. if (orient === 'vertical') {
  55530. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55531. node.setLayout({
  55532. x: nodeX
  55533. }, true);
  55534. } else {
  55535. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55536. node.setLayout({
  55537. y: nodeY
  55538. }, true);
  55539. }
  55540. }
  55541. });
  55542. });
  55543. }
  55544. function weightedTarget(edge, orient) {
  55545. return center$1(edge.node2, orient) * edge.getValue();
  55546. }
  55547. function centerTarget(edge, orient) {
  55548. return center$1(edge.node2, orient);
  55549. }
  55550. function weightedSource(edge, orient) {
  55551. return center$1(edge.node1, orient) * edge.getValue();
  55552. }
  55553. function centerSource(edge, orient) {
  55554. return center$1(edge.node1, orient);
  55555. }
  55556. function center$1(node, orient) {
  55557. return orient === 'vertical' ? node.getLayout().x + node.getLayout().dx / 2 : node.getLayout().y + node.getLayout().dy / 2;
  55558. }
  55559. function getEdgeValue(edge) {
  55560. return edge.getValue();
  55561. }
  55562. function sum(array, cb, orient) {
  55563. var sum = 0;
  55564. var len = array.length;
  55565. var i = -1;
  55566. while (++i < len) {
  55567. var value = +cb.call(array, array[i], orient);
  55568. if (!isNaN(value)) {
  55569. sum += value;
  55570. }
  55571. }
  55572. return sum;
  55573. }
  55574. /**
  55575. * Change the y-position of the nodes, except most the left side nodes
  55576. *
  55577. * @param {Array.<Array.<module:echarts/data/Graph~Node>>} nodesByBreadth
  55578. * group by the array of all sankey nodes based on the node x-position.
  55579. * @param {number} alpha parameter used to adjust the nodes y-position
  55580. */
  55581. function relaxLeftToRight(nodesByBreadth, alpha, orient) {
  55582. each$1(nodesByBreadth, function (nodes) {
  55583. each$1(nodes, function (node) {
  55584. if (node.inEdges.length) {
  55585. var y = sum(node.inEdges, weightedSource, orient) / sum(node.inEdges, getEdgeValue, orient);
  55586. if (isNaN(y)) {
  55587. var len = node.inEdges.length;
  55588. y = len ? sum(node.inEdges, centerSource, orient) / len : 0;
  55589. }
  55590. if (orient === 'vertical') {
  55591. var nodeX = node.getLayout().x + (y - center$1(node, orient)) * alpha;
  55592. node.setLayout({
  55593. x: nodeX
  55594. }, true);
  55595. } else {
  55596. var nodeY = node.getLayout().y + (y - center$1(node, orient)) * alpha;
  55597. node.setLayout({
  55598. y: nodeY
  55599. }, true);
  55600. }
  55601. }
  55602. });
  55603. });
  55604. }
  55605. /**
  55606. * Compute the depth(y-position) of each edge
  55607. *
  55608. * @param {module:echarts/data/Graph~Node} nodes node of sankey view
  55609. */
  55610. function computeEdgeDepths(nodes, orient) {
  55611. var keyAttr = orient === 'vertical' ? 'x' : 'y';
  55612. each$1(nodes, function (node) {
  55613. node.outEdges.sort(function (a, b) {
  55614. return a.node2.getLayout()[keyAttr] - b.node2.getLayout()[keyAttr];
  55615. });
  55616. node.inEdges.sort(function (a, b) {
  55617. return a.node1.getLayout()[keyAttr] - b.node1.getLayout()[keyAttr];
  55618. });
  55619. });
  55620. each$1(nodes, function (node) {
  55621. var sy = 0;
  55622. var ty = 0;
  55623. each$1(node.outEdges, function (edge) {
  55624. edge.setLayout({
  55625. sy: sy
  55626. }, true);
  55627. sy += edge.getLayout().dy;
  55628. });
  55629. each$1(node.inEdges, function (edge) {
  55630. edge.setLayout({
  55631. ty: ty
  55632. }, true);
  55633. ty += edge.getLayout().dy;
  55634. });
  55635. });
  55636. }
  55637. /*
  55638. * Licensed to the Apache Software Foundation (ASF) under one
  55639. * or more contributor license agreements. See the NOTICE file
  55640. * distributed with this work for additional information
  55641. * regarding copyright ownership. The ASF licenses this file
  55642. * to you under the Apache License, Version 2.0 (the
  55643. * "License"); you may not use this file except in compliance
  55644. * with the License. You may obtain a copy of the License at
  55645. *
  55646. * http://www.apache.org/licenses/LICENSE-2.0
  55647. *
  55648. * Unless required by applicable law or agreed to in writing,
  55649. * software distributed under the License is distributed on an
  55650. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55651. * KIND, either express or implied. See the License for the
  55652. * specific language governing permissions and limitations
  55653. * under the License.
  55654. */
  55655. var sankeyVisual = function (ecModel, payload) {
  55656. ecModel.eachSeriesByType('sankey', function (seriesModel) {
  55657. var graph = seriesModel.getGraph();
  55658. var nodes = graph.nodes;
  55659. if (nodes.length) {
  55660. var minValue = Infinity;
  55661. var maxValue = -Infinity;
  55662. each$1(nodes, function (node) {
  55663. var nodeValue = node.getLayout().value;
  55664. if (nodeValue < minValue) {
  55665. minValue = nodeValue;
  55666. }
  55667. if (nodeValue > maxValue) {
  55668. maxValue = nodeValue;
  55669. }
  55670. });
  55671. each$1(nodes, function (node) {
  55672. var mapping = new VisualMapping({
  55673. type: 'color',
  55674. mappingMethod: 'linear',
  55675. dataExtent: [minValue, maxValue],
  55676. visual: seriesModel.get('color')
  55677. });
  55678. var mapValueToColor = mapping.mapValueToVisual(node.getLayout().value);
  55679. var customColor = node.getModel().get('itemStyle.color');
  55680. customColor != null ? node.setVisual('color', customColor) : node.setVisual('color', mapValueToColor);
  55681. });
  55682. }
  55683. });
  55684. };
  55685. /*
  55686. * Licensed to the Apache Software Foundation (ASF) under one
  55687. * or more contributor license agreements. See the NOTICE file
  55688. * distributed with this work for additional information
  55689. * regarding copyright ownership. The ASF licenses this file
  55690. * to you under the Apache License, Version 2.0 (the
  55691. * "License"); you may not use this file except in compliance
  55692. * with the License. You may obtain a copy of the License at
  55693. *
  55694. * http://www.apache.org/licenses/LICENSE-2.0
  55695. *
  55696. * Unless required by applicable law or agreed to in writing,
  55697. * software distributed under the License is distributed on an
  55698. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55699. * KIND, either express or implied. See the License for the
  55700. * specific language governing permissions and limitations
  55701. * under the License.
  55702. */
  55703. registerLayout(sankeyLayout);
  55704. registerVisual(sankeyVisual);
  55705. /*
  55706. * Licensed to the Apache Software Foundation (ASF) under one
  55707. * or more contributor license agreements. See the NOTICE file
  55708. * distributed with this work for additional information
  55709. * regarding copyright ownership. The ASF licenses this file
  55710. * to you under the Apache License, Version 2.0 (the
  55711. * "License"); you may not use this file except in compliance
  55712. * with the License. You may obtain a copy of the License at
  55713. *
  55714. * http://www.apache.org/licenses/LICENSE-2.0
  55715. *
  55716. * Unless required by applicable law or agreed to in writing,
  55717. * software distributed under the License is distributed on an
  55718. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55719. * KIND, either express or implied. See the License for the
  55720. * specific language governing permissions and limitations
  55721. * under the License.
  55722. */
  55723. /**
  55724. * @constructor module:echarts/coord/single/SingleAxis
  55725. * @extends {module:echarts/coord/Axis}
  55726. * @param {string} dim
  55727. * @param {*} scale
  55728. * @param {Array.<number>} coordExtent
  55729. * @param {string} axisType
  55730. * @param {string} position
  55731. */
  55732. var SingleAxis = function (dim, scale, coordExtent, axisType, position) {
  55733. Axis.call(this, dim, scale, coordExtent);
  55734. /**
  55735. * Axis type
  55736. * - 'category'
  55737. * - 'value'
  55738. * - 'time'
  55739. * - 'log'
  55740. * @type {string}
  55741. */
  55742. this.type = axisType || 'value';
  55743. /**
  55744. * Axis position
  55745. * - 'top'
  55746. * - 'bottom'
  55747. * - 'left'
  55748. * - 'right'
  55749. * @type {string}
  55750. */
  55751. this.position = position || 'bottom';
  55752. /**
  55753. * Axis orient
  55754. * - 'horizontal'
  55755. * - 'vertical'
  55756. * @type {[type]}
  55757. */
  55758. this.orient = null;
  55759. };
  55760. SingleAxis.prototype = {
  55761. constructor: SingleAxis,
  55762. /**
  55763. * Axis model
  55764. * @type {module:echarts/coord/single/AxisModel}
  55765. */
  55766. model: null,
  55767. /**
  55768. * Judge the orient of the axis.
  55769. * @return {boolean}
  55770. */
  55771. isHorizontal: function () {
  55772. var position = this.position;
  55773. return position === 'top' || position === 'bottom';
  55774. },
  55775. /**
  55776. * @override
  55777. */
  55778. pointToData: function (point, clamp) {
  55779. return this.coordinateSystem.pointToData(point, clamp)[0];
  55780. },
  55781. /**
  55782. * Convert the local coord(processed by dataToCoord())
  55783. * to global coord(concrete pixel coord).
  55784. * designated by module:echarts/coord/single/Single.
  55785. * @type {Function}
  55786. */
  55787. toGlobalCoord: null,
  55788. /**
  55789. * Convert the global coord to local coord.
  55790. * designated by module:echarts/coord/single/Single.
  55791. * @type {Function}
  55792. */
  55793. toLocalCoord: null
  55794. };
  55795. inherits(SingleAxis, Axis);
  55796. /*
  55797. * Licensed to the Apache Software Foundation (ASF) under one
  55798. * or more contributor license agreements. See the NOTICE file
  55799. * distributed with this work for additional information
  55800. * regarding copyright ownership. The ASF licenses this file
  55801. * to you under the Apache License, Version 2.0 (the
  55802. * "License"); you may not use this file except in compliance
  55803. * with the License. You may obtain a copy of the License at
  55804. *
  55805. * http://www.apache.org/licenses/LICENSE-2.0
  55806. *
  55807. * Unless required by applicable law or agreed to in writing,
  55808. * software distributed under the License is distributed on an
  55809. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  55810. * KIND, either express or implied. See the License for the
  55811. * specific language governing permissions and limitations
  55812. * under the License.
  55813. */
  55814. /**
  55815. * Single coordinates system.
  55816. */
  55817. /**
  55818. * Create a single coordinates system.
  55819. *
  55820. * @param {module:echarts/coord/single/AxisModel} axisModel
  55821. * @param {module:echarts/model/Global} ecModel
  55822. * @param {module:echarts/ExtensionAPI} api
  55823. */
  55824. function Single(axisModel, ecModel, api) {
  55825. /**
  55826. * @type {string}
  55827. * @readOnly
  55828. */
  55829. this.dimension = 'single';
  55830. /**
  55831. * Add it just for draw tooltip.
  55832. *
  55833. * @type {Array.<string>}
  55834. * @readOnly
  55835. */
  55836. this.dimensions = ['single'];
  55837. /**
  55838. * @private
  55839. * @type {module:echarts/coord/single/SingleAxis}.
  55840. */
  55841. this._axis = null;
  55842. /**
  55843. * @private
  55844. * @type {module:zrender/core/BoundingRect}
  55845. */
  55846. this._rect;
  55847. this._init(axisModel, ecModel, api);
  55848. /**
  55849. * @type {module:echarts/coord/single/AxisModel}
  55850. */
  55851. this.model = axisModel;
  55852. }
  55853. Single.prototype = {
  55854. type: 'singleAxis',
  55855. axisPointerEnabled: true,
  55856. constructor: Single,
  55857. /**
  55858. * Initialize single coordinate system.
  55859. *
  55860. * @param {module:echarts/coord/single/AxisModel} axisModel
  55861. * @param {module:echarts/model/Global} ecModel
  55862. * @param {module:echarts/ExtensionAPI} api
  55863. * @private
  55864. */
  55865. _init: function (axisModel, ecModel, api) {
  55866. var dim = this.dimension;
  55867. var axis = new SingleAxis(dim, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisModel.get('position'));
  55868. var isCategory = axis.type === 'category';
  55869. axis.onBand = isCategory && axisModel.get('boundaryGap');
  55870. axis.inverse = axisModel.get('inverse');
  55871. axis.orient = axisModel.get('orient');
  55872. axisModel.axis = axis;
  55873. axis.model = axisModel;
  55874. axis.coordinateSystem = this;
  55875. this._axis = axis;
  55876. },
  55877. /**
  55878. * Update axis scale after data processed
  55879. * @param {module:echarts/model/Global} ecModel
  55880. * @param {module:echarts/ExtensionAPI} api
  55881. */
  55882. update: function (ecModel, api) {
  55883. ecModel.eachSeries(function (seriesModel) {
  55884. if (seriesModel.coordinateSystem === this) {
  55885. var data = seriesModel.getData();
  55886. each$1(data.mapDimension(this.dimension, true), function (dim) {
  55887. this._axis.scale.unionExtentFromData(data, dim);
  55888. }, this);
  55889. niceScaleExtent(this._axis.scale, this._axis.model);
  55890. }
  55891. }, this);
  55892. },
  55893. /**
  55894. * Resize the single coordinate system.
  55895. *
  55896. * @param {module:echarts/coord/single/AxisModel} axisModel
  55897. * @param {module:echarts/ExtensionAPI} api
  55898. */
  55899. resize: function (axisModel, api) {
  55900. this._rect = getLayoutRect({
  55901. left: axisModel.get('left'),
  55902. top: axisModel.get('top'),
  55903. right: axisModel.get('right'),
  55904. bottom: axisModel.get('bottom'),
  55905. width: axisModel.get('width'),
  55906. height: axisModel.get('height')
  55907. }, {
  55908. width: api.getWidth(),
  55909. height: api.getHeight()
  55910. });
  55911. this._adjustAxis();
  55912. },
  55913. /**
  55914. * @return {module:zrender/core/BoundingRect}
  55915. */
  55916. getRect: function () {
  55917. return this._rect;
  55918. },
  55919. /**
  55920. * @private
  55921. */
  55922. _adjustAxis: function () {
  55923. var rect = this._rect;
  55924. var axis = this._axis;
  55925. var isHorizontal = axis.isHorizontal();
  55926. var extent = isHorizontal ? [0, rect.width] : [0, rect.height];
  55927. var idx = axis.reverse ? 1 : 0;
  55928. axis.setExtent(extent[idx], extent[1 - idx]);
  55929. this._updateAxisTransform(axis, isHorizontal ? rect.x : rect.y);
  55930. },
  55931. /**
  55932. * @param {module:echarts/coord/single/SingleAxis} axis
  55933. * @param {number} coordBase
  55934. */
  55935. _updateAxisTransform: function (axis, coordBase) {
  55936. var axisExtent = axis.getExtent();
  55937. var extentSum = axisExtent[0] + axisExtent[1];
  55938. var isHorizontal = axis.isHorizontal();
  55939. axis.toGlobalCoord = isHorizontal ? function (coord) {
  55940. return coord + coordBase;
  55941. } : function (coord) {
  55942. return extentSum - coord + coordBase;
  55943. };
  55944. axis.toLocalCoord = isHorizontal ? function (coord) {
  55945. return coord - coordBase;
  55946. } : function (coord) {
  55947. return extentSum - coord + coordBase;
  55948. };
  55949. },
  55950. /**
  55951. * Get axis.
  55952. *
  55953. * @return {module:echarts/coord/single/SingleAxis}
  55954. */
  55955. getAxis: function () {
  55956. return this._axis;
  55957. },
  55958. /**
  55959. * Get axis, add it just for draw tooltip.
  55960. *
  55961. * @return {[type]} [description]
  55962. */
  55963. getBaseAxis: function () {
  55964. return this._axis;
  55965. },
  55966. /**
  55967. * @return {Array.<module:echarts/coord/Axis>}
  55968. */
  55969. getAxes: function () {
  55970. return [this._axis];
  55971. },
  55972. /**
  55973. * @return {Object} {baseAxes: [], otherAxes: []}
  55974. */
  55975. getTooltipAxes: function () {
  55976. return {
  55977. baseAxes: [this.getAxis()]
  55978. };
  55979. },
  55980. /**
  55981. * If contain point.
  55982. *
  55983. * @param {Array.<number>} point
  55984. * @return {boolean}
  55985. */
  55986. containPoint: function (point) {
  55987. var rect = this.getRect();
  55988. var axis = this.getAxis();
  55989. var orient = axis.orient;
  55990. if (orient === 'horizontal') {
  55991. return axis.contain(axis.toLocalCoord(point[0])) && point[1] >= rect.y && point[1] <= rect.y + rect.height;
  55992. } else {
  55993. return axis.contain(axis.toLocalCoord(point[1])) && point[0] >= rect.y && point[0] <= rect.y + rect.height;
  55994. }
  55995. },
  55996. /**
  55997. * @param {Array.<number>} point
  55998. * @return {Array.<number>}
  55999. */
  56000. pointToData: function (point) {
  56001. var axis = this.getAxis();
  56002. return [axis.coordToData(axis.toLocalCoord(point[axis.orient === 'horizontal' ? 0 : 1]))];
  56003. },
  56004. /**
  56005. * Convert the series data to concrete point.
  56006. *
  56007. * @param {number|Array.<number>} val
  56008. * @return {Array.<number>}
  56009. */
  56010. dataToPoint: function (val) {
  56011. var axis = this.getAxis();
  56012. var rect = this.getRect();
  56013. var pt = [];
  56014. var idx = axis.orient === 'horizontal' ? 0 : 1;
  56015. if (val instanceof Array) {
  56016. val = val[0];
  56017. }
  56018. pt[idx] = axis.toGlobalCoord(axis.dataToCoord(+val));
  56019. pt[1 - idx] = idx === 0 ? rect.y + rect.height / 2 : rect.x + rect.width / 2;
  56020. return pt;
  56021. }
  56022. };
  56023. /*
  56024. * Licensed to the Apache Software Foundation (ASF) under one
  56025. * or more contributor license agreements. See the NOTICE file
  56026. * distributed with this work for additional information
  56027. * regarding copyright ownership. The ASF licenses this file
  56028. * to you under the Apache License, Version 2.0 (the
  56029. * "License"); you may not use this file except in compliance
  56030. * with the License. You may obtain a copy of the License at
  56031. *
  56032. * http://www.apache.org/licenses/LICENSE-2.0
  56033. *
  56034. * Unless required by applicable law or agreed to in writing,
  56035. * software distributed under the License is distributed on an
  56036. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56037. * KIND, either express or implied. See the License for the
  56038. * specific language governing permissions and limitations
  56039. * under the License.
  56040. */
  56041. /**
  56042. * Single coordinate system creator.
  56043. */
  56044. /**
  56045. * Create single coordinate system and inject it into seriesModel.
  56046. *
  56047. * @param {module:echarts/model/Global} ecModel
  56048. * @param {module:echarts/ExtensionAPI} api
  56049. * @return {Array.<module:echarts/coord/single/Single>}
  56050. */
  56051. function create$3(ecModel, api) {
  56052. var singles = [];
  56053. ecModel.eachComponent('singleAxis', function (axisModel, idx) {
  56054. var single = new Single(axisModel, ecModel, api);
  56055. single.name = 'single_' + idx;
  56056. single.resize(axisModel, api);
  56057. axisModel.coordinateSystem = single;
  56058. singles.push(single);
  56059. });
  56060. ecModel.eachSeries(function (seriesModel) {
  56061. if (seriesModel.get('coordinateSystem') === 'singleAxis') {
  56062. var singleAxisModel = ecModel.queryComponents({
  56063. mainType: 'singleAxis',
  56064. index: seriesModel.get('singleAxisIndex'),
  56065. id: seriesModel.get('singleAxisId')
  56066. })[0];
  56067. seriesModel.coordinateSystem = singleAxisModel && singleAxisModel.coordinateSystem;
  56068. }
  56069. });
  56070. return singles;
  56071. }
  56072. CoordinateSystemManager.register('single', {
  56073. create: create$3,
  56074. dimensions: Single.prototype.dimensions
  56075. });
  56076. /*
  56077. * Licensed to the Apache Software Foundation (ASF) under one
  56078. * or more contributor license agreements. See the NOTICE file
  56079. * distributed with this work for additional information
  56080. * regarding copyright ownership. The ASF licenses this file
  56081. * to you under the Apache License, Version 2.0 (the
  56082. * "License"); you may not use this file except in compliance
  56083. * with the License. You may obtain a copy of the License at
  56084. *
  56085. * http://www.apache.org/licenses/LICENSE-2.0
  56086. *
  56087. * Unless required by applicable law or agreed to in writing,
  56088. * software distributed under the License is distributed on an
  56089. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56090. * KIND, either express or implied. See the License for the
  56091. * specific language governing permissions and limitations
  56092. * under the License.
  56093. */
  56094. /**
  56095. * @param {Object} opt {labelInside}
  56096. * @return {Object} {
  56097. * position, rotation, labelDirection, labelOffset,
  56098. * tickDirection, labelRotate, z2
  56099. * }
  56100. */
  56101. function layout$2(axisModel, opt) {
  56102. opt = opt || {};
  56103. var single = axisModel.coordinateSystem;
  56104. var axis = axisModel.axis;
  56105. var layout = {};
  56106. var axisPosition = axis.position;
  56107. var orient = axis.orient;
  56108. var rect = single.getRect();
  56109. var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height];
  56110. var positionMap = {
  56111. horizontal: {
  56112. top: rectBound[2],
  56113. bottom: rectBound[3]
  56114. },
  56115. vertical: {
  56116. left: rectBound[0],
  56117. right: rectBound[1]
  56118. }
  56119. };
  56120. layout.position = [orient === 'vertical' ? positionMap.vertical[axisPosition] : rectBound[0], orient === 'horizontal' ? positionMap.horizontal[axisPosition] : rectBound[3]];
  56121. var r = {
  56122. horizontal: 0,
  56123. vertical: 1
  56124. };
  56125. layout.rotation = Math.PI / 2 * r[orient];
  56126. var directionMap = {
  56127. top: -1,
  56128. bottom: 1,
  56129. right: 1,
  56130. left: -1
  56131. };
  56132. layout.labelDirection = layout.tickDirection = layout.nameDirection = directionMap[axisPosition];
  56133. if (axisModel.get('axisTick.inside')) {
  56134. layout.tickDirection = -layout.tickDirection;
  56135. }
  56136. if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) {
  56137. layout.labelDirection = -layout.labelDirection;
  56138. }
  56139. var labelRotation = opt.rotate;
  56140. labelRotation == null && (labelRotation = axisModel.get('axisLabel.rotate'));
  56141. layout.labelRotation = axisPosition === 'top' ? -labelRotation : labelRotation;
  56142. layout.z2 = 1;
  56143. return layout;
  56144. }
  56145. /*
  56146. * Licensed to the Apache Software Foundation (ASF) under one
  56147. * or more contributor license agreements. See the NOTICE file
  56148. * distributed with this work for additional information
  56149. * regarding copyright ownership. The ASF licenses this file
  56150. * to you under the Apache License, Version 2.0 (the
  56151. * "License"); you may not use this file except in compliance
  56152. * with the License. You may obtain a copy of the License at
  56153. *
  56154. * http://www.apache.org/licenses/LICENSE-2.0
  56155. *
  56156. * Unless required by applicable law or agreed to in writing,
  56157. * software distributed under the License is distributed on an
  56158. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56159. * KIND, either express or implied. See the License for the
  56160. * specific language governing permissions and limitations
  56161. * under the License.
  56162. */
  56163. var axisBuilderAttrs$2 = ['axisLine', 'axisTickLabel', 'axisName'];
  56164. var selfBuilderAttrs$1 = ['splitArea', 'splitLine'];
  56165. var SingleAxisView = AxisView.extend({
  56166. type: 'singleAxis',
  56167. axisPointerClass: 'SingleAxisPointer',
  56168. render: function (axisModel, ecModel, api, payload) {
  56169. var group = this.group;
  56170. group.removeAll();
  56171. var oldAxisGroup = this._axisGroup;
  56172. this._axisGroup = new Group();
  56173. var layout = layout$2(axisModel);
  56174. var axisBuilder = new AxisBuilder(axisModel, layout);
  56175. each$1(axisBuilderAttrs$2, axisBuilder.add, axisBuilder);
  56176. group.add(this._axisGroup);
  56177. group.add(axisBuilder.getGroup());
  56178. each$1(selfBuilderAttrs$1, function (name) {
  56179. if (axisModel.get(name + '.show')) {
  56180. this['_' + name](axisModel);
  56181. }
  56182. }, this);
  56183. groupTransition(oldAxisGroup, this._axisGroup, axisModel);
  56184. SingleAxisView.superCall(this, 'render', axisModel, ecModel, api, payload);
  56185. },
  56186. remove: function () {
  56187. rectCoordAxisHandleRemove(this);
  56188. },
  56189. _splitLine: function (axisModel) {
  56190. var axis = axisModel.axis;
  56191. if (axis.scale.isBlank()) {
  56192. return;
  56193. }
  56194. var splitLineModel = axisModel.getModel('splitLine');
  56195. var lineStyleModel = splitLineModel.getModel('lineStyle');
  56196. var lineWidth = lineStyleModel.get('width');
  56197. var lineColors = lineStyleModel.get('color');
  56198. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  56199. var gridRect = axisModel.coordinateSystem.getRect();
  56200. var isHorizontal = axis.isHorizontal();
  56201. var splitLines = [];
  56202. var lineCount = 0;
  56203. var ticksCoords = axis.getTicksCoords({
  56204. tickModel: splitLineModel
  56205. });
  56206. var p1 = [];
  56207. var p2 = [];
  56208. for (var i = 0; i < ticksCoords.length; ++i) {
  56209. var tickCoord = axis.toGlobalCoord(ticksCoords[i].coord);
  56210. if (isHorizontal) {
  56211. p1[0] = tickCoord;
  56212. p1[1] = gridRect.y;
  56213. p2[0] = tickCoord;
  56214. p2[1] = gridRect.y + gridRect.height;
  56215. } else {
  56216. p1[0] = gridRect.x;
  56217. p1[1] = tickCoord;
  56218. p2[0] = gridRect.x + gridRect.width;
  56219. p2[1] = tickCoord;
  56220. }
  56221. var colorIndex = lineCount++ % lineColors.length;
  56222. splitLines[colorIndex] = splitLines[colorIndex] || [];
  56223. splitLines[colorIndex].push(new Line({
  56224. subPixelOptimize: true,
  56225. shape: {
  56226. x1: p1[0],
  56227. y1: p1[1],
  56228. x2: p2[0],
  56229. y2: p2[1]
  56230. },
  56231. style: {
  56232. lineWidth: lineWidth
  56233. },
  56234. silent: true
  56235. }));
  56236. }
  56237. for (var i = 0; i < splitLines.length; ++i) {
  56238. this.group.add(mergePath(splitLines[i], {
  56239. style: {
  56240. stroke: lineColors[i % lineColors.length],
  56241. lineDash: lineStyleModel.getLineDash(lineWidth),
  56242. lineWidth: lineWidth
  56243. },
  56244. silent: true
  56245. }));
  56246. }
  56247. },
  56248. _splitArea: function (axisModel) {
  56249. rectCoordAxisBuildSplitArea(this, this._axisGroup, axisModel, axisModel);
  56250. }
  56251. });
  56252. /*
  56253. * Licensed to the Apache Software Foundation (ASF) under one
  56254. * or more contributor license agreements. See the NOTICE file
  56255. * distributed with this work for additional information
  56256. * regarding copyright ownership. The ASF licenses this file
  56257. * to you under the Apache License, Version 2.0 (the
  56258. * "License"); you may not use this file except in compliance
  56259. * with the License. You may obtain a copy of the License at
  56260. *
  56261. * http://www.apache.org/licenses/LICENSE-2.0
  56262. *
  56263. * Unless required by applicable law or agreed to in writing,
  56264. * software distributed under the License is distributed on an
  56265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56266. * KIND, either express or implied. See the License for the
  56267. * specific language governing permissions and limitations
  56268. * under the License.
  56269. */
  56270. var AxisModel$4 = ComponentModel.extend({
  56271. type: 'singleAxis',
  56272. layoutMode: 'box',
  56273. /**
  56274. * @type {module:echarts/coord/single/SingleAxis}
  56275. */
  56276. axis: null,
  56277. /**
  56278. * @type {module:echarts/coord/single/Single}
  56279. */
  56280. coordinateSystem: null,
  56281. /**
  56282. * @override
  56283. */
  56284. getCoordSysModel: function () {
  56285. return this;
  56286. }
  56287. });
  56288. var defaultOption$2 = {
  56289. left: '5%',
  56290. top: '5%',
  56291. right: '5%',
  56292. bottom: '5%',
  56293. type: 'value',
  56294. position: 'bottom',
  56295. orient: 'horizontal',
  56296. axisLine: {
  56297. show: true,
  56298. lineStyle: {
  56299. width: 1,
  56300. type: 'solid'
  56301. }
  56302. },
  56303. // Single coordinate system and single axis is the,
  56304. // which is used as the parent tooltip model.
  56305. // same model, so we set default tooltip show as true.
  56306. tooltip: {
  56307. show: true
  56308. },
  56309. axisTick: {
  56310. show: true,
  56311. length: 6,
  56312. lineStyle: {
  56313. width: 1
  56314. }
  56315. },
  56316. axisLabel: {
  56317. show: true,
  56318. interval: 'auto'
  56319. },
  56320. splitLine: {
  56321. show: true,
  56322. lineStyle: {
  56323. type: 'dashed',
  56324. opacity: 0.2
  56325. }
  56326. }
  56327. };
  56328. function getAxisType$2(axisName, option) {
  56329. return option.type || (option.data ? 'category' : 'value');
  56330. }
  56331. merge(AxisModel$4.prototype, axisModelCommonMixin);
  56332. axisModelCreator('single', AxisModel$4, getAxisType$2, defaultOption$2);
  56333. /*
  56334. * Licensed to the Apache Software Foundation (ASF) under one
  56335. * or more contributor license agreements. See the NOTICE file
  56336. * distributed with this work for additional information
  56337. * regarding copyright ownership. The ASF licenses this file
  56338. * to you under the Apache License, Version 2.0 (the
  56339. * "License"); you may not use this file except in compliance
  56340. * with the License. You may obtain a copy of the License at
  56341. *
  56342. * http://www.apache.org/licenses/LICENSE-2.0
  56343. *
  56344. * Unless required by applicable law or agreed to in writing,
  56345. * software distributed under the License is distributed on an
  56346. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56347. * KIND, either express or implied. See the License for the
  56348. * specific language governing permissions and limitations
  56349. * under the License.
  56350. */
  56351. /**
  56352. * @param {Object} finder contains {seriesIndex, dataIndex, dataIndexInside}
  56353. * @param {module:echarts/model/Global} ecModel
  56354. * @return {Object} {point: [x, y], el: ...} point Will not be null.
  56355. */
  56356. var findPointFromSeries = function (finder, ecModel) {
  56357. var point = [];
  56358. var seriesIndex = finder.seriesIndex;
  56359. var seriesModel;
  56360. if (seriesIndex == null || !(seriesModel = ecModel.getSeriesByIndex(seriesIndex))) {
  56361. return {
  56362. point: []
  56363. };
  56364. }
  56365. var data = seriesModel.getData();
  56366. var dataIndex = queryDataIndex(data, finder);
  56367. if (dataIndex == null || dataIndex < 0 || isArray(dataIndex)) {
  56368. return {
  56369. point: []
  56370. };
  56371. }
  56372. var el = data.getItemGraphicEl(dataIndex);
  56373. var coordSys = seriesModel.coordinateSystem;
  56374. if (seriesModel.getTooltipPosition) {
  56375. point = seriesModel.getTooltipPosition(dataIndex) || [];
  56376. } else if (coordSys && coordSys.dataToPoint) {
  56377. point = coordSys.dataToPoint(data.getValues(map(coordSys.dimensions, function (dim) {
  56378. return data.mapDimension(dim);
  56379. }), dataIndex, true)) || [];
  56380. } else if (el) {
  56381. // Use graphic bounding rect
  56382. var rect = el.getBoundingRect().clone();
  56383. rect.applyTransform(el.transform);
  56384. point = [rect.x + rect.width / 2, rect.y + rect.height / 2];
  56385. }
  56386. return {
  56387. point: point,
  56388. el: el
  56389. };
  56390. };
  56391. /*
  56392. * Licensed to the Apache Software Foundation (ASF) under one
  56393. * or more contributor license agreements. See the NOTICE file
  56394. * distributed with this work for additional information
  56395. * regarding copyright ownership. The ASF licenses this file
  56396. * to you under the Apache License, Version 2.0 (the
  56397. * "License"); you may not use this file except in compliance
  56398. * with the License. You may obtain a copy of the License at
  56399. *
  56400. * http://www.apache.org/licenses/LICENSE-2.0
  56401. *
  56402. * Unless required by applicable law or agreed to in writing,
  56403. * software distributed under the License is distributed on an
  56404. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56405. * KIND, either express or implied. See the License for the
  56406. * specific language governing permissions and limitations
  56407. * under the License.
  56408. */
  56409. var each$14 = each$1;
  56410. var curry$3 = curry;
  56411. var inner$9 = makeInner();
  56412. /**
  56413. * Basic logic: check all axis, if they do not demand show/highlight,
  56414. * then hide/downplay them.
  56415. *
  56416. * @param {Object} coordSysAxesInfo
  56417. * @param {Object} payload
  56418. * @param {string} [payload.currTrigger] 'click' | 'mousemove' | 'leave'
  56419. * @param {Array.<number>} [payload.x] x and y, which are mandatory, specify a point to
  56420. * trigger axisPointer and tooltip.
  56421. * @param {Array.<number>} [payload.y] x and y, which are mandatory, specify a point to
  56422. * trigger axisPointer and tooltip.
  56423. * @param {Object} [payload.seriesIndex] finder, optional, restrict target axes.
  56424. * @param {Object} [payload.dataIndex] finder, restrict target axes.
  56425. * @param {Object} [payload.axesInfo] finder, restrict target axes.
  56426. * [{
  56427. * axisDim: 'x'|'y'|'angle'|...,
  56428. * axisIndex: ...,
  56429. * value: ...
  56430. * }, ...]
  56431. * @param {Function} [payload.dispatchAction]
  56432. * @param {Object} [payload.tooltipOption]
  56433. * @param {Object|Array.<number>|Function} [payload.position] Tooltip position,
  56434. * which can be specified in dispatchAction
  56435. * @param {module:echarts/model/Global} ecModel
  56436. * @param {module:echarts/ExtensionAPI} api
  56437. * @return {Object} content of event obj for echarts.connect.
  56438. */
  56439. var axisTrigger = function (payload, ecModel, api) {
  56440. var currTrigger = payload.currTrigger;
  56441. var point = [payload.x, payload.y];
  56442. var finder = payload;
  56443. var dispatchAction = payload.dispatchAction || bind(api.dispatchAction, api);
  56444. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo; // Pending
  56445. // See #6121. But we are not able to reproduce it yet.
  56446. if (!coordSysAxesInfo) {
  56447. return;
  56448. }
  56449. if (illegalPoint(point)) {
  56450. // Used in the default behavior of `connection`: use the sample seriesIndex
  56451. // and dataIndex. And also used in the tooltipView trigger.
  56452. point = findPointFromSeries({
  56453. seriesIndex: finder.seriesIndex,
  56454. // Do not use dataIndexInside from other ec instance.
  56455. // FIXME: auto detect it?
  56456. dataIndex: finder.dataIndex
  56457. }, ecModel).point;
  56458. }
  56459. var isIllegalPoint = illegalPoint(point); // Axis and value can be specified when calling dispatchAction({type: 'updateAxisPointer'}).
  56460. // Notice: In this case, it is difficult to get the `point` (which is necessary to show
  56461. // tooltip, so if point is not given, we just use the point found by sample seriesIndex
  56462. // and dataIndex.
  56463. var inputAxesInfo = finder.axesInfo;
  56464. var axesInfo = coordSysAxesInfo.axesInfo;
  56465. var shouldHide = currTrigger === 'leave' || illegalPoint(point);
  56466. var outputFinder = {};
  56467. var showValueMap = {};
  56468. var dataByCoordSys = {
  56469. list: [],
  56470. map: {}
  56471. };
  56472. var updaters = {
  56473. showPointer: curry$3(showPointer, showValueMap),
  56474. showTooltip: curry$3(showTooltip, dataByCoordSys)
  56475. }; // Process for triggered axes.
  56476. each$14(coordSysAxesInfo.coordSysMap, function (coordSys, coordSysKey) {
  56477. // If a point given, it must be contained by the coordinate system.
  56478. var coordSysContainsPoint = isIllegalPoint || coordSys.containPoint(point);
  56479. each$14(coordSysAxesInfo.coordSysAxesInfo[coordSysKey], function (axisInfo, key) {
  56480. var axis = axisInfo.axis;
  56481. var inputAxisInfo = findInputAxisInfo(inputAxesInfo, axisInfo); // If no inputAxesInfo, no axis is restricted.
  56482. if (!shouldHide && coordSysContainsPoint && (!inputAxesInfo || inputAxisInfo)) {
  56483. var val = inputAxisInfo && inputAxisInfo.value;
  56484. if (val == null && !isIllegalPoint) {
  56485. val = axis.pointToData(point);
  56486. }
  56487. val != null && processOnAxis(axisInfo, val, updaters, false, outputFinder);
  56488. }
  56489. });
  56490. }); // Process for linked axes.
  56491. var linkTriggers = {};
  56492. each$14(axesInfo, function (tarAxisInfo, tarKey) {
  56493. var linkGroup = tarAxisInfo.linkGroup; // If axis has been triggered in the previous stage, it should not be triggered by link.
  56494. if (linkGroup && !showValueMap[tarKey]) {
  56495. each$14(linkGroup.axesInfo, function (srcAxisInfo, srcKey) {
  56496. var srcValItem = showValueMap[srcKey]; // If srcValItem exist, source axis is triggered, so link to target axis.
  56497. if (srcAxisInfo !== tarAxisInfo && srcValItem) {
  56498. var val = srcValItem.value;
  56499. linkGroup.mapper && (val = tarAxisInfo.axis.scale.parse(linkGroup.mapper(val, makeMapperParam(srcAxisInfo), makeMapperParam(tarAxisInfo))));
  56500. linkTriggers[tarAxisInfo.key] = val;
  56501. }
  56502. });
  56503. }
  56504. });
  56505. each$14(linkTriggers, function (val, tarKey) {
  56506. processOnAxis(axesInfo[tarKey], val, updaters, true, outputFinder);
  56507. });
  56508. updateModelActually(showValueMap, axesInfo, outputFinder);
  56509. dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction);
  56510. dispatchHighDownActually(axesInfo, dispatchAction, api);
  56511. return outputFinder;
  56512. };
  56513. function processOnAxis(axisInfo, newValue, updaters, dontSnap, outputFinder) {
  56514. var axis = axisInfo.axis;
  56515. if (axis.scale.isBlank() || !axis.containData(newValue)) {
  56516. return;
  56517. }
  56518. if (!axisInfo.involveSeries) {
  56519. updaters.showPointer(axisInfo, newValue);
  56520. return;
  56521. } // Heavy calculation. So put it after axis.containData checking.
  56522. var payloadInfo = buildPayloadsBySeries(newValue, axisInfo);
  56523. var payloadBatch = payloadInfo.payloadBatch;
  56524. var snapToValue = payloadInfo.snapToValue; // Fill content of event obj for echarts.connect.
  56525. // By defualt use the first involved series data as a sample to connect.
  56526. if (payloadBatch[0] && outputFinder.seriesIndex == null) {
  56527. extend(outputFinder, payloadBatch[0]);
  56528. } // If no linkSource input, this process is for collecting link
  56529. // target, where snap should not be accepted.
  56530. if (!dontSnap && axisInfo.snap) {
  56531. if (axis.containData(snapToValue) && snapToValue != null) {
  56532. newValue = snapToValue;
  56533. }
  56534. }
  56535. updaters.showPointer(axisInfo, newValue, payloadBatch, outputFinder); // Tooltip should always be snapToValue, otherwise there will be
  56536. // incorrect "axis value ~ series value" mapping displayed in tooltip.
  56537. updaters.showTooltip(axisInfo, payloadInfo, snapToValue);
  56538. }
  56539. function buildPayloadsBySeries(value, axisInfo) {
  56540. var axis = axisInfo.axis;
  56541. var dim = axis.dim;
  56542. var snapToValue = value;
  56543. var payloadBatch = [];
  56544. var minDist = Number.MAX_VALUE;
  56545. var minDiff = -1;
  56546. each$14(axisInfo.seriesModels, function (series, idx) {
  56547. var dataDim = series.getData().mapDimension(dim, true);
  56548. var seriesNestestValue;
  56549. var dataIndices;
  56550. if (series.getAxisTooltipData) {
  56551. var result = series.getAxisTooltipData(dataDim, value, axis);
  56552. dataIndices = result.dataIndices;
  56553. seriesNestestValue = result.nestestValue;
  56554. } else {
  56555. dataIndices = series.getData().indicesOfNearest(dataDim[0], value, // Add a threshold to avoid find the wrong dataIndex
  56556. // when data length is not same.
  56557. // false,
  56558. axis.type === 'category' ? 0.5 : null);
  56559. if (!dataIndices.length) {
  56560. return;
  56561. }
  56562. seriesNestestValue = series.getData().get(dataDim[0], dataIndices[0]);
  56563. }
  56564. if (seriesNestestValue == null || !isFinite(seriesNestestValue)) {
  56565. return;
  56566. }
  56567. var diff = value - seriesNestestValue;
  56568. var dist = Math.abs(diff); // Consider category case
  56569. if (dist <= minDist) {
  56570. if (dist < minDist || diff >= 0 && minDiff < 0) {
  56571. minDist = dist;
  56572. minDiff = diff;
  56573. snapToValue = seriesNestestValue;
  56574. payloadBatch.length = 0;
  56575. }
  56576. each$14(dataIndices, function (dataIndex) {
  56577. payloadBatch.push({
  56578. seriesIndex: series.seriesIndex,
  56579. dataIndexInside: dataIndex,
  56580. dataIndex: series.getData().getRawIndex(dataIndex)
  56581. });
  56582. });
  56583. }
  56584. });
  56585. return {
  56586. payloadBatch: payloadBatch,
  56587. snapToValue: snapToValue
  56588. };
  56589. }
  56590. function showPointer(showValueMap, axisInfo, value, payloadBatch) {
  56591. showValueMap[axisInfo.key] = {
  56592. value: value,
  56593. payloadBatch: payloadBatch
  56594. };
  56595. }
  56596. function showTooltip(dataByCoordSys, axisInfo, payloadInfo, value) {
  56597. var payloadBatch = payloadInfo.payloadBatch;
  56598. var axis = axisInfo.axis;
  56599. var axisModel = axis.model;
  56600. var axisPointerModel = axisInfo.axisPointerModel; // If no data, do not create anything in dataByCoordSys,
  56601. // whose length will be used to judge whether dispatch action.
  56602. if (!axisInfo.triggerTooltip || !payloadBatch.length) {
  56603. return;
  56604. }
  56605. var coordSysModel = axisInfo.coordSys.model;
  56606. var coordSysKey = makeKey(coordSysModel);
  56607. var coordSysItem = dataByCoordSys.map[coordSysKey];
  56608. if (!coordSysItem) {
  56609. coordSysItem = dataByCoordSys.map[coordSysKey] = {
  56610. coordSysId: coordSysModel.id,
  56611. coordSysIndex: coordSysModel.componentIndex,
  56612. coordSysType: coordSysModel.type,
  56613. coordSysMainType: coordSysModel.mainType,
  56614. dataByAxis: []
  56615. };
  56616. dataByCoordSys.list.push(coordSysItem);
  56617. }
  56618. coordSysItem.dataByAxis.push({
  56619. axisDim: axis.dim,
  56620. axisIndex: axisModel.componentIndex,
  56621. axisType: axisModel.type,
  56622. axisId: axisModel.id,
  56623. value: value,
  56624. // Caustion: viewHelper.getValueLabel is actually on "view stage", which
  56625. // depends that all models have been updated. So it should not be performed
  56626. // here. Considering axisPointerModel used here is volatile, which is hard
  56627. // to be retrieve in TooltipView, we prepare parameters here.
  56628. valueLabelOpt: {
  56629. precision: axisPointerModel.get('label.precision'),
  56630. formatter: axisPointerModel.get('label.formatter')
  56631. },
  56632. seriesDataIndices: payloadBatch.slice()
  56633. });
  56634. }
  56635. function updateModelActually(showValueMap, axesInfo, outputFinder) {
  56636. var outputAxesInfo = outputFinder.axesInfo = []; // Basic logic: If no 'show' required, 'hide' this axisPointer.
  56637. each$14(axesInfo, function (axisInfo, key) {
  56638. var option = axisInfo.axisPointerModel.option;
  56639. var valItem = showValueMap[key];
  56640. if (valItem) {
  56641. !axisInfo.useHandle && (option.status = 'show');
  56642. option.value = valItem.value; // For label formatter param and highlight.
  56643. option.seriesDataIndices = (valItem.payloadBatch || []).slice();
  56644. } // When always show (e.g., handle used), remain
  56645. // original value and status.
  56646. else {
  56647. // If hide, value still need to be set, consider
  56648. // click legend to toggle axis blank.
  56649. !axisInfo.useHandle && (option.status = 'hide');
  56650. } // If status is 'hide', should be no info in payload.
  56651. option.status === 'show' && outputAxesInfo.push({
  56652. axisDim: axisInfo.axis.dim,
  56653. axisIndex: axisInfo.axis.model.componentIndex,
  56654. value: option.value
  56655. });
  56656. });
  56657. }
  56658. function dispatchTooltipActually(dataByCoordSys, point, payload, dispatchAction) {
  56659. // Basic logic: If no showTip required, hideTip will be dispatched.
  56660. if (illegalPoint(point) || !dataByCoordSys.list.length) {
  56661. dispatchAction({
  56662. type: 'hideTip'
  56663. });
  56664. return;
  56665. } // In most case only one axis (or event one series is used). It is
  56666. // convinient to fetch payload.seriesIndex and payload.dataIndex
  56667. // dirtectly. So put the first seriesIndex and dataIndex of the first
  56668. // axis on the payload.
  56669. var sampleItem = ((dataByCoordSys.list[0].dataByAxis[0] || {}).seriesDataIndices || [])[0] || {};
  56670. dispatchAction({
  56671. type: 'showTip',
  56672. escapeConnect: true,
  56673. x: point[0],
  56674. y: point[1],
  56675. tooltipOption: payload.tooltipOption,
  56676. position: payload.position,
  56677. dataIndexInside: sampleItem.dataIndexInside,
  56678. dataIndex: sampleItem.dataIndex,
  56679. seriesIndex: sampleItem.seriesIndex,
  56680. dataByCoordSys: dataByCoordSys.list
  56681. });
  56682. }
  56683. function dispatchHighDownActually(axesInfo, dispatchAction, api) {
  56684. // FIXME
  56685. // highlight status modification shoule be a stage of main process?
  56686. // (Consider confilct (e.g., legend and axisPointer) and setOption)
  56687. var zr = api.getZr();
  56688. var highDownKey = 'axisPointerLastHighlights';
  56689. var lastHighlights = inner$9(zr)[highDownKey] || {};
  56690. var newHighlights = inner$9(zr)[highDownKey] = {}; // Update highlight/downplay status according to axisPointer model.
  56691. // Build hash map and remove duplicate incidentally.
  56692. each$14(axesInfo, function (axisInfo, key) {
  56693. var option = axisInfo.axisPointerModel.option;
  56694. option.status === 'show' && each$14(option.seriesDataIndices, function (batchItem) {
  56695. var key = batchItem.seriesIndex + ' | ' + batchItem.dataIndex;
  56696. newHighlights[key] = batchItem;
  56697. });
  56698. }); // Diff.
  56699. var toHighlight = [];
  56700. var toDownplay = [];
  56701. each$1(lastHighlights, function (batchItem, key) {
  56702. !newHighlights[key] && toDownplay.push(batchItem);
  56703. });
  56704. each$1(newHighlights, function (batchItem, key) {
  56705. !lastHighlights[key] && toHighlight.push(batchItem);
  56706. });
  56707. toDownplay.length && api.dispatchAction({
  56708. type: 'downplay',
  56709. escapeConnect: true,
  56710. batch: toDownplay
  56711. });
  56712. toHighlight.length && api.dispatchAction({
  56713. type: 'highlight',
  56714. escapeConnect: true,
  56715. batch: toHighlight
  56716. });
  56717. }
  56718. function findInputAxisInfo(inputAxesInfo, axisInfo) {
  56719. for (var i = 0; i < (inputAxesInfo || []).length; i++) {
  56720. var inputAxisInfo = inputAxesInfo[i];
  56721. if (axisInfo.axis.dim === inputAxisInfo.axisDim && axisInfo.axis.model.componentIndex === inputAxisInfo.axisIndex) {
  56722. return inputAxisInfo;
  56723. }
  56724. }
  56725. }
  56726. function makeMapperParam(axisInfo) {
  56727. var axisModel = axisInfo.axis.model;
  56728. var item = {};
  56729. var dim = item.axisDim = axisInfo.axis.dim;
  56730. item.axisIndex = item[dim + 'AxisIndex'] = axisModel.componentIndex;
  56731. item.axisName = item[dim + 'AxisName'] = axisModel.name;
  56732. item.axisId = item[dim + 'AxisId'] = axisModel.id;
  56733. return item;
  56734. }
  56735. function illegalPoint(point) {
  56736. return !point || point[0] == null || isNaN(point[0]) || point[1] == null || isNaN(point[1]);
  56737. }
  56738. /*
  56739. * Licensed to the Apache Software Foundation (ASF) under one
  56740. * or more contributor license agreements. See the NOTICE file
  56741. * distributed with this work for additional information
  56742. * regarding copyright ownership. The ASF licenses this file
  56743. * to you under the Apache License, Version 2.0 (the
  56744. * "License"); you may not use this file except in compliance
  56745. * with the License. You may obtain a copy of the License at
  56746. *
  56747. * http://www.apache.org/licenses/LICENSE-2.0
  56748. *
  56749. * Unless required by applicable law or agreed to in writing,
  56750. * software distributed under the License is distributed on an
  56751. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56752. * KIND, either express or implied. See the License for the
  56753. * specific language governing permissions and limitations
  56754. * under the License.
  56755. */
  56756. var AxisPointerModel = extendComponentModel({
  56757. type: 'axisPointer',
  56758. coordSysAxesInfo: null,
  56759. defaultOption: {
  56760. // 'auto' means that show when triggered by tooltip or handle.
  56761. show: 'auto',
  56762. // 'click' | 'mousemove' | 'none'
  56763. triggerOn: null,
  56764. // set default in AxisPonterView.js
  56765. zlevel: 0,
  56766. z: 50,
  56767. type: 'line',
  56768. // 'line' 'shadow' 'cross' 'none'.
  56769. // axispointer triggered by tootip determine snap automatically,
  56770. // see `modelHelper`.
  56771. snap: false,
  56772. triggerTooltip: true,
  56773. value: null,
  56774. status: null,
  56775. // Init value depends on whether handle is used.
  56776. // [group0, group1, ...]
  56777. // Each group can be: {
  56778. // mapper: function () {},
  56779. // singleTooltip: 'multiple', // 'multiple' or 'single'
  56780. // xAxisId: ...,
  56781. // yAxisName: ...,
  56782. // angleAxisIndex: ...
  56783. // }
  56784. // mapper: can be ignored.
  56785. // input: {axisInfo, value}
  56786. // output: {axisInfo, value}
  56787. link: [],
  56788. // Do not set 'auto' here, otherwise global animation: false
  56789. // will not effect at this axispointer.
  56790. animation: null,
  56791. animationDurationUpdate: 200,
  56792. lineStyle: {
  56793. color: '#aaa',
  56794. width: 1,
  56795. type: 'solid'
  56796. },
  56797. shadowStyle: {
  56798. color: 'rgba(150,150,150,0.3)'
  56799. },
  56800. label: {
  56801. show: true,
  56802. formatter: null,
  56803. // string | Function
  56804. precision: 'auto',
  56805. // Or a number like 0, 1, 2 ...
  56806. margin: 3,
  56807. color: '#fff',
  56808. padding: [5, 7, 5, 7],
  56809. backgroundColor: 'auto',
  56810. // default: axis line color
  56811. borderColor: null,
  56812. borderWidth: 0,
  56813. shadowBlur: 3,
  56814. shadowColor: '#aaa' // Considering applicability, common style should
  56815. // better not have shadowOffset.
  56816. // shadowOffsetX: 0,
  56817. // shadowOffsetY: 2
  56818. },
  56819. handle: {
  56820. show: false,
  56821. /* eslint-disable */
  56822. 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',
  56823. // jshint ignore:line
  56824. /* eslint-enable */
  56825. size: 45,
  56826. // handle margin is from symbol center to axis, which is stable when circular move.
  56827. margin: 50,
  56828. // color: '#1b8bbd'
  56829. // color: '#2f4554'
  56830. color: '#333',
  56831. shadowBlur: 3,
  56832. shadowColor: '#aaa',
  56833. shadowOffsetX: 0,
  56834. shadowOffsetY: 2,
  56835. // For mobile performance
  56836. throttle: 40
  56837. }
  56838. }
  56839. });
  56840. /*
  56841. * Licensed to the Apache Software Foundation (ASF) under one
  56842. * or more contributor license agreements. See the NOTICE file
  56843. * distributed with this work for additional information
  56844. * regarding copyright ownership. The ASF licenses this file
  56845. * to you under the Apache License, Version 2.0 (the
  56846. * "License"); you may not use this file except in compliance
  56847. * with the License. You may obtain a copy of the License at
  56848. *
  56849. * http://www.apache.org/licenses/LICENSE-2.0
  56850. *
  56851. * Unless required by applicable law or agreed to in writing,
  56852. * software distributed under the License is distributed on an
  56853. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56854. * KIND, either express or implied. See the License for the
  56855. * specific language governing permissions and limitations
  56856. * under the License.
  56857. */
  56858. var inner$10 = makeInner();
  56859. var each$15 = each$1;
  56860. /**
  56861. * @param {string} key
  56862. * @param {module:echarts/ExtensionAPI} api
  56863. * @param {Function} handler
  56864. * param: {string} currTrigger
  56865. * param: {Array.<number>} point
  56866. */
  56867. function register(key, api, handler) {
  56868. if (env$1.node) {
  56869. return;
  56870. }
  56871. var zr = api.getZr();
  56872. inner$10(zr).records || (inner$10(zr).records = {});
  56873. initGlobalListeners(zr, api);
  56874. var record = inner$10(zr).records[key] || (inner$10(zr).records[key] = {});
  56875. record.handler = handler;
  56876. }
  56877. function initGlobalListeners(zr, api) {
  56878. if (inner$10(zr).initialized) {
  56879. return;
  56880. }
  56881. inner$10(zr).initialized = true;
  56882. useHandler('click', curry(doEnter, 'click'));
  56883. useHandler('mousemove', curry(doEnter, 'mousemove')); // useHandler('mouseout', onLeave);
  56884. useHandler('globalout', onLeave);
  56885. function useHandler(eventType, cb) {
  56886. zr.on(eventType, function (e) {
  56887. var dis = makeDispatchAction(api);
  56888. each$15(inner$10(zr).records, function (record) {
  56889. record && cb(record, e, dis.dispatchAction);
  56890. });
  56891. dispatchTooltipFinally(dis.pendings, api);
  56892. });
  56893. }
  56894. }
  56895. function dispatchTooltipFinally(pendings, api) {
  56896. var showLen = pendings.showTip.length;
  56897. var hideLen = pendings.hideTip.length;
  56898. var actuallyPayload;
  56899. if (showLen) {
  56900. actuallyPayload = pendings.showTip[showLen - 1];
  56901. } else if (hideLen) {
  56902. actuallyPayload = pendings.hideTip[hideLen - 1];
  56903. }
  56904. if (actuallyPayload) {
  56905. actuallyPayload.dispatchAction = null;
  56906. api.dispatchAction(actuallyPayload);
  56907. }
  56908. }
  56909. function onLeave(record, e, dispatchAction) {
  56910. record.handler('leave', null, dispatchAction);
  56911. }
  56912. function doEnter(currTrigger, record, e, dispatchAction) {
  56913. record.handler(currTrigger, e, dispatchAction);
  56914. }
  56915. function makeDispatchAction(api) {
  56916. var pendings = {
  56917. showTip: [],
  56918. hideTip: []
  56919. }; // FIXME
  56920. // better approach?
  56921. // 'showTip' and 'hideTip' can be triggered by axisPointer and tooltip,
  56922. // which may be conflict, (axisPointer call showTip but tooltip call hideTip);
  56923. // So we have to add "final stage" to merge those dispatched actions.
  56924. var dispatchAction = function (payload) {
  56925. var pendingList = pendings[payload.type];
  56926. if (pendingList) {
  56927. pendingList.push(payload);
  56928. } else {
  56929. payload.dispatchAction = dispatchAction;
  56930. api.dispatchAction(payload);
  56931. }
  56932. };
  56933. return {
  56934. dispatchAction: dispatchAction,
  56935. pendings: pendings
  56936. };
  56937. }
  56938. /**
  56939. * @param {string} key
  56940. * @param {module:echarts/ExtensionAPI} api
  56941. */
  56942. function unregister(key, api) {
  56943. if (env$1.node) {
  56944. return;
  56945. }
  56946. var zr = api.getZr();
  56947. var record = (inner$10(zr).records || {})[key];
  56948. if (record) {
  56949. inner$10(zr).records[key] = null;
  56950. }
  56951. }
  56952. /*
  56953. * Licensed to the Apache Software Foundation (ASF) under one
  56954. * or more contributor license agreements. See the NOTICE file
  56955. * distributed with this work for additional information
  56956. * regarding copyright ownership. The ASF licenses this file
  56957. * to you under the Apache License, Version 2.0 (the
  56958. * "License"); you may not use this file except in compliance
  56959. * with the License. You may obtain a copy of the License at
  56960. *
  56961. * http://www.apache.org/licenses/LICENSE-2.0
  56962. *
  56963. * Unless required by applicable law or agreed to in writing,
  56964. * software distributed under the License is distributed on an
  56965. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  56966. * KIND, either express or implied. See the License for the
  56967. * specific language governing permissions and limitations
  56968. * under the License.
  56969. */
  56970. var AxisPointerView = extendComponentView({
  56971. type: 'axisPointer',
  56972. render: function (globalAxisPointerModel, ecModel, api) {
  56973. var globalTooltipModel = ecModel.getComponent('tooltip');
  56974. var triggerOn = globalAxisPointerModel.get('triggerOn') || globalTooltipModel && globalTooltipModel.get('triggerOn') || 'mousemove|click'; // Register global listener in AxisPointerView to enable
  56975. // AxisPointerView to be independent to Tooltip.
  56976. register('axisPointer', api, function (currTrigger, e, dispatchAction) {
  56977. // If 'none', it is not controlled by mouse totally.
  56978. if (triggerOn !== 'none' && (currTrigger === 'leave' || triggerOn.indexOf(currTrigger) >= 0)) {
  56979. dispatchAction({
  56980. type: 'updateAxisPointer',
  56981. currTrigger: currTrigger,
  56982. x: e && e.offsetX,
  56983. y: e && e.offsetY
  56984. });
  56985. }
  56986. });
  56987. },
  56988. /**
  56989. * @override
  56990. */
  56991. remove: function (ecModel, api) {
  56992. unregister(api.getZr(), 'axisPointer');
  56993. AxisPointerView.superApply(this._model, 'remove', arguments);
  56994. },
  56995. /**
  56996. * @override
  56997. */
  56998. dispose: function (ecModel, api) {
  56999. unregister('axisPointer', api);
  57000. AxisPointerView.superApply(this._model, 'dispose', arguments);
  57001. }
  57002. });
  57003. /*
  57004. * Licensed to the Apache Software Foundation (ASF) under one
  57005. * or more contributor license agreements. See the NOTICE file
  57006. * distributed with this work for additional information
  57007. * regarding copyright ownership. The ASF licenses this file
  57008. * to you under the Apache License, Version 2.0 (the
  57009. * "License"); you may not use this file except in compliance
  57010. * with the License. You may obtain a copy of the License at
  57011. *
  57012. * http://www.apache.org/licenses/LICENSE-2.0
  57013. *
  57014. * Unless required by applicable law or agreed to in writing,
  57015. * software distributed under the License is distributed on an
  57016. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57017. * KIND, either express or implied. See the License for the
  57018. * specific language governing permissions and limitations
  57019. * under the License.
  57020. */
  57021. var inner$11 = makeInner();
  57022. var clone$4 = clone;
  57023. var bind$2 = bind;
  57024. /**
  57025. * Base axis pointer class in 2D.
  57026. * Implemenents {module:echarts/component/axis/IAxisPointer}.
  57027. */
  57028. function BaseAxisPointer() {}
  57029. BaseAxisPointer.prototype = {
  57030. /**
  57031. * @private
  57032. */
  57033. _group: null,
  57034. /**
  57035. * @private
  57036. */
  57037. _lastGraphicKey: null,
  57038. /**
  57039. * @private
  57040. */
  57041. _handle: null,
  57042. /**
  57043. * @private
  57044. */
  57045. _dragging: false,
  57046. /**
  57047. * @private
  57048. */
  57049. _lastValue: null,
  57050. /**
  57051. * @private
  57052. */
  57053. _lastStatus: null,
  57054. /**
  57055. * @private
  57056. */
  57057. _payloadInfo: null,
  57058. /**
  57059. * In px, arbitrary value. Do not set too small,
  57060. * no animation is ok for most cases.
  57061. * @protected
  57062. */
  57063. animationThreshold: 15,
  57064. /**
  57065. * @implement
  57066. */
  57067. render: function (axisModel, axisPointerModel, api, forceRender) {
  57068. var value = axisPointerModel.get('value');
  57069. var status = axisPointerModel.get('status'); // Bind them to `this`, not in closure, otherwise they will not
  57070. // be replaced when user calling setOption in not merge mode.
  57071. this._axisModel = axisModel;
  57072. this._axisPointerModel = axisPointerModel;
  57073. this._api = api; // Optimize: `render` will be called repeatly during mouse move.
  57074. // So it is power consuming if performing `render` each time,
  57075. // especially on mobile device.
  57076. if (!forceRender && this._lastValue === value && this._lastStatus === status) {
  57077. return;
  57078. }
  57079. this._lastValue = value;
  57080. this._lastStatus = status;
  57081. var group = this._group;
  57082. var handle = this._handle;
  57083. if (!status || status === 'hide') {
  57084. // Do not clear here, for animation better.
  57085. group && group.hide();
  57086. handle && handle.hide();
  57087. return;
  57088. }
  57089. group && group.show();
  57090. handle && handle.show(); // Otherwise status is 'show'
  57091. var elOption = {};
  57092. this.makeElOption(elOption, value, axisModel, axisPointerModel, api); // Enable change axis pointer type.
  57093. var graphicKey = elOption.graphicKey;
  57094. if (graphicKey !== this._lastGraphicKey) {
  57095. this.clear(api);
  57096. }
  57097. this._lastGraphicKey = graphicKey;
  57098. var moveAnimation = this._moveAnimation = this.determineAnimation(axisModel, axisPointerModel);
  57099. if (!group) {
  57100. group = this._group = new Group();
  57101. this.createPointerEl(group, elOption, axisModel, axisPointerModel);
  57102. this.createLabelEl(group, elOption, axisModel, axisPointerModel);
  57103. api.getZr().add(group);
  57104. } else {
  57105. var doUpdateProps = curry(updateProps$1, axisPointerModel, moveAnimation);
  57106. this.updatePointerEl(group, elOption, doUpdateProps, axisPointerModel);
  57107. this.updateLabelEl(group, elOption, doUpdateProps, axisPointerModel);
  57108. }
  57109. updateMandatoryProps(group, axisPointerModel, true);
  57110. this._renderHandle(value);
  57111. },
  57112. /**
  57113. * @implement
  57114. */
  57115. remove: function (api) {
  57116. this.clear(api);
  57117. },
  57118. /**
  57119. * @implement
  57120. */
  57121. dispose: function (api) {
  57122. this.clear(api);
  57123. },
  57124. /**
  57125. * @protected
  57126. */
  57127. determineAnimation: function (axisModel, axisPointerModel) {
  57128. var animation = axisPointerModel.get('animation');
  57129. var axis = axisModel.axis;
  57130. var isCategoryAxis = axis.type === 'category';
  57131. var useSnap = axisPointerModel.get('snap'); // Value axis without snap always do not snap.
  57132. if (!useSnap && !isCategoryAxis) {
  57133. return false;
  57134. }
  57135. if (animation === 'auto' || animation == null) {
  57136. var animationThreshold = this.animationThreshold;
  57137. if (isCategoryAxis && axis.getBandWidth() > animationThreshold) {
  57138. return true;
  57139. } // It is important to auto animation when snap used. Consider if there is
  57140. // a dataZoom, animation will be disabled when too many points exist, while
  57141. // it will be enabled for better visual effect when little points exist.
  57142. if (useSnap) {
  57143. var seriesDataCount = getAxisInfo(axisModel).seriesDataCount;
  57144. var axisExtent = axis.getExtent(); // Approximate band width
  57145. return Math.abs(axisExtent[0] - axisExtent[1]) / seriesDataCount > animationThreshold;
  57146. }
  57147. return false;
  57148. }
  57149. return animation === true;
  57150. },
  57151. /**
  57152. * add {pointer, label, graphicKey} to elOption
  57153. * @protected
  57154. */
  57155. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {// Shoule be implemenented by sub-class.
  57156. },
  57157. /**
  57158. * @protected
  57159. */
  57160. createPointerEl: function (group, elOption, axisModel, axisPointerModel) {
  57161. var pointerOption = elOption.pointer;
  57162. if (pointerOption) {
  57163. var pointerEl = inner$11(group).pointerEl = new graphic[pointerOption.type](clone$4(elOption.pointer));
  57164. group.add(pointerEl);
  57165. }
  57166. },
  57167. /**
  57168. * @protected
  57169. */
  57170. createLabelEl: function (group, elOption, axisModel, axisPointerModel) {
  57171. if (elOption.label) {
  57172. var labelEl = inner$11(group).labelEl = new Rect(clone$4(elOption.label));
  57173. group.add(labelEl);
  57174. updateLabelShowHide(labelEl, axisPointerModel);
  57175. }
  57176. },
  57177. /**
  57178. * @protected
  57179. */
  57180. updatePointerEl: function (group, elOption, updateProps$$1) {
  57181. var pointerEl = inner$11(group).pointerEl;
  57182. if (pointerEl && elOption.pointer) {
  57183. pointerEl.setStyle(elOption.pointer.style);
  57184. updateProps$$1(pointerEl, {
  57185. shape: elOption.pointer.shape
  57186. });
  57187. }
  57188. },
  57189. /**
  57190. * @protected
  57191. */
  57192. updateLabelEl: function (group, elOption, updateProps$$1, axisPointerModel) {
  57193. var labelEl = inner$11(group).labelEl;
  57194. if (labelEl) {
  57195. labelEl.setStyle(elOption.label.style);
  57196. updateProps$$1(labelEl, {
  57197. // Consider text length change in vertical axis, animation should
  57198. // be used on shape, otherwise the effect will be weird.
  57199. shape: elOption.label.shape,
  57200. position: elOption.label.position
  57201. });
  57202. updateLabelShowHide(labelEl, axisPointerModel);
  57203. }
  57204. },
  57205. /**
  57206. * @private
  57207. */
  57208. _renderHandle: function (value) {
  57209. if (this._dragging || !this.updateHandleTransform) {
  57210. return;
  57211. }
  57212. var axisPointerModel = this._axisPointerModel;
  57213. var zr = this._api.getZr();
  57214. var handle = this._handle;
  57215. var handleModel = axisPointerModel.getModel('handle');
  57216. var status = axisPointerModel.get('status');
  57217. if (!handleModel.get('show') || !status || status === 'hide') {
  57218. handle && zr.remove(handle);
  57219. this._handle = null;
  57220. return;
  57221. }
  57222. var isInit;
  57223. if (!this._handle) {
  57224. isInit = true;
  57225. handle = this._handle = createIcon(handleModel.get('icon'), {
  57226. cursor: 'move',
  57227. draggable: true,
  57228. onmousemove: function (e) {
  57229. // Fot mobile devicem, prevent screen slider on the button.
  57230. stop(e.event);
  57231. },
  57232. onmousedown: bind$2(this._onHandleDragMove, this, 0, 0),
  57233. drift: bind$2(this._onHandleDragMove, this),
  57234. ondragend: bind$2(this._onHandleDragEnd, this)
  57235. });
  57236. zr.add(handle);
  57237. }
  57238. updateMandatoryProps(handle, axisPointerModel, false); // update style
  57239. var includeStyles = ['color', 'borderColor', 'borderWidth', 'opacity', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY'];
  57240. handle.setStyle(handleModel.getItemStyle(null, includeStyles)); // update position
  57241. var handleSize = handleModel.get('size');
  57242. if (!isArray(handleSize)) {
  57243. handleSize = [handleSize, handleSize];
  57244. }
  57245. handle.attr('scale', [handleSize[0] / 2, handleSize[1] / 2]);
  57246. createOrUpdate(this, '_doDispatchAxisPointer', handleModel.get('throttle') || 0, 'fixRate');
  57247. this._moveHandleToValue(value, isInit);
  57248. },
  57249. /**
  57250. * @private
  57251. */
  57252. _moveHandleToValue: function (value, isInit) {
  57253. updateProps$1(this._axisPointerModel, !isInit && this._moveAnimation, this._handle, getHandleTransProps(this.getHandleTransform(value, this._axisModel, this._axisPointerModel)));
  57254. },
  57255. /**
  57256. * @private
  57257. */
  57258. _onHandleDragMove: function (dx, dy) {
  57259. var handle = this._handle;
  57260. if (!handle) {
  57261. return;
  57262. }
  57263. this._dragging = true; // Persistent for throttle.
  57264. var trans = this.updateHandleTransform(getHandleTransProps(handle), [dx, dy], this._axisModel, this._axisPointerModel);
  57265. this._payloadInfo = trans;
  57266. handle.stopAnimation();
  57267. handle.attr(getHandleTransProps(trans));
  57268. inner$11(handle).lastProp = null;
  57269. this._doDispatchAxisPointer();
  57270. },
  57271. /**
  57272. * Throttled method.
  57273. * @private
  57274. */
  57275. _doDispatchAxisPointer: function () {
  57276. var handle = this._handle;
  57277. if (!handle) {
  57278. return;
  57279. }
  57280. var payloadInfo = this._payloadInfo;
  57281. var axisModel = this._axisModel;
  57282. this._api.dispatchAction({
  57283. type: 'updateAxisPointer',
  57284. x: payloadInfo.cursorPoint[0],
  57285. y: payloadInfo.cursorPoint[1],
  57286. tooltipOption: payloadInfo.tooltipOption,
  57287. axesInfo: [{
  57288. axisDim: axisModel.axis.dim,
  57289. axisIndex: axisModel.componentIndex
  57290. }]
  57291. });
  57292. },
  57293. /**
  57294. * @private
  57295. */
  57296. _onHandleDragEnd: function (moveAnimation) {
  57297. this._dragging = false;
  57298. var handle = this._handle;
  57299. if (!handle) {
  57300. return;
  57301. }
  57302. var value = this._axisPointerModel.get('value'); // Consider snap or categroy axis, handle may be not consistent with
  57303. // axisPointer. So move handle to align the exact value position when
  57304. // drag ended.
  57305. this._moveHandleToValue(value); // For the effect: tooltip will be shown when finger holding on handle
  57306. // button, and will be hidden after finger left handle button.
  57307. this._api.dispatchAction({
  57308. type: 'hideTip'
  57309. });
  57310. },
  57311. /**
  57312. * Should be implemenented by sub-class if support `handle`.
  57313. * @protected
  57314. * @param {number} value
  57315. * @param {module:echarts/model/Model} axisModel
  57316. * @param {module:echarts/model/Model} axisPointerModel
  57317. * @return {Object} {position: [x, y], rotation: 0}
  57318. */
  57319. getHandleTransform: null,
  57320. /**
  57321. * * Should be implemenented by sub-class if support `handle`.
  57322. * @protected
  57323. * @param {Object} transform {position, rotation}
  57324. * @param {Array.<number>} delta [dx, dy]
  57325. * @param {module:echarts/model/Model} axisModel
  57326. * @param {module:echarts/model/Model} axisPointerModel
  57327. * @return {Object} {position: [x, y], rotation: 0, cursorPoint: [x, y]}
  57328. */
  57329. updateHandleTransform: null,
  57330. /**
  57331. * @private
  57332. */
  57333. clear: function (api) {
  57334. this._lastValue = null;
  57335. this._lastStatus = null;
  57336. var zr = api.getZr();
  57337. var group = this._group;
  57338. var handle = this._handle;
  57339. if (zr && group) {
  57340. this._lastGraphicKey = null;
  57341. group && zr.remove(group);
  57342. handle && zr.remove(handle);
  57343. this._group = null;
  57344. this._handle = null;
  57345. this._payloadInfo = null;
  57346. }
  57347. },
  57348. /**
  57349. * @protected
  57350. */
  57351. doClear: function () {// Implemented by sub-class if necessary.
  57352. },
  57353. /**
  57354. * @protected
  57355. * @param {Array.<number>} xy
  57356. * @param {Array.<number>} wh
  57357. * @param {number} [xDimIndex=0] or 1
  57358. */
  57359. buildLabel: function (xy, wh, xDimIndex) {
  57360. xDimIndex = xDimIndex || 0;
  57361. return {
  57362. x: xy[xDimIndex],
  57363. y: xy[1 - xDimIndex],
  57364. width: wh[xDimIndex],
  57365. height: wh[1 - xDimIndex]
  57366. };
  57367. }
  57368. };
  57369. BaseAxisPointer.prototype.constructor = BaseAxisPointer;
  57370. function updateProps$1(animationModel, moveAnimation, el, props) {
  57371. // Animation optimize.
  57372. if (!propsEqual(inner$11(el).lastProp, props)) {
  57373. inner$11(el).lastProp = props;
  57374. moveAnimation ? updateProps(el, props, animationModel) : (el.stopAnimation(), el.attr(props));
  57375. }
  57376. }
  57377. function propsEqual(lastProps, newProps) {
  57378. if (isObject$1(lastProps) && isObject$1(newProps)) {
  57379. var equals = true;
  57380. each$1(newProps, function (item, key) {
  57381. equals = equals && propsEqual(lastProps[key], item);
  57382. });
  57383. return !!equals;
  57384. } else {
  57385. return lastProps === newProps;
  57386. }
  57387. }
  57388. function updateLabelShowHide(labelEl, axisPointerModel) {
  57389. labelEl[axisPointerModel.get('label.show') ? 'show' : 'hide']();
  57390. }
  57391. function getHandleTransProps(trans) {
  57392. return {
  57393. position: trans.position.slice(),
  57394. rotation: trans.rotation || 0
  57395. };
  57396. }
  57397. function updateMandatoryProps(group, axisPointerModel, silent) {
  57398. var z = axisPointerModel.get('z');
  57399. var zlevel = axisPointerModel.get('zlevel');
  57400. group && group.traverse(function (el) {
  57401. if (el.type !== 'group') {
  57402. z != null && (el.z = z);
  57403. zlevel != null && (el.zlevel = zlevel);
  57404. el.silent = silent;
  57405. }
  57406. });
  57407. }
  57408. enableClassExtend(BaseAxisPointer);
  57409. /*
  57410. * Licensed to the Apache Software Foundation (ASF) under one
  57411. * or more contributor license agreements. See the NOTICE file
  57412. * distributed with this work for additional information
  57413. * regarding copyright ownership. The ASF licenses this file
  57414. * to you under the Apache License, Version 2.0 (the
  57415. * "License"); you may not use this file except in compliance
  57416. * with the License. You may obtain a copy of the License at
  57417. *
  57418. * http://www.apache.org/licenses/LICENSE-2.0
  57419. *
  57420. * Unless required by applicable law or agreed to in writing,
  57421. * software distributed under the License is distributed on an
  57422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57423. * KIND, either express or implied. See the License for the
  57424. * specific language governing permissions and limitations
  57425. * under the License.
  57426. */
  57427. /**
  57428. * @param {module:echarts/model/Model} axisPointerModel
  57429. */
  57430. function buildElStyle(axisPointerModel) {
  57431. var axisPointerType = axisPointerModel.get('type');
  57432. var styleModel = axisPointerModel.getModel(axisPointerType + 'Style');
  57433. var style;
  57434. if (axisPointerType === 'line') {
  57435. style = styleModel.getLineStyle();
  57436. style.fill = null;
  57437. } else if (axisPointerType === 'shadow') {
  57438. style = styleModel.getAreaStyle();
  57439. style.stroke = null;
  57440. }
  57441. return style;
  57442. }
  57443. /**
  57444. * @param {Function} labelPos {align, verticalAlign, position}
  57445. */
  57446. function buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos) {
  57447. var value = axisPointerModel.get('value');
  57448. var text = getValueLabel(value, axisModel.axis, axisModel.ecModel, axisPointerModel.get('seriesDataIndices'), {
  57449. precision: axisPointerModel.get('label.precision'),
  57450. formatter: axisPointerModel.get('label.formatter')
  57451. });
  57452. var labelModel = axisPointerModel.getModel('label');
  57453. var paddings = normalizeCssArray$1(labelModel.get('padding') || 0);
  57454. var font = labelModel.getFont();
  57455. var textRect = getBoundingRect(text, font);
  57456. var position = labelPos.position;
  57457. var width = textRect.width + paddings[1] + paddings[3];
  57458. var height = textRect.height + paddings[0] + paddings[2]; // Adjust by align.
  57459. var align = labelPos.align;
  57460. align === 'right' && (position[0] -= width);
  57461. align === 'center' && (position[0] -= width / 2);
  57462. var verticalAlign = labelPos.verticalAlign;
  57463. verticalAlign === 'bottom' && (position[1] -= height);
  57464. verticalAlign === 'middle' && (position[1] -= height / 2); // Not overflow ec container
  57465. confineInContainer(position, width, height, api);
  57466. var bgColor = labelModel.get('backgroundColor');
  57467. if (!bgColor || bgColor === 'auto') {
  57468. bgColor = axisModel.get('axisLine.lineStyle.color');
  57469. }
  57470. elOption.label = {
  57471. shape: {
  57472. x: 0,
  57473. y: 0,
  57474. width: width,
  57475. height: height,
  57476. r: labelModel.get('borderRadius')
  57477. },
  57478. position: position.slice(),
  57479. // TODO: rich
  57480. style: {
  57481. text: text,
  57482. textFont: font,
  57483. textFill: labelModel.getTextColor(),
  57484. textPosition: 'inside',
  57485. textPadding: paddings,
  57486. fill: bgColor,
  57487. stroke: labelModel.get('borderColor') || 'transparent',
  57488. lineWidth: labelModel.get('borderWidth') || 0,
  57489. shadowBlur: labelModel.get('shadowBlur'),
  57490. shadowColor: labelModel.get('shadowColor'),
  57491. shadowOffsetX: labelModel.get('shadowOffsetX'),
  57492. shadowOffsetY: labelModel.get('shadowOffsetY')
  57493. },
  57494. // Lable should be over axisPointer.
  57495. z2: 10
  57496. };
  57497. } // Do not overflow ec container
  57498. function confineInContainer(position, width, height, api) {
  57499. var viewWidth = api.getWidth();
  57500. var viewHeight = api.getHeight();
  57501. position[0] = Math.min(position[0] + width, viewWidth) - width;
  57502. position[1] = Math.min(position[1] + height, viewHeight) - height;
  57503. position[0] = Math.max(position[0], 0);
  57504. position[1] = Math.max(position[1], 0);
  57505. }
  57506. /**
  57507. * @param {number} value
  57508. * @param {module:echarts/coord/Axis} axis
  57509. * @param {module:echarts/model/Global} ecModel
  57510. * @param {Object} opt
  57511. * @param {Array.<Object>} seriesDataIndices
  57512. * @param {number|string} opt.precision 'auto' or a number
  57513. * @param {string|Function} opt.formatter label formatter
  57514. */
  57515. function getValueLabel(value, axis, ecModel, seriesDataIndices, opt) {
  57516. value = axis.scale.parse(value);
  57517. var text = axis.scale.getLabel( // If `precision` is set, width can be fixed (like '12.00500'), which
  57518. // helps to debounce when when moving label.
  57519. value, {
  57520. precision: opt.precision
  57521. });
  57522. var formatter = opt.formatter;
  57523. if (formatter) {
  57524. var params = {
  57525. value: getAxisRawValue(axis, value),
  57526. axisDimension: axis.dim,
  57527. axisIndex: axis.index,
  57528. seriesData: []
  57529. };
  57530. each$1(seriesDataIndices, function (idxItem) {
  57531. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  57532. var dataIndex = idxItem.dataIndexInside;
  57533. var dataParams = series && series.getDataParams(dataIndex);
  57534. dataParams && params.seriesData.push(dataParams);
  57535. });
  57536. if (isString(formatter)) {
  57537. text = formatter.replace('{value}', text);
  57538. } else if (isFunction$1(formatter)) {
  57539. text = formatter(params);
  57540. }
  57541. }
  57542. return text;
  57543. }
  57544. /**
  57545. * @param {module:echarts/coord/Axis} axis
  57546. * @param {number} value
  57547. * @param {Object} layoutInfo {
  57548. * rotation, position, labelOffset, labelDirection, labelMargin
  57549. * }
  57550. */
  57551. function getTransformedPosition(axis, value, layoutInfo) {
  57552. var transform = create$1();
  57553. rotate(transform, transform, layoutInfo.rotation);
  57554. translate(transform, transform, layoutInfo.position);
  57555. return applyTransform$1([axis.dataToCoord(value), (layoutInfo.labelOffset || 0) + (layoutInfo.labelDirection || 1) * (layoutInfo.labelMargin || 0)], transform);
  57556. }
  57557. function buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api) {
  57558. var textLayout = AxisBuilder.innerTextLayout(layoutInfo.rotation, 0, layoutInfo.labelDirection);
  57559. layoutInfo.labelMargin = axisPointerModel.get('label.margin');
  57560. buildLabelElOption(elOption, axisModel, axisPointerModel, api, {
  57561. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  57562. align: textLayout.textAlign,
  57563. verticalAlign: textLayout.textVerticalAlign
  57564. });
  57565. }
  57566. /**
  57567. * @param {Array.<number>} p1
  57568. * @param {Array.<number>} p2
  57569. * @param {number} [xDimIndex=0] or 1
  57570. */
  57571. function makeLineShape(p1, p2, xDimIndex) {
  57572. xDimIndex = xDimIndex || 0;
  57573. return {
  57574. x1: p1[xDimIndex],
  57575. y1: p1[1 - xDimIndex],
  57576. x2: p2[xDimIndex],
  57577. y2: p2[1 - xDimIndex]
  57578. };
  57579. }
  57580. /**
  57581. * @param {Array.<number>} xy
  57582. * @param {Array.<number>} wh
  57583. * @param {number} [xDimIndex=0] or 1
  57584. */
  57585. function makeRectShape(xy, wh, xDimIndex) {
  57586. xDimIndex = xDimIndex || 0;
  57587. return {
  57588. x: xy[xDimIndex],
  57589. y: xy[1 - xDimIndex],
  57590. width: wh[xDimIndex],
  57591. height: wh[1 - xDimIndex]
  57592. };
  57593. }
  57594. function makeSectorShape(cx, cy, r0, r, startAngle, endAngle) {
  57595. return {
  57596. cx: cx,
  57597. cy: cy,
  57598. r0: r0,
  57599. r: r,
  57600. startAngle: startAngle,
  57601. endAngle: endAngle,
  57602. clockwise: true
  57603. };
  57604. }
  57605. /*
  57606. * Licensed to the Apache Software Foundation (ASF) under one
  57607. * or more contributor license agreements. See the NOTICE file
  57608. * distributed with this work for additional information
  57609. * regarding copyright ownership. The ASF licenses this file
  57610. * to you under the Apache License, Version 2.0 (the
  57611. * "License"); you may not use this file except in compliance
  57612. * with the License. You may obtain a copy of the License at
  57613. *
  57614. * http://www.apache.org/licenses/LICENSE-2.0
  57615. *
  57616. * Unless required by applicable law or agreed to in writing,
  57617. * software distributed under the License is distributed on an
  57618. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57619. * KIND, either express or implied. See the License for the
  57620. * specific language governing permissions and limitations
  57621. * under the License.
  57622. */
  57623. var CartesianAxisPointer = BaseAxisPointer.extend({
  57624. /**
  57625. * @override
  57626. */
  57627. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  57628. var axis = axisModel.axis;
  57629. var grid = axis.grid;
  57630. var axisPointerType = axisPointerModel.get('type');
  57631. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  57632. var pixelValue = axis.toGlobalCoord(axis.dataToCoord(value, true));
  57633. if (axisPointerType && axisPointerType !== 'none') {
  57634. var elStyle = buildElStyle(axisPointerModel);
  57635. var pointerOption = pointerShapeBuilder[axisPointerType](axis, pixelValue, otherExtent);
  57636. pointerOption.style = elStyle;
  57637. elOption.graphicKey = pointerOption.type;
  57638. elOption.pointer = pointerOption;
  57639. }
  57640. var layoutInfo = layout$1(grid.model, axisModel);
  57641. buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  57642. },
  57643. /**
  57644. * @override
  57645. */
  57646. getHandleTransform: function (value, axisModel, axisPointerModel) {
  57647. var layoutInfo = layout$1(axisModel.axis.grid.model, axisModel, {
  57648. labelInside: false
  57649. });
  57650. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  57651. return {
  57652. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  57653. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  57654. };
  57655. },
  57656. /**
  57657. * @override
  57658. */
  57659. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  57660. var axis = axisModel.axis;
  57661. var grid = axis.grid;
  57662. var axisExtent = axis.getGlobalExtent(true);
  57663. var otherExtent = getCartesian(grid, axis).getOtherAxis(axis).getGlobalExtent();
  57664. var dimIndex = axis.dim === 'x' ? 0 : 1;
  57665. var currPosition = transform.position;
  57666. currPosition[dimIndex] += delta[dimIndex];
  57667. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  57668. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  57669. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  57670. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  57671. cursorPoint[dimIndex] = currPosition[dimIndex]; // Make tooltip do not overlap axisPointer and in the middle of the grid.
  57672. var tooltipOptions = [{
  57673. verticalAlign: 'middle'
  57674. }, {
  57675. align: 'center'
  57676. }];
  57677. return {
  57678. position: currPosition,
  57679. rotation: transform.rotation,
  57680. cursorPoint: cursorPoint,
  57681. tooltipOption: tooltipOptions[dimIndex]
  57682. };
  57683. }
  57684. });
  57685. function getCartesian(grid, axis) {
  57686. var opt = {};
  57687. opt[axis.dim + 'AxisIndex'] = axis.index;
  57688. return grid.getCartesian(opt);
  57689. }
  57690. var pointerShapeBuilder = {
  57691. line: function (axis, pixelValue, otherExtent) {
  57692. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getAxisDimIndex(axis));
  57693. return {
  57694. type: 'Line',
  57695. subPixelOptimize: true,
  57696. shape: targetShape
  57697. };
  57698. },
  57699. shadow: function (axis, pixelValue, otherExtent) {
  57700. var bandWidth = Math.max(1, axis.getBandWidth());
  57701. var span = otherExtent[1] - otherExtent[0];
  57702. return {
  57703. type: 'Rect',
  57704. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getAxisDimIndex(axis))
  57705. };
  57706. }
  57707. };
  57708. function getAxisDimIndex(axis) {
  57709. return axis.dim === 'x' ? 0 : 1;
  57710. }
  57711. AxisView.registerAxisPointerClass('CartesianAxisPointer', CartesianAxisPointer);
  57712. /*
  57713. * Licensed to the Apache Software Foundation (ASF) under one
  57714. * or more contributor license agreements. See the NOTICE file
  57715. * distributed with this work for additional information
  57716. * regarding copyright ownership. The ASF licenses this file
  57717. * to you under the Apache License, Version 2.0 (the
  57718. * "License"); you may not use this file except in compliance
  57719. * with the License. You may obtain a copy of the License at
  57720. *
  57721. * http://www.apache.org/licenses/LICENSE-2.0
  57722. *
  57723. * Unless required by applicable law or agreed to in writing,
  57724. * software distributed under the License is distributed on an
  57725. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57726. * KIND, either express or implied. See the License for the
  57727. * specific language governing permissions and limitations
  57728. * under the License.
  57729. */
  57730. // echarts.simple.js and online build tooltip, which only require gridSimple,
  57731. // CartesianAxisPointer should be able to required somewhere.
  57732. registerPreprocessor(function (option) {
  57733. // Always has a global axisPointerModel for default setting.
  57734. if (option) {
  57735. (!option.axisPointer || option.axisPointer.length === 0) && (option.axisPointer = {});
  57736. var link = option.axisPointer.link; // Normalize to array to avoid object mergin. But if link
  57737. // is not set, remain null/undefined, otherwise it will
  57738. // override existent link setting.
  57739. if (link && !isArray(link)) {
  57740. option.axisPointer.link = [link];
  57741. }
  57742. }
  57743. }); // This process should proformed after coordinate systems created
  57744. // and series data processed. So put it on statistic processing stage.
  57745. registerProcessor(PRIORITY.PROCESSOR.STATISTIC, function (ecModel, api) {
  57746. // Build axisPointerModel, mergin tooltip.axisPointer model for each axis.
  57747. // allAxesInfo should be updated when setOption performed.
  57748. ecModel.getComponent('axisPointer').coordSysAxesInfo = collect(ecModel, api);
  57749. }); // Broadcast to all views.
  57750. registerAction({
  57751. type: 'updateAxisPointer',
  57752. event: 'updateAxisPointer',
  57753. update: ':updateAxisPointer'
  57754. }, axisTrigger);
  57755. /*
  57756. * Licensed to the Apache Software Foundation (ASF) under one
  57757. * or more contributor license agreements. See the NOTICE file
  57758. * distributed with this work for additional information
  57759. * regarding copyright ownership. The ASF licenses this file
  57760. * to you under the Apache License, Version 2.0 (the
  57761. * "License"); you may not use this file except in compliance
  57762. * with the License. You may obtain a copy of the License at
  57763. *
  57764. * http://www.apache.org/licenses/LICENSE-2.0
  57765. *
  57766. * Unless required by applicable law or agreed to in writing,
  57767. * software distributed under the License is distributed on an
  57768. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57769. * KIND, either express or implied. See the License for the
  57770. * specific language governing permissions and limitations
  57771. * under the License.
  57772. */
  57773. var XY = ['x', 'y'];
  57774. var WH = ['width', 'height'];
  57775. var SingleAxisPointer = BaseAxisPointer.extend({
  57776. /**
  57777. * @override
  57778. */
  57779. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  57780. var axis = axisModel.axis;
  57781. var coordSys = axis.coordinateSystem;
  57782. var otherExtent = getGlobalExtent(coordSys, 1 - getPointDimIndex(axis));
  57783. var pixelValue = coordSys.dataToPoint(value)[0];
  57784. var axisPointerType = axisPointerModel.get('type');
  57785. if (axisPointerType && axisPointerType !== 'none') {
  57786. var elStyle = buildElStyle(axisPointerModel);
  57787. var pointerOption = pointerShapeBuilder$1[axisPointerType](axis, pixelValue, otherExtent);
  57788. pointerOption.style = elStyle;
  57789. elOption.graphicKey = pointerOption.type;
  57790. elOption.pointer = pointerOption;
  57791. }
  57792. var layoutInfo = layout$2(axisModel);
  57793. buildCartesianSingleLabelElOption(value, elOption, layoutInfo, axisModel, axisPointerModel, api);
  57794. },
  57795. /**
  57796. * @override
  57797. */
  57798. getHandleTransform: function (value, axisModel, axisPointerModel) {
  57799. var layoutInfo = layout$2(axisModel, {
  57800. labelInside: false
  57801. });
  57802. layoutInfo.labelMargin = axisPointerModel.get('handle.margin');
  57803. return {
  57804. position: getTransformedPosition(axisModel.axis, value, layoutInfo),
  57805. rotation: layoutInfo.rotation + (layoutInfo.labelDirection < 0 ? Math.PI : 0)
  57806. };
  57807. },
  57808. /**
  57809. * @override
  57810. */
  57811. updateHandleTransform: function (transform, delta, axisModel, axisPointerModel) {
  57812. var axis = axisModel.axis;
  57813. var coordSys = axis.coordinateSystem;
  57814. var dimIndex = getPointDimIndex(axis);
  57815. var axisExtent = getGlobalExtent(coordSys, dimIndex);
  57816. var currPosition = transform.position;
  57817. currPosition[dimIndex] += delta[dimIndex];
  57818. currPosition[dimIndex] = Math.min(axisExtent[1], currPosition[dimIndex]);
  57819. currPosition[dimIndex] = Math.max(axisExtent[0], currPosition[dimIndex]);
  57820. var otherExtent = getGlobalExtent(coordSys, 1 - dimIndex);
  57821. var cursorOtherValue = (otherExtent[1] + otherExtent[0]) / 2;
  57822. var cursorPoint = [cursorOtherValue, cursorOtherValue];
  57823. cursorPoint[dimIndex] = currPosition[dimIndex];
  57824. return {
  57825. position: currPosition,
  57826. rotation: transform.rotation,
  57827. cursorPoint: cursorPoint,
  57828. tooltipOption: {
  57829. verticalAlign: 'middle'
  57830. }
  57831. };
  57832. }
  57833. });
  57834. var pointerShapeBuilder$1 = {
  57835. line: function (axis, pixelValue, otherExtent) {
  57836. var targetShape = makeLineShape([pixelValue, otherExtent[0]], [pixelValue, otherExtent[1]], getPointDimIndex(axis));
  57837. return {
  57838. type: 'Line',
  57839. subPixelOptimize: true,
  57840. shape: targetShape
  57841. };
  57842. },
  57843. shadow: function (axis, pixelValue, otherExtent) {
  57844. var bandWidth = axis.getBandWidth();
  57845. var span = otherExtent[1] - otherExtent[0];
  57846. return {
  57847. type: 'Rect',
  57848. shape: makeRectShape([pixelValue - bandWidth / 2, otherExtent[0]], [bandWidth, span], getPointDimIndex(axis))
  57849. };
  57850. }
  57851. };
  57852. function getPointDimIndex(axis) {
  57853. return axis.isHorizontal() ? 0 : 1;
  57854. }
  57855. function getGlobalExtent(coordSys, dimIndex) {
  57856. var rect = coordSys.getRect();
  57857. return [rect[XY[dimIndex]], rect[XY[dimIndex]] + rect[WH[dimIndex]]];
  57858. }
  57859. AxisView.registerAxisPointerClass('SingleAxisPointer', SingleAxisPointer);
  57860. /*
  57861. * Licensed to the Apache Software Foundation (ASF) under one
  57862. * or more contributor license agreements. See the NOTICE file
  57863. * distributed with this work for additional information
  57864. * regarding copyright ownership. The ASF licenses this file
  57865. * to you under the Apache License, Version 2.0 (the
  57866. * "License"); you may not use this file except in compliance
  57867. * with the License. You may obtain a copy of the License at
  57868. *
  57869. * http://www.apache.org/licenses/LICENSE-2.0
  57870. *
  57871. * Unless required by applicable law or agreed to in writing,
  57872. * software distributed under the License is distributed on an
  57873. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57874. * KIND, either express or implied. See the License for the
  57875. * specific language governing permissions and limitations
  57876. * under the License.
  57877. */
  57878. extendComponentView({
  57879. type: 'single'
  57880. });
  57881. /*
  57882. * Licensed to the Apache Software Foundation (ASF) under one
  57883. * or more contributor license agreements. See the NOTICE file
  57884. * distributed with this work for additional information
  57885. * regarding copyright ownership. The ASF licenses this file
  57886. * to you under the Apache License, Version 2.0 (the
  57887. * "License"); you may not use this file except in compliance
  57888. * with the License. You may obtain a copy of the License at
  57889. *
  57890. * http://www.apache.org/licenses/LICENSE-2.0
  57891. *
  57892. * Unless required by applicable law or agreed to in writing,
  57893. * software distributed under the License is distributed on an
  57894. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  57895. * KIND, either express or implied. See the License for the
  57896. * specific language governing permissions and limitations
  57897. * under the License.
  57898. */
  57899. var DATA_NAME_INDEX = 2;
  57900. var ThemeRiverSeries = SeriesModel.extend({
  57901. type: 'series.themeRiver',
  57902. dependencies: ['singleAxis'],
  57903. /**
  57904. * @readOnly
  57905. * @type {module:zrender/core/util#HashMap}
  57906. */
  57907. nameMap: null,
  57908. /**
  57909. * @override
  57910. */
  57911. init: function (option) {
  57912. // eslint-disable-next-line
  57913. ThemeRiverSeries.superApply(this, 'init', arguments); // Put this function here is for the sake of consistency of code style.
  57914. // Enable legend selection for each data item
  57915. // Use a function instead of direct access because data reference may changed
  57916. this.legendVisualProvider = new LegendVisualProvider(bind(this.getData, this), bind(this.getRawData, this));
  57917. },
  57918. /**
  57919. * If there is no value of a certain point in the time for some event,set it value to 0.
  57920. *
  57921. * @param {Array} data initial data in the option
  57922. * @return {Array}
  57923. */
  57924. fixData: function (data) {
  57925. var rawDataLength = data.length; // grouped data by name
  57926. var groupResult = groupData(data, function (item) {
  57927. return item[2];
  57928. });
  57929. var layData = [];
  57930. groupResult.buckets.each(function (items, key) {
  57931. layData.push({
  57932. name: key,
  57933. dataList: items
  57934. });
  57935. });
  57936. var layerNum = layData.length;
  57937. var largestLayer = -1;
  57938. var index = -1;
  57939. for (var i = 0; i < layerNum; ++i) {
  57940. var len = layData[i].dataList.length;
  57941. if (len > largestLayer) {
  57942. largestLayer = len;
  57943. index = i;
  57944. }
  57945. }
  57946. for (var k = 0; k < layerNum; ++k) {
  57947. if (k === index) {
  57948. continue;
  57949. }
  57950. var name = layData[k].name;
  57951. for (var j = 0; j < largestLayer; ++j) {
  57952. var timeValue = layData[index].dataList[j][0];
  57953. var length = layData[k].dataList.length;
  57954. var keyIndex = -1;
  57955. for (var l = 0; l < length; ++l) {
  57956. var value = layData[k].dataList[l][0];
  57957. if (value === timeValue) {
  57958. keyIndex = l;
  57959. break;
  57960. }
  57961. }
  57962. if (keyIndex === -1) {
  57963. data[rawDataLength] = [];
  57964. data[rawDataLength][0] = timeValue;
  57965. data[rawDataLength][1] = 0;
  57966. data[rawDataLength][2] = name;
  57967. rawDataLength++;
  57968. }
  57969. }
  57970. }
  57971. return data;
  57972. },
  57973. /**
  57974. * @override
  57975. * @param {Object} option the initial option that user gived
  57976. * @param {module:echarts/model/Model} ecModel the model object for themeRiver option
  57977. * @return {module:echarts/data/List}
  57978. */
  57979. getInitialData: function (option, ecModel) {
  57980. var singleAxisModel = ecModel.queryComponents({
  57981. mainType: 'singleAxis',
  57982. index: this.get('singleAxisIndex'),
  57983. id: this.get('singleAxisId')
  57984. })[0];
  57985. var axisType = singleAxisModel.get('type'); // filter the data item with the value of label is undefined
  57986. var filterData = filter(option.data, function (dataItem) {
  57987. return dataItem[2] !== undefined;
  57988. }); // ??? TODO design a stage to transfer data for themeRiver and lines?
  57989. var data = this.fixData(filterData || []);
  57990. var nameList = [];
  57991. var nameMap = this.nameMap = createHashMap();
  57992. var count = 0;
  57993. for (var i = 0; i < data.length; ++i) {
  57994. nameList.push(data[i][DATA_NAME_INDEX]);
  57995. if (!nameMap.get(data[i][DATA_NAME_INDEX])) {
  57996. nameMap.set(data[i][DATA_NAME_INDEX], count);
  57997. count++;
  57998. }
  57999. }
  58000. var dimensionsInfo = createDimensions(data, {
  58001. coordDimensions: ['single'],
  58002. dimensionsDefine: [{
  58003. name: 'time',
  58004. type: getDimensionTypeByAxis(axisType)
  58005. }, {
  58006. name: 'value',
  58007. type: 'float'
  58008. }, {
  58009. name: 'name',
  58010. type: 'ordinal'
  58011. }],
  58012. encodeDefine: {
  58013. single: 0,
  58014. value: 1,
  58015. itemName: 2
  58016. }
  58017. });
  58018. var list = new List(dimensionsInfo, this);
  58019. list.initData(data);
  58020. return list;
  58021. },
  58022. /**
  58023. * The raw data is divided into multiple layers and each layer
  58024. * has same name.
  58025. *
  58026. * @return {Array.<Array.<number>>}
  58027. */
  58028. getLayerSeries: function () {
  58029. var data = this.getData();
  58030. var lenCount = data.count();
  58031. var indexArr = [];
  58032. for (var i = 0; i < lenCount; ++i) {
  58033. indexArr[i] = i;
  58034. }
  58035. var timeDim = data.mapDimension('single'); // data group by name
  58036. var groupResult = groupData(indexArr, function (index) {
  58037. return data.get('name', index);
  58038. });
  58039. var layerSeries = [];
  58040. groupResult.buckets.each(function (items, key) {
  58041. items.sort(function (index1, index2) {
  58042. return data.get(timeDim, index1) - data.get(timeDim, index2);
  58043. });
  58044. layerSeries.push({
  58045. name: key,
  58046. indices: items
  58047. });
  58048. });
  58049. return layerSeries;
  58050. },
  58051. /**
  58052. * Get data indices for show tooltip content
  58053. * @param {Array.<string>|string} dim single coordinate dimension
  58054. * @param {number} value axis value
  58055. * @param {module:echarts/coord/single/SingleAxis} baseAxis single Axis used
  58056. * the themeRiver.
  58057. * @return {Object} {dataIndices, nestestValue}
  58058. */
  58059. getAxisTooltipData: function (dim, value, baseAxis) {
  58060. if (!isArray(dim)) {
  58061. dim = dim ? [dim] : [];
  58062. }
  58063. var data = this.getData();
  58064. var layerSeries = this.getLayerSeries();
  58065. var indices = [];
  58066. var layerNum = layerSeries.length;
  58067. var nestestValue;
  58068. for (var i = 0; i < layerNum; ++i) {
  58069. var minDist = Number.MAX_VALUE;
  58070. var nearestIdx = -1;
  58071. var pointNum = layerSeries[i].indices.length;
  58072. for (var j = 0; j < pointNum; ++j) {
  58073. var theValue = data.get(dim[0], layerSeries[i].indices[j]);
  58074. var dist = Math.abs(theValue - value);
  58075. if (dist <= minDist) {
  58076. nestestValue = theValue;
  58077. minDist = dist;
  58078. nearestIdx = layerSeries[i].indices[j];
  58079. }
  58080. }
  58081. indices.push(nearestIdx);
  58082. }
  58083. return {
  58084. dataIndices: indices,
  58085. nestestValue: nestestValue
  58086. };
  58087. },
  58088. /**
  58089. * @override
  58090. * @param {number} dataIndex index of data
  58091. */
  58092. formatTooltip: function (dataIndex) {
  58093. var data = this.getData();
  58094. var htmlName = data.getName(dataIndex);
  58095. var htmlValue = data.get(data.mapDimension('value'), dataIndex);
  58096. if (isNaN(htmlValue) || htmlValue == null) {
  58097. htmlValue = '-';
  58098. }
  58099. return encodeHTML(htmlName + ' : ' + htmlValue);
  58100. },
  58101. defaultOption: {
  58102. zlevel: 0,
  58103. z: 2,
  58104. coordinateSystem: 'singleAxis',
  58105. // gap in axis's orthogonal orientation
  58106. boundaryGap: ['10%', '10%'],
  58107. // legendHoverLink: true,
  58108. singleAxisIndex: 0,
  58109. animationEasing: 'linear',
  58110. label: {
  58111. margin: 4,
  58112. show: true,
  58113. position: 'left',
  58114. color: '#000',
  58115. fontSize: 11
  58116. },
  58117. emphasis: {
  58118. label: {
  58119. show: true
  58120. }
  58121. }
  58122. }
  58123. });
  58124. /*
  58125. * Licensed to the Apache Software Foundation (ASF) under one
  58126. * or more contributor license agreements. See the NOTICE file
  58127. * distributed with this work for additional information
  58128. * regarding copyright ownership. The ASF licenses this file
  58129. * to you under the Apache License, Version 2.0 (the
  58130. * "License"); you may not use this file except in compliance
  58131. * with the License. You may obtain a copy of the License at
  58132. *
  58133. * http://www.apache.org/licenses/LICENSE-2.0
  58134. *
  58135. * Unless required by applicable law or agreed to in writing,
  58136. * software distributed under the License is distributed on an
  58137. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58138. * KIND, either express or implied. See the License for the
  58139. * specific language governing permissions and limitations
  58140. * under the License.
  58141. */
  58142. extendChartView({
  58143. type: 'themeRiver',
  58144. init: function () {
  58145. this._layers = [];
  58146. },
  58147. render: function (seriesModel, ecModel, api) {
  58148. var data = seriesModel.getData();
  58149. var group = this.group;
  58150. var layerSeries = seriesModel.getLayerSeries();
  58151. var layoutInfo = data.getLayout('layoutInfo');
  58152. var rect = layoutInfo.rect;
  58153. var boundaryGap = layoutInfo.boundaryGap;
  58154. group.attr('position', [0, rect.y + boundaryGap[0]]);
  58155. function keyGetter(item) {
  58156. return item.name;
  58157. }
  58158. var dataDiffer = new DataDiffer(this._layersSeries || [], layerSeries, keyGetter, keyGetter);
  58159. var newLayersGroups = {};
  58160. dataDiffer.add(bind(process, this, 'add')).update(bind(process, this, 'update')).remove(bind(process, this, 'remove')).execute();
  58161. function process(status, idx, oldIdx) {
  58162. var oldLayersGroups = this._layers;
  58163. if (status === 'remove') {
  58164. group.remove(oldLayersGroups[idx]);
  58165. return;
  58166. }
  58167. var points0 = [];
  58168. var points1 = [];
  58169. var color;
  58170. var indices = layerSeries[idx].indices;
  58171. for (var j = 0; j < indices.length; j++) {
  58172. var layout = data.getItemLayout(indices[j]);
  58173. var x = layout.x;
  58174. var y0 = layout.y0;
  58175. var y = layout.y;
  58176. points0.push([x, y0]);
  58177. points1.push([x, y0 + y]);
  58178. color = data.getItemVisual(indices[j], 'color');
  58179. }
  58180. var polygon;
  58181. var text;
  58182. var textLayout = data.getItemLayout(indices[0]);
  58183. var itemModel = data.getItemModel(indices[j - 1]);
  58184. var labelModel = itemModel.getModel('label');
  58185. var margin = labelModel.get('margin');
  58186. if (status === 'add') {
  58187. var layerGroup = newLayersGroups[idx] = new Group();
  58188. polygon = new Polygon$1({
  58189. shape: {
  58190. points: points0,
  58191. stackedOnPoints: points1,
  58192. smooth: 0.4,
  58193. stackedOnSmooth: 0.4,
  58194. smoothConstraint: false
  58195. },
  58196. z2: 0
  58197. });
  58198. text = new Text({
  58199. style: {
  58200. x: textLayout.x - margin,
  58201. y: textLayout.y0 + textLayout.y / 2
  58202. }
  58203. });
  58204. layerGroup.add(polygon);
  58205. layerGroup.add(text);
  58206. group.add(layerGroup);
  58207. polygon.setClipPath(createGridClipShape$2(polygon.getBoundingRect(), seriesModel, function () {
  58208. polygon.removeClipPath();
  58209. }));
  58210. } else {
  58211. var layerGroup = oldLayersGroups[oldIdx];
  58212. polygon = layerGroup.childAt(0);
  58213. text = layerGroup.childAt(1);
  58214. group.add(layerGroup);
  58215. newLayersGroups[idx] = layerGroup;
  58216. updateProps(polygon, {
  58217. shape: {
  58218. points: points0,
  58219. stackedOnPoints: points1
  58220. }
  58221. }, seriesModel);
  58222. updateProps(text, {
  58223. style: {
  58224. x: textLayout.x - margin,
  58225. y: textLayout.y0 + textLayout.y / 2
  58226. }
  58227. }, seriesModel);
  58228. }
  58229. var hoverItemStyleModel = itemModel.getModel('emphasis.itemStyle');
  58230. var itemStyleModel = itemModel.getModel('itemStyle');
  58231. setTextStyle(text.style, labelModel, {
  58232. text: labelModel.get('show') ? seriesModel.getFormattedLabel(indices[j - 1], 'normal') || data.getName(indices[j - 1]) : null,
  58233. textVerticalAlign: 'middle'
  58234. });
  58235. polygon.setStyle(extend({
  58236. fill: color
  58237. }, itemStyleModel.getItemStyle(['color'])));
  58238. setHoverStyle(polygon, hoverItemStyleModel.getItemStyle());
  58239. }
  58240. this._layersSeries = layerSeries;
  58241. this._layers = newLayersGroups;
  58242. },
  58243. dispose: function () {}
  58244. }); // add animation to the view
  58245. function createGridClipShape$2(rect, seriesModel, cb) {
  58246. var rectEl = new Rect({
  58247. shape: {
  58248. x: rect.x - 10,
  58249. y: rect.y - 10,
  58250. width: 0,
  58251. height: rect.height + 20
  58252. }
  58253. });
  58254. initProps(rectEl, {
  58255. shape: {
  58256. width: rect.width + 20,
  58257. height: rect.height + 20
  58258. }
  58259. }, seriesModel, cb);
  58260. return rectEl;
  58261. }
  58262. /*
  58263. * Licensed to the Apache Software Foundation (ASF) under one
  58264. * or more contributor license agreements. See the NOTICE file
  58265. * distributed with this work for additional information
  58266. * regarding copyright ownership. The ASF licenses this file
  58267. * to you under the Apache License, Version 2.0 (the
  58268. * "License"); you may not use this file except in compliance
  58269. * with the License. You may obtain a copy of the License at
  58270. *
  58271. * http://www.apache.org/licenses/LICENSE-2.0
  58272. *
  58273. * Unless required by applicable law or agreed to in writing,
  58274. * software distributed under the License is distributed on an
  58275. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58276. * KIND, either express or implied. See the License for the
  58277. * specific language governing permissions and limitations
  58278. * under the License.
  58279. */
  58280. var themeRiverLayout = function (ecModel, api) {
  58281. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  58282. var data = seriesModel.getData();
  58283. var single = seriesModel.coordinateSystem;
  58284. var layoutInfo = {}; // use the axis boundingRect for view
  58285. var rect = single.getRect();
  58286. layoutInfo.rect = rect;
  58287. var boundaryGap = seriesModel.get('boundaryGap');
  58288. var axis = single.getAxis();
  58289. layoutInfo.boundaryGap = boundaryGap;
  58290. if (axis.orient === 'horizontal') {
  58291. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.height);
  58292. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.height);
  58293. var height = rect.height - boundaryGap[0] - boundaryGap[1];
  58294. themeRiverLayout$1(data, seriesModel, height);
  58295. } else {
  58296. boundaryGap[0] = parsePercent$1(boundaryGap[0], rect.width);
  58297. boundaryGap[1] = parsePercent$1(boundaryGap[1], rect.width);
  58298. var width = rect.width - boundaryGap[0] - boundaryGap[1];
  58299. themeRiverLayout$1(data, seriesModel, width);
  58300. }
  58301. data.setLayout('layoutInfo', layoutInfo);
  58302. });
  58303. };
  58304. /**
  58305. * The layout information about themeriver
  58306. *
  58307. * @param {module:echarts/data/List} data data in the series
  58308. * @param {module:echarts/model/Series} seriesModel the model object of themeRiver series
  58309. * @param {number} height value used to compute every series height
  58310. */
  58311. function themeRiverLayout$1(data, seriesModel, height) {
  58312. if (!data.count()) {
  58313. return;
  58314. }
  58315. var coordSys = seriesModel.coordinateSystem; // the data in each layer are organized into a series.
  58316. var layerSeries = seriesModel.getLayerSeries(); // the points in each layer.
  58317. var timeDim = data.mapDimension('single');
  58318. var valueDim = data.mapDimension('value');
  58319. var layerPoints = map(layerSeries, function (singleLayer) {
  58320. return map(singleLayer.indices, function (idx) {
  58321. var pt = coordSys.dataToPoint(data.get(timeDim, idx));
  58322. pt[1] = data.get(valueDim, idx);
  58323. return pt;
  58324. });
  58325. });
  58326. var base = computeBaseline(layerPoints);
  58327. var baseLine = base.y0;
  58328. var ky = height / base.max; // set layout information for each item.
  58329. var n = layerSeries.length;
  58330. var m = layerSeries[0].indices.length;
  58331. var baseY0;
  58332. for (var j = 0; j < m; ++j) {
  58333. baseY0 = baseLine[j] * ky;
  58334. data.setItemLayout(layerSeries[0].indices[j], {
  58335. layerIndex: 0,
  58336. x: layerPoints[0][j][0],
  58337. y0: baseY0,
  58338. y: layerPoints[0][j][1] * ky
  58339. });
  58340. for (var i = 1; i < n; ++i) {
  58341. baseY0 += layerPoints[i - 1][j][1] * ky;
  58342. data.setItemLayout(layerSeries[i].indices[j], {
  58343. layerIndex: i,
  58344. x: layerPoints[i][j][0],
  58345. y0: baseY0,
  58346. y: layerPoints[i][j][1] * ky
  58347. });
  58348. }
  58349. }
  58350. }
  58351. /**
  58352. * Compute the baseLine of the rawdata
  58353. * Inspired by Lee Byron's paper Stacked Graphs - Geometry & Aesthetics
  58354. *
  58355. * @param {Array.<Array>} data the points in each layer
  58356. * @return {Object}
  58357. */
  58358. function computeBaseline(data) {
  58359. var layerNum = data.length;
  58360. var pointNum = data[0].length;
  58361. var sums = [];
  58362. var y0 = [];
  58363. var max = 0;
  58364. var temp;
  58365. var base = {};
  58366. for (var i = 0; i < pointNum; ++i) {
  58367. for (var j = 0, temp = 0; j < layerNum; ++j) {
  58368. temp += data[j][i][1];
  58369. }
  58370. if (temp > max) {
  58371. max = temp;
  58372. }
  58373. sums.push(temp);
  58374. }
  58375. for (var k = 0; k < pointNum; ++k) {
  58376. y0[k] = (max - sums[k]) / 2;
  58377. }
  58378. max = 0;
  58379. for (var l = 0; l < pointNum; ++l) {
  58380. var sum = sums[l] + y0[l];
  58381. if (sum > max) {
  58382. max = sum;
  58383. }
  58384. }
  58385. base.y0 = y0;
  58386. base.max = max;
  58387. return base;
  58388. }
  58389. /*
  58390. * Licensed to the Apache Software Foundation (ASF) under one
  58391. * or more contributor license agreements. See the NOTICE file
  58392. * distributed with this work for additional information
  58393. * regarding copyright ownership. The ASF licenses this file
  58394. * to you under the Apache License, Version 2.0 (the
  58395. * "License"); you may not use this file except in compliance
  58396. * with the License. You may obtain a copy of the License at
  58397. *
  58398. * http://www.apache.org/licenses/LICENSE-2.0
  58399. *
  58400. * Unless required by applicable law or agreed to in writing,
  58401. * software distributed under the License is distributed on an
  58402. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58403. * KIND, either express or implied. See the License for the
  58404. * specific language governing permissions and limitations
  58405. * under the License.
  58406. */
  58407. var themeRiverVisual = function (ecModel) {
  58408. ecModel.eachSeriesByType('themeRiver', function (seriesModel) {
  58409. var data = seriesModel.getData();
  58410. var rawData = seriesModel.getRawData();
  58411. var colorList = seriesModel.get('color');
  58412. var idxMap = createHashMap();
  58413. data.each(function (idx) {
  58414. idxMap.set(data.getRawIndex(idx), idx);
  58415. });
  58416. rawData.each(function (rawIndex) {
  58417. var name = rawData.getName(rawIndex);
  58418. var color = colorList[(seriesModel.nameMap.get(name) - 1) % colorList.length];
  58419. rawData.setItemVisual(rawIndex, 'color', color);
  58420. var idx = idxMap.get(rawIndex);
  58421. if (idx != null) {
  58422. data.setItemVisual(idx, 'color', color);
  58423. }
  58424. });
  58425. });
  58426. };
  58427. /*
  58428. * Licensed to the Apache Software Foundation (ASF) under one
  58429. * or more contributor license agreements. See the NOTICE file
  58430. * distributed with this work for additional information
  58431. * regarding copyright ownership. The ASF licenses this file
  58432. * to you under the Apache License, Version 2.0 (the
  58433. * "License"); you may not use this file except in compliance
  58434. * with the License. You may obtain a copy of the License at
  58435. *
  58436. * http://www.apache.org/licenses/LICENSE-2.0
  58437. *
  58438. * Unless required by applicable law or agreed to in writing,
  58439. * software distributed under the License is distributed on an
  58440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58441. * KIND, either express or implied. See the License for the
  58442. * specific language governing permissions and limitations
  58443. * under the License.
  58444. */
  58445. registerLayout(themeRiverLayout);
  58446. registerVisual(themeRiverVisual);
  58447. registerProcessor(dataFilter('themeRiver'));
  58448. /*
  58449. * Licensed to the Apache Software Foundation (ASF) under one
  58450. * or more contributor license agreements. See the NOTICE file
  58451. * distributed with this work for additional information
  58452. * regarding copyright ownership. The ASF licenses this file
  58453. * to you under the Apache License, Version 2.0 (the
  58454. * "License"); you may not use this file except in compliance
  58455. * with the License. You may obtain a copy of the License at
  58456. *
  58457. * http://www.apache.org/licenses/LICENSE-2.0
  58458. *
  58459. * Unless required by applicable law or agreed to in writing,
  58460. * software distributed under the License is distributed on an
  58461. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58462. * KIND, either express or implied. See the License for the
  58463. * specific language governing permissions and limitations
  58464. * under the License.
  58465. */
  58466. var PictorialBarSeries = BaseBarSeries.extend({
  58467. type: 'series.pictorialBar',
  58468. dependencies: ['grid'],
  58469. defaultOption: {
  58470. symbol: 'circle',
  58471. // Customized bar shape
  58472. symbolSize: null,
  58473. // Can be ['100%', '100%'], null means auto.
  58474. symbolRotate: null,
  58475. symbolPosition: null,
  58476. // 'start' or 'end' or 'center', null means auto.
  58477. symbolOffset: null,
  58478. symbolMargin: null,
  58479. // start margin and end margin. Can be a number or a percent string.
  58480. // Auto margin by defualt.
  58481. symbolRepeat: false,
  58482. // false/null/undefined, means no repeat.
  58483. // Can be true, means auto calculate repeat times and cut by data.
  58484. // Can be a number, specifies repeat times, and do not cut by data.
  58485. // Can be 'fixed', means auto calculate repeat times but do not cut by data.
  58486. symbolRepeatDirection: 'end',
  58487. // 'end' means from 'start' to 'end'.
  58488. symbolClip: false,
  58489. symbolBoundingData: null,
  58490. // Can be 60 or -40 or [-40, 60]
  58491. symbolPatternSize: 400,
  58492. // 400 * 400 px
  58493. barGap: '-100%',
  58494. // In most case, overlap is needed.
  58495. // z can be set in data item, which is z2 actually.
  58496. // Disable progressive
  58497. progressive: 0,
  58498. hoverAnimation: false // Open only when needed.
  58499. },
  58500. getInitialData: function (option) {
  58501. // Disable stack.
  58502. option.stack = null;
  58503. return PictorialBarSeries.superApply(this, 'getInitialData', arguments);
  58504. }
  58505. });
  58506. /*
  58507. * Licensed to the Apache Software Foundation (ASF) under one
  58508. * or more contributor license agreements. See the NOTICE file
  58509. * distributed with this work for additional information
  58510. * regarding copyright ownership. The ASF licenses this file
  58511. * to you under the Apache License, Version 2.0 (the
  58512. * "License"); you may not use this file except in compliance
  58513. * with the License. You may obtain a copy of the License at
  58514. *
  58515. * http://www.apache.org/licenses/LICENSE-2.0
  58516. *
  58517. * Unless required by applicable law or agreed to in writing,
  58518. * software distributed under the License is distributed on an
  58519. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  58520. * KIND, either express or implied. See the License for the
  58521. * specific language governing permissions and limitations
  58522. * under the License.
  58523. */
  58524. var BAR_BORDER_WIDTH_QUERY$1 = ['itemStyle', 'borderWidth']; // index: +isHorizontal
  58525. var LAYOUT_ATTRS = [{
  58526. xy: 'x',
  58527. wh: 'width',
  58528. index: 0,
  58529. posDesc: ['left', 'right']
  58530. }, {
  58531. xy: 'y',
  58532. wh: 'height',
  58533. index: 1,
  58534. posDesc: ['top', 'bottom']
  58535. }];
  58536. var pathForLineWidth = new Circle();
  58537. var BarView$1 = extendChartView({
  58538. type: 'pictorialBar',
  58539. render: function (seriesModel, ecModel, api) {
  58540. var group = this.group;
  58541. var data = seriesModel.getData();
  58542. var oldData = this._data;
  58543. var cartesian = seriesModel.coordinateSystem;
  58544. var baseAxis = cartesian.getBaseAxis();
  58545. var isHorizontal = !!baseAxis.isHorizontal();
  58546. var coordSysRect = cartesian.grid.getRect();
  58547. var opt = {
  58548. ecSize: {
  58549. width: api.getWidth(),
  58550. height: api.getHeight()
  58551. },
  58552. seriesModel: seriesModel,
  58553. coordSys: cartesian,
  58554. coordSysExtent: [[coordSysRect.x, coordSysRect.x + coordSysRect.width], [coordSysRect.y, coordSysRect.y + coordSysRect.height]],
  58555. isHorizontal: isHorizontal,
  58556. valueDim: LAYOUT_ATTRS[+isHorizontal],
  58557. categoryDim: LAYOUT_ATTRS[1 - isHorizontal]
  58558. };
  58559. data.diff(oldData).add(function (dataIndex) {
  58560. if (!data.hasValue(dataIndex)) {
  58561. return;
  58562. }
  58563. var itemModel = getItemModel(data, dataIndex);
  58564. var symbolMeta = getSymbolMeta(data, dataIndex, itemModel, opt);
  58565. var bar = createBar(data, opt, symbolMeta);
  58566. data.setItemGraphicEl(dataIndex, bar);
  58567. group.add(bar);
  58568. updateCommon$1(bar, opt, symbolMeta);
  58569. }).update(function (newIndex, oldIndex) {
  58570. var bar = oldData.getItemGraphicEl(oldIndex);
  58571. if (!data.hasValue(newIndex)) {
  58572. group.remove(bar);
  58573. return;
  58574. }
  58575. var itemModel = getItemModel(data, newIndex);
  58576. var symbolMeta = getSymbolMeta(data, newIndex, itemModel, opt);
  58577. var pictorialShapeStr = getShapeStr(data, symbolMeta);
  58578. if (bar && pictorialShapeStr !== bar.__pictorialShapeStr) {
  58579. group.remove(bar);
  58580. data.setItemGraphicEl(newIndex, null);
  58581. bar = null;
  58582. }
  58583. if (bar) {
  58584. updateBar(bar, opt, symbolMeta);
  58585. } else {
  58586. bar = createBar(data, opt, symbolMeta, true);
  58587. }
  58588. data.setItemGraphicEl(newIndex, bar);
  58589. bar.__pictorialSymbolMeta = symbolMeta; // Add back
  58590. group.add(bar);
  58591. updateCommon$1(bar, opt, symbolMeta);
  58592. }).remove(function (dataIndex) {
  58593. var bar = oldData.getItemGraphicEl(dataIndex);
  58594. bar && removeBar(oldData, dataIndex, bar.__pictorialSymbolMeta.animationModel, bar);
  58595. }).execute();
  58596. this._data = data;
  58597. return this.group;
  58598. },
  58599. dispose: noop,
  58600. remove: function (ecModel, api) {
  58601. var group = this.group;
  58602. var data = this._data;
  58603. if (ecModel.get('animation')) {
  58604. if (data) {
  58605. data.eachItemGraphicEl(function (bar) {
  58606. removeBar(data, bar.dataIndex, ecModel, bar);
  58607. });
  58608. }
  58609. } else {
  58610. group.removeAll();
  58611. }
  58612. }
  58613. }); // Set or calculate default value about symbol, and calculate layout info.
  58614. function getSymbolMeta(data, dataIndex, itemModel, opt) {
  58615. var layout = data.getItemLayout(dataIndex);
  58616. var symbolRepeat = itemModel.get('symbolRepeat');
  58617. var symbolClip = itemModel.get('symbolClip');
  58618. var symbolPosition = itemModel.get('symbolPosition') || 'start';
  58619. var symbolRotate = itemModel.get('symbolRotate');
  58620. var rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  58621. var symbolPatternSize = itemModel.get('symbolPatternSize') || 2;
  58622. var isAnimationEnabled = itemModel.isAnimationEnabled();
  58623. var symbolMeta = {
  58624. dataIndex: dataIndex,
  58625. layout: layout,
  58626. itemModel: itemModel,
  58627. symbolType: data.getItemVisual(dataIndex, 'symbol') || 'circle',
  58628. color: data.getItemVisual(dataIndex, 'color'),
  58629. symbolClip: symbolClip,
  58630. symbolRepeat: symbolRepeat,
  58631. symbolRepeatDirection: itemModel.get('symbolRepeatDirection'),
  58632. symbolPatternSize: symbolPatternSize,
  58633. rotation: rotation,
  58634. animationModel: isAnimationEnabled ? itemModel : null,
  58635. hoverAnimation: isAnimationEnabled && itemModel.get('hoverAnimation'),
  58636. z2: itemModel.getShallow('z', true) || 0
  58637. };
  58638. prepareBarLength(itemModel, symbolRepeat, layout, opt, symbolMeta);
  58639. prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, symbolMeta.boundingLength, symbolMeta.pxSign, symbolPatternSize, opt, symbolMeta);
  58640. prepareLineWidth(itemModel, symbolMeta.symbolScale, rotation, opt, symbolMeta);
  58641. var symbolSize = symbolMeta.symbolSize;
  58642. var symbolOffset = itemModel.get('symbolOffset');
  58643. if (isArray(symbolOffset)) {
  58644. symbolOffset = [parsePercent$1(symbolOffset[0], symbolSize[0]), parsePercent$1(symbolOffset[1], symbolSize[1])];
  58645. }
  58646. prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, symbolMeta.valueLineWidth, symbolMeta.boundingLength, symbolMeta.repeatCutLength, opt, symbolMeta);
  58647. return symbolMeta;
  58648. } // bar length can be negative.
  58649. function prepareBarLength(itemModel, symbolRepeat, layout, opt, output) {
  58650. var valueDim = opt.valueDim;
  58651. var symbolBoundingData = itemModel.get('symbolBoundingData');
  58652. var valueAxis = opt.coordSys.getOtherAxis(opt.coordSys.getBaseAxis());
  58653. var zeroPx = valueAxis.toGlobalCoord(valueAxis.dataToCoord(0));
  58654. var pxSignIdx = 1 - +(layout[valueDim.wh] <= 0);
  58655. var boundingLength;
  58656. if (isArray(symbolBoundingData)) {
  58657. var symbolBoundingExtent = [convertToCoordOnAxis(valueAxis, symbolBoundingData[0]) - zeroPx, convertToCoordOnAxis(valueAxis, symbolBoundingData[1]) - zeroPx];
  58658. symbolBoundingExtent[1] < symbolBoundingExtent[0] && symbolBoundingExtent.reverse();
  58659. boundingLength = symbolBoundingExtent[pxSignIdx];
  58660. } else if (symbolBoundingData != null) {
  58661. boundingLength = convertToCoordOnAxis(valueAxis, symbolBoundingData) - zeroPx;
  58662. } else if (symbolRepeat) {
  58663. boundingLength = opt.coordSysExtent[valueDim.index][pxSignIdx] - zeroPx;
  58664. } else {
  58665. boundingLength = layout[valueDim.wh];
  58666. }
  58667. output.boundingLength = boundingLength;
  58668. if (symbolRepeat) {
  58669. output.repeatCutLength = layout[valueDim.wh];
  58670. }
  58671. output.pxSign = boundingLength > 0 ? 1 : boundingLength < 0 ? -1 : 0;
  58672. }
  58673. function convertToCoordOnAxis(axis, value) {
  58674. return axis.toGlobalCoord(axis.dataToCoord(axis.scale.parse(value)));
  58675. } // Support ['100%', '100%']
  58676. function prepareSymbolSize(data, dataIndex, layout, symbolRepeat, symbolClip, boundingLength, pxSign, symbolPatternSize, opt, output) {
  58677. var valueDim = opt.valueDim;
  58678. var categoryDim = opt.categoryDim;
  58679. var categorySize = Math.abs(layout[categoryDim.wh]);
  58680. var symbolSize = data.getItemVisual(dataIndex, 'symbolSize');
  58681. if (isArray(symbolSize)) {
  58682. symbolSize = symbolSize.slice();
  58683. } else {
  58684. if (symbolSize == null) {
  58685. symbolSize = '100%';
  58686. }
  58687. symbolSize = [symbolSize, symbolSize];
  58688. } // Note: percentage symbolSize (like '100%') do not consider lineWidth, because it is
  58689. // to complicated to calculate real percent value if considering scaled lineWidth.
  58690. // So the actual size will bigger than layout size if lineWidth is bigger than zero,
  58691. // which can be tolerated in pictorial chart.
  58692. symbolSize[categoryDim.index] = parsePercent$1(symbolSize[categoryDim.index], categorySize);
  58693. symbolSize[valueDim.index] = parsePercent$1(symbolSize[valueDim.index], symbolRepeat ? categorySize : Math.abs(boundingLength));
  58694. output.symbolSize = symbolSize; // If x or y is less than zero, show reversed shape.
  58695. var symbolScale = output.symbolScale = [symbolSize[0] / symbolPatternSize, symbolSize[1] / symbolPatternSize]; // Follow convention, 'right' and 'top' is the normal scale.
  58696. symbolScale[valueDim.index] *= (opt.isHorizontal ? -1 : 1) * pxSign;
  58697. }
  58698. function prepareLineWidth(itemModel, symbolScale, rotation, opt, output) {
  58699. // In symbols are drawn with scale, so do not need to care about the case that width
  58700. // or height are too small. But symbol use strokeNoScale, where acture lineWidth should
  58701. // be calculated.
  58702. var valueLineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY$1) || 0;
  58703. if (valueLineWidth) {
  58704. pathForLineWidth.attr({
  58705. scale: symbolScale.slice(),
  58706. rotation: rotation
  58707. });
  58708. pathForLineWidth.updateTransform();
  58709. valueLineWidth /= pathForLineWidth.getLineScale();
  58710. valueLineWidth *= symbolScale[opt.valueDim.index];
  58711. }
  58712. output.valueLineWidth = valueLineWidth;
  58713. }
  58714. function prepareLayoutInfo(itemModel, symbolSize, layout, symbolRepeat, symbolClip, symbolOffset, symbolPosition, valueLineWidth, boundingLength, repeatCutLength, opt, output) {
  58715. var categoryDim = opt.categoryDim;
  58716. var valueDim = opt.valueDim;
  58717. var pxSign = output.pxSign;
  58718. var unitLength = Math.max(symbolSize[valueDim.index] + valueLineWidth, 0);
  58719. var pathLen = unitLength; // Note: rotation will not effect the layout of symbols, because user may
  58720. // want symbols to rotate on its center, which should not be translated
  58721. // when rotating.
  58722. if (symbolRepeat) {
  58723. var absBoundingLength = Math.abs(boundingLength);
  58724. var symbolMargin = retrieve(itemModel.get('symbolMargin'), '15%') + '';
  58725. var hasEndGap = false;
  58726. if (symbolMargin.lastIndexOf('!') === symbolMargin.length - 1) {
  58727. hasEndGap = true;
  58728. symbolMargin = symbolMargin.slice(0, symbolMargin.length - 1);
  58729. }
  58730. symbolMargin = parsePercent$1(symbolMargin, symbolSize[valueDim.index]);
  58731. var uLenWithMargin = Math.max(unitLength + symbolMargin * 2, 0); // When symbol margin is less than 0, margin at both ends will be subtracted
  58732. // to ensure that all of the symbols will not be overflow the given area.
  58733. var endFix = hasEndGap ? 0 : symbolMargin * 2; // Both final repeatTimes and final symbolMargin area calculated based on
  58734. // boundingLength.
  58735. var repeatSpecified = isNumeric(symbolRepeat);
  58736. var repeatTimes = repeatSpecified ? symbolRepeat : toIntTimes((absBoundingLength + endFix) / uLenWithMargin); // Adjust calculate margin, to ensure each symbol is displayed
  58737. // entirely in the given layout area.
  58738. var mDiff = absBoundingLength - repeatTimes * unitLength;
  58739. symbolMargin = mDiff / 2 / (hasEndGap ? repeatTimes : repeatTimes - 1);
  58740. uLenWithMargin = unitLength + symbolMargin * 2;
  58741. endFix = hasEndGap ? 0 : symbolMargin * 2; // Update repeatTimes when not all symbol will be shown.
  58742. if (!repeatSpecified && symbolRepeat !== 'fixed') {
  58743. repeatTimes = repeatCutLength ? toIntTimes((Math.abs(repeatCutLength) + endFix) / uLenWithMargin) : 0;
  58744. }
  58745. pathLen = repeatTimes * uLenWithMargin - endFix;
  58746. output.repeatTimes = repeatTimes;
  58747. output.symbolMargin = symbolMargin;
  58748. }
  58749. var sizeFix = pxSign * (pathLen / 2);
  58750. var pathPosition = output.pathPosition = [];
  58751. pathPosition[categoryDim.index] = layout[categoryDim.wh] / 2;
  58752. pathPosition[valueDim.index] = symbolPosition === 'start' ? sizeFix : symbolPosition === 'end' ? boundingLength - sizeFix : boundingLength / 2; // 'center'
  58753. if (symbolOffset) {
  58754. pathPosition[0] += symbolOffset[0];
  58755. pathPosition[1] += symbolOffset[1];
  58756. }
  58757. var bundlePosition = output.bundlePosition = [];
  58758. bundlePosition[categoryDim.index] = layout[categoryDim.xy];
  58759. bundlePosition[valueDim.index] = layout[valueDim.xy];
  58760. var barRectShape = output.barRectShape = extend({}, layout);
  58761. barRectShape[valueDim.wh] = pxSign * Math.max(Math.abs(layout[valueDim.wh]), Math.abs(pathPosition[valueDim.index] + sizeFix));
  58762. barRectShape[categoryDim.wh] = layout[categoryDim.wh];
  58763. var clipShape = output.clipShape = {}; // Consider that symbol may be overflow layout rect.
  58764. clipShape[categoryDim.xy] = -layout[categoryDim.xy];
  58765. clipShape[categoryDim.wh] = opt.ecSize[categoryDim.wh];
  58766. clipShape[valueDim.xy] = 0;
  58767. clipShape[valueDim.wh] = layout[valueDim.wh];
  58768. }
  58769. function createPath(symbolMeta) {
  58770. var symbolPatternSize = symbolMeta.symbolPatternSize;
  58771. var path = createSymbol( // Consider texture img, make a big size.
  58772. symbolMeta.symbolType, -symbolPatternSize / 2, -symbolPatternSize / 2, symbolPatternSize, symbolPatternSize, symbolMeta.color);
  58773. path.attr({
  58774. culling: true
  58775. });
  58776. path.type !== 'image' && path.setStyle({
  58777. strokeNoScale: true
  58778. });
  58779. return path;
  58780. }
  58781. function createOrUpdateRepeatSymbols(bar, opt, symbolMeta, isUpdate) {
  58782. var bundle = bar.__pictorialBundle;
  58783. var symbolSize = symbolMeta.symbolSize;
  58784. var valueLineWidth = symbolMeta.valueLineWidth;
  58785. var pathPosition = symbolMeta.pathPosition;
  58786. var valueDim = opt.valueDim;
  58787. var repeatTimes = symbolMeta.repeatTimes || 0;
  58788. var index = 0;
  58789. var unit = symbolSize[opt.valueDim.index] + valueLineWidth + symbolMeta.symbolMargin * 2;
  58790. eachPath(bar, function (path) {
  58791. path.__pictorialAnimationIndex = index;
  58792. path.__pictorialRepeatTimes = repeatTimes;
  58793. if (index < repeatTimes) {
  58794. updateAttr(path, null, makeTarget(index), symbolMeta, isUpdate);
  58795. } else {
  58796. updateAttr(path, null, {
  58797. scale: [0, 0]
  58798. }, symbolMeta, isUpdate, function () {
  58799. bundle.remove(path);
  58800. });
  58801. }
  58802. updateHoverAnimation(path, symbolMeta);
  58803. index++;
  58804. });
  58805. for (; index < repeatTimes; index++) {
  58806. var path = createPath(symbolMeta);
  58807. path.__pictorialAnimationIndex = index;
  58808. path.__pictorialRepeatTimes = repeatTimes;
  58809. bundle.add(path);
  58810. var target = makeTarget(index);
  58811. updateAttr(path, {
  58812. position: target.position,
  58813. scale: [0, 0]
  58814. }, {
  58815. scale: target.scale,
  58816. rotation: target.rotation
  58817. }, symbolMeta, isUpdate); // FIXME
  58818. // If all emphasis/normal through action.
  58819. path.on('mouseover', onMouseOver).on('mouseout', onMouseOut);
  58820. updateHoverAnimation(path, symbolMeta);
  58821. }
  58822. function makeTarget(index) {
  58823. var position = pathPosition.slice(); // (start && pxSign > 0) || (end && pxSign < 0): i = repeatTimes - index
  58824. // Otherwise: i = index;
  58825. var pxSign = symbolMeta.pxSign;
  58826. var i = index;
  58827. if (symbolMeta.symbolRepeatDirection === 'start' ? pxSign > 0 : pxSign < 0) {
  58828. i = repeatTimes - 1 - index;
  58829. }
  58830. position[valueDim.index] = unit * (i - repeatTimes / 2 + 0.5) + pathPosition[valueDim.index];
  58831. return {
  58832. position: position,
  58833. scale: symbolMeta.symbolScale.slice(),
  58834. rotation: symbolMeta.rotation
  58835. };
  58836. }
  58837. function onMouseOver() {
  58838. eachPath(bar, function (path) {
  58839. path.trigger('emphasis');
  58840. });
  58841. }
  58842. function onMouseOut() {
  58843. eachPath(bar, function (path) {
  58844. path.trigger('normal');
  58845. });
  58846. }
  58847. }
  58848. function createOrUpdateSingleSymbol(bar, opt, symbolMeta, isUpdate) {
  58849. var bundle = bar.__pictorialBundle;
  58850. var mainPath = bar.__pictorialMainPath;
  58851. if (!mainPath) {
  58852. mainPath = bar.__pictorialMainPath = createPath(symbolMeta);
  58853. bundle.add(mainPath);
  58854. updateAttr(mainPath, {
  58855. position: symbolMeta.pathPosition.slice(),
  58856. scale: [0, 0],
  58857. rotation: symbolMeta.rotation
  58858. }, {
  58859. scale: symbolMeta.symbolScale.slice()
  58860. }, symbolMeta, isUpdate);
  58861. mainPath.on('mouseover', onMouseOver).on('mouseout', onMouseOut);
  58862. } else {
  58863. updateAttr(mainPath, null, {
  58864. position: symbolMeta.pathPosition.slice(),
  58865. scale: symbolMeta.symbolScale.slice(),
  58866. rotation: symbolMeta.rotation
  58867. }, symbolMeta, isUpdate);
  58868. }
  58869. updateHoverAnimation(mainPath, symbolMeta);
  58870. function onMouseOver() {
  58871. this.trigger('emphasis');
  58872. }
  58873. function onMouseOut() {
  58874. this.trigger('normal');
  58875. }
  58876. } // bar rect is used for label.
  58877. function createOrUpdateBarRect(bar, symbolMeta, isUpdate) {
  58878. var rectShape = extend({}, symbolMeta.barRectShape);
  58879. var barRect = bar.__pictorialBarRect;
  58880. if (!barRect) {
  58881. barRect = bar.__pictorialBarRect = new Rect({
  58882. z2: 2,
  58883. shape: rectShape,
  58884. silent: true,
  58885. style: {
  58886. stroke: 'transparent',
  58887. fill: 'transparent',
  58888. lineWidth: 0
  58889. }
  58890. });
  58891. bar.add(barRect);
  58892. } else {
  58893. updateAttr(barRect, null, {
  58894. shape: rectShape
  58895. }, symbolMeta, isUpdate);
  58896. }
  58897. }
  58898. function createOrUpdateClip(bar, opt, symbolMeta, isUpdate) {
  58899. // If not clip, symbol will be remove and rebuilt.
  58900. if (symbolMeta.symbolClip) {
  58901. var clipPath = bar.__pictorialClipPath;
  58902. var clipShape = extend({}, symbolMeta.clipShape);
  58903. var valueDim = opt.valueDim;
  58904. var animationModel = symbolMeta.animationModel;
  58905. var dataIndex = symbolMeta.dataIndex;
  58906. if (clipPath) {
  58907. updateProps(clipPath, {
  58908. shape: clipShape
  58909. }, animationModel, dataIndex);
  58910. } else {
  58911. clipShape[valueDim.wh] = 0;
  58912. clipPath = new Rect({
  58913. shape: clipShape
  58914. });
  58915. bar.__pictorialBundle.setClipPath(clipPath);
  58916. bar.__pictorialClipPath = clipPath;
  58917. var target = {};
  58918. target[valueDim.wh] = symbolMeta.clipShape[valueDim.wh];
  58919. graphic[isUpdate ? 'updateProps' : 'initProps'](clipPath, {
  58920. shape: target
  58921. }, animationModel, dataIndex);
  58922. }
  58923. }
  58924. }
  58925. function getItemModel(data, dataIndex) {
  58926. var itemModel = data.getItemModel(dataIndex);
  58927. itemModel.getAnimationDelayParams = getAnimationDelayParams;
  58928. itemModel.isAnimationEnabled = isAnimationEnabled;
  58929. return itemModel;
  58930. }
  58931. function getAnimationDelayParams(path) {
  58932. // The order is the same as the z-order, see `symbolRepeatDiretion`.
  58933. return {
  58934. index: path.__pictorialAnimationIndex,
  58935. count: path.__pictorialRepeatTimes
  58936. };
  58937. }
  58938. function isAnimationEnabled() {
  58939. // `animation` prop can be set on itemModel in pictorial bar chart.
  58940. return this.parentModel.isAnimationEnabled() && !!this.getShallow('animation');
  58941. }
  58942. function updateHoverAnimation(path, symbolMeta) {
  58943. path.off('emphasis').off('normal');
  58944. var scale = symbolMeta.symbolScale.slice();
  58945. symbolMeta.hoverAnimation && path.on('emphasis', function () {
  58946. this.animateTo({
  58947. scale: [scale[0] * 1.1, scale[1] * 1.1]
  58948. }, 400, 'elasticOut');
  58949. }).on('normal', function () {
  58950. this.animateTo({
  58951. scale: scale.slice()
  58952. }, 400, 'elasticOut');
  58953. });
  58954. }
  58955. function createBar(data, opt, symbolMeta, isUpdate) {
  58956. // bar is the main element for each data.
  58957. var bar = new Group(); // bundle is used for location and clip.
  58958. var bundle = new Group();
  58959. bar.add(bundle);
  58960. bar.__pictorialBundle = bundle;
  58961. bundle.attr('position', symbolMeta.bundlePosition.slice());
  58962. if (symbolMeta.symbolRepeat) {
  58963. createOrUpdateRepeatSymbols(bar, opt, symbolMeta);
  58964. } else {
  58965. createOrUpdateSingleSymbol(bar, opt, symbolMeta);
  58966. }
  58967. createOrUpdateBarRect(bar, symbolMeta, isUpdate);
  58968. createOrUpdateClip(bar, opt, symbolMeta, isUpdate);
  58969. bar.__pictorialShapeStr = getShapeStr(data, symbolMeta);
  58970. bar.__pictorialSymbolMeta = symbolMeta;
  58971. return bar;
  58972. }
  58973. function updateBar(bar, opt, symbolMeta) {
  58974. var animationModel = symbolMeta.animationModel;
  58975. var dataIndex = symbolMeta.dataIndex;
  58976. var bundle = bar.__pictorialBundle;
  58977. updateProps(bundle, {
  58978. position: symbolMeta.bundlePosition.slice()
  58979. }, animationModel, dataIndex);
  58980. if (symbolMeta.symbolRepeat) {
  58981. createOrUpdateRepeatSymbols(bar, opt, symbolMeta, true);
  58982. } else {
  58983. createOrUpdateSingleSymbol(bar, opt, symbolMeta, true);
  58984. }
  58985. createOrUpdateBarRect(bar, symbolMeta, true);
  58986. createOrUpdateClip(bar, opt, symbolMeta, true);
  58987. }
  58988. function removeBar(data, dataIndex, animationModel, bar) {
  58989. // Not show text when animating
  58990. var labelRect = bar.__pictorialBarRect;
  58991. labelRect && (labelRect.style.text = null);
  58992. var pathes = [];
  58993. eachPath(bar, function (path) {
  58994. pathes.push(path);
  58995. });
  58996. bar.__pictorialMainPath && pathes.push(bar.__pictorialMainPath); // I do not find proper remove animation for clip yet.
  58997. bar.__pictorialClipPath && (animationModel = null);
  58998. each$1(pathes, function (path) {
  58999. updateProps(path, {
  59000. scale: [0, 0]
  59001. }, animationModel, dataIndex, function () {
  59002. bar.parent && bar.parent.remove(bar);
  59003. });
  59004. });
  59005. data.setItemGraphicEl(dataIndex, null);
  59006. }
  59007. function getShapeStr(data, symbolMeta) {
  59008. return [data.getItemVisual(symbolMeta.dataIndex, 'symbol') || 'none', !!symbolMeta.symbolRepeat, !!symbolMeta.symbolClip].join(':');
  59009. }
  59010. function eachPath(bar, cb, context) {
  59011. // Do not use Group#eachChild, because it do not support remove.
  59012. each$1(bar.__pictorialBundle.children(), function (el) {
  59013. el !== bar.__pictorialBarRect && cb.call(context, el);
  59014. });
  59015. }
  59016. function updateAttr(el, immediateAttrs, animationAttrs, symbolMeta, isUpdate, cb) {
  59017. immediateAttrs && el.attr(immediateAttrs); // when symbolCip used, only clip path has init animation, otherwise it would be weird effect.
  59018. if (symbolMeta.symbolClip && !isUpdate) {
  59019. animationAttrs && el.attr(animationAttrs);
  59020. } else {
  59021. animationAttrs && graphic[isUpdate ? 'updateProps' : 'initProps'](el, animationAttrs, symbolMeta.animationModel, symbolMeta.dataIndex, cb);
  59022. }
  59023. }
  59024. function updateCommon$1(bar, opt, symbolMeta) {
  59025. var color = symbolMeta.color;
  59026. var dataIndex = symbolMeta.dataIndex;
  59027. var itemModel = symbolMeta.itemModel; // Color must be excluded.
  59028. // Because symbol provide setColor individually to set fill and stroke
  59029. var normalStyle = itemModel.getModel('itemStyle').getItemStyle(['color']);
  59030. var hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  59031. var cursorStyle = itemModel.getShallow('cursor');
  59032. eachPath(bar, function (path) {
  59033. // PENDING setColor should be before setStyle!!!
  59034. path.setColor(color);
  59035. path.setStyle(defaults({
  59036. fill: color,
  59037. opacity: symbolMeta.opacity
  59038. }, normalStyle));
  59039. setHoverStyle(path, hoverStyle);
  59040. cursorStyle && (path.cursor = cursorStyle);
  59041. path.z2 = symbolMeta.z2;
  59042. });
  59043. var barRectHoverStyle = {};
  59044. var barPositionOutside = opt.valueDim.posDesc[+(symbolMeta.boundingLength > 0)];
  59045. var barRect = bar.__pictorialBarRect;
  59046. setLabel(barRect.style, barRectHoverStyle, itemModel, color, opt.seriesModel, dataIndex, barPositionOutside);
  59047. setHoverStyle(barRect, barRectHoverStyle);
  59048. }
  59049. function toIntTimes(times) {
  59050. var roundedTimes = Math.round(times); // Escapse accurate error
  59051. return Math.abs(times - roundedTimes) < 1e-4 ? roundedTimes : Math.ceil(times);
  59052. }
  59053. /*
  59054. * Licensed to the Apache Software Foundation (ASF) under one
  59055. * or more contributor license agreements. See the NOTICE file
  59056. * distributed with this work for additional information
  59057. * regarding copyright ownership. The ASF licenses this file
  59058. * to you under the Apache License, Version 2.0 (the
  59059. * "License"); you may not use this file except in compliance
  59060. * with the License. You may obtain a copy of the License at
  59061. *
  59062. * http://www.apache.org/licenses/LICENSE-2.0
  59063. *
  59064. * Unless required by applicable law or agreed to in writing,
  59065. * software distributed under the License is distributed on an
  59066. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59067. * KIND, either express or implied. See the License for the
  59068. * specific language governing permissions and limitations
  59069. * under the License.
  59070. */
  59071. registerLayout(curry(layout, 'pictorialBar'));
  59072. registerVisual(visualSymbol('pictorialBar', 'roundRect'));
  59073. /*
  59074. * Licensed to the Apache Software Foundation (ASF) under one
  59075. * or more contributor license agreements. See the NOTICE file
  59076. * distributed with this work for additional information
  59077. * regarding copyright ownership. The ASF licenses this file
  59078. * to you under the Apache License, Version 2.0 (the
  59079. * "License"); you may not use this file except in compliance
  59080. * with the License. You may obtain a copy of the License at
  59081. *
  59082. * http://www.apache.org/licenses/LICENSE-2.0
  59083. *
  59084. * Unless required by applicable law or agreed to in writing,
  59085. * software distributed under the License is distributed on an
  59086. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59087. * KIND, either express or implied. See the License for the
  59088. * specific language governing permissions and limitations
  59089. * under the License.
  59090. */
  59091. function dataToCoordSize(dataSize, dataItem) {
  59092. // dataItem is necessary in log axis.
  59093. dataItem = dataItem || [0, 0];
  59094. return map(['x', 'y'], function (dim, dimIdx) {
  59095. var axis = this.getAxis(dim);
  59096. var val = dataItem[dimIdx];
  59097. var halfSize = dataSize[dimIdx] / 2;
  59098. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  59099. }, this);
  59100. }
  59101. var prepareCartesian2d = function (coordSys) {
  59102. var rect = coordSys.grid.getRect();
  59103. return {
  59104. coordSys: {
  59105. // The name exposed to user is always 'cartesian2d' but not 'grid'.
  59106. type: 'cartesian2d',
  59107. x: rect.x,
  59108. y: rect.y,
  59109. width: rect.width,
  59110. height: rect.height
  59111. },
  59112. api: {
  59113. coord: function (data) {
  59114. // do not provide "out" param
  59115. return coordSys.dataToPoint(data);
  59116. },
  59117. size: bind(dataToCoordSize, coordSys)
  59118. }
  59119. };
  59120. };
  59121. /*
  59122. * Licensed to the Apache Software Foundation (ASF) under one
  59123. * or more contributor license agreements. See the NOTICE file
  59124. * distributed with this work for additional information
  59125. * regarding copyright ownership. The ASF licenses this file
  59126. * to you under the Apache License, Version 2.0 (the
  59127. * "License"); you may not use this file except in compliance
  59128. * with the License. You may obtain a copy of the License at
  59129. *
  59130. * http://www.apache.org/licenses/LICENSE-2.0
  59131. *
  59132. * Unless required by applicable law or agreed to in writing,
  59133. * software distributed under the License is distributed on an
  59134. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59135. * KIND, either express or implied. See the License for the
  59136. * specific language governing permissions and limitations
  59137. * under the License.
  59138. */
  59139. function dataToCoordSize$1(dataSize, dataItem) {
  59140. dataItem = dataItem || [0, 0];
  59141. return map([0, 1], function (dimIdx) {
  59142. var val = dataItem[dimIdx];
  59143. var halfSize = dataSize[dimIdx] / 2;
  59144. var p1 = [];
  59145. var p2 = [];
  59146. p1[dimIdx] = val - halfSize;
  59147. p2[dimIdx] = val + halfSize;
  59148. p1[1 - dimIdx] = p2[1 - dimIdx] = dataItem[1 - dimIdx];
  59149. return Math.abs(this.dataToPoint(p1)[dimIdx] - this.dataToPoint(p2)[dimIdx]);
  59150. }, this);
  59151. }
  59152. var prepareGeo = function (coordSys) {
  59153. var rect = coordSys.getBoundingRect();
  59154. return {
  59155. coordSys: {
  59156. type: 'geo',
  59157. x: rect.x,
  59158. y: rect.y,
  59159. width: rect.width,
  59160. height: rect.height,
  59161. zoom: coordSys.getZoom()
  59162. },
  59163. api: {
  59164. coord: function (data) {
  59165. // do not provide "out" and noRoam param,
  59166. // Compatible with this usage:
  59167. // echarts.util.map(item.points, api.coord)
  59168. return coordSys.dataToPoint(data);
  59169. },
  59170. size: bind(dataToCoordSize$1, coordSys)
  59171. }
  59172. };
  59173. };
  59174. /*
  59175. * Licensed to the Apache Software Foundation (ASF) under one
  59176. * or more contributor license agreements. See the NOTICE file
  59177. * distributed with this work for additional information
  59178. * regarding copyright ownership. The ASF licenses this file
  59179. * to you under the Apache License, Version 2.0 (the
  59180. * "License"); you may not use this file except in compliance
  59181. * with the License. You may obtain a copy of the License at
  59182. *
  59183. * http://www.apache.org/licenses/LICENSE-2.0
  59184. *
  59185. * Unless required by applicable law or agreed to in writing,
  59186. * software distributed under the License is distributed on an
  59187. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59188. * KIND, either express or implied. See the License for the
  59189. * specific language governing permissions and limitations
  59190. * under the License.
  59191. */
  59192. function dataToCoordSize$2(dataSize, dataItem) {
  59193. // dataItem is necessary in log axis.
  59194. var axis = this.getAxis();
  59195. var val = dataItem instanceof Array ? dataItem[0] : dataItem;
  59196. var halfSize = (dataSize instanceof Array ? dataSize[0] : dataSize) / 2;
  59197. return axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis.dataToCoord(val - halfSize) - axis.dataToCoord(val + halfSize));
  59198. }
  59199. var prepareSingleAxis = function (coordSys) {
  59200. var rect = coordSys.getRect();
  59201. return {
  59202. coordSys: {
  59203. type: 'singleAxis',
  59204. x: rect.x,
  59205. y: rect.y,
  59206. width: rect.width,
  59207. height: rect.height
  59208. },
  59209. api: {
  59210. coord: function (val) {
  59211. // do not provide "out" param
  59212. return coordSys.dataToPoint(val);
  59213. },
  59214. size: bind(dataToCoordSize$2, coordSys)
  59215. }
  59216. };
  59217. };
  59218. /*
  59219. * Licensed to the Apache Software Foundation (ASF) under one
  59220. * or more contributor license agreements. See the NOTICE file
  59221. * distributed with this work for additional information
  59222. * regarding copyright ownership. The ASF licenses this file
  59223. * to you under the Apache License, Version 2.0 (the
  59224. * "License"); you may not use this file except in compliance
  59225. * with the License. You may obtain a copy of the License at
  59226. *
  59227. * http://www.apache.org/licenses/LICENSE-2.0
  59228. *
  59229. * Unless required by applicable law or agreed to in writing,
  59230. * software distributed under the License is distributed on an
  59231. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59232. * KIND, either express or implied. See the License for the
  59233. * specific language governing permissions and limitations
  59234. * under the License.
  59235. */
  59236. function dataToCoordSize$3(dataSize, dataItem) {
  59237. // dataItem is necessary in log axis.
  59238. return map(['Radius', 'Angle'], function (dim, dimIdx) {
  59239. var axis = this['get' + dim + 'Axis']();
  59240. var val = dataItem[dimIdx];
  59241. var halfSize = dataSize[dimIdx] / 2;
  59242. var method = 'dataTo' + dim;
  59243. var result = axis.type === 'category' ? axis.getBandWidth() : Math.abs(axis[method](val - halfSize) - axis[method](val + halfSize));
  59244. if (dim === 'Angle') {
  59245. result = result * Math.PI / 180;
  59246. }
  59247. return result;
  59248. }, this);
  59249. }
  59250. var preparePolar = function (coordSys) {
  59251. var radiusAxis = coordSys.getRadiusAxis();
  59252. var angleAxis = coordSys.getAngleAxis();
  59253. var radius = radiusAxis.getExtent();
  59254. radius[0] > radius[1] && radius.reverse();
  59255. return {
  59256. coordSys: {
  59257. type: 'polar',
  59258. cx: coordSys.cx,
  59259. cy: coordSys.cy,
  59260. r: radius[1],
  59261. r0: radius[0]
  59262. },
  59263. api: {
  59264. coord: bind(function (data) {
  59265. var radius = radiusAxis.dataToRadius(data[0]);
  59266. var angle = angleAxis.dataToAngle(data[1]);
  59267. var coord = coordSys.coordToPoint([radius, angle]);
  59268. coord.push(radius, angle * Math.PI / 180);
  59269. return coord;
  59270. }),
  59271. size: bind(dataToCoordSize$3, coordSys)
  59272. }
  59273. };
  59274. };
  59275. /*
  59276. * Licensed to the Apache Software Foundation (ASF) under one
  59277. * or more contributor license agreements. See the NOTICE file
  59278. * distributed with this work for additional information
  59279. * regarding copyright ownership. The ASF licenses this file
  59280. * to you under the Apache License, Version 2.0 (the
  59281. * "License"); you may not use this file except in compliance
  59282. * with the License. You may obtain a copy of the License at
  59283. *
  59284. * http://www.apache.org/licenses/LICENSE-2.0
  59285. *
  59286. * Unless required by applicable law or agreed to in writing,
  59287. * software distributed under the License is distributed on an
  59288. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59289. * KIND, either express or implied. See the License for the
  59290. * specific language governing permissions and limitations
  59291. * under the License.
  59292. */
  59293. var prepareCalendar = function (coordSys) {
  59294. var rect = coordSys.getRect();
  59295. var rangeInfo = coordSys.getRangeInfo();
  59296. return {
  59297. coordSys: {
  59298. type: 'calendar',
  59299. x: rect.x,
  59300. y: rect.y,
  59301. width: rect.width,
  59302. height: rect.height,
  59303. cellWidth: coordSys.getCellWidth(),
  59304. cellHeight: coordSys.getCellHeight(),
  59305. rangeInfo: {
  59306. start: rangeInfo.start,
  59307. end: rangeInfo.end,
  59308. weeks: rangeInfo.weeks,
  59309. dayCount: rangeInfo.allDay
  59310. }
  59311. },
  59312. api: {
  59313. coord: function (data, clamp) {
  59314. return coordSys.dataToPoint(data, clamp);
  59315. }
  59316. }
  59317. };
  59318. };
  59319. /*
  59320. * Licensed to the Apache Software Foundation (ASF) under one
  59321. * or more contributor license agreements. See the NOTICE file
  59322. * distributed with this work for additional information
  59323. * regarding copyright ownership. The ASF licenses this file
  59324. * to you under the Apache License, Version 2.0 (the
  59325. * "License"); you may not use this file except in compliance
  59326. * with the License. You may obtain a copy of the License at
  59327. *
  59328. * http://www.apache.org/licenses/LICENSE-2.0
  59329. *
  59330. * Unless required by applicable law or agreed to in writing,
  59331. * software distributed under the License is distributed on an
  59332. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59333. * KIND, either express or implied. See the License for the
  59334. * specific language governing permissions and limitations
  59335. * under the License.
  59336. */
  59337. var CACHED_LABEL_STYLE_PROPERTIES$1 = CACHED_LABEL_STYLE_PROPERTIES;
  59338. var ITEM_STYLE_NORMAL_PATH = ['itemStyle'];
  59339. var ITEM_STYLE_EMPHASIS_PATH = ['emphasis', 'itemStyle'];
  59340. var LABEL_NORMAL = ['label'];
  59341. var LABEL_EMPHASIS = ['emphasis', 'label']; // Use prefix to avoid index to be the same as el.name,
  59342. // which will cause weird udpate animation.
  59343. var GROUP_DIFF_PREFIX = 'e\0\0';
  59344. /**
  59345. * To reduce total package size of each coordinate systems, the modules `prepareCustom`
  59346. * of each coordinate systems are not required by each coordinate systems directly, but
  59347. * required by the module `custom`.
  59348. *
  59349. * prepareInfoForCustomSeries {Function}: optional
  59350. * @return {Object} {coordSys: {...}, api: {
  59351. * coord: function (data, clamp) {}, // return point in global.
  59352. * size: function (dataSize, dataItem) {} // return size of each axis in coordSys.
  59353. * }}
  59354. */
  59355. var prepareCustoms = {
  59356. cartesian2d: prepareCartesian2d,
  59357. geo: prepareGeo,
  59358. singleAxis: prepareSingleAxis,
  59359. polar: preparePolar,
  59360. calendar: prepareCalendar
  59361. }; // ------
  59362. // Model
  59363. // ------
  59364. SeriesModel.extend({
  59365. type: 'series.custom',
  59366. dependencies: ['grid', 'polar', 'geo', 'singleAxis', 'calendar'],
  59367. defaultOption: {
  59368. coordinateSystem: 'cartesian2d',
  59369. // Can be set as 'none'
  59370. zlevel: 0,
  59371. z: 2,
  59372. legendHoverLink: true,
  59373. useTransform: true,
  59374. // Custom series will not clip by default.
  59375. // Some case will use custom series to draw label
  59376. // For example https://echarts.apache.org/examples/en/editor.html?c=custom-gantt-flight
  59377. // Only works on polar and cartesian2d coordinate system.
  59378. clip: false // Cartesian coordinate system
  59379. // xAxisIndex: 0,
  59380. // yAxisIndex: 0,
  59381. // Polar coordinate system
  59382. // polarIndex: 0,
  59383. // Geo coordinate system
  59384. // geoIndex: 0,
  59385. // label: {}
  59386. // itemStyle: {}
  59387. },
  59388. /**
  59389. * @override
  59390. */
  59391. getInitialData: function (option, ecModel) {
  59392. return createListFromArray(this.getSource(), this);
  59393. },
  59394. /**
  59395. * @override
  59396. */
  59397. getDataParams: function (dataIndex, dataType, el) {
  59398. var params = SeriesModel.prototype.getDataParams.apply(this, arguments);
  59399. el && (params.info = el.info);
  59400. return params;
  59401. }
  59402. }); // -----
  59403. // View
  59404. // -----
  59405. Chart.extend({
  59406. type: 'custom',
  59407. /**
  59408. * @private
  59409. * @type {module:echarts/data/List}
  59410. */
  59411. _data: null,
  59412. /**
  59413. * @override
  59414. */
  59415. render: function (customSeries, ecModel, api, payload) {
  59416. var oldData = this._data;
  59417. var data = customSeries.getData();
  59418. var group = this.group;
  59419. var renderItem = makeRenderItem(customSeries, data, ecModel, api); // By default, merge mode is applied. In most cases, custom series is
  59420. // used in the scenario that data amount is not large but graphic elements
  59421. // is complicated, where merge mode is probably necessary for optimization.
  59422. // For example, reuse graphic elements and only update the transform when
  59423. // roam or data zoom according to `actionType`.
  59424. data.diff(oldData).add(function (newIdx) {
  59425. createOrUpdate$1(null, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  59426. }).update(function (newIdx, oldIdx) {
  59427. var el = oldData.getItemGraphicEl(oldIdx);
  59428. createOrUpdate$1(el, newIdx, renderItem(newIdx, payload), customSeries, group, data);
  59429. }).remove(function (oldIdx) {
  59430. var el = oldData.getItemGraphicEl(oldIdx);
  59431. el && group.remove(el);
  59432. }).execute(); // Do clipping
  59433. var clipPath = customSeries.get('clip', true) ? createClipPath(customSeries.coordinateSystem, false, customSeries) : null;
  59434. if (clipPath) {
  59435. group.setClipPath(clipPath);
  59436. } else {
  59437. group.removeClipPath();
  59438. }
  59439. this._data = data;
  59440. },
  59441. incrementalPrepareRender: function (customSeries, ecModel, api) {
  59442. this.group.removeAll();
  59443. this._data = null;
  59444. },
  59445. incrementalRender: function (params, customSeries, ecModel, api, payload) {
  59446. var data = customSeries.getData();
  59447. var renderItem = makeRenderItem(customSeries, data, ecModel, api);
  59448. function setIncrementalAndHoverLayer(el) {
  59449. if (!el.isGroup) {
  59450. el.incremental = true;
  59451. el.useHoverLayer = true;
  59452. }
  59453. }
  59454. for (var idx = params.start; idx < params.end; idx++) {
  59455. var el = createOrUpdate$1(null, idx, renderItem(idx, payload), customSeries, this.group, data);
  59456. el.traverse(setIncrementalAndHoverLayer);
  59457. }
  59458. },
  59459. /**
  59460. * @override
  59461. */
  59462. dispose: noop,
  59463. /**
  59464. * @override
  59465. */
  59466. filterForExposedEvent: function (eventType, query, targetEl, packedEvent) {
  59467. var elementName = query.element;
  59468. if (elementName == null || targetEl.name === elementName) {
  59469. return true;
  59470. } // Enable to give a name on a group made by `renderItem`, and listen
  59471. // events that triggerd by its descendents.
  59472. while ((targetEl = targetEl.parent) && targetEl !== this.group) {
  59473. if (targetEl.name === elementName) {
  59474. return true;
  59475. }
  59476. }
  59477. return false;
  59478. }
  59479. });
  59480. function createEl(elOption) {
  59481. var graphicType = elOption.type;
  59482. var el; // Those graphic elements are not shapes. They should not be
  59483. // overwritten by users, so do them first.
  59484. if (graphicType === 'path') {
  59485. var shape = elOption.shape; // Using pathRect brings convenience to users sacle svg path.
  59486. var pathRect = shape.width != null && shape.height != null ? {
  59487. x: shape.x || 0,
  59488. y: shape.y || 0,
  59489. width: shape.width,
  59490. height: shape.height
  59491. } : null;
  59492. var pathData = getPathData(shape); // Path is also used for icon, so layout 'center' by default.
  59493. el = makePath(pathData, null, pathRect, shape.layout || 'center');
  59494. el.__customPathData = pathData;
  59495. } else if (graphicType === 'image') {
  59496. el = new ZImage({});
  59497. el.__customImagePath = elOption.style.image;
  59498. } else if (graphicType === 'text') {
  59499. el = new Text({});
  59500. el.__customText = elOption.style.text;
  59501. } else if (graphicType === 'group') {
  59502. el = new Group();
  59503. } else if (graphicType === 'compoundPath') {
  59504. throw new Error('"compoundPath" is not supported yet.');
  59505. } else {
  59506. var Clz = getShapeClass(graphicType);
  59507. el = new Clz();
  59508. }
  59509. el.__customGraphicType = graphicType;
  59510. el.name = elOption.name;
  59511. return el;
  59512. }
  59513. function updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot) {
  59514. var transitionProps = {};
  59515. var elOptionStyle = elOption.style || {};
  59516. elOption.shape && (transitionProps.shape = clone(elOption.shape));
  59517. elOption.position && (transitionProps.position = elOption.position.slice());
  59518. elOption.scale && (transitionProps.scale = elOption.scale.slice());
  59519. elOption.origin && (transitionProps.origin = elOption.origin.slice());
  59520. elOption.rotation && (transitionProps.rotation = elOption.rotation);
  59521. if (el.type === 'image' && elOption.style) {
  59522. var targetStyle = transitionProps.style = {};
  59523. each$1(['x', 'y', 'width', 'height'], function (prop) {
  59524. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  59525. });
  59526. }
  59527. if (el.type === 'text' && elOption.style) {
  59528. var targetStyle = transitionProps.style = {};
  59529. each$1(['x', 'y'], function (prop) {
  59530. prepareStyleTransition(prop, targetStyle, elOptionStyle, el.style, isInit);
  59531. }); // Compatible with previous: both support
  59532. // textFill and fill, textStroke and stroke in 'text' element.
  59533. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (elOptionStyle.textFill = elOptionStyle.fill);
  59534. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (elOptionStyle.textStroke = elOptionStyle.stroke);
  59535. }
  59536. if (el.type !== 'group') {
  59537. el.useStyle(elOptionStyle); // Init animation.
  59538. if (isInit) {
  59539. el.style.opacity = 0;
  59540. var targetOpacity = elOptionStyle.opacity;
  59541. targetOpacity == null && (targetOpacity = 1);
  59542. initProps(el, {
  59543. style: {
  59544. opacity: targetOpacity
  59545. }
  59546. }, animatableModel, dataIndex);
  59547. }
  59548. }
  59549. if (isInit) {
  59550. el.attr(transitionProps);
  59551. } else {
  59552. updateProps(el, transitionProps, animatableModel, dataIndex);
  59553. } // Merge by default.
  59554. // z2 must not be null/undefined, otherwise sort error may occur.
  59555. elOption.hasOwnProperty('z2') && el.attr('z2', elOption.z2 || 0);
  59556. elOption.hasOwnProperty('silent') && el.attr('silent', elOption.silent);
  59557. elOption.hasOwnProperty('invisible') && el.attr('invisible', elOption.invisible);
  59558. elOption.hasOwnProperty('ignore') && el.attr('ignore', elOption.ignore); // `elOption.info` enables user to mount some info on
  59559. // elements and use them in event handlers.
  59560. // Update them only when user specified, otherwise, remain.
  59561. elOption.hasOwnProperty('info') && el.attr('info', elOption.info); // If `elOption.styleEmphasis` is `false`, remove hover style. The
  59562. // logic is ensured by `graphicUtil.setElementHoverStyle`.
  59563. var styleEmphasis = elOption.styleEmphasis; // hoverStyle should always be set here, because if the hover style
  59564. // may already be changed, where the inner cache should be reset.
  59565. setElementHoverStyle(el, styleEmphasis);
  59566. if (isRoot) {
  59567. setAsHighDownDispatcher(el, styleEmphasis !== false);
  59568. }
  59569. }
  59570. function prepareStyleTransition(prop, targetStyle, elOptionStyle, oldElStyle, isInit) {
  59571. if (elOptionStyle[prop] != null && !isInit) {
  59572. targetStyle[prop] = elOptionStyle[prop];
  59573. elOptionStyle[prop] = oldElStyle[prop];
  59574. }
  59575. }
  59576. function makeRenderItem(customSeries, data, ecModel, api) {
  59577. var renderItem = customSeries.get('renderItem');
  59578. var coordSys = customSeries.coordinateSystem;
  59579. var prepareResult = {};
  59580. if (coordSys) {
  59581. prepareResult = coordSys.prepareCustoms ? coordSys.prepareCustoms() : prepareCustoms[coordSys.type](coordSys);
  59582. }
  59583. var userAPI = defaults({
  59584. getWidth: api.getWidth,
  59585. getHeight: api.getHeight,
  59586. getZr: api.getZr,
  59587. getDevicePixelRatio: api.getDevicePixelRatio,
  59588. value: value,
  59589. style: style,
  59590. styleEmphasis: styleEmphasis,
  59591. visual: visual,
  59592. barLayout: barLayout,
  59593. currentSeriesIndices: currentSeriesIndices,
  59594. font: font
  59595. }, prepareResult.api || {});
  59596. var userParams = {
  59597. // The life cycle of context: current round of rendering.
  59598. // The global life cycle is probably not necessary, because
  59599. // user can store global status by themselves.
  59600. context: {},
  59601. seriesId: customSeries.id,
  59602. seriesName: customSeries.name,
  59603. seriesIndex: customSeries.seriesIndex,
  59604. coordSys: prepareResult.coordSys,
  59605. dataInsideLength: data.count(),
  59606. encode: wrapEncodeDef(customSeries.getData())
  59607. }; // Do not support call `api` asynchronously without dataIndexInside input.
  59608. var currDataIndexInside;
  59609. var currDirty = true;
  59610. var currItemModel;
  59611. var currLabelNormalModel;
  59612. var currLabelEmphasisModel;
  59613. var currVisualColor;
  59614. return function (dataIndexInside, payload) {
  59615. currDataIndexInside = dataIndexInside;
  59616. currDirty = true;
  59617. return renderItem && renderItem(defaults({
  59618. dataIndexInside: dataIndexInside,
  59619. dataIndex: data.getRawIndex(dataIndexInside),
  59620. // Can be used for optimization when zoom or roam.
  59621. actionType: payload ? payload.type : null
  59622. }, userParams), userAPI);
  59623. }; // Do not update cache until api called.
  59624. function updateCache(dataIndexInside) {
  59625. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  59626. if (currDirty) {
  59627. currItemModel = data.getItemModel(dataIndexInside);
  59628. currLabelNormalModel = currItemModel.getModel(LABEL_NORMAL);
  59629. currLabelEmphasisModel = currItemModel.getModel(LABEL_EMPHASIS);
  59630. currVisualColor = data.getItemVisual(dataIndexInside, 'color');
  59631. currDirty = false;
  59632. }
  59633. }
  59634. /**
  59635. * @public
  59636. * @param {number|string} dim
  59637. * @param {number} [dataIndexInside=currDataIndexInside]
  59638. * @return {number|string} value
  59639. */
  59640. function value(dim, dataIndexInside) {
  59641. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  59642. return data.get(data.getDimension(dim || 0), dataIndexInside);
  59643. }
  59644. /**
  59645. * By default, `visual` is applied to style (to support visualMap).
  59646. * `visual.color` is applied at `fill`. If user want apply visual.color on `stroke`,
  59647. * it can be implemented as:
  59648. * `api.style({stroke: api.visual('color'), fill: null})`;
  59649. * @public
  59650. * @param {Object} [extra]
  59651. * @param {number} [dataIndexInside=currDataIndexInside]
  59652. */
  59653. function style(extra, dataIndexInside) {
  59654. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  59655. updateCache(dataIndexInside);
  59656. var itemStyle = currItemModel.getModel(ITEM_STYLE_NORMAL_PATH).getItemStyle();
  59657. currVisualColor != null && (itemStyle.fill = currVisualColor);
  59658. var opacity = data.getItemVisual(dataIndexInside, 'opacity');
  59659. opacity != null && (itemStyle.opacity = opacity);
  59660. var labelModel = extra ? applyExtraBefore(extra, currLabelNormalModel) : currLabelNormalModel;
  59661. setTextStyle(itemStyle, labelModel, null, {
  59662. autoColor: currVisualColor,
  59663. isRectText: true
  59664. });
  59665. itemStyle.text = labelModel.getShallow('show') ? retrieve2(customSeries.getFormattedLabel(dataIndexInside, 'normal'), getDefaultLabel(data, dataIndexInside)) : null;
  59666. extra && applyExtraAfter(itemStyle, extra);
  59667. return itemStyle;
  59668. }
  59669. /**
  59670. * @public
  59671. * @param {Object} [extra]
  59672. * @param {number} [dataIndexInside=currDataIndexInside]
  59673. */
  59674. function styleEmphasis(extra, dataIndexInside) {
  59675. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  59676. updateCache(dataIndexInside);
  59677. var itemStyle = currItemModel.getModel(ITEM_STYLE_EMPHASIS_PATH).getItemStyle();
  59678. var labelModel = extra ? applyExtraBefore(extra, currLabelEmphasisModel) : currLabelEmphasisModel;
  59679. setTextStyle(itemStyle, labelModel, null, {
  59680. isRectText: true
  59681. }, true);
  59682. itemStyle.text = labelModel.getShallow('show') ? retrieve3(customSeries.getFormattedLabel(dataIndexInside, 'emphasis'), customSeries.getFormattedLabel(dataIndexInside, 'normal'), getDefaultLabel(data, dataIndexInside)) : null;
  59683. extra && applyExtraAfter(itemStyle, extra);
  59684. return itemStyle;
  59685. }
  59686. /**
  59687. * @public
  59688. * @param {string} visualType
  59689. * @param {number} [dataIndexInside=currDataIndexInside]
  59690. */
  59691. function visual(visualType, dataIndexInside) {
  59692. dataIndexInside == null && (dataIndexInside = currDataIndexInside);
  59693. return data.getItemVisual(dataIndexInside, visualType);
  59694. }
  59695. /**
  59696. * @public
  59697. * @param {number} opt.count Positive interger.
  59698. * @param {number} [opt.barWidth]
  59699. * @param {number} [opt.barMaxWidth]
  59700. * @param {number} [opt.barMinWidth]
  59701. * @param {number} [opt.barGap]
  59702. * @param {number} [opt.barCategoryGap]
  59703. * @return {Object} {width, offset, offsetCenter} is not support, return undefined.
  59704. */
  59705. function barLayout(opt) {
  59706. if (coordSys.getBaseAxis) {
  59707. var baseAxis = coordSys.getBaseAxis();
  59708. return getLayoutOnAxis(defaults({
  59709. axis: baseAxis
  59710. }, opt), api);
  59711. }
  59712. }
  59713. /**
  59714. * @public
  59715. * @return {Array.<number>}
  59716. */
  59717. function currentSeriesIndices() {
  59718. return ecModel.getCurrentSeriesIndices();
  59719. }
  59720. /**
  59721. * @public
  59722. * @param {Object} opt
  59723. * @param {string} [opt.fontStyle]
  59724. * @param {number} [opt.fontWeight]
  59725. * @param {number} [opt.fontSize]
  59726. * @param {string} [opt.fontFamily]
  59727. * @return {string} font string
  59728. */
  59729. function font(opt) {
  59730. return getFont(opt, ecModel);
  59731. }
  59732. }
  59733. function wrapEncodeDef(data) {
  59734. var encodeDef = {};
  59735. each$1(data.dimensions, function (dimName, dataDimIndex) {
  59736. var dimInfo = data.getDimensionInfo(dimName);
  59737. if (!dimInfo.isExtraCoord) {
  59738. var coordDim = dimInfo.coordDim;
  59739. var dataDims = encodeDef[coordDim] = encodeDef[coordDim] || [];
  59740. dataDims[dimInfo.coordDimIndex] = dataDimIndex;
  59741. }
  59742. });
  59743. return encodeDef;
  59744. }
  59745. function createOrUpdate$1(el, dataIndex, elOption, animatableModel, group, data) {
  59746. el = doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, true);
  59747. el && data.setItemGraphicEl(dataIndex, el);
  59748. return el;
  59749. }
  59750. function doCreateOrUpdate(el, dataIndex, elOption, animatableModel, group, data, isRoot) {
  59751. // [Rule]
  59752. // By default, follow merge mode.
  59753. // (It probably brings benifit for performance in some cases of large data, where
  59754. // user program can be optimized to that only updated props needed to be re-calculated,
  59755. // or according to `actionType` some calculation can be skipped.)
  59756. // If `renderItem` returns `null`/`undefined`/`false`, remove the previous el if existing.
  59757. // (It seems that violate the "merge" principle, but most of users probably intuitively
  59758. // regard "return;" as "show nothing element whatever", so make a exception to meet the
  59759. // most cases.)
  59760. var simplyRemove = !elOption; // `null`/`undefined`/`false`
  59761. elOption = elOption || {};
  59762. var elOptionType = elOption.type;
  59763. var elOptionShape = elOption.shape;
  59764. var elOptionStyle = elOption.style;
  59765. if (el && (simplyRemove // || elOption.$merge === false
  59766. // If `elOptionType` is `null`, follow the merge principle.
  59767. || elOptionType != null && elOptionType !== el.__customGraphicType || elOptionType === 'path' && hasOwnPathData(elOptionShape) && getPathData(elOptionShape) !== el.__customPathData || elOptionType === 'image' && hasOwn(elOptionStyle, 'image') && elOptionStyle.image !== el.__customImagePath // FIXME test and remove this restriction?
  59768. || elOptionType === 'text' && hasOwn(elOptionShape, 'text') && elOptionStyle.text !== el.__customText)) {
  59769. group.remove(el);
  59770. el = null;
  59771. } // `elOption.type` is undefined when `renderItem` returns nothing.
  59772. if (simplyRemove) {
  59773. return;
  59774. }
  59775. var isInit = !el;
  59776. !el && (el = createEl(elOption));
  59777. updateEl(el, dataIndex, elOption, animatableModel, data, isInit, isRoot);
  59778. if (elOptionType === 'group') {
  59779. mergeChildren(el, dataIndex, elOption, animatableModel, data);
  59780. } // Always add whatever already added to ensure sequence.
  59781. group.add(el);
  59782. return el;
  59783. } // Usage:
  59784. // (1) By default, `elOption.$mergeChildren` is `'byIndex'`, which indicates that
  59785. // the existing children will not be removed, and enables the feature that
  59786. // update some of the props of some of the children simply by construct
  59787. // the returned children of `renderItem` like:
  59788. // `var children = group.children = []; children[3] = {opacity: 0.5};`
  59789. // (2) If `elOption.$mergeChildren` is `'byName'`, add/update/remove children
  59790. // by child.name. But that might be lower performance.
  59791. // (3) If `elOption.$mergeChildren` is `false`, the existing children will be
  59792. // replaced totally.
  59793. // (4) If `!elOption.children`, following the "merge" principle, nothing will happen.
  59794. //
  59795. // For implementation simpleness, do not provide a direct way to remove sinlge
  59796. // child (otherwise the total indicies of the children array have to be modified).
  59797. // User can remove a single child by set its `ignore` as `true` or replace
  59798. // it by another element, where its `$merge` can be set as `true` if necessary.
  59799. function mergeChildren(el, dataIndex, elOption, animatableModel, data) {
  59800. var newChildren = elOption.children;
  59801. var newLen = newChildren ? newChildren.length : 0;
  59802. var mergeChildren = elOption.$mergeChildren; // `diffChildrenByName` has been deprecated.
  59803. var byName = mergeChildren === 'byName' || elOption.diffChildrenByName;
  59804. var notMerge = mergeChildren === false; // For better performance on roam update, only enter if necessary.
  59805. if (!newLen && !byName && !notMerge) {
  59806. return;
  59807. }
  59808. if (byName) {
  59809. diffGroupChildren({
  59810. oldChildren: el.children() || [],
  59811. newChildren: newChildren || [],
  59812. dataIndex: dataIndex,
  59813. animatableModel: animatableModel,
  59814. group: el,
  59815. data: data
  59816. });
  59817. return;
  59818. }
  59819. notMerge && el.removeAll(); // Mapping children of a group simply by index, which
  59820. // might be better performance.
  59821. var index = 0;
  59822. for (; index < newLen; index++) {
  59823. newChildren[index] && doCreateOrUpdate(el.childAt(index), dataIndex, newChildren[index], animatableModel, el, data);
  59824. }
  59825. }
  59826. function diffGroupChildren(context) {
  59827. new DataDiffer(context.oldChildren, context.newChildren, getKey, getKey, context).add(processAddUpdate).update(processAddUpdate).remove(processRemove).execute();
  59828. }
  59829. function getKey(item, idx) {
  59830. var name = item && item.name;
  59831. return name != null ? name : GROUP_DIFF_PREFIX + idx;
  59832. }
  59833. function processAddUpdate(newIndex, oldIndex) {
  59834. var context = this.context;
  59835. var childOption = newIndex != null ? context.newChildren[newIndex] : null;
  59836. var child = oldIndex != null ? context.oldChildren[oldIndex] : null;
  59837. doCreateOrUpdate(child, context.dataIndex, childOption, context.animatableModel, context.group, context.data);
  59838. } // `graphic#applyDefaultTextStyle` will cache
  59839. // textFill, textStroke, textStrokeWidth.
  59840. // We have to do this trick.
  59841. function applyExtraBefore(extra, model) {
  59842. var dummyModel = new Model({}, model);
  59843. each$1(CACHED_LABEL_STYLE_PROPERTIES$1, function (stylePropName, modelPropName) {
  59844. if (extra.hasOwnProperty(stylePropName)) {
  59845. dummyModel.option[modelPropName] = extra[stylePropName];
  59846. }
  59847. });
  59848. return dummyModel;
  59849. }
  59850. function applyExtraAfter(itemStyle, extra) {
  59851. for (var key in extra) {
  59852. if (extra.hasOwnProperty(key) || !CACHED_LABEL_STYLE_PROPERTIES$1.hasOwnProperty(key)) {
  59853. itemStyle[key] = extra[key];
  59854. }
  59855. }
  59856. }
  59857. function processRemove(oldIndex) {
  59858. var context = this.context;
  59859. var child = context.oldChildren[oldIndex];
  59860. child && context.group.remove(child);
  59861. }
  59862. function getPathData(shape) {
  59863. // "d" follows the SVG convention.
  59864. return shape && (shape.pathData || shape.d);
  59865. }
  59866. function hasOwnPathData(shape) {
  59867. return shape && (shape.hasOwnProperty('pathData') || shape.hasOwnProperty('d'));
  59868. }
  59869. function hasOwn(host, prop) {
  59870. return host && host.hasOwnProperty(prop);
  59871. }
  59872. /*
  59873. * Licensed to the Apache Software Foundation (ASF) under one
  59874. * or more contributor license agreements. See the NOTICE file
  59875. * distributed with this work for additional information
  59876. * regarding copyright ownership. The ASF licenses this file
  59877. * to you under the Apache License, Version 2.0 (the
  59878. * "License"); you may not use this file except in compliance
  59879. * with the License. You may obtain a copy of the License at
  59880. *
  59881. * http://www.apache.org/licenses/LICENSE-2.0
  59882. *
  59883. * Unless required by applicable law or agreed to in writing,
  59884. * software distributed under the License is distributed on an
  59885. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  59886. * KIND, either express or implied. See the License for the
  59887. * specific language governing permissions and limitations
  59888. * under the License.
  59889. */
  59890. function getSeriesStackId$1(seriesModel) {
  59891. return seriesModel.get('stack') || '__ec_stack_' + seriesModel.seriesIndex;
  59892. }
  59893. function getAxisKey$1(polar, axis) {
  59894. return axis.dim + polar.model.componentIndex;
  59895. }
  59896. /**
  59897. * @param {string} seriesType
  59898. * @param {module:echarts/model/Global} ecModel
  59899. * @param {module:echarts/ExtensionAPI} api
  59900. */
  59901. function barLayoutPolar(seriesType, ecModel, api) {
  59902. var lastStackCoords = {};
  59903. var barWidthAndOffset = calRadialBar(filter(ecModel.getSeriesByType(seriesType), function (seriesModel) {
  59904. return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'polar';
  59905. }));
  59906. ecModel.eachSeriesByType(seriesType, function (seriesModel) {
  59907. // Check series coordinate, do layout for polar only
  59908. if (seriesModel.coordinateSystem.type !== 'polar') {
  59909. return;
  59910. }
  59911. var data = seriesModel.getData();
  59912. var polar = seriesModel.coordinateSystem;
  59913. var baseAxis = polar.getBaseAxis();
  59914. var axisKey = getAxisKey$1(polar, baseAxis);
  59915. var stackId = getSeriesStackId$1(seriesModel);
  59916. var columnLayoutInfo = barWidthAndOffset[axisKey][stackId];
  59917. var columnOffset = columnLayoutInfo.offset;
  59918. var columnWidth = columnLayoutInfo.width;
  59919. var valueAxis = polar.getOtherAxis(baseAxis);
  59920. var cx = seriesModel.coordinateSystem.cx;
  59921. var cy = seriesModel.coordinateSystem.cy;
  59922. var barMinHeight = seriesModel.get('barMinHeight') || 0;
  59923. var barMinAngle = seriesModel.get('barMinAngle') || 0;
  59924. lastStackCoords[stackId] = lastStackCoords[stackId] || [];
  59925. var valueDim = data.mapDimension(valueAxis.dim);
  59926. var baseDim = data.mapDimension(baseAxis.dim);
  59927. var stacked = isDimensionStacked(data, valueDim
  59928. /*, baseDim*/
  59929. );
  59930. var clampLayout = baseAxis.dim !== 'radius' || !seriesModel.get('roundCap', true);
  59931. var valueAxisStart = valueAxis.getExtent()[0];
  59932. for (var idx = 0, len = data.count(); idx < len; idx++) {
  59933. var value = data.get(valueDim, idx);
  59934. var baseValue = data.get(baseDim, idx);
  59935. var sign = value >= 0 ? 'p' : 'n';
  59936. var baseCoord = valueAxisStart; // Because of the barMinHeight, we can not use the value in
  59937. // stackResultDimension directly.
  59938. // Only ordinal axis can be stacked.
  59939. if (stacked) {
  59940. if (!lastStackCoords[stackId][baseValue]) {
  59941. lastStackCoords[stackId][baseValue] = {
  59942. p: valueAxisStart,
  59943. // Positive stack
  59944. n: valueAxisStart // Negative stack
  59945. };
  59946. } // Should also consider #4243
  59947. baseCoord = lastStackCoords[stackId][baseValue][sign];
  59948. }
  59949. var r0;
  59950. var r;
  59951. var startAngle;
  59952. var endAngle; // radial sector
  59953. if (valueAxis.dim === 'radius') {
  59954. var radiusSpan = valueAxis.dataToRadius(value) - valueAxisStart;
  59955. var angle = baseAxis.dataToAngle(baseValue);
  59956. if (Math.abs(radiusSpan) < barMinHeight) {
  59957. radiusSpan = (radiusSpan < 0 ? -1 : 1) * barMinHeight;
  59958. }
  59959. r0 = baseCoord;
  59960. r = baseCoord + radiusSpan;
  59961. startAngle = angle - columnOffset;
  59962. endAngle = startAngle - columnWidth;
  59963. stacked && (lastStackCoords[stackId][baseValue][sign] = r);
  59964. } // tangential sector
  59965. else {
  59966. var angleSpan = valueAxis.dataToAngle(value, clampLayout) - valueAxisStart;
  59967. var radius = baseAxis.dataToRadius(baseValue);
  59968. if (Math.abs(angleSpan) < barMinAngle) {
  59969. angleSpan = (angleSpan < 0 ? -1 : 1) * barMinAngle;
  59970. }
  59971. r0 = radius + columnOffset;
  59972. r = r0 + columnWidth;
  59973. startAngle = baseCoord;
  59974. endAngle = baseCoord + angleSpan; // if the previous stack is at the end of the ring,
  59975. // add a round to differentiate it from origin
  59976. // var extent = angleAxis.getExtent();
  59977. // var stackCoord = angle;
  59978. // if (stackCoord === extent[0] && value > 0) {
  59979. // stackCoord = extent[1];
  59980. // }
  59981. // else if (stackCoord === extent[1] && value < 0) {
  59982. // stackCoord = extent[0];
  59983. // }
  59984. stacked && (lastStackCoords[stackId][baseValue][sign] = endAngle);
  59985. }
  59986. data.setItemLayout(idx, {
  59987. cx: cx,
  59988. cy: cy,
  59989. r0: r0,
  59990. r: r,
  59991. // Consider that positive angle is anti-clockwise,
  59992. // while positive radian of sector is clockwise
  59993. startAngle: -startAngle * Math.PI / 180,
  59994. endAngle: -endAngle * Math.PI / 180
  59995. });
  59996. }
  59997. }, this);
  59998. }
  59999. /**
  60000. * Calculate bar width and offset for radial bar charts
  60001. */
  60002. function calRadialBar(barSeries, api) {
  60003. // Columns info on each category axis. Key is polar name
  60004. var columnsMap = {};
  60005. each$1(barSeries, function (seriesModel, idx) {
  60006. var data = seriesModel.getData();
  60007. var polar = seriesModel.coordinateSystem;
  60008. var baseAxis = polar.getBaseAxis();
  60009. var axisKey = getAxisKey$1(polar, baseAxis);
  60010. var axisExtent = baseAxis.getExtent();
  60011. var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : Math.abs(axisExtent[1] - axisExtent[0]) / data.count();
  60012. var columnsOnAxis = columnsMap[axisKey] || {
  60013. bandWidth: bandWidth,
  60014. remainedWidth: bandWidth,
  60015. autoWidthCount: 0,
  60016. categoryGap: '20%',
  60017. gap: '30%',
  60018. stacks: {}
  60019. };
  60020. var stacks = columnsOnAxis.stacks;
  60021. columnsMap[axisKey] = columnsOnAxis;
  60022. var stackId = getSeriesStackId$1(seriesModel);
  60023. if (!stacks[stackId]) {
  60024. columnsOnAxis.autoWidthCount++;
  60025. }
  60026. stacks[stackId] = stacks[stackId] || {
  60027. width: 0,
  60028. maxWidth: 0
  60029. };
  60030. var barWidth = parsePercent$1(seriesModel.get('barWidth'), bandWidth);
  60031. var barMaxWidth = parsePercent$1(seriesModel.get('barMaxWidth'), bandWidth);
  60032. var barGap = seriesModel.get('barGap');
  60033. var barCategoryGap = seriesModel.get('barCategoryGap');
  60034. if (barWidth && !stacks[stackId].width) {
  60035. barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth);
  60036. stacks[stackId].width = barWidth;
  60037. columnsOnAxis.remainedWidth -= barWidth;
  60038. }
  60039. barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth);
  60040. barGap != null && (columnsOnAxis.gap = barGap);
  60041. barCategoryGap != null && (columnsOnAxis.categoryGap = barCategoryGap);
  60042. });
  60043. var result = {};
  60044. each$1(columnsMap, function (columnsOnAxis, coordSysName) {
  60045. result[coordSysName] = {};
  60046. var stacks = columnsOnAxis.stacks;
  60047. var bandWidth = columnsOnAxis.bandWidth;
  60048. var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth);
  60049. var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1);
  60050. var remainedWidth = columnsOnAxis.remainedWidth;
  60051. var autoWidthCount = columnsOnAxis.autoWidthCount;
  60052. var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  60053. autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth
  60054. each$1(stacks, function (column, stack) {
  60055. var maxWidth = column.maxWidth;
  60056. if (maxWidth && maxWidth < autoWidth) {
  60057. maxWidth = Math.min(maxWidth, remainedWidth);
  60058. if (column.width) {
  60059. maxWidth = Math.min(maxWidth, column.width);
  60060. }
  60061. remainedWidth -= maxWidth;
  60062. column.width = maxWidth;
  60063. autoWidthCount--;
  60064. }
  60065. }); // Recalculate width again
  60066. autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent);
  60067. autoWidth = Math.max(autoWidth, 0);
  60068. var widthSum = 0;
  60069. var lastColumn;
  60070. each$1(stacks, function (column, idx) {
  60071. if (!column.width) {
  60072. column.width = autoWidth;
  60073. }
  60074. lastColumn = column;
  60075. widthSum += column.width * (1 + barGapPercent);
  60076. });
  60077. if (lastColumn) {
  60078. widthSum -= lastColumn.width * barGapPercent;
  60079. }
  60080. var offset = -widthSum / 2;
  60081. each$1(stacks, function (column, stackId) {
  60082. result[coordSysName][stackId] = result[coordSysName][stackId] || {
  60083. offset: offset,
  60084. width: column.width
  60085. };
  60086. offset += column.width * (1 + barGapPercent);
  60087. });
  60088. });
  60089. return result;
  60090. }
  60091. /*
  60092. * Licensed to the Apache Software Foundation (ASF) under one
  60093. * or more contributor license agreements. See the NOTICE file
  60094. * distributed with this work for additional information
  60095. * regarding copyright ownership. The ASF licenses this file
  60096. * to you under the Apache License, Version 2.0 (the
  60097. * "License"); you may not use this file except in compliance
  60098. * with the License. You may obtain a copy of the License at
  60099. *
  60100. * http://www.apache.org/licenses/LICENSE-2.0
  60101. *
  60102. * Unless required by applicable law or agreed to in writing,
  60103. * software distributed under the License is distributed on an
  60104. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60105. * KIND, either express or implied. See the License for the
  60106. * specific language governing permissions and limitations
  60107. * under the License.
  60108. */
  60109. function RadiusAxis(scale, radiusExtent) {
  60110. Axis.call(this, 'radius', scale, radiusExtent);
  60111. /**
  60112. * Axis type
  60113. * - 'category'
  60114. * - 'value'
  60115. * - 'time'
  60116. * - 'log'
  60117. * @type {string}
  60118. */
  60119. this.type = 'category';
  60120. }
  60121. RadiusAxis.prototype = {
  60122. constructor: RadiusAxis,
  60123. /**
  60124. * @override
  60125. */
  60126. pointToData: function (point, clamp) {
  60127. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  60128. },
  60129. dataToRadius: Axis.prototype.dataToCoord,
  60130. radiusToData: Axis.prototype.coordToData
  60131. };
  60132. inherits(RadiusAxis, Axis);
  60133. /*
  60134. * Licensed to the Apache Software Foundation (ASF) under one
  60135. * or more contributor license agreements. See the NOTICE file
  60136. * distributed with this work for additional information
  60137. * regarding copyright ownership. The ASF licenses this file
  60138. * to you under the Apache License, Version 2.0 (the
  60139. * "License"); you may not use this file except in compliance
  60140. * with the License. You may obtain a copy of the License at
  60141. *
  60142. * http://www.apache.org/licenses/LICENSE-2.0
  60143. *
  60144. * Unless required by applicable law or agreed to in writing,
  60145. * software distributed under the License is distributed on an
  60146. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60147. * KIND, either express or implied. See the License for the
  60148. * specific language governing permissions and limitations
  60149. * under the License.
  60150. */
  60151. var inner$12 = makeInner();
  60152. function AngleAxis(scale, angleExtent) {
  60153. angleExtent = angleExtent || [0, 360];
  60154. Axis.call(this, 'angle', scale, angleExtent);
  60155. /**
  60156. * Axis type
  60157. * - 'category'
  60158. * - 'value'
  60159. * - 'time'
  60160. * - 'log'
  60161. * @type {string}
  60162. */
  60163. this.type = 'category';
  60164. }
  60165. AngleAxis.prototype = {
  60166. constructor: AngleAxis,
  60167. /**
  60168. * @override
  60169. */
  60170. pointToData: function (point, clamp) {
  60171. return this.polar.pointToData(point, clamp)[this.dim === 'radius' ? 0 : 1];
  60172. },
  60173. dataToAngle: Axis.prototype.dataToCoord,
  60174. angleToData: Axis.prototype.coordToData,
  60175. /**
  60176. * Only be called in category axis.
  60177. * Angle axis uses text height to decide interval
  60178. *
  60179. * @override
  60180. * @return {number} Auto interval for cateogry axis tick and label
  60181. */
  60182. calculateCategoryInterval: function () {
  60183. var axis = this;
  60184. var labelModel = axis.getLabelModel();
  60185. var ordinalScale = axis.scale;
  60186. var ordinalExtent = ordinalScale.getExtent(); // Providing this method is for optimization:
  60187. // avoid generating a long array by `getTicks`
  60188. // in large category data case.
  60189. var tickCount = ordinalScale.count();
  60190. if (ordinalExtent[1] - ordinalExtent[0] < 1) {
  60191. return 0;
  60192. }
  60193. var tickValue = ordinalExtent[0];
  60194. var unitSpan = axis.dataToCoord(tickValue + 1) - axis.dataToCoord(tickValue);
  60195. var unitH = Math.abs(unitSpan); // Not precise, just use height as text width
  60196. // and each distance from axis line yet.
  60197. var rect = getBoundingRect(tickValue, labelModel.getFont(), 'center', 'top');
  60198. var maxH = Math.max(rect.height, 7);
  60199. var dh = maxH / unitH; // 0/0 is NaN, 1/0 is Infinity.
  60200. isNaN(dh) && (dh = Infinity);
  60201. var interval = Math.max(0, Math.floor(dh));
  60202. var cache = inner$12(axis.model);
  60203. var lastAutoInterval = cache.lastAutoInterval;
  60204. var lastTickCount = cache.lastTickCount; // Use cache to keep interval stable while moving zoom window,
  60205. // otherwise the calculated interval might jitter when the zoom
  60206. // window size is close to the interval-changing size.
  60207. if (lastAutoInterval != null && lastTickCount != null && Math.abs(lastAutoInterval - interval) <= 1 && Math.abs(lastTickCount - tickCount) <= 1 // Always choose the bigger one, otherwise the critical
  60208. // point is not the same when zooming in or zooming out.
  60209. && lastAutoInterval > interval) {
  60210. interval = lastAutoInterval;
  60211. } // Only update cache if cache not used, otherwise the
  60212. // changing of interval is too insensitive.
  60213. else {
  60214. cache.lastTickCount = tickCount;
  60215. cache.lastAutoInterval = interval;
  60216. }
  60217. return interval;
  60218. }
  60219. };
  60220. inherits(AngleAxis, Axis);
  60221. /*
  60222. * Licensed to the Apache Software Foundation (ASF) under one
  60223. * or more contributor license agreements. See the NOTICE file
  60224. * distributed with this work for additional information
  60225. * regarding copyright ownership. The ASF licenses this file
  60226. * to you under the Apache License, Version 2.0 (the
  60227. * "License"); you may not use this file except in compliance
  60228. * with the License. You may obtain a copy of the License at
  60229. *
  60230. * http://www.apache.org/licenses/LICENSE-2.0
  60231. *
  60232. * Unless required by applicable law or agreed to in writing,
  60233. * software distributed under the License is distributed on an
  60234. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60235. * KIND, either express or implied. See the License for the
  60236. * specific language governing permissions and limitations
  60237. * under the License.
  60238. */
  60239. /**
  60240. * @module echarts/coord/polar/Polar
  60241. */
  60242. /**
  60243. * @alias {module:echarts/coord/polar/Polar}
  60244. * @constructor
  60245. * @param {string} name
  60246. */
  60247. var Polar = function (name) {
  60248. /**
  60249. * @type {string}
  60250. */
  60251. this.name = name || '';
  60252. /**
  60253. * x of polar center
  60254. * @type {number}
  60255. */
  60256. this.cx = 0;
  60257. /**
  60258. * y of polar center
  60259. * @type {number}
  60260. */
  60261. this.cy = 0;
  60262. /**
  60263. * @type {module:echarts/coord/polar/RadiusAxis}
  60264. * @private
  60265. */
  60266. this._radiusAxis = new RadiusAxis();
  60267. /**
  60268. * @type {module:echarts/coord/polar/AngleAxis}
  60269. * @private
  60270. */
  60271. this._angleAxis = new AngleAxis();
  60272. this._radiusAxis.polar = this._angleAxis.polar = this;
  60273. };
  60274. Polar.prototype = {
  60275. type: 'polar',
  60276. axisPointerEnabled: true,
  60277. constructor: Polar,
  60278. /**
  60279. * @param {Array.<string>}
  60280. * @readOnly
  60281. */
  60282. dimensions: ['radius', 'angle'],
  60283. /**
  60284. * @type {module:echarts/coord/PolarModel}
  60285. */
  60286. model: null,
  60287. /**
  60288. * If contain coord
  60289. * @param {Array.<number>} point
  60290. * @return {boolean}
  60291. */
  60292. containPoint: function (point) {
  60293. var coord = this.pointToCoord(point);
  60294. return this._radiusAxis.contain(coord[0]) && this._angleAxis.contain(coord[1]);
  60295. },
  60296. /**
  60297. * If contain data
  60298. * @param {Array.<number>} data
  60299. * @return {boolean}
  60300. */
  60301. containData: function (data) {
  60302. return this._radiusAxis.containData(data[0]) && this._angleAxis.containData(data[1]);
  60303. },
  60304. /**
  60305. * @param {string} dim
  60306. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  60307. */
  60308. getAxis: function (dim) {
  60309. return this['_' + dim + 'Axis'];
  60310. },
  60311. /**
  60312. * @return {Array.<module:echarts/coord/Axis>}
  60313. */
  60314. getAxes: function () {
  60315. return [this._radiusAxis, this._angleAxis];
  60316. },
  60317. /**
  60318. * Get axes by type of scale
  60319. * @param {string} scaleType
  60320. * @return {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  60321. */
  60322. getAxesByScale: function (scaleType) {
  60323. var axes = [];
  60324. var angleAxis = this._angleAxis;
  60325. var radiusAxis = this._radiusAxis;
  60326. angleAxis.scale.type === scaleType && axes.push(angleAxis);
  60327. radiusAxis.scale.type === scaleType && axes.push(radiusAxis);
  60328. return axes;
  60329. },
  60330. /**
  60331. * @return {module:echarts/coord/polar/AngleAxis}
  60332. */
  60333. getAngleAxis: function () {
  60334. return this._angleAxis;
  60335. },
  60336. /**
  60337. * @return {module:echarts/coord/polar/RadiusAxis}
  60338. */
  60339. getRadiusAxis: function () {
  60340. return this._radiusAxis;
  60341. },
  60342. /**
  60343. * @param {module:echarts/coord/polar/Axis}
  60344. * @return {module:echarts/coord/polar/Axis}
  60345. */
  60346. getOtherAxis: function (axis) {
  60347. var angleAxis = this._angleAxis;
  60348. return axis === angleAxis ? this._radiusAxis : angleAxis;
  60349. },
  60350. /**
  60351. * Base axis will be used on stacking.
  60352. *
  60353. * @return {module:echarts/coord/polar/Axis}
  60354. */
  60355. getBaseAxis: function () {
  60356. return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAngleAxis();
  60357. },
  60358. /**
  60359. * @param {string} [dim] 'radius' or 'angle' or 'auto' or null/undefined
  60360. * @return {Object} {baseAxes: [], otherAxes: []}
  60361. */
  60362. getTooltipAxes: function (dim) {
  60363. var baseAxis = dim != null && dim !== 'auto' ? this.getAxis(dim) : this.getBaseAxis();
  60364. return {
  60365. baseAxes: [baseAxis],
  60366. otherAxes: [this.getOtherAxis(baseAxis)]
  60367. };
  60368. },
  60369. /**
  60370. * Convert a single data item to (x, y) point.
  60371. * Parameter data is an array which the first element is radius and the second is angle
  60372. * @param {Array.<number>} data
  60373. * @param {boolean} [clamp=false]
  60374. * @return {Array.<number>}
  60375. */
  60376. dataToPoint: function (data, clamp) {
  60377. return this.coordToPoint([this._radiusAxis.dataToRadius(data[0], clamp), this._angleAxis.dataToAngle(data[1], clamp)]);
  60378. },
  60379. /**
  60380. * Convert a (x, y) point to data
  60381. * @param {Array.<number>} point
  60382. * @param {boolean} [clamp=false]
  60383. * @return {Array.<number>}
  60384. */
  60385. pointToData: function (point, clamp) {
  60386. var coord = this.pointToCoord(point);
  60387. return [this._radiusAxis.radiusToData(coord[0], clamp), this._angleAxis.angleToData(coord[1], clamp)];
  60388. },
  60389. /**
  60390. * Convert a (x, y) point to (radius, angle) coord
  60391. * @param {Array.<number>} point
  60392. * @return {Array.<number>}
  60393. */
  60394. pointToCoord: function (point) {
  60395. var dx = point[0] - this.cx;
  60396. var dy = point[1] - this.cy;
  60397. var angleAxis = this.getAngleAxis();
  60398. var extent = angleAxis.getExtent();
  60399. var minAngle = Math.min(extent[0], extent[1]);
  60400. var maxAngle = Math.max(extent[0], extent[1]); // Fix fixed extent in polarCreator
  60401. // FIXME
  60402. angleAxis.inverse ? minAngle = maxAngle - 360 : maxAngle = minAngle + 360;
  60403. var radius = Math.sqrt(dx * dx + dy * dy);
  60404. dx /= radius;
  60405. dy /= radius;
  60406. var radian = Math.atan2(-dy, dx) / Math.PI * 180; // move to angleExtent
  60407. var dir = radian < minAngle ? 1 : -1;
  60408. while (radian < minAngle || radian > maxAngle) {
  60409. radian += dir * 360;
  60410. }
  60411. return [radius, radian];
  60412. },
  60413. /**
  60414. * Convert a (radius, angle) coord to (x, y) point
  60415. * @param {Array.<number>} coord
  60416. * @return {Array.<number>}
  60417. */
  60418. coordToPoint: function (coord) {
  60419. var radius = coord[0];
  60420. var radian = coord[1] / 180 * Math.PI;
  60421. var x = Math.cos(radian) * radius + this.cx; // Inverse the y
  60422. var y = -Math.sin(radian) * radius + this.cy;
  60423. return [x, y];
  60424. },
  60425. /**
  60426. * Get ring area of cartesian.
  60427. * Area will have a contain function to determine if a point is in the coordinate system.
  60428. * @return {Ring}
  60429. */
  60430. getArea: function () {
  60431. var angleAxis = this.getAngleAxis();
  60432. var radiusAxis = this.getRadiusAxis();
  60433. var radiusExtent = radiusAxis.getExtent().slice();
  60434. radiusExtent[0] > radiusExtent[1] && radiusExtent.reverse();
  60435. var angleExtent = angleAxis.getExtent();
  60436. var RADIAN = Math.PI / 180;
  60437. return {
  60438. cx: this.cx,
  60439. cy: this.cy,
  60440. r0: radiusExtent[0],
  60441. r: radiusExtent[1],
  60442. startAngle: -angleExtent[0] * RADIAN,
  60443. endAngle: -angleExtent[1] * RADIAN,
  60444. clockwise: angleAxis.inverse,
  60445. contain: function (x, y) {
  60446. // It's a ring shape.
  60447. // Start angle and end angle don't matter
  60448. var dx = x - this.cx;
  60449. var dy = y - this.cy;
  60450. var d2 = dx * dx + dy * dy;
  60451. var r = this.r;
  60452. var r0 = this.r0;
  60453. return d2 <= r * r && d2 >= r0 * r0;
  60454. }
  60455. };
  60456. }
  60457. };
  60458. /*
  60459. * Licensed to the Apache Software Foundation (ASF) under one
  60460. * or more contributor license agreements. See the NOTICE file
  60461. * distributed with this work for additional information
  60462. * regarding copyright ownership. The ASF licenses this file
  60463. * to you under the Apache License, Version 2.0 (the
  60464. * "License"); you may not use this file except in compliance
  60465. * with the License. You may obtain a copy of the License at
  60466. *
  60467. * http://www.apache.org/licenses/LICENSE-2.0
  60468. *
  60469. * Unless required by applicable law or agreed to in writing,
  60470. * software distributed under the License is distributed on an
  60471. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60472. * KIND, either express or implied. See the License for the
  60473. * specific language governing permissions and limitations
  60474. * under the License.
  60475. */
  60476. var PolarAxisModel = ComponentModel.extend({
  60477. type: 'polarAxis',
  60478. /**
  60479. * @type {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  60480. */
  60481. axis: null,
  60482. /**
  60483. * @override
  60484. */
  60485. getCoordSysModel: function () {
  60486. return this.ecModel.queryComponents({
  60487. mainType: 'polar',
  60488. index: this.option.polarIndex,
  60489. id: this.option.polarId
  60490. })[0];
  60491. }
  60492. });
  60493. merge(PolarAxisModel.prototype, axisModelCommonMixin);
  60494. var polarAxisDefaultExtendedOption = {
  60495. angle: {
  60496. // polarIndex: 0,
  60497. // polarId: '',
  60498. startAngle: 90,
  60499. clockwise: true,
  60500. splitNumber: 12,
  60501. axisLabel: {
  60502. rotate: false
  60503. }
  60504. },
  60505. radius: {
  60506. // polarIndex: 0,
  60507. // polarId: '',
  60508. splitNumber: 5
  60509. }
  60510. };
  60511. function getAxisType$3(axisDim, option) {
  60512. // Default axis with data is category axis
  60513. return option.type || (option.data ? 'category' : 'value');
  60514. }
  60515. axisModelCreator('angle', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.angle);
  60516. axisModelCreator('radius', PolarAxisModel, getAxisType$3, polarAxisDefaultExtendedOption.radius);
  60517. /*
  60518. * Licensed to the Apache Software Foundation (ASF) under one
  60519. * or more contributor license agreements. See the NOTICE file
  60520. * distributed with this work for additional information
  60521. * regarding copyright ownership. The ASF licenses this file
  60522. * to you under the Apache License, Version 2.0 (the
  60523. * "License"); you may not use this file except in compliance
  60524. * with the License. You may obtain a copy of the License at
  60525. *
  60526. * http://www.apache.org/licenses/LICENSE-2.0
  60527. *
  60528. * Unless required by applicable law or agreed to in writing,
  60529. * software distributed under the License is distributed on an
  60530. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60531. * KIND, either express or implied. See the License for the
  60532. * specific language governing permissions and limitations
  60533. * under the License.
  60534. */
  60535. extendComponentModel({
  60536. type: 'polar',
  60537. dependencies: ['polarAxis', 'angleAxis'],
  60538. /**
  60539. * @type {module:echarts/coord/polar/Polar}
  60540. */
  60541. coordinateSystem: null,
  60542. /**
  60543. * @param {string} axisType
  60544. * @return {module:echarts/coord/polar/AxisModel}
  60545. */
  60546. findAxisModel: function (axisType) {
  60547. var foundAxisModel;
  60548. var ecModel = this.ecModel;
  60549. ecModel.eachComponent(axisType, function (axisModel) {
  60550. if (axisModel.getCoordSysModel() === this) {
  60551. foundAxisModel = axisModel;
  60552. }
  60553. }, this);
  60554. return foundAxisModel;
  60555. },
  60556. defaultOption: {
  60557. zlevel: 0,
  60558. z: 0,
  60559. center: ['50%', '50%'],
  60560. radius: '80%'
  60561. }
  60562. });
  60563. /*
  60564. * Licensed to the Apache Software Foundation (ASF) under one
  60565. * or more contributor license agreements. See the NOTICE file
  60566. * distributed with this work for additional information
  60567. * regarding copyright ownership. The ASF licenses this file
  60568. * to you under the Apache License, Version 2.0 (the
  60569. * "License"); you may not use this file except in compliance
  60570. * with the License. You may obtain a copy of the License at
  60571. *
  60572. * http://www.apache.org/licenses/LICENSE-2.0
  60573. *
  60574. * Unless required by applicable law or agreed to in writing,
  60575. * software distributed under the License is distributed on an
  60576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60577. * KIND, either express or implied. See the License for the
  60578. * specific language governing permissions and limitations
  60579. * under the License.
  60580. */
  60581. // TODO Axis scale
  60582. /**
  60583. * Resize method bound to the polar
  60584. * @param {module:echarts/coord/polar/PolarModel} polarModel
  60585. * @param {module:echarts/ExtensionAPI} api
  60586. */
  60587. function resizePolar(polar, polarModel, api) {
  60588. var center = polarModel.get('center');
  60589. var width = api.getWidth();
  60590. var height = api.getHeight();
  60591. polar.cx = parsePercent$1(center[0], width);
  60592. polar.cy = parsePercent$1(center[1], height);
  60593. var radiusAxis = polar.getRadiusAxis();
  60594. var size = Math.min(width, height) / 2;
  60595. var radius = polarModel.get('radius');
  60596. if (radius == null) {
  60597. radius = [0, '100%'];
  60598. } else if (!isArray(radius)) {
  60599. // r0 = 0
  60600. radius = [0, radius];
  60601. }
  60602. radius = [parsePercent$1(radius[0], size), parsePercent$1(radius[1], size)];
  60603. radiusAxis.inverse ? radiusAxis.setExtent(radius[1], radius[0]) : radiusAxis.setExtent(radius[0], radius[1]);
  60604. }
  60605. /**
  60606. * Update polar
  60607. */
  60608. function updatePolarScale(ecModel, api) {
  60609. var polar = this;
  60610. var angleAxis = polar.getAngleAxis();
  60611. var radiusAxis = polar.getRadiusAxis(); // Reset scale
  60612. angleAxis.scale.setExtent(Infinity, -Infinity);
  60613. radiusAxis.scale.setExtent(Infinity, -Infinity);
  60614. ecModel.eachSeries(function (seriesModel) {
  60615. if (seriesModel.coordinateSystem === polar) {
  60616. var data = seriesModel.getData();
  60617. each$1(data.mapDimension('radius', true), function (dim) {
  60618. radiusAxis.scale.unionExtentFromData(data, getStackedDimension(data, dim));
  60619. });
  60620. each$1(data.mapDimension('angle', true), function (dim) {
  60621. angleAxis.scale.unionExtentFromData(data, getStackedDimension(data, dim));
  60622. });
  60623. }
  60624. });
  60625. niceScaleExtent(angleAxis.scale, angleAxis.model);
  60626. niceScaleExtent(radiusAxis.scale, radiusAxis.model); // Fix extent of category angle axis
  60627. if (angleAxis.type === 'category' && !angleAxis.onBand) {
  60628. var extent = angleAxis.getExtent();
  60629. var diff = 360 / angleAxis.scale.count();
  60630. angleAxis.inverse ? extent[1] += diff : extent[1] -= diff;
  60631. angleAxis.setExtent(extent[0], extent[1]);
  60632. }
  60633. }
  60634. /**
  60635. * Set common axis properties
  60636. * @param {module:echarts/coord/polar/AngleAxis|module:echarts/coord/polar/RadiusAxis}
  60637. * @param {module:echarts/coord/polar/AxisModel}
  60638. * @inner
  60639. */
  60640. function setAxis(axis, axisModel) {
  60641. axis.type = axisModel.get('type');
  60642. axis.scale = createScaleByModel(axisModel);
  60643. axis.onBand = axisModel.get('boundaryGap') && axis.type === 'category';
  60644. axis.inverse = axisModel.get('inverse');
  60645. if (axisModel.mainType === 'angleAxis') {
  60646. axis.inverse ^= axisModel.get('clockwise');
  60647. var startAngle = axisModel.get('startAngle');
  60648. axis.setExtent(startAngle, startAngle + (axis.inverse ? -360 : 360));
  60649. } // Inject axis instance
  60650. axisModel.axis = axis;
  60651. axis.model = axisModel;
  60652. }
  60653. var polarCreator = {
  60654. dimensions: Polar.prototype.dimensions,
  60655. create: function (ecModel, api) {
  60656. var polarList = [];
  60657. ecModel.eachComponent('polar', function (polarModel, idx) {
  60658. var polar = new Polar(idx); // Inject resize and update method
  60659. polar.update = updatePolarScale;
  60660. var radiusAxis = polar.getRadiusAxis();
  60661. var angleAxis = polar.getAngleAxis();
  60662. var radiusAxisModel = polarModel.findAxisModel('radiusAxis');
  60663. var angleAxisModel = polarModel.findAxisModel('angleAxis');
  60664. setAxis(radiusAxis, radiusAxisModel);
  60665. setAxis(angleAxis, angleAxisModel);
  60666. resizePolar(polar, polarModel, api);
  60667. polarList.push(polar);
  60668. polarModel.coordinateSystem = polar;
  60669. polar.model = polarModel;
  60670. }); // Inject coordinateSystem to series
  60671. ecModel.eachSeries(function (seriesModel) {
  60672. if (seriesModel.get('coordinateSystem') === 'polar') {
  60673. var polarModel = ecModel.queryComponents({
  60674. mainType: 'polar',
  60675. index: seriesModel.get('polarIndex'),
  60676. id: seriesModel.get('polarId')
  60677. })[0];
  60678. seriesModel.coordinateSystem = polarModel.coordinateSystem;
  60679. }
  60680. });
  60681. return polarList;
  60682. }
  60683. };
  60684. CoordinateSystemManager.register('polar', polarCreator);
  60685. /*
  60686. * Licensed to the Apache Software Foundation (ASF) under one
  60687. * or more contributor license agreements. See the NOTICE file
  60688. * distributed with this work for additional information
  60689. * regarding copyright ownership. The ASF licenses this file
  60690. * to you under the Apache License, Version 2.0 (the
  60691. * "License"); you may not use this file except in compliance
  60692. * with the License. You may obtain a copy of the License at
  60693. *
  60694. * http://www.apache.org/licenses/LICENSE-2.0
  60695. *
  60696. * Unless required by applicable law or agreed to in writing,
  60697. * software distributed under the License is distributed on an
  60698. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60699. * KIND, either express or implied. See the License for the
  60700. * specific language governing permissions and limitations
  60701. * under the License.
  60702. */
  60703. var elementList$1 = ['axisLine', 'axisLabel', 'axisTick', 'minorTick', 'splitLine', 'minorSplitLine', 'splitArea'];
  60704. function getAxisLineShape(polar, rExtent, angle) {
  60705. rExtent[1] > rExtent[0] && (rExtent = rExtent.slice().reverse());
  60706. var start = polar.coordToPoint([rExtent[0], angle]);
  60707. var end = polar.coordToPoint([rExtent[1], angle]);
  60708. return {
  60709. x1: start[0],
  60710. y1: start[1],
  60711. x2: end[0],
  60712. y2: end[1]
  60713. };
  60714. }
  60715. function getRadiusIdx(polar) {
  60716. var radiusAxis = polar.getRadiusAxis();
  60717. return radiusAxis.inverse ? 0 : 1;
  60718. } // Remove the last tick which will overlap the first tick
  60719. function fixAngleOverlap(list) {
  60720. var firstItem = list[0];
  60721. var lastItem = list[list.length - 1];
  60722. if (firstItem && lastItem && Math.abs(Math.abs(firstItem.coord - lastItem.coord) - 360) < 1e-4) {
  60723. list.pop();
  60724. }
  60725. }
  60726. AxisView.extend({
  60727. type: 'angleAxis',
  60728. axisPointerClass: 'PolarAxisPointer',
  60729. render: function (angleAxisModel, ecModel) {
  60730. this.group.removeAll();
  60731. if (!angleAxisModel.get('show')) {
  60732. return;
  60733. }
  60734. var angleAxis = angleAxisModel.axis;
  60735. var polar = angleAxis.polar;
  60736. var radiusExtent = polar.getRadiusAxis().getExtent();
  60737. var ticksAngles = angleAxis.getTicksCoords();
  60738. var minorTickAngles = angleAxis.getMinorTicksCoords();
  60739. var labels = map(angleAxis.getViewLabels(), function (labelItem) {
  60740. var labelItem = clone(labelItem);
  60741. labelItem.coord = angleAxis.dataToCoord(labelItem.tickValue);
  60742. return labelItem;
  60743. });
  60744. fixAngleOverlap(labels);
  60745. fixAngleOverlap(ticksAngles);
  60746. each$1(elementList$1, function (name) {
  60747. if (angleAxisModel.get(name + '.show') && (!angleAxis.scale.isBlank() || name === 'axisLine')) {
  60748. this['_' + name](angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels);
  60749. }
  60750. }, this);
  60751. },
  60752. /**
  60753. * @private
  60754. */
  60755. _axisLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  60756. var lineStyleModel = angleAxisModel.getModel('axisLine.lineStyle'); // extent id of the axis radius (r0 and r)
  60757. var rId = getRadiusIdx(polar);
  60758. var r0Id = rId ? 0 : 1;
  60759. var shape;
  60760. if (radiusExtent[r0Id] === 0) {
  60761. shape = new Circle({
  60762. shape: {
  60763. cx: polar.cx,
  60764. cy: polar.cy,
  60765. r: radiusExtent[rId]
  60766. },
  60767. style: lineStyleModel.getLineStyle(),
  60768. z2: 1,
  60769. silent: true
  60770. });
  60771. } else {
  60772. shape = new Ring({
  60773. shape: {
  60774. cx: polar.cx,
  60775. cy: polar.cy,
  60776. r: radiusExtent[rId],
  60777. r0: radiusExtent[r0Id]
  60778. },
  60779. style: lineStyleModel.getLineStyle(),
  60780. z2: 1,
  60781. silent: true
  60782. });
  60783. }
  60784. shape.style.fill = null;
  60785. this.group.add(shape);
  60786. },
  60787. /**
  60788. * @private
  60789. */
  60790. _axisTick: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  60791. var tickModel = angleAxisModel.getModel('axisTick');
  60792. var tickLen = (tickModel.get('inside') ? -1 : 1) * tickModel.get('length');
  60793. var radius = radiusExtent[getRadiusIdx(polar)];
  60794. var lines = map(ticksAngles, function (tickAngleItem) {
  60795. return new Line({
  60796. shape: getAxisLineShape(polar, [radius, radius + tickLen], tickAngleItem.coord)
  60797. });
  60798. });
  60799. this.group.add(mergePath(lines, {
  60800. style: defaults(tickModel.getModel('lineStyle').getLineStyle(), {
  60801. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  60802. })
  60803. }));
  60804. },
  60805. /**
  60806. * @private
  60807. */
  60808. _minorTick: function (angleAxisModel, polar, tickAngles, minorTickAngles, radiusExtent) {
  60809. if (!minorTickAngles.length) {
  60810. return;
  60811. }
  60812. var tickModel = angleAxisModel.getModel('axisTick');
  60813. var minorTickModel = angleAxisModel.getModel('minorTick');
  60814. var tickLen = (tickModel.get('inside') ? -1 : 1) * minorTickModel.get('length');
  60815. var radius = radiusExtent[getRadiusIdx(polar)];
  60816. var lines = [];
  60817. for (var i = 0; i < minorTickAngles.length; i++) {
  60818. for (var k = 0; k < minorTickAngles[i].length; k++) {
  60819. lines.push(new Line({
  60820. shape: getAxisLineShape(polar, [radius, radius + tickLen], minorTickAngles[i][k].coord)
  60821. }));
  60822. }
  60823. }
  60824. this.group.add(mergePath(lines, {
  60825. style: defaults(minorTickModel.getModel('lineStyle').getLineStyle(), defaults(tickModel.getLineStyle(), {
  60826. stroke: angleAxisModel.get('axisLine.lineStyle.color')
  60827. }))
  60828. }));
  60829. },
  60830. /**
  60831. * @private
  60832. */
  60833. _axisLabel: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent, labels) {
  60834. var rawCategoryData = angleAxisModel.getCategories(true);
  60835. var commonLabelModel = angleAxisModel.getModel('axisLabel');
  60836. var labelMargin = commonLabelModel.get('margin');
  60837. var triggerEvent = angleAxisModel.get('triggerEvent'); // Use length of ticksAngles because it may remove the last tick to avoid overlapping
  60838. each$1(labels, function (labelItem, idx) {
  60839. var labelModel = commonLabelModel;
  60840. var tickValue = labelItem.tickValue;
  60841. var r = radiusExtent[getRadiusIdx(polar)];
  60842. var p = polar.coordToPoint([r + labelMargin, labelItem.coord]);
  60843. var cx = polar.cx;
  60844. var cy = polar.cy;
  60845. var labelTextAlign = Math.abs(p[0] - cx) / r < 0.3 ? 'center' : p[0] > cx ? 'left' : 'right';
  60846. var labelTextVerticalAlign = Math.abs(p[1] - cy) / r < 0.3 ? 'middle' : p[1] > cy ? 'top' : 'bottom';
  60847. if (rawCategoryData && rawCategoryData[tickValue] && rawCategoryData[tickValue].textStyle) {
  60848. labelModel = new Model(rawCategoryData[tickValue].textStyle, commonLabelModel, commonLabelModel.ecModel);
  60849. }
  60850. var textEl = new Text({
  60851. silent: AxisBuilder.isLabelSilent(angleAxisModel)
  60852. });
  60853. this.group.add(textEl);
  60854. setTextStyle(textEl.style, labelModel, {
  60855. x: p[0],
  60856. y: p[1],
  60857. textFill: labelModel.getTextColor() || angleAxisModel.get('axisLine.lineStyle.color'),
  60858. text: labelItem.formattedLabel,
  60859. textAlign: labelTextAlign,
  60860. textVerticalAlign: labelTextVerticalAlign
  60861. }); // Pack data for mouse event
  60862. if (triggerEvent) {
  60863. textEl.eventData = AxisBuilder.makeAxisEventDataBase(angleAxisModel);
  60864. textEl.eventData.targetType = 'axisLabel';
  60865. textEl.eventData.value = labelItem.rawLabel;
  60866. }
  60867. }, this);
  60868. },
  60869. /**
  60870. * @private
  60871. */
  60872. _splitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  60873. var splitLineModel = angleAxisModel.getModel('splitLine');
  60874. var lineStyleModel = splitLineModel.getModel('lineStyle');
  60875. var lineColors = lineStyleModel.get('color');
  60876. var lineCount = 0;
  60877. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  60878. var splitLines = [];
  60879. for (var i = 0; i < ticksAngles.length; i++) {
  60880. var colorIndex = lineCount++ % lineColors.length;
  60881. splitLines[colorIndex] = splitLines[colorIndex] || [];
  60882. splitLines[colorIndex].push(new Line({
  60883. shape: getAxisLineShape(polar, radiusExtent, ticksAngles[i].coord)
  60884. }));
  60885. } // Simple optimization
  60886. // Batching the lines if color are the same
  60887. for (var i = 0; i < splitLines.length; i++) {
  60888. this.group.add(mergePath(splitLines[i], {
  60889. style: defaults({
  60890. stroke: lineColors[i % lineColors.length]
  60891. }, lineStyleModel.getLineStyle()),
  60892. silent: true,
  60893. z: angleAxisModel.get('z')
  60894. }));
  60895. }
  60896. },
  60897. /**
  60898. * @private
  60899. */
  60900. _minorSplitLine: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  60901. if (!minorTickAngles.length) {
  60902. return;
  60903. }
  60904. var minorSplitLineModel = angleAxisModel.getModel('minorSplitLine');
  60905. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  60906. var lines = [];
  60907. for (var i = 0; i < minorTickAngles.length; i++) {
  60908. for (var k = 0; k < minorTickAngles[i].length; k++) {
  60909. lines.push(new Line({
  60910. shape: getAxisLineShape(polar, radiusExtent, minorTickAngles[i][k].coord)
  60911. }));
  60912. }
  60913. }
  60914. this.group.add(mergePath(lines, {
  60915. style: lineStyleModel.getLineStyle(),
  60916. silent: true,
  60917. z: angleAxisModel.get('z')
  60918. }));
  60919. },
  60920. /**
  60921. * @private
  60922. */
  60923. _splitArea: function (angleAxisModel, polar, ticksAngles, minorTickAngles, radiusExtent) {
  60924. if (!ticksAngles.length) {
  60925. return;
  60926. }
  60927. var splitAreaModel = angleAxisModel.getModel('splitArea');
  60928. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  60929. var areaColors = areaStyleModel.get('color');
  60930. var lineCount = 0;
  60931. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  60932. var splitAreas = [];
  60933. var RADIAN = Math.PI / 180;
  60934. var prevAngle = -ticksAngles[0].coord * RADIAN;
  60935. var r0 = Math.min(radiusExtent[0], radiusExtent[1]);
  60936. var r1 = Math.max(radiusExtent[0], radiusExtent[1]);
  60937. var clockwise = angleAxisModel.get('clockwise');
  60938. for (var i = 1; i < ticksAngles.length; i++) {
  60939. var colorIndex = lineCount++ % areaColors.length;
  60940. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  60941. splitAreas[colorIndex].push(new Sector({
  60942. shape: {
  60943. cx: polar.cx,
  60944. cy: polar.cy,
  60945. r0: r0,
  60946. r: r1,
  60947. startAngle: prevAngle,
  60948. endAngle: -ticksAngles[i].coord * RADIAN,
  60949. clockwise: clockwise
  60950. },
  60951. silent: true
  60952. }));
  60953. prevAngle = -ticksAngles[i].coord * RADIAN;
  60954. } // Simple optimization
  60955. // Batching the lines if color are the same
  60956. for (var i = 0; i < splitAreas.length; i++) {
  60957. this.group.add(mergePath(splitAreas[i], {
  60958. style: defaults({
  60959. fill: areaColors[i % areaColors.length]
  60960. }, areaStyleModel.getAreaStyle()),
  60961. silent: true
  60962. }));
  60963. }
  60964. }
  60965. });
  60966. /*
  60967. * Licensed to the Apache Software Foundation (ASF) under one
  60968. * or more contributor license agreements. See the NOTICE file
  60969. * distributed with this work for additional information
  60970. * regarding copyright ownership. The ASF licenses this file
  60971. * to you under the Apache License, Version 2.0 (the
  60972. * "License"); you may not use this file except in compliance
  60973. * with the License. You may obtain a copy of the License at
  60974. *
  60975. * http://www.apache.org/licenses/LICENSE-2.0
  60976. *
  60977. * Unless required by applicable law or agreed to in writing,
  60978. * software distributed under the License is distributed on an
  60979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60980. * KIND, either express or implied. See the License for the
  60981. * specific language governing permissions and limitations
  60982. * under the License.
  60983. */
  60984. /*
  60985. * Licensed to the Apache Software Foundation (ASF) under one
  60986. * or more contributor license agreements. See the NOTICE file
  60987. * distributed with this work for additional information
  60988. * regarding copyright ownership. The ASF licenses this file
  60989. * to you under the Apache License, Version 2.0 (the
  60990. * "License"); you may not use this file except in compliance
  60991. * with the License. You may obtain a copy of the License at
  60992. *
  60993. * http://www.apache.org/licenses/LICENSE-2.0
  60994. *
  60995. * Unless required by applicable law or agreed to in writing,
  60996. * software distributed under the License is distributed on an
  60997. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  60998. * KIND, either express or implied. See the License for the
  60999. * specific language governing permissions and limitations
  61000. * under the License.
  61001. */
  61002. var axisBuilderAttrs$3 = ['axisLine', 'axisTickLabel', 'axisName'];
  61003. var selfBuilderAttrs$2 = ['splitLine', 'splitArea', 'minorSplitLine'];
  61004. AxisView.extend({
  61005. type: 'radiusAxis',
  61006. axisPointerClass: 'PolarAxisPointer',
  61007. render: function (radiusAxisModel, ecModel) {
  61008. this.group.removeAll();
  61009. if (!radiusAxisModel.get('show')) {
  61010. return;
  61011. }
  61012. var radiusAxis = radiusAxisModel.axis;
  61013. var polar = radiusAxis.polar;
  61014. var angleAxis = polar.getAngleAxis();
  61015. var ticksCoords = radiusAxis.getTicksCoords();
  61016. var minorTicksCoords = radiusAxis.getMinorTicksCoords();
  61017. var axisAngle = angleAxis.getExtent()[0];
  61018. var radiusExtent = radiusAxis.getExtent();
  61019. var layout = layoutAxis(polar, radiusAxisModel, axisAngle);
  61020. var axisBuilder = new AxisBuilder(radiusAxisModel, layout);
  61021. each$1(axisBuilderAttrs$3, axisBuilder.add, axisBuilder);
  61022. this.group.add(axisBuilder.getGroup());
  61023. each$1(selfBuilderAttrs$2, function (name) {
  61024. if (radiusAxisModel.get(name + '.show') && !radiusAxis.scale.isBlank()) {
  61025. this['_' + name](radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords);
  61026. }
  61027. }, this);
  61028. },
  61029. /**
  61030. * @private
  61031. */
  61032. _splitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  61033. var splitLineModel = radiusAxisModel.getModel('splitLine');
  61034. var lineStyleModel = splitLineModel.getModel('lineStyle');
  61035. var lineColors = lineStyleModel.get('color');
  61036. var lineCount = 0;
  61037. lineColors = lineColors instanceof Array ? lineColors : [lineColors];
  61038. var splitLines = [];
  61039. for (var i = 0; i < ticksCoords.length; i++) {
  61040. var colorIndex = lineCount++ % lineColors.length;
  61041. splitLines[colorIndex] = splitLines[colorIndex] || [];
  61042. splitLines[colorIndex].push(new Circle({
  61043. shape: {
  61044. cx: polar.cx,
  61045. cy: polar.cy,
  61046. r: ticksCoords[i].coord
  61047. }
  61048. }));
  61049. } // Simple optimization
  61050. // Batching the lines if color are the same
  61051. for (var i = 0; i < splitLines.length; i++) {
  61052. this.group.add(mergePath(splitLines[i], {
  61053. style: defaults({
  61054. stroke: lineColors[i % lineColors.length],
  61055. fill: null
  61056. }, lineStyleModel.getLineStyle()),
  61057. silent: true
  61058. }));
  61059. }
  61060. },
  61061. /**
  61062. * @private
  61063. */
  61064. _minorSplitLine: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords, minorTicksCoords) {
  61065. if (!minorTicksCoords.length) {
  61066. return;
  61067. }
  61068. var minorSplitLineModel = radiusAxisModel.getModel('minorSplitLine');
  61069. var lineStyleModel = minorSplitLineModel.getModel('lineStyle');
  61070. var lines = [];
  61071. for (var i = 0; i < minorTicksCoords.length; i++) {
  61072. for (var k = 0; k < minorTicksCoords[i].length; k++) {
  61073. lines.push(new Circle({
  61074. shape: {
  61075. cx: polar.cx,
  61076. cy: polar.cy,
  61077. r: minorTicksCoords[i][k].coord
  61078. }
  61079. }));
  61080. }
  61081. }
  61082. this.group.add(mergePath(lines, {
  61083. style: defaults({
  61084. fill: null
  61085. }, lineStyleModel.getLineStyle()),
  61086. silent: true
  61087. }));
  61088. },
  61089. /**
  61090. * @private
  61091. */
  61092. _splitArea: function (radiusAxisModel, polar, axisAngle, radiusExtent, ticksCoords) {
  61093. if (!ticksCoords.length) {
  61094. return;
  61095. }
  61096. var splitAreaModel = radiusAxisModel.getModel('splitArea');
  61097. var areaStyleModel = splitAreaModel.getModel('areaStyle');
  61098. var areaColors = areaStyleModel.get('color');
  61099. var lineCount = 0;
  61100. areaColors = areaColors instanceof Array ? areaColors : [areaColors];
  61101. var splitAreas = [];
  61102. var prevRadius = ticksCoords[0].coord;
  61103. for (var i = 1; i < ticksCoords.length; i++) {
  61104. var colorIndex = lineCount++ % areaColors.length;
  61105. splitAreas[colorIndex] = splitAreas[colorIndex] || [];
  61106. splitAreas[colorIndex].push(new Sector({
  61107. shape: {
  61108. cx: polar.cx,
  61109. cy: polar.cy,
  61110. r0: prevRadius,
  61111. r: ticksCoords[i].coord,
  61112. startAngle: 0,
  61113. endAngle: Math.PI * 2
  61114. },
  61115. silent: true
  61116. }));
  61117. prevRadius = ticksCoords[i].coord;
  61118. } // Simple optimization
  61119. // Batching the lines if color are the same
  61120. for (var i = 0; i < splitAreas.length; i++) {
  61121. this.group.add(mergePath(splitAreas[i], {
  61122. style: defaults({
  61123. fill: areaColors[i % areaColors.length]
  61124. }, areaStyleModel.getAreaStyle()),
  61125. silent: true
  61126. }));
  61127. }
  61128. }
  61129. });
  61130. /**
  61131. * @inner
  61132. */
  61133. function layoutAxis(polar, radiusAxisModel, axisAngle) {
  61134. return {
  61135. position: [polar.cx, polar.cy],
  61136. rotation: axisAngle / 180 * Math.PI,
  61137. labelDirection: -1,
  61138. tickDirection: -1,
  61139. nameDirection: 1,
  61140. labelRotate: radiusAxisModel.getModel('axisLabel').get('rotate'),
  61141. // Over splitLine and splitArea
  61142. z2: 1
  61143. };
  61144. }
  61145. /*
  61146. * Licensed to the Apache Software Foundation (ASF) under one
  61147. * or more contributor license agreements. See the NOTICE file
  61148. * distributed with this work for additional information
  61149. * regarding copyright ownership. The ASF licenses this file
  61150. * to you under the Apache License, Version 2.0 (the
  61151. * "License"); you may not use this file except in compliance
  61152. * with the License. You may obtain a copy of the License at
  61153. *
  61154. * http://www.apache.org/licenses/LICENSE-2.0
  61155. *
  61156. * Unless required by applicable law or agreed to in writing,
  61157. * software distributed under the License is distributed on an
  61158. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61159. * KIND, either express or implied. See the License for the
  61160. * specific language governing permissions and limitations
  61161. * under the License.
  61162. */
  61163. /*
  61164. * Licensed to the Apache Software Foundation (ASF) under one
  61165. * or more contributor license agreements. See the NOTICE file
  61166. * distributed with this work for additional information
  61167. * regarding copyright ownership. The ASF licenses this file
  61168. * to you under the Apache License, Version 2.0 (the
  61169. * "License"); you may not use this file except in compliance
  61170. * with the License. You may obtain a copy of the License at
  61171. *
  61172. * http://www.apache.org/licenses/LICENSE-2.0
  61173. *
  61174. * Unless required by applicable law or agreed to in writing,
  61175. * software distributed under the License is distributed on an
  61176. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61177. * KIND, either express or implied. See the License for the
  61178. * specific language governing permissions and limitations
  61179. * under the License.
  61180. */
  61181. var PolarAxisPointer = BaseAxisPointer.extend({
  61182. /**
  61183. * @override
  61184. */
  61185. makeElOption: function (elOption, value, axisModel, axisPointerModel, api) {
  61186. var axis = axisModel.axis;
  61187. if (axis.dim === 'angle') {
  61188. this.animationThreshold = Math.PI / 18;
  61189. }
  61190. var polar = axis.polar;
  61191. var otherAxis = polar.getOtherAxis(axis);
  61192. var otherExtent = otherAxis.getExtent();
  61193. var coordValue;
  61194. coordValue = axis['dataTo' + capitalFirst(axis.dim)](value);
  61195. var axisPointerType = axisPointerModel.get('type');
  61196. if (axisPointerType && axisPointerType !== 'none') {
  61197. var elStyle = buildElStyle(axisPointerModel);
  61198. var pointerOption = pointerShapeBuilder$2[axisPointerType](axis, polar, coordValue, otherExtent, elStyle);
  61199. pointerOption.style = elStyle;
  61200. elOption.graphicKey = pointerOption.type;
  61201. elOption.pointer = pointerOption;
  61202. }
  61203. var labelMargin = axisPointerModel.get('label.margin');
  61204. var labelPos = getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin);
  61205. buildLabelElOption(elOption, axisModel, axisPointerModel, api, labelPos);
  61206. } // Do not support handle, utill any user requires it.
  61207. });
  61208. function getLabelPosition(value, axisModel, axisPointerModel, polar, labelMargin) {
  61209. var axis = axisModel.axis;
  61210. var coord = axis.dataToCoord(value);
  61211. var axisAngle = polar.getAngleAxis().getExtent()[0];
  61212. axisAngle = axisAngle / 180 * Math.PI;
  61213. var radiusExtent = polar.getRadiusAxis().getExtent();
  61214. var position;
  61215. var align;
  61216. var verticalAlign;
  61217. if (axis.dim === 'radius') {
  61218. var transform = create$1();
  61219. rotate(transform, transform, axisAngle);
  61220. translate(transform, transform, [polar.cx, polar.cy]);
  61221. position = applyTransform$1([coord, -labelMargin], transform);
  61222. var labelRotation = axisModel.getModel('axisLabel').get('rotate') || 0;
  61223. var labelLayout = AxisBuilder.innerTextLayout(axisAngle, labelRotation * Math.PI / 180, -1);
  61224. align = labelLayout.textAlign;
  61225. verticalAlign = labelLayout.textVerticalAlign;
  61226. } else {
  61227. // angle axis
  61228. var r = radiusExtent[1];
  61229. position = polar.coordToPoint([r + labelMargin, coord]);
  61230. var cx = polar.cx;
  61231. var cy = polar.cy;
  61232. align = Math.abs(position[0] - cx) / r < 0.3 ? 'center' : position[0] > cx ? 'left' : 'right';
  61233. verticalAlign = Math.abs(position[1] - cy) / r < 0.3 ? 'middle' : position[1] > cy ? 'top' : 'bottom';
  61234. }
  61235. return {
  61236. position: position,
  61237. align: align,
  61238. verticalAlign: verticalAlign
  61239. };
  61240. }
  61241. var pointerShapeBuilder$2 = {
  61242. line: function (axis, polar, coordValue, otherExtent, elStyle) {
  61243. return axis.dim === 'angle' ? {
  61244. type: 'Line',
  61245. shape: makeLineShape(polar.coordToPoint([otherExtent[0], coordValue]), polar.coordToPoint([otherExtent[1], coordValue]))
  61246. } : {
  61247. type: 'Circle',
  61248. shape: {
  61249. cx: polar.cx,
  61250. cy: polar.cy,
  61251. r: coordValue
  61252. }
  61253. };
  61254. },
  61255. shadow: function (axis, polar, coordValue, otherExtent, elStyle) {
  61256. var bandWidth = Math.max(1, axis.getBandWidth());
  61257. var radian = Math.PI / 180;
  61258. return axis.dim === 'angle' ? {
  61259. type: 'Sector',
  61260. shape: makeSectorShape(polar.cx, polar.cy, otherExtent[0], otherExtent[1], // In ECharts y is negative if angle is positive
  61261. (-coordValue - bandWidth / 2) * radian, (-coordValue + bandWidth / 2) * radian)
  61262. } : {
  61263. type: 'Sector',
  61264. shape: makeSectorShape(polar.cx, polar.cy, coordValue - bandWidth / 2, coordValue + bandWidth / 2, 0, Math.PI * 2)
  61265. };
  61266. }
  61267. };
  61268. AxisView.registerAxisPointerClass('PolarAxisPointer', PolarAxisPointer);
  61269. /*
  61270. * Licensed to the Apache Software Foundation (ASF) under one
  61271. * or more contributor license agreements. See the NOTICE file
  61272. * distributed with this work for additional information
  61273. * regarding copyright ownership. The ASF licenses this file
  61274. * to you under the Apache License, Version 2.0 (the
  61275. * "License"); you may not use this file except in compliance
  61276. * with the License. You may obtain a copy of the License at
  61277. *
  61278. * http://www.apache.org/licenses/LICENSE-2.0
  61279. *
  61280. * Unless required by applicable law or agreed to in writing,
  61281. * software distributed under the License is distributed on an
  61282. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61283. * KIND, either express or implied. See the License for the
  61284. * specific language governing permissions and limitations
  61285. * under the License.
  61286. */
  61287. registerLayout(curry(barLayoutPolar, 'bar')); // Polar view
  61288. extendComponentView({
  61289. type: 'polar'
  61290. });
  61291. /*
  61292. * Licensed to the Apache Software Foundation (ASF) under one
  61293. * or more contributor license agreements. See the NOTICE file
  61294. * distributed with this work for additional information
  61295. * regarding copyright ownership. The ASF licenses this file
  61296. * to you under the Apache License, Version 2.0 (the
  61297. * "License"); you may not use this file except in compliance
  61298. * with the License. You may obtain a copy of the License at
  61299. *
  61300. * http://www.apache.org/licenses/LICENSE-2.0
  61301. *
  61302. * Unless required by applicable law or agreed to in writing,
  61303. * software distributed under the License is distributed on an
  61304. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61305. * KIND, either express or implied. See the License for the
  61306. * specific language governing permissions and limitations
  61307. * under the License.
  61308. */
  61309. var GeoModel = ComponentModel.extend({
  61310. type: 'geo',
  61311. /**
  61312. * @type {module:echarts/coord/geo/Geo}
  61313. */
  61314. coordinateSystem: null,
  61315. layoutMode: 'box',
  61316. init: function (option) {
  61317. ComponentModel.prototype.init.apply(this, arguments); // Default label emphasis `show`
  61318. defaultEmphasis(option, 'label', ['show']);
  61319. },
  61320. optionUpdated: function () {
  61321. var option = this.option;
  61322. var self = this;
  61323. option.regions = geoCreator.getFilledRegions(option.regions, option.map, option.nameMap);
  61324. this._optionModelMap = reduce(option.regions || [], function (optionModelMap, regionOpt) {
  61325. if (regionOpt.name) {
  61326. optionModelMap.set(regionOpt.name, new Model(regionOpt, self));
  61327. }
  61328. return optionModelMap;
  61329. }, createHashMap());
  61330. this.updateSelectedMap(option.regions);
  61331. },
  61332. defaultOption: {
  61333. zlevel: 0,
  61334. z: 0,
  61335. show: true,
  61336. left: 'center',
  61337. top: 'center',
  61338. // width:,
  61339. // height:,
  61340. // right
  61341. // bottom
  61342. // Aspect is width / height. Inited to be geoJson bbox aspect
  61343. // This parameter is used for scale this aspect
  61344. // If svg used, aspectScale is 1 by default.
  61345. // aspectScale: 0.75,
  61346. aspectScale: null,
  61347. ///// Layout with center and size
  61348. // If you wan't to put map in a fixed size box with right aspect ratio
  61349. // This two properties may more conveninet
  61350. // layoutCenter: [50%, 50%]
  61351. // layoutSize: 100
  61352. silent: false,
  61353. // Map type
  61354. map: '',
  61355. // Define left-top, right-bottom coords to control view
  61356. // For example, [ [180, 90], [-180, -90] ]
  61357. boundingCoords: null,
  61358. // Default on center of map
  61359. center: null,
  61360. zoom: 1,
  61361. scaleLimit: null,
  61362. // selectedMode: false
  61363. label: {
  61364. show: false,
  61365. color: '#000'
  61366. },
  61367. itemStyle: {
  61368. // color: 各异,
  61369. borderWidth: 0.5,
  61370. borderColor: '#444',
  61371. color: '#eee'
  61372. },
  61373. emphasis: {
  61374. label: {
  61375. show: true,
  61376. color: 'rgb(100,0,0)'
  61377. },
  61378. itemStyle: {
  61379. color: 'rgba(255,215,0,0.8)'
  61380. }
  61381. },
  61382. regions: []
  61383. },
  61384. /**
  61385. * Get model of region
  61386. * @param {string} name
  61387. * @return {module:echarts/model/Model}
  61388. */
  61389. getRegionModel: function (name) {
  61390. return this._optionModelMap.get(name) || new Model(null, this, this.ecModel);
  61391. },
  61392. /**
  61393. * Format label
  61394. * @param {string} name Region name
  61395. * @param {string} [status='normal'] 'normal' or 'emphasis'
  61396. * @return {string}
  61397. */
  61398. getFormattedLabel: function (name, status) {
  61399. var regionModel = this.getRegionModel(name);
  61400. var formatter = regionModel.get('label' + (status === 'normal' ? '.' : status + '.') + 'formatter');
  61401. var params = {
  61402. name: name
  61403. };
  61404. if (typeof formatter === 'function') {
  61405. params.status = status;
  61406. return formatter(params);
  61407. } else if (typeof formatter === 'string') {
  61408. return formatter.replace('{a}', name != null ? name : '');
  61409. }
  61410. },
  61411. setZoom: function (zoom) {
  61412. this.option.zoom = zoom;
  61413. },
  61414. setCenter: function (center) {
  61415. this.option.center = center;
  61416. }
  61417. });
  61418. mixin(GeoModel, selectableMixin);
  61419. /*
  61420. * Licensed to the Apache Software Foundation (ASF) under one
  61421. * or more contributor license agreements. See the NOTICE file
  61422. * distributed with this work for additional information
  61423. * regarding copyright ownership. The ASF licenses this file
  61424. * to you under the Apache License, Version 2.0 (the
  61425. * "License"); you may not use this file except in compliance
  61426. * with the License. You may obtain a copy of the License at
  61427. *
  61428. * http://www.apache.org/licenses/LICENSE-2.0
  61429. *
  61430. * Unless required by applicable law or agreed to in writing,
  61431. * software distributed under the License is distributed on an
  61432. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61433. * KIND, either express or implied. See the License for the
  61434. * specific language governing permissions and limitations
  61435. * under the License.
  61436. */
  61437. extendComponentView({
  61438. type: 'geo',
  61439. init: function (ecModel, api) {
  61440. var mapDraw = new MapDraw(api, true);
  61441. this._mapDraw = mapDraw;
  61442. this.group.add(mapDraw.group);
  61443. },
  61444. render: function (geoModel, ecModel, api, payload) {
  61445. // Not render if it is an toggleSelect action from self
  61446. if (payload && payload.type === 'geoToggleSelect' && payload.from === this.uid) {
  61447. return;
  61448. }
  61449. var mapDraw = this._mapDraw;
  61450. if (geoModel.get('show')) {
  61451. mapDraw.draw(geoModel, ecModel, api, this, payload);
  61452. } else {
  61453. this._mapDraw.group.removeAll();
  61454. }
  61455. this.group.silent = geoModel.get('silent');
  61456. },
  61457. dispose: function () {
  61458. this._mapDraw && this._mapDraw.remove();
  61459. }
  61460. });
  61461. /*
  61462. * Licensed to the Apache Software Foundation (ASF) under one
  61463. * or more contributor license agreements. See the NOTICE file
  61464. * distributed with this work for additional information
  61465. * regarding copyright ownership. The ASF licenses this file
  61466. * to you under the Apache License, Version 2.0 (the
  61467. * "License"); you may not use this file except in compliance
  61468. * with the License. You may obtain a copy of the License at
  61469. *
  61470. * http://www.apache.org/licenses/LICENSE-2.0
  61471. *
  61472. * Unless required by applicable law or agreed to in writing,
  61473. * software distributed under the License is distributed on an
  61474. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61475. * KIND, either express or implied. See the License for the
  61476. * specific language governing permissions and limitations
  61477. * under the License.
  61478. */
  61479. function makeAction(method, actionInfo) {
  61480. actionInfo.update = 'updateView';
  61481. registerAction(actionInfo, function (payload, ecModel) {
  61482. var selected = {};
  61483. ecModel.eachComponent({
  61484. mainType: 'geo',
  61485. query: payload
  61486. }, function (geoModel) {
  61487. geoModel[method](payload.name);
  61488. var geo = geoModel.coordinateSystem;
  61489. each$1(geo.regions, function (region) {
  61490. selected[region.name] = geoModel.isSelected(region.name) || false;
  61491. });
  61492. });
  61493. return {
  61494. selected: selected,
  61495. name: payload.name
  61496. };
  61497. });
  61498. }
  61499. makeAction('toggleSelected', {
  61500. type: 'geoToggleSelect',
  61501. event: 'geoselectchanged'
  61502. });
  61503. makeAction('select', {
  61504. type: 'geoSelect',
  61505. event: 'geoselected'
  61506. });
  61507. makeAction('unSelect', {
  61508. type: 'geoUnSelect',
  61509. event: 'geounselected'
  61510. });
  61511. /*
  61512. * Licensed to the Apache Software Foundation (ASF) under one
  61513. * or more contributor license agreements. See the NOTICE file
  61514. * distributed with this work for additional information
  61515. * regarding copyright ownership. The ASF licenses this file
  61516. * to you under the Apache License, Version 2.0 (the
  61517. * "License"); you may not use this file except in compliance
  61518. * with the License. You may obtain a copy of the License at
  61519. *
  61520. * http://www.apache.org/licenses/LICENSE-2.0
  61521. *
  61522. * Unless required by applicable law or agreed to in writing,
  61523. * software distributed under the License is distributed on an
  61524. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61525. * KIND, either express or implied. See the License for the
  61526. * specific language governing permissions and limitations
  61527. * under the License.
  61528. */
  61529. var PROXIMATE_ONE_DAY = 86400000;
  61530. /**
  61531. * Calendar
  61532. *
  61533. * @constructor
  61534. *
  61535. * @param {Object} calendarModel calendarModel
  61536. * @param {Object} ecModel ecModel
  61537. * @param {Object} api api
  61538. */
  61539. function Calendar(calendarModel, ecModel, api) {
  61540. this._model = calendarModel;
  61541. }
  61542. Calendar.prototype = {
  61543. constructor: Calendar,
  61544. type: 'calendar',
  61545. dimensions: ['time', 'value'],
  61546. // Required in createListFromData
  61547. getDimensionsInfo: function () {
  61548. return [{
  61549. name: 'time',
  61550. type: 'time'
  61551. }, 'value'];
  61552. },
  61553. getRangeInfo: function () {
  61554. return this._rangeInfo;
  61555. },
  61556. getModel: function () {
  61557. return this._model;
  61558. },
  61559. getRect: function () {
  61560. return this._rect;
  61561. },
  61562. getCellWidth: function () {
  61563. return this._sw;
  61564. },
  61565. getCellHeight: function () {
  61566. return this._sh;
  61567. },
  61568. getOrient: function () {
  61569. return this._orient;
  61570. },
  61571. /**
  61572. * getFirstDayOfWeek
  61573. *
  61574. * @example
  61575. * 0 : start at Sunday
  61576. * 1 : start at Monday
  61577. *
  61578. * @return {number}
  61579. */
  61580. getFirstDayOfWeek: function () {
  61581. return this._firstDayOfWeek;
  61582. },
  61583. /**
  61584. * get date info
  61585. *
  61586. * @param {string|number} date date
  61587. * @return {Object}
  61588. * {
  61589. * y: string, local full year, eg., '1940',
  61590. * m: string, local month, from '01' ot '12',
  61591. * d: string, local date, from '01' to '31' (if exists),
  61592. * day: It is not date.getDay(). It is the location of the cell in a week, from 0 to 6,
  61593. * time: timestamp,
  61594. * formatedDate: string, yyyy-MM-dd,
  61595. * date: original date object.
  61596. * }
  61597. */
  61598. getDateInfo: function (date) {
  61599. date = parseDate(date);
  61600. var y = date.getFullYear();
  61601. var m = date.getMonth() + 1;
  61602. m = m < 10 ? '0' + m : m;
  61603. var d = date.getDate();
  61604. d = d < 10 ? '0' + d : d;
  61605. var day = date.getDay();
  61606. day = Math.abs((day + 7 - this.getFirstDayOfWeek()) % 7);
  61607. return {
  61608. y: y,
  61609. m: m,
  61610. d: d,
  61611. day: day,
  61612. time: date.getTime(),
  61613. formatedDate: y + '-' + m + '-' + d,
  61614. date: date
  61615. };
  61616. },
  61617. getNextNDay: function (date, n) {
  61618. n = n || 0;
  61619. if (n === 0) {
  61620. return this.getDateInfo(date);
  61621. }
  61622. date = new Date(this.getDateInfo(date).time);
  61623. date.setDate(date.getDate() + n);
  61624. return this.getDateInfo(date);
  61625. },
  61626. update: function (ecModel, api) {
  61627. this._firstDayOfWeek = +this._model.getModel('dayLabel').get('firstDay');
  61628. this._orient = this._model.get('orient');
  61629. this._lineWidth = this._model.getModel('itemStyle').getItemStyle().lineWidth || 0;
  61630. this._rangeInfo = this._getRangeInfo(this._initRangeOption());
  61631. var weeks = this._rangeInfo.weeks || 1;
  61632. var whNames = ['width', 'height'];
  61633. var cellSize = this._model.get('cellSize').slice();
  61634. var layoutParams = this._model.getBoxLayoutParams();
  61635. var cellNumbers = this._orient === 'horizontal' ? [weeks, 7] : [7, weeks];
  61636. each$1([0, 1], function (idx) {
  61637. if (cellSizeSpecified(cellSize, idx)) {
  61638. layoutParams[whNames[idx]] = cellSize[idx] * cellNumbers[idx];
  61639. }
  61640. });
  61641. var whGlobal = {
  61642. width: api.getWidth(),
  61643. height: api.getHeight()
  61644. };
  61645. var calendarRect = this._rect = getLayoutRect(layoutParams, whGlobal);
  61646. each$1([0, 1], function (idx) {
  61647. if (!cellSizeSpecified(cellSize, idx)) {
  61648. cellSize[idx] = calendarRect[whNames[idx]] / cellNumbers[idx];
  61649. }
  61650. });
  61651. function cellSizeSpecified(cellSize, idx) {
  61652. return cellSize[idx] != null && cellSize[idx] !== 'auto';
  61653. }
  61654. this._sw = cellSize[0];
  61655. this._sh = cellSize[1];
  61656. },
  61657. /**
  61658. * Convert a time data(time, value) item to (x, y) point.
  61659. *
  61660. * @override
  61661. * @param {Array|number} data data
  61662. * @param {boolean} [clamp=true] out of range
  61663. * @return {Array} point
  61664. */
  61665. dataToPoint: function (data, clamp) {
  61666. isArray(data) && (data = data[0]);
  61667. clamp == null && (clamp = true);
  61668. var dayInfo = this.getDateInfo(data);
  61669. var range = this._rangeInfo;
  61670. var date = dayInfo.formatedDate; // if not in range return [NaN, NaN]
  61671. if (clamp && !(dayInfo.time >= range.start.time && dayInfo.time < range.end.time + PROXIMATE_ONE_DAY)) {
  61672. return [NaN, NaN];
  61673. }
  61674. var week = dayInfo.day;
  61675. var nthWeek = this._getRangeInfo([range.start.time, date]).nthWeek;
  61676. if (this._orient === 'vertical') {
  61677. return [this._rect.x + week * this._sw + this._sw / 2, this._rect.y + nthWeek * this._sh + this._sh / 2];
  61678. }
  61679. return [this._rect.x + nthWeek * this._sw + this._sw / 2, this._rect.y + week * this._sh + this._sh / 2];
  61680. },
  61681. /**
  61682. * Convert a (x, y) point to time data
  61683. *
  61684. * @override
  61685. * @param {string} point point
  61686. * @return {string} data
  61687. */
  61688. pointToData: function (point) {
  61689. var date = this.pointToDate(point);
  61690. return date && date.time;
  61691. },
  61692. /**
  61693. * Convert a time date item to (x, y) four point.
  61694. *
  61695. * @param {Array} data date[0] is date
  61696. * @param {boolean} [clamp=true] out of range
  61697. * @return {Object} point
  61698. */
  61699. dataToRect: function (data, clamp) {
  61700. var point = this.dataToPoint(data, clamp);
  61701. return {
  61702. contentShape: {
  61703. x: point[0] - (this._sw - this._lineWidth) / 2,
  61704. y: point[1] - (this._sh - this._lineWidth) / 2,
  61705. width: this._sw - this._lineWidth,
  61706. height: this._sh - this._lineWidth
  61707. },
  61708. center: point,
  61709. tl: [point[0] - this._sw / 2, point[1] - this._sh / 2],
  61710. tr: [point[0] + this._sw / 2, point[1] - this._sh / 2],
  61711. br: [point[0] + this._sw / 2, point[1] + this._sh / 2],
  61712. bl: [point[0] - this._sw / 2, point[1] + this._sh / 2]
  61713. };
  61714. },
  61715. /**
  61716. * Convert a (x, y) point to time date
  61717. *
  61718. * @param {Array} point point
  61719. * @return {Object} date
  61720. */
  61721. pointToDate: function (point) {
  61722. var nthX = Math.floor((point[0] - this._rect.x) / this._sw) + 1;
  61723. var nthY = Math.floor((point[1] - this._rect.y) / this._sh) + 1;
  61724. var range = this._rangeInfo.range;
  61725. if (this._orient === 'vertical') {
  61726. return this._getDateByWeeksAndDay(nthY, nthX - 1, range);
  61727. }
  61728. return this._getDateByWeeksAndDay(nthX, nthY - 1, range);
  61729. },
  61730. /**
  61731. * @inheritDoc
  61732. */
  61733. convertToPixel: curry(doConvert$2, 'dataToPoint'),
  61734. /**
  61735. * @inheritDoc
  61736. */
  61737. convertFromPixel: curry(doConvert$2, 'pointToData'),
  61738. /**
  61739. * initRange
  61740. *
  61741. * @private
  61742. * @return {Array} [start, end]
  61743. */
  61744. _initRangeOption: function () {
  61745. var range = this._model.get('range');
  61746. var rg = range;
  61747. if (isArray(rg) && rg.length === 1) {
  61748. rg = rg[0];
  61749. }
  61750. if (/^\d{4}$/.test(rg)) {
  61751. range = [rg + '-01-01', rg + '-12-31'];
  61752. }
  61753. if (/^\d{4}[\/|-]\d{1,2}$/.test(rg)) {
  61754. var start = this.getDateInfo(rg);
  61755. var firstDay = start.date;
  61756. firstDay.setMonth(firstDay.getMonth() + 1);
  61757. var end = this.getNextNDay(firstDay, -1);
  61758. range = [start.formatedDate, end.formatedDate];
  61759. }
  61760. if (/^\d{4}[\/|-]\d{1,2}[\/|-]\d{1,2}$/.test(rg)) {
  61761. range = [rg, rg];
  61762. }
  61763. var tmp = this._getRangeInfo(range);
  61764. if (tmp.start.time > tmp.end.time) {
  61765. range.reverse();
  61766. }
  61767. return range;
  61768. },
  61769. /**
  61770. * range info
  61771. *
  61772. * @private
  61773. * @param {Array} range range ['2017-01-01', '2017-07-08']
  61774. * If range[0] > range[1], they will not be reversed.
  61775. * @return {Object} obj
  61776. */
  61777. _getRangeInfo: function (range) {
  61778. range = [this.getDateInfo(range[0]), this.getDateInfo(range[1])];
  61779. var reversed;
  61780. if (range[0].time > range[1].time) {
  61781. reversed = true;
  61782. range.reverse();
  61783. }
  61784. var allDay = Math.floor(range[1].time / PROXIMATE_ONE_DAY) - Math.floor(range[0].time / PROXIMATE_ONE_DAY) + 1; // Consider case1 (#11677 #10430):
  61785. // Set the system timezone as "UK", set the range to `['2016-07-01', '2016-12-31']`
  61786. // Consider case2:
  61787. // Firstly set system timezone as "Time Zone: America/Toronto",
  61788. // ```
  61789. // var first = new Date(1478412000000 - 3600 * 1000 * 2.5);
  61790. // var second = new Date(1478412000000);
  61791. // var allDays = Math.floor(second / ONE_DAY) - Math.floor(first / ONE_DAY) + 1;
  61792. // ```
  61793. // will get wrong result because of DST. So we should fix it.
  61794. var date = new Date(range[0].time);
  61795. var startDateNum = date.getDate();
  61796. var endDateNum = range[1].date.getDate();
  61797. date.setDate(startDateNum + allDay - 1); // The bias can not over a month, so just compare date.
  61798. var dateNum = date.getDate();
  61799. if (dateNum !== endDateNum) {
  61800. var sign = date.getTime() - range[1].time > 0 ? 1 : -1;
  61801. while ((dateNum = date.getDate()) !== endDateNum && (date.getTime() - range[1].time) * sign > 0) {
  61802. allDay -= sign;
  61803. date.setDate(dateNum - sign);
  61804. }
  61805. }
  61806. var weeks = Math.floor((allDay + range[0].day + 6) / 7);
  61807. var nthWeek = reversed ? -weeks + 1 : weeks - 1;
  61808. reversed && range.reverse();
  61809. return {
  61810. range: [range[0].formatedDate, range[1].formatedDate],
  61811. start: range[0],
  61812. end: range[1],
  61813. allDay: allDay,
  61814. weeks: weeks,
  61815. // From 0.
  61816. nthWeek: nthWeek,
  61817. fweek: range[0].day,
  61818. lweek: range[1].day
  61819. };
  61820. },
  61821. /**
  61822. * get date by nthWeeks and week day in range
  61823. *
  61824. * @private
  61825. * @param {number} nthWeek the week
  61826. * @param {number} day the week day
  61827. * @param {Array} range [d1, d2]
  61828. * @return {Object}
  61829. */
  61830. _getDateByWeeksAndDay: function (nthWeek, day, range) {
  61831. var rangeInfo = this._getRangeInfo(range);
  61832. if (nthWeek > rangeInfo.weeks || nthWeek === 0 && day < rangeInfo.fweek || nthWeek === rangeInfo.weeks && day > rangeInfo.lweek) {
  61833. return false;
  61834. }
  61835. var nthDay = (nthWeek - 1) * 7 - rangeInfo.fweek + day;
  61836. var date = new Date(rangeInfo.start.time);
  61837. date.setDate(rangeInfo.start.d + nthDay);
  61838. return this.getDateInfo(date);
  61839. }
  61840. };
  61841. Calendar.dimensions = Calendar.prototype.dimensions;
  61842. Calendar.getDimensionsInfo = Calendar.prototype.getDimensionsInfo;
  61843. Calendar.create = function (ecModel, api) {
  61844. var calendarList = [];
  61845. ecModel.eachComponent('calendar', function (calendarModel) {
  61846. var calendar = new Calendar(calendarModel, ecModel, api);
  61847. calendarList.push(calendar);
  61848. calendarModel.coordinateSystem = calendar;
  61849. });
  61850. ecModel.eachSeries(function (calendarSeries) {
  61851. if (calendarSeries.get('coordinateSystem') === 'calendar') {
  61852. // Inject coordinate system
  61853. calendarSeries.coordinateSystem = calendarList[calendarSeries.get('calendarIndex') || 0];
  61854. }
  61855. });
  61856. return calendarList;
  61857. };
  61858. function doConvert$2(methodName, ecModel, finder, value) {
  61859. var calendarModel = finder.calendarModel;
  61860. var seriesModel = finder.seriesModel;
  61861. var coordSys = calendarModel ? calendarModel.coordinateSystem : seriesModel ? seriesModel.coordinateSystem : null;
  61862. return coordSys === this ? coordSys[methodName](value) : null;
  61863. }
  61864. CoordinateSystemManager.register('calendar', Calendar);
  61865. /*
  61866. * Licensed to the Apache Software Foundation (ASF) under one
  61867. * or more contributor license agreements. See the NOTICE file
  61868. * distributed with this work for additional information
  61869. * regarding copyright ownership. The ASF licenses this file
  61870. * to you under the Apache License, Version 2.0 (the
  61871. * "License"); you may not use this file except in compliance
  61872. * with the License. You may obtain a copy of the License at
  61873. *
  61874. * http://www.apache.org/licenses/LICENSE-2.0
  61875. *
  61876. * Unless required by applicable law or agreed to in writing,
  61877. * software distributed under the License is distributed on an
  61878. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  61879. * KIND, either express or implied. See the License for the
  61880. * specific language governing permissions and limitations
  61881. * under the License.
  61882. */
  61883. var CalendarModel = ComponentModel.extend({
  61884. type: 'calendar',
  61885. /**
  61886. * @type {module:echarts/coord/calendar/Calendar}
  61887. */
  61888. coordinateSystem: null,
  61889. defaultOption: {
  61890. zlevel: 0,
  61891. z: 2,
  61892. left: 80,
  61893. top: 60,
  61894. cellSize: 20,
  61895. // horizontal vertical
  61896. orient: 'horizontal',
  61897. // month separate line style
  61898. splitLine: {
  61899. show: true,
  61900. lineStyle: {
  61901. color: '#000',
  61902. width: 1,
  61903. type: 'solid'
  61904. }
  61905. },
  61906. // rect style temporarily unused emphasis
  61907. itemStyle: {
  61908. color: '#fff',
  61909. borderWidth: 1,
  61910. borderColor: '#ccc'
  61911. },
  61912. // week text style
  61913. dayLabel: {
  61914. show: true,
  61915. // a week first day
  61916. firstDay: 0,
  61917. // start end
  61918. position: 'start',
  61919. margin: '50%',
  61920. // 50% of cellSize
  61921. nameMap: 'en',
  61922. color: '#000'
  61923. },
  61924. // month text style
  61925. monthLabel: {
  61926. show: true,
  61927. // start end
  61928. position: 'start',
  61929. margin: 5,
  61930. // center or left
  61931. align: 'center',
  61932. // cn en []
  61933. nameMap: 'en',
  61934. formatter: null,
  61935. color: '#000'
  61936. },
  61937. // year text style
  61938. yearLabel: {
  61939. show: true,
  61940. // top bottom left right
  61941. position: null,
  61942. margin: 30,
  61943. formatter: null,
  61944. color: '#ccc',
  61945. fontFamily: 'sans-serif',
  61946. fontWeight: 'bolder',
  61947. fontSize: 20
  61948. }
  61949. },
  61950. /**
  61951. * @override
  61952. */
  61953. init: function (option, parentModel, ecModel, extraOpt) {
  61954. var inputPositionParams = getLayoutParams(option);
  61955. CalendarModel.superApply(this, 'init', arguments);
  61956. mergeAndNormalizeLayoutParams(option, inputPositionParams);
  61957. },
  61958. /**
  61959. * @override
  61960. */
  61961. mergeOption: function (option, extraOpt) {
  61962. CalendarModel.superApply(this, 'mergeOption', arguments);
  61963. mergeAndNormalizeLayoutParams(this.option, option);
  61964. }
  61965. });
  61966. function mergeAndNormalizeLayoutParams(target, raw) {
  61967. // Normalize cellSize
  61968. var cellSize = target.cellSize;
  61969. if (!isArray(cellSize)) {
  61970. cellSize = target.cellSize = [cellSize, cellSize];
  61971. } else if (cellSize.length === 1) {
  61972. cellSize[1] = cellSize[0];
  61973. }
  61974. var ignoreSize = map([0, 1], function (hvIdx) {
  61975. // If user have set `width` or both `left` and `right`, cellSize
  61976. // will be automatically set to 'auto', otherwise the default
  61977. // setting of cellSize will make `width` setting not work.
  61978. if (sizeCalculable(raw, hvIdx)) {
  61979. cellSize[hvIdx] = 'auto';
  61980. }
  61981. return cellSize[hvIdx] != null && cellSize[hvIdx] !== 'auto';
  61982. });
  61983. mergeLayoutParam(target, raw, {
  61984. type: 'box',
  61985. ignoreSize: ignoreSize
  61986. });
  61987. }
  61988. /*
  61989. * Licensed to the Apache Software Foundation (ASF) under one
  61990. * or more contributor license agreements. See the NOTICE file
  61991. * distributed with this work for additional information
  61992. * regarding copyright ownership. The ASF licenses this file
  61993. * to you under the Apache License, Version 2.0 (the
  61994. * "License"); you may not use this file except in compliance
  61995. * with the License. You may obtain a copy of the License at
  61996. *
  61997. * http://www.apache.org/licenses/LICENSE-2.0
  61998. *
  61999. * Unless required by applicable law or agreed to in writing,
  62000. * software distributed under the License is distributed on an
  62001. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62002. * KIND, either express or implied. See the License for the
  62003. * specific language governing permissions and limitations
  62004. * under the License.
  62005. */
  62006. var MONTH_TEXT = {
  62007. EN: ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'],
  62008. CN: ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月']
  62009. };
  62010. var WEEK_TEXT = {
  62011. EN: ['S', 'M', 'T', 'W', 'T', 'F', 'S'],
  62012. CN: ['日', '一', '二', '三', '四', '五', '六']
  62013. };
  62014. extendComponentView({
  62015. type: 'calendar',
  62016. /**
  62017. * top/left line points
  62018. * @private
  62019. */
  62020. _tlpoints: null,
  62021. /**
  62022. * bottom/right line points
  62023. * @private
  62024. */
  62025. _blpoints: null,
  62026. /**
  62027. * first day of month
  62028. * @private
  62029. */
  62030. _firstDayOfMonth: null,
  62031. /**
  62032. * first day point of month
  62033. * @private
  62034. */
  62035. _firstDayPoints: null,
  62036. render: function (calendarModel, ecModel, api) {
  62037. var group = this.group;
  62038. group.removeAll();
  62039. var coordSys = calendarModel.coordinateSystem; // range info
  62040. var rangeData = coordSys.getRangeInfo();
  62041. var orient = coordSys.getOrient();
  62042. this._renderDayRect(calendarModel, rangeData, group); // _renderLines must be called prior to following function
  62043. this._renderLines(calendarModel, rangeData, orient, group);
  62044. this._renderYearText(calendarModel, rangeData, orient, group);
  62045. this._renderMonthText(calendarModel, orient, group);
  62046. this._renderWeekText(calendarModel, rangeData, orient, group);
  62047. },
  62048. // render day rect
  62049. _renderDayRect: function (calendarModel, rangeData, group) {
  62050. var coordSys = calendarModel.coordinateSystem;
  62051. var itemRectStyleModel = calendarModel.getModel('itemStyle').getItemStyle();
  62052. var sw = coordSys.getCellWidth();
  62053. var sh = coordSys.getCellHeight();
  62054. for (var i = rangeData.start.time; i <= rangeData.end.time; i = coordSys.getNextNDay(i, 1).time) {
  62055. var point = coordSys.dataToRect([i], false).tl; // every rect
  62056. var rect = new Rect({
  62057. shape: {
  62058. x: point[0],
  62059. y: point[1],
  62060. width: sw,
  62061. height: sh
  62062. },
  62063. cursor: 'default',
  62064. style: itemRectStyleModel
  62065. });
  62066. group.add(rect);
  62067. }
  62068. },
  62069. // render separate line
  62070. _renderLines: function (calendarModel, rangeData, orient, group) {
  62071. var self = this;
  62072. var coordSys = calendarModel.coordinateSystem;
  62073. var lineStyleModel = calendarModel.getModel('splitLine.lineStyle').getLineStyle();
  62074. var show = calendarModel.get('splitLine.show');
  62075. var lineWidth = lineStyleModel.lineWidth;
  62076. this._tlpoints = [];
  62077. this._blpoints = [];
  62078. this._firstDayOfMonth = [];
  62079. this._firstDayPoints = [];
  62080. var firstDay = rangeData.start;
  62081. for (var i = 0; firstDay.time <= rangeData.end.time; i++) {
  62082. addPoints(firstDay.formatedDate);
  62083. if (i === 0) {
  62084. firstDay = coordSys.getDateInfo(rangeData.start.y + '-' + rangeData.start.m);
  62085. }
  62086. var date = firstDay.date;
  62087. date.setMonth(date.getMonth() + 1);
  62088. firstDay = coordSys.getDateInfo(date);
  62089. }
  62090. addPoints(coordSys.getNextNDay(rangeData.end.time, 1).formatedDate);
  62091. function addPoints(date) {
  62092. self._firstDayOfMonth.push(coordSys.getDateInfo(date));
  62093. self._firstDayPoints.push(coordSys.dataToRect([date], false).tl);
  62094. var points = self._getLinePointsOfOneWeek(calendarModel, date, orient);
  62095. self._tlpoints.push(points[0]);
  62096. self._blpoints.push(points[points.length - 1]);
  62097. show && self._drawSplitline(points, lineStyleModel, group);
  62098. } // render top/left line
  62099. show && this._drawSplitline(self._getEdgesPoints(self._tlpoints, lineWidth, orient), lineStyleModel, group); // render bottom/right line
  62100. show && this._drawSplitline(self._getEdgesPoints(self._blpoints, lineWidth, orient), lineStyleModel, group);
  62101. },
  62102. // get points at both ends
  62103. _getEdgesPoints: function (points, lineWidth, orient) {
  62104. var rs = [points[0].slice(), points[points.length - 1].slice()];
  62105. var idx = orient === 'horizontal' ? 0 : 1; // both ends of the line are extend half lineWidth
  62106. rs[0][idx] = rs[0][idx] - lineWidth / 2;
  62107. rs[1][idx] = rs[1][idx] + lineWidth / 2;
  62108. return rs;
  62109. },
  62110. // render split line
  62111. _drawSplitline: function (points, lineStyleModel, group) {
  62112. var poyline = new Polyline({
  62113. z2: 20,
  62114. shape: {
  62115. points: points
  62116. },
  62117. style: lineStyleModel
  62118. });
  62119. group.add(poyline);
  62120. },
  62121. // render month line of one week points
  62122. _getLinePointsOfOneWeek: function (calendarModel, date, orient) {
  62123. var coordSys = calendarModel.coordinateSystem;
  62124. date = coordSys.getDateInfo(date);
  62125. var points = [];
  62126. for (var i = 0; i < 7; i++) {
  62127. var tmpD = coordSys.getNextNDay(date.time, i);
  62128. var point = coordSys.dataToRect([tmpD.time], false);
  62129. points[2 * tmpD.day] = point.tl;
  62130. points[2 * tmpD.day + 1] = point[orient === 'horizontal' ? 'bl' : 'tr'];
  62131. }
  62132. return points;
  62133. },
  62134. _formatterLabel: function (formatter, params) {
  62135. if (typeof formatter === 'string' && formatter) {
  62136. return formatTplSimple(formatter, params);
  62137. }
  62138. if (typeof formatter === 'function') {
  62139. return formatter(params);
  62140. }
  62141. return params.nameMap;
  62142. },
  62143. _yearTextPositionControl: function (textEl, point, orient, position, margin) {
  62144. point = point.slice();
  62145. var aligns = ['center', 'bottom'];
  62146. if (position === 'bottom') {
  62147. point[1] += margin;
  62148. aligns = ['center', 'top'];
  62149. } else if (position === 'left') {
  62150. point[0] -= margin;
  62151. } else if (position === 'right') {
  62152. point[0] += margin;
  62153. aligns = ['center', 'top'];
  62154. } else {
  62155. // top
  62156. point[1] -= margin;
  62157. }
  62158. var rotate = 0;
  62159. if (position === 'left' || position === 'right') {
  62160. rotate = Math.PI / 2;
  62161. }
  62162. return {
  62163. rotation: rotate,
  62164. position: point,
  62165. style: {
  62166. textAlign: aligns[0],
  62167. textVerticalAlign: aligns[1]
  62168. }
  62169. };
  62170. },
  62171. // render year
  62172. _renderYearText: function (calendarModel, rangeData, orient, group) {
  62173. var yearLabel = calendarModel.getModel('yearLabel');
  62174. if (!yearLabel.get('show')) {
  62175. return;
  62176. }
  62177. var margin = yearLabel.get('margin');
  62178. var pos = yearLabel.get('position');
  62179. if (!pos) {
  62180. pos = orient !== 'horizontal' ? 'top' : 'left';
  62181. }
  62182. var points = [this._tlpoints[this._tlpoints.length - 1], this._blpoints[0]];
  62183. var xc = (points[0][0] + points[1][0]) / 2;
  62184. var yc = (points[0][1] + points[1][1]) / 2;
  62185. var idx = orient === 'horizontal' ? 0 : 1;
  62186. var posPoints = {
  62187. top: [xc, points[idx][1]],
  62188. bottom: [xc, points[1 - idx][1]],
  62189. left: [points[1 - idx][0], yc],
  62190. right: [points[idx][0], yc]
  62191. };
  62192. var name = rangeData.start.y;
  62193. if (+rangeData.end.y > +rangeData.start.y) {
  62194. name = name + '-' + rangeData.end.y;
  62195. }
  62196. var formatter = yearLabel.get('formatter');
  62197. var params = {
  62198. start: rangeData.start.y,
  62199. end: rangeData.end.y,
  62200. nameMap: name
  62201. };
  62202. var content = this._formatterLabel(formatter, params);
  62203. var yearText = new Text({
  62204. z2: 30
  62205. });
  62206. setTextStyle(yearText.style, yearLabel, {
  62207. text: content
  62208. }), yearText.attr(this._yearTextPositionControl(yearText, posPoints[pos], orient, pos, margin));
  62209. group.add(yearText);
  62210. },
  62211. _monthTextPositionControl: function (point, isCenter, orient, position, margin) {
  62212. var align = 'left';
  62213. var vAlign = 'top';
  62214. var x = point[0];
  62215. var y = point[1];
  62216. if (orient === 'horizontal') {
  62217. y = y + margin;
  62218. if (isCenter) {
  62219. align = 'center';
  62220. }
  62221. if (position === 'start') {
  62222. vAlign = 'bottom';
  62223. }
  62224. } else {
  62225. x = x + margin;
  62226. if (isCenter) {
  62227. vAlign = 'middle';
  62228. }
  62229. if (position === 'start') {
  62230. align = 'right';
  62231. }
  62232. }
  62233. return {
  62234. x: x,
  62235. y: y,
  62236. textAlign: align,
  62237. textVerticalAlign: vAlign
  62238. };
  62239. },
  62240. // render month and year text
  62241. _renderMonthText: function (calendarModel, orient, group) {
  62242. var monthLabel = calendarModel.getModel('monthLabel');
  62243. if (!monthLabel.get('show')) {
  62244. return;
  62245. }
  62246. var nameMap = monthLabel.get('nameMap');
  62247. var margin = monthLabel.get('margin');
  62248. var pos = monthLabel.get('position');
  62249. var align = monthLabel.get('align');
  62250. var termPoints = [this._tlpoints, this._blpoints];
  62251. if (isString(nameMap)) {
  62252. nameMap = MONTH_TEXT[nameMap.toUpperCase()] || [];
  62253. }
  62254. var idx = pos === 'start' ? 0 : 1;
  62255. var axis = orient === 'horizontal' ? 0 : 1;
  62256. margin = pos === 'start' ? -margin : margin;
  62257. var isCenter = align === 'center';
  62258. for (var i = 0; i < termPoints[idx].length - 1; i++) {
  62259. var tmp = termPoints[idx][i].slice();
  62260. var firstDay = this._firstDayOfMonth[i];
  62261. if (isCenter) {
  62262. var firstDayPoints = this._firstDayPoints[i];
  62263. tmp[axis] = (firstDayPoints[axis] + termPoints[0][i + 1][axis]) / 2;
  62264. }
  62265. var formatter = monthLabel.get('formatter');
  62266. var name = nameMap[+firstDay.m - 1];
  62267. var params = {
  62268. yyyy: firstDay.y,
  62269. yy: (firstDay.y + '').slice(2),
  62270. MM: firstDay.m,
  62271. M: +firstDay.m,
  62272. nameMap: name
  62273. };
  62274. var content = this._formatterLabel(formatter, params);
  62275. var monthText = new Text({
  62276. z2: 30
  62277. });
  62278. extend(setTextStyle(monthText.style, monthLabel, {
  62279. text: content
  62280. }), this._monthTextPositionControl(tmp, isCenter, orient, pos, margin));
  62281. group.add(monthText);
  62282. }
  62283. },
  62284. _weekTextPositionControl: function (point, orient, position, margin, cellSize) {
  62285. var align = 'center';
  62286. var vAlign = 'middle';
  62287. var x = point[0];
  62288. var y = point[1];
  62289. var isStart = position === 'start';
  62290. if (orient === 'horizontal') {
  62291. x = x + margin + (isStart ? 1 : -1) * cellSize[0] / 2;
  62292. align = isStart ? 'right' : 'left';
  62293. } else {
  62294. y = y + margin + (isStart ? 1 : -1) * cellSize[1] / 2;
  62295. vAlign = isStart ? 'bottom' : 'top';
  62296. }
  62297. return {
  62298. x: x,
  62299. y: y,
  62300. textAlign: align,
  62301. textVerticalAlign: vAlign
  62302. };
  62303. },
  62304. // render weeks
  62305. _renderWeekText: function (calendarModel, rangeData, orient, group) {
  62306. var dayLabel = calendarModel.getModel('dayLabel');
  62307. if (!dayLabel.get('show')) {
  62308. return;
  62309. }
  62310. var coordSys = calendarModel.coordinateSystem;
  62311. var pos = dayLabel.get('position');
  62312. var nameMap = dayLabel.get('nameMap');
  62313. var margin = dayLabel.get('margin');
  62314. var firstDayOfWeek = coordSys.getFirstDayOfWeek();
  62315. if (isString(nameMap)) {
  62316. nameMap = WEEK_TEXT[nameMap.toUpperCase()] || [];
  62317. }
  62318. var start = coordSys.getNextNDay(rangeData.end.time, 7 - rangeData.lweek).time;
  62319. var cellSize = [coordSys.getCellWidth(), coordSys.getCellHeight()];
  62320. margin = parsePercent$1(margin, cellSize[orient === 'horizontal' ? 0 : 1]);
  62321. if (pos === 'start') {
  62322. start = coordSys.getNextNDay(rangeData.start.time, -(7 + rangeData.fweek)).time;
  62323. margin = -margin;
  62324. }
  62325. for (var i = 0; i < 7; i++) {
  62326. var tmpD = coordSys.getNextNDay(start, i);
  62327. var point = coordSys.dataToRect([tmpD.time], false).center;
  62328. var day = i;
  62329. day = Math.abs((i + firstDayOfWeek) % 7);
  62330. var weekText = new Text({
  62331. z2: 30
  62332. });
  62333. extend(setTextStyle(weekText.style, dayLabel, {
  62334. text: nameMap[day]
  62335. }), this._weekTextPositionControl(point, orient, pos, margin, cellSize));
  62336. group.add(weekText);
  62337. }
  62338. }
  62339. });
  62340. /*
  62341. * Licensed to the Apache Software Foundation (ASF) under one
  62342. * or more contributor license agreements. See the NOTICE file
  62343. * distributed with this work for additional information
  62344. * regarding copyright ownership. The ASF licenses this file
  62345. * to you under the Apache License, Version 2.0 (the
  62346. * "License"); you may not use this file except in compliance
  62347. * with the License. You may obtain a copy of the License at
  62348. *
  62349. * http://www.apache.org/licenses/LICENSE-2.0
  62350. *
  62351. * Unless required by applicable law or agreed to in writing,
  62352. * software distributed under the License is distributed on an
  62353. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62354. * KIND, either express or implied. See the License for the
  62355. * specific language governing permissions and limitations
  62356. * under the License.
  62357. */
  62358. /*
  62359. * Licensed to the Apache Software Foundation (ASF) under one
  62360. * or more contributor license agreements. See the NOTICE file
  62361. * distributed with this work for additional information
  62362. * regarding copyright ownership. The ASF licenses this file
  62363. * to you under the Apache License, Version 2.0 (the
  62364. * "License"); you may not use this file except in compliance
  62365. * with the License. You may obtain a copy of the License at
  62366. *
  62367. * http://www.apache.org/licenses/LICENSE-2.0
  62368. *
  62369. * Unless required by applicable law or agreed to in writing,
  62370. * software distributed under the License is distributed on an
  62371. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62372. * KIND, either express or implied. See the License for the
  62373. * specific language governing permissions and limitations
  62374. * under the License.
  62375. */
  62376. extendComponentModel({
  62377. type: 'title',
  62378. layoutMode: {
  62379. type: 'box',
  62380. ignoreSize: true
  62381. },
  62382. defaultOption: {
  62383. // 一级层叠
  62384. zlevel: 0,
  62385. // 二级层叠
  62386. z: 6,
  62387. show: true,
  62388. text: '',
  62389. // 超链接跳转
  62390. // link: null,
  62391. // 仅支持self | blank
  62392. target: 'blank',
  62393. subtext: '',
  62394. // 超链接跳转
  62395. // sublink: null,
  62396. // 仅支持self | blank
  62397. subtarget: 'blank',
  62398. // 'center' ¦ 'left' ¦ 'right'
  62399. // ¦ {number}(x坐标,单位px)
  62400. left: 0,
  62401. // 'top' ¦ 'bottom' ¦ 'center'
  62402. // ¦ {number}(y坐标,单位px)
  62403. top: 0,
  62404. // 水平对齐
  62405. // 'auto' | 'left' | 'right' | 'center'
  62406. // 默认根据 left 的位置判断是左对齐还是右对齐
  62407. // textAlign: null
  62408. //
  62409. // 垂直对齐
  62410. // 'auto' | 'top' | 'bottom' | 'middle'
  62411. // 默认根据 top 位置判断是上对齐还是下对齐
  62412. // textVerticalAlign: null
  62413. // textBaseline: null // The same as textVerticalAlign.
  62414. backgroundColor: 'rgba(0,0,0,0)',
  62415. // 标题边框颜色
  62416. borderColor: '#ccc',
  62417. // 标题边框线宽,单位px,默认为0(无边框)
  62418. borderWidth: 0,
  62419. // 标题内边距,单位px,默认各方向内边距为5,
  62420. // 接受数组分别设定上右下左边距,同css
  62421. padding: 5,
  62422. // 主副标题纵向间隔,单位px,默认为10,
  62423. itemGap: 10,
  62424. textStyle: {
  62425. fontSize: 18,
  62426. fontWeight: 'bolder',
  62427. color: '#333'
  62428. },
  62429. subtextStyle: {
  62430. color: '#aaa'
  62431. }
  62432. }
  62433. }); // View
  62434. extendComponentView({
  62435. type: 'title',
  62436. render: function (titleModel, ecModel, api) {
  62437. this.group.removeAll();
  62438. if (!titleModel.get('show')) {
  62439. return;
  62440. }
  62441. var group = this.group;
  62442. var textStyleModel = titleModel.getModel('textStyle');
  62443. var subtextStyleModel = titleModel.getModel('subtextStyle');
  62444. var textAlign = titleModel.get('textAlign');
  62445. var textVerticalAlign = retrieve2(titleModel.get('textBaseline'), titleModel.get('textVerticalAlign'));
  62446. var textEl = new Text({
  62447. style: setTextStyle({}, textStyleModel, {
  62448. text: titleModel.get('text'),
  62449. textFill: textStyleModel.getTextColor()
  62450. }, {
  62451. disableBox: true
  62452. }),
  62453. z2: 10
  62454. });
  62455. var textRect = textEl.getBoundingRect();
  62456. var subText = titleModel.get('subtext');
  62457. var subTextEl = new Text({
  62458. style: setTextStyle({}, subtextStyleModel, {
  62459. text: subText,
  62460. textFill: subtextStyleModel.getTextColor(),
  62461. y: textRect.height + titleModel.get('itemGap'),
  62462. textVerticalAlign: 'top'
  62463. }, {
  62464. disableBox: true
  62465. }),
  62466. z2: 10
  62467. });
  62468. var link = titleModel.get('link');
  62469. var sublink = titleModel.get('sublink');
  62470. var triggerEvent = titleModel.get('triggerEvent', true);
  62471. textEl.silent = !link && !triggerEvent;
  62472. subTextEl.silent = !sublink && !triggerEvent;
  62473. if (link) {
  62474. textEl.on('click', function () {
  62475. windowOpen(link, '_' + titleModel.get('target'));
  62476. });
  62477. }
  62478. if (sublink) {
  62479. subTextEl.on('click', function () {
  62480. windowOpen(link, '_' + titleModel.get('subtarget'));
  62481. });
  62482. }
  62483. textEl.eventData = subTextEl.eventData = triggerEvent ? {
  62484. componentType: 'title',
  62485. componentIndex: titleModel.componentIndex
  62486. } : null;
  62487. group.add(textEl);
  62488. subText && group.add(subTextEl); // If no subText, but add subTextEl, there will be an empty line.
  62489. var groupRect = group.getBoundingRect();
  62490. var layoutOption = titleModel.getBoxLayoutParams();
  62491. layoutOption.width = groupRect.width;
  62492. layoutOption.height = groupRect.height;
  62493. var layoutRect = getLayoutRect(layoutOption, {
  62494. width: api.getWidth(),
  62495. height: api.getHeight()
  62496. }, titleModel.get('padding')); // Adjust text align based on position
  62497. if (!textAlign) {
  62498. // Align left if title is on the left. center and right is same
  62499. textAlign = titleModel.get('left') || titleModel.get('right');
  62500. if (textAlign === 'middle') {
  62501. textAlign = 'center';
  62502. } // Adjust layout by text align
  62503. if (textAlign === 'right') {
  62504. layoutRect.x += layoutRect.width;
  62505. } else if (textAlign === 'center') {
  62506. layoutRect.x += layoutRect.width / 2;
  62507. }
  62508. }
  62509. if (!textVerticalAlign) {
  62510. textVerticalAlign = titleModel.get('top') || titleModel.get('bottom');
  62511. if (textVerticalAlign === 'center') {
  62512. textVerticalAlign = 'middle';
  62513. }
  62514. if (textVerticalAlign === 'bottom') {
  62515. layoutRect.y += layoutRect.height;
  62516. } else if (textVerticalAlign === 'middle') {
  62517. layoutRect.y += layoutRect.height / 2;
  62518. }
  62519. textVerticalAlign = textVerticalAlign || 'top';
  62520. }
  62521. group.attr('position', [layoutRect.x, layoutRect.y]);
  62522. var alignStyle = {
  62523. textAlign: textAlign,
  62524. textVerticalAlign: textVerticalAlign
  62525. };
  62526. textEl.setStyle(alignStyle);
  62527. subTextEl.setStyle(alignStyle); // Render background
  62528. // Get groupRect again because textAlign has been changed
  62529. groupRect = group.getBoundingRect();
  62530. var padding = layoutRect.margin;
  62531. var style = titleModel.getItemStyle(['color', 'opacity']);
  62532. style.fill = titleModel.get('backgroundColor');
  62533. var rect = new Rect({
  62534. shape: {
  62535. x: groupRect.x - padding[3],
  62536. y: groupRect.y - padding[0],
  62537. width: groupRect.width + padding[1] + padding[3],
  62538. height: groupRect.height + padding[0] + padding[2],
  62539. r: titleModel.get('borderRadius')
  62540. },
  62541. style: style,
  62542. subPixelOptimize: true,
  62543. silent: true
  62544. });
  62545. group.add(rect);
  62546. }
  62547. });
  62548. /*
  62549. * Licensed to the Apache Software Foundation (ASF) under one
  62550. * or more contributor license agreements. See the NOTICE file
  62551. * distributed with this work for additional information
  62552. * regarding copyright ownership. The ASF licenses this file
  62553. * to you under the Apache License, Version 2.0 (the
  62554. * "License"); you may not use this file except in compliance
  62555. * with the License. You may obtain a copy of the License at
  62556. *
  62557. * http://www.apache.org/licenses/LICENSE-2.0
  62558. *
  62559. * Unless required by applicable law or agreed to in writing,
  62560. * software distributed under the License is distributed on an
  62561. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62562. * KIND, either express or implied. See the License for the
  62563. * specific language governing permissions and limitations
  62564. * under the License.
  62565. */
  62566. var langSelector = lang.legend.selector;
  62567. var defaultSelectorOption = {
  62568. all: {
  62569. type: 'all',
  62570. title: clone(langSelector.all)
  62571. },
  62572. inverse: {
  62573. type: 'inverse',
  62574. title: clone(langSelector.inverse)
  62575. }
  62576. };
  62577. var LegendModel = extendComponentModel({
  62578. type: 'legend.plain',
  62579. dependencies: ['series'],
  62580. layoutMode: {
  62581. type: 'box',
  62582. // legend.width/height are maxWidth/maxHeight actually,
  62583. // whereas realy width/height is calculated by its content.
  62584. // (Setting {left: 10, right: 10} does not make sense).
  62585. // So consider the case:
  62586. // `setOption({legend: {left: 10});`
  62587. // then `setOption({legend: {right: 10});`
  62588. // The previous `left` should be cleared by setting `ignoreSize`.
  62589. ignoreSize: true
  62590. },
  62591. init: function (option, parentModel, ecModel) {
  62592. this.mergeDefaultAndTheme(option, ecModel);
  62593. option.selected = option.selected || {};
  62594. this._updateSelector(option);
  62595. },
  62596. mergeOption: function (option) {
  62597. LegendModel.superCall(this, 'mergeOption', option);
  62598. this._updateSelector(option);
  62599. },
  62600. _updateSelector: function (option) {
  62601. var selector = option.selector;
  62602. if (selector === true) {
  62603. selector = option.selector = ['all', 'inverse'];
  62604. }
  62605. if (isArray(selector)) {
  62606. each$1(selector, function (item, index) {
  62607. isString(item) && (item = {
  62608. type: item
  62609. });
  62610. selector[index] = merge(item, defaultSelectorOption[item.type]);
  62611. });
  62612. }
  62613. },
  62614. optionUpdated: function () {
  62615. this._updateData(this.ecModel);
  62616. var legendData = this._data; // If selectedMode is single, try to select one
  62617. if (legendData[0] && this.get('selectedMode') === 'single') {
  62618. var hasSelected = false; // If has any selected in option.selected
  62619. for (var i = 0; i < legendData.length; i++) {
  62620. var name = legendData[i].get('name');
  62621. if (this.isSelected(name)) {
  62622. // Force to unselect others
  62623. this.select(name);
  62624. hasSelected = true;
  62625. break;
  62626. }
  62627. } // Try select the first if selectedMode is single
  62628. !hasSelected && this.select(legendData[0].get('name'));
  62629. }
  62630. },
  62631. _updateData: function (ecModel) {
  62632. var potentialData = [];
  62633. var availableNames = [];
  62634. ecModel.eachRawSeries(function (seriesModel) {
  62635. var seriesName = seriesModel.name;
  62636. availableNames.push(seriesName);
  62637. var isPotential;
  62638. if (seriesModel.legendVisualProvider) {
  62639. var provider = seriesModel.legendVisualProvider;
  62640. var names = provider.getAllNames();
  62641. if (!ecModel.isSeriesFiltered(seriesModel)) {
  62642. availableNames = availableNames.concat(names);
  62643. }
  62644. if (names.length) {
  62645. potentialData = potentialData.concat(names);
  62646. } else {
  62647. isPotential = true;
  62648. }
  62649. } else {
  62650. isPotential = true;
  62651. }
  62652. if (isPotential && isNameSpecified(seriesModel)) {
  62653. potentialData.push(seriesModel.name);
  62654. }
  62655. });
  62656. /**
  62657. * @type {Array.<string>}
  62658. * @private
  62659. */
  62660. this._availableNames = availableNames; // If legend.data not specified in option, use availableNames as data,
  62661. // which is convinient for user preparing option.
  62662. var rawData = this.get('data') || potentialData;
  62663. var legendData = map(rawData, function (dataItem) {
  62664. // Can be string or number
  62665. if (typeof dataItem === 'string' || typeof dataItem === 'number') {
  62666. dataItem = {
  62667. name: dataItem
  62668. };
  62669. }
  62670. return new Model(dataItem, this, this.ecModel);
  62671. }, this);
  62672. /**
  62673. * @type {Array.<module:echarts/model/Model>}
  62674. * @private
  62675. */
  62676. this._data = legendData;
  62677. },
  62678. /**
  62679. * @return {Array.<module:echarts/model/Model>}
  62680. */
  62681. getData: function () {
  62682. return this._data;
  62683. },
  62684. /**
  62685. * @param {string} name
  62686. */
  62687. select: function (name) {
  62688. var selected = this.option.selected;
  62689. var selectedMode = this.get('selectedMode');
  62690. if (selectedMode === 'single') {
  62691. var data = this._data;
  62692. each$1(data, function (dataItem) {
  62693. selected[dataItem.get('name')] = false;
  62694. });
  62695. }
  62696. selected[name] = true;
  62697. },
  62698. /**
  62699. * @param {string} name
  62700. */
  62701. unSelect: function (name) {
  62702. if (this.get('selectedMode') !== 'single') {
  62703. this.option.selected[name] = false;
  62704. }
  62705. },
  62706. /**
  62707. * @param {string} name
  62708. */
  62709. toggleSelected: function (name) {
  62710. var selected = this.option.selected; // Default is true
  62711. if (!selected.hasOwnProperty(name)) {
  62712. selected[name] = true;
  62713. }
  62714. this[selected[name] ? 'unSelect' : 'select'](name);
  62715. },
  62716. allSelect: function () {
  62717. var data = this._data;
  62718. var selected = this.option.selected;
  62719. each$1(data, function (dataItem) {
  62720. selected[dataItem.get('name', true)] = true;
  62721. });
  62722. },
  62723. inverseSelect: function () {
  62724. var data = this._data;
  62725. var selected = this.option.selected;
  62726. each$1(data, function (dataItem) {
  62727. var name = dataItem.get('name', true); // Initially, default value is true
  62728. if (!selected.hasOwnProperty(name)) {
  62729. selected[name] = true;
  62730. }
  62731. selected[name] = !selected[name];
  62732. });
  62733. },
  62734. /**
  62735. * @param {string} name
  62736. */
  62737. isSelected: function (name) {
  62738. var selected = this.option.selected;
  62739. return !(selected.hasOwnProperty(name) && !selected[name]) && indexOf(this._availableNames, name) >= 0;
  62740. },
  62741. getOrient: function () {
  62742. return this.get('orient') === 'vertical' ? {
  62743. index: 1,
  62744. name: 'vertical'
  62745. } : {
  62746. index: 0,
  62747. name: 'horizontal'
  62748. };
  62749. },
  62750. defaultOption: {
  62751. // 一级层叠
  62752. zlevel: 0,
  62753. // 二级层叠
  62754. z: 4,
  62755. show: true,
  62756. // 布局方式,默认为水平布局,可选为:
  62757. // 'horizontal' | 'vertical'
  62758. orient: 'horizontal',
  62759. left: 'center',
  62760. // right: 'center',
  62761. top: 0,
  62762. // bottom: null,
  62763. // 水平对齐
  62764. // 'auto' | 'left' | 'right'
  62765. // 默认为 'auto', 根据 x 的位置判断是左对齐还是右对齐
  62766. align: 'auto',
  62767. backgroundColor: 'rgba(0,0,0,0)',
  62768. // 图例边框颜色
  62769. borderColor: '#ccc',
  62770. borderRadius: 0,
  62771. // 图例边框线宽,单位px,默认为0(无边框)
  62772. borderWidth: 0,
  62773. // 图例内边距,单位px,默认各方向内边距为5,
  62774. // 接受数组分别设定上右下左边距,同css
  62775. padding: 5,
  62776. // 各个item之间的间隔,单位px,默认为10,
  62777. // 横向布局时为水平间隔,纵向布局时为纵向间隔
  62778. itemGap: 10,
  62779. // the width of legend symbol
  62780. itemWidth: 25,
  62781. // the height of legend symbol
  62782. itemHeight: 14,
  62783. // the color of unselected legend symbol
  62784. inactiveColor: '#ccc',
  62785. // the borderColor of unselected legend symbol
  62786. inactiveBorderColor: '#ccc',
  62787. itemStyle: {
  62788. // the default borderWidth of legend symbol
  62789. borderWidth: 0
  62790. },
  62791. textStyle: {
  62792. // 图例文字颜色
  62793. color: '#333'
  62794. },
  62795. // formatter: '',
  62796. // 选择模式,默认开启图例开关
  62797. selectedMode: true,
  62798. // 配置默认选中状态,可配合LEGEND.SELECTED事件做动态数据载入
  62799. // selected: null,
  62800. // 图例内容(详见legend.data,数组中每一项代表一个item
  62801. // data: [],
  62802. // Usage:
  62803. // selector: [{type: 'all or inverse', title: xxx}]
  62804. // or
  62805. // selector: true
  62806. // or
  62807. // selector: ['all', 'inverse']
  62808. selector: false,
  62809. selectorLabel: {
  62810. show: true,
  62811. borderRadius: 10,
  62812. padding: [3, 5, 3, 5],
  62813. fontSize: 12,
  62814. fontFamily: ' sans-serif',
  62815. color: '#666',
  62816. borderWidth: 1,
  62817. borderColor: '#666'
  62818. },
  62819. emphasis: {
  62820. selectorLabel: {
  62821. show: true,
  62822. color: '#eee',
  62823. backgroundColor: '#666'
  62824. }
  62825. },
  62826. // Value can be 'start' or 'end'
  62827. selectorPosition: 'auto',
  62828. selectorItemGap: 7,
  62829. selectorButtonGap: 10,
  62830. // Tooltip 相关配置
  62831. tooltip: {
  62832. show: false
  62833. }
  62834. }
  62835. });
  62836. /*
  62837. * Licensed to the Apache Software Foundation (ASF) under one
  62838. * or more contributor license agreements. See the NOTICE file
  62839. * distributed with this work for additional information
  62840. * regarding copyright ownership. The ASF licenses this file
  62841. * to you under the Apache License, Version 2.0 (the
  62842. * "License"); you may not use this file except in compliance
  62843. * with the License. You may obtain a copy of the License at
  62844. *
  62845. * http://www.apache.org/licenses/LICENSE-2.0
  62846. *
  62847. * Unless required by applicable law or agreed to in writing,
  62848. * software distributed under the License is distributed on an
  62849. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62850. * KIND, either express or implied. See the License for the
  62851. * specific language governing permissions and limitations
  62852. * under the License.
  62853. */
  62854. function legendSelectActionHandler(methodName, payload, ecModel) {
  62855. var selectedMap = {};
  62856. var isToggleSelect = methodName === 'toggleSelected';
  62857. var isSelected; // Update all legend components
  62858. ecModel.eachComponent('legend', function (legendModel) {
  62859. if (isToggleSelect && isSelected != null) {
  62860. // Force other legend has same selected status
  62861. // Or the first is toggled to true and other are toggled to false
  62862. // In the case one legend has some item unSelected in option. And if other legend
  62863. // doesn't has the item, they will assume it is selected.
  62864. legendModel[isSelected ? 'select' : 'unSelect'](payload.name);
  62865. } else if (methodName === 'allSelect' || methodName === 'inverseSelect') {
  62866. legendModel[methodName]();
  62867. } else {
  62868. legendModel[methodName](payload.name);
  62869. isSelected = legendModel.isSelected(payload.name);
  62870. }
  62871. var legendData = legendModel.getData();
  62872. each$1(legendData, function (model) {
  62873. var name = model.get('name'); // Wrap element
  62874. if (name === '\n' || name === '') {
  62875. return;
  62876. }
  62877. var isItemSelected = legendModel.isSelected(name);
  62878. if (selectedMap.hasOwnProperty(name)) {
  62879. // Unselected if any legend is unselected
  62880. selectedMap[name] = selectedMap[name] && isItemSelected;
  62881. } else {
  62882. selectedMap[name] = isItemSelected;
  62883. }
  62884. });
  62885. }); // Return the event explicitly
  62886. return methodName === 'allSelect' || methodName === 'inverseSelect' ? {
  62887. selected: selectedMap
  62888. } : {
  62889. name: payload.name,
  62890. selected: selectedMap
  62891. };
  62892. }
  62893. /**
  62894. * @event legendToggleSelect
  62895. * @type {Object}
  62896. * @property {string} type 'legendToggleSelect'
  62897. * @property {string} [from]
  62898. * @property {string} name Series name or data item name
  62899. */
  62900. registerAction('legendToggleSelect', 'legendselectchanged', curry(legendSelectActionHandler, 'toggleSelected'));
  62901. registerAction('legendAllSelect', 'legendselectall', curry(legendSelectActionHandler, 'allSelect'));
  62902. registerAction('legendInverseSelect', 'legendinverseselect', curry(legendSelectActionHandler, 'inverseSelect'));
  62903. /**
  62904. * @event legendSelect
  62905. * @type {Object}
  62906. * @property {string} type 'legendSelect'
  62907. * @property {string} name Series name or data item name
  62908. */
  62909. registerAction('legendSelect', 'legendselected', curry(legendSelectActionHandler, 'select'));
  62910. /**
  62911. * @event legendUnSelect
  62912. * @type {Object}
  62913. * @property {string} type 'legendUnSelect'
  62914. * @property {string} name Series name or data item name
  62915. */
  62916. registerAction('legendUnSelect', 'legendunselected', curry(legendSelectActionHandler, 'unSelect'));
  62917. /*
  62918. * Licensed to the Apache Software Foundation (ASF) under one
  62919. * or more contributor license agreements. See the NOTICE file
  62920. * distributed with this work for additional information
  62921. * regarding copyright ownership. The ASF licenses this file
  62922. * to you under the Apache License, Version 2.0 (the
  62923. * "License"); you may not use this file except in compliance
  62924. * with the License. You may obtain a copy of the License at
  62925. *
  62926. * http://www.apache.org/licenses/LICENSE-2.0
  62927. *
  62928. * Unless required by applicable law or agreed to in writing,
  62929. * software distributed under the License is distributed on an
  62930. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62931. * KIND, either express or implied. See the License for the
  62932. * specific language governing permissions and limitations
  62933. * under the License.
  62934. */
  62935. /**
  62936. * Layout list like component.
  62937. * It will box layout each items in group of component and then position the whole group in the viewport
  62938. * @param {module:zrender/group/Group} group
  62939. * @param {module:echarts/model/Component} componentModel
  62940. * @param {module:echarts/ExtensionAPI}
  62941. */
  62942. function layout$3(group, componentModel, api) {
  62943. var boxLayoutParams = componentModel.getBoxLayoutParams();
  62944. var padding = componentModel.get('padding');
  62945. var viewportSize = {
  62946. width: api.getWidth(),
  62947. height: api.getHeight()
  62948. };
  62949. var rect = getLayoutRect(boxLayoutParams, viewportSize, padding);
  62950. box(componentModel.get('orient'), group, componentModel.get('itemGap'), rect.width, rect.height);
  62951. positionElement(group, boxLayoutParams, viewportSize, padding);
  62952. }
  62953. function makeBackground(rect, componentModel) {
  62954. var padding = normalizeCssArray$1(componentModel.get('padding'));
  62955. var style = componentModel.getItemStyle(['color', 'opacity']);
  62956. style.fill = componentModel.get('backgroundColor');
  62957. var rect = new Rect({
  62958. shape: {
  62959. x: rect.x - padding[3],
  62960. y: rect.y - padding[0],
  62961. width: rect.width + padding[1] + padding[3],
  62962. height: rect.height + padding[0] + padding[2],
  62963. r: componentModel.get('borderRadius')
  62964. },
  62965. style: style,
  62966. silent: true,
  62967. z2: -1
  62968. }); // FIXME
  62969. // `subPixelOptimizeRect` may bring some gap between edge of viewpart
  62970. // and background rect when setting like `left: 0`, `top: 0`.
  62971. // graphic.subPixelOptimizeRect(rect);
  62972. return rect;
  62973. }
  62974. /*
  62975. * Licensed to the Apache Software Foundation (ASF) under one
  62976. * or more contributor license agreements. See the NOTICE file
  62977. * distributed with this work for additional information
  62978. * regarding copyright ownership. The ASF licenses this file
  62979. * to you under the Apache License, Version 2.0 (the
  62980. * "License"); you may not use this file except in compliance
  62981. * with the License. You may obtain a copy of the License at
  62982. *
  62983. * http://www.apache.org/licenses/LICENSE-2.0
  62984. *
  62985. * Unless required by applicable law or agreed to in writing,
  62986. * software distributed under the License is distributed on an
  62987. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  62988. * KIND, either express or implied. See the License for the
  62989. * specific language governing permissions and limitations
  62990. * under the License.
  62991. */
  62992. var curry$4 = curry;
  62993. var each$16 = each$1;
  62994. var Group$3 = Group;
  62995. var LegendView = extendComponentView({
  62996. type: 'legend.plain',
  62997. newlineDisabled: false,
  62998. /**
  62999. * @override
  63000. */
  63001. init: function () {
  63002. /**
  63003. * @private
  63004. * @type {module:zrender/container/Group}
  63005. */
  63006. this.group.add(this._contentGroup = new Group$3());
  63007. /**
  63008. * @private
  63009. * @type {module:zrender/Element}
  63010. */
  63011. this._backgroundEl;
  63012. /**
  63013. * @private
  63014. * @type {module:zrender/container/Group}
  63015. */
  63016. this.group.add(this._selectorGroup = new Group$3());
  63017. /**
  63018. * If first rendering, `contentGroup.position` is [0, 0], which
  63019. * does not make sense and may cause unexepcted animation if adopted.
  63020. * @private
  63021. * @type {boolean}
  63022. */
  63023. this._isFirstRender = true;
  63024. },
  63025. /**
  63026. * @protected
  63027. */
  63028. getContentGroup: function () {
  63029. return this._contentGroup;
  63030. },
  63031. /**
  63032. * @protected
  63033. */
  63034. getSelectorGroup: function () {
  63035. return this._selectorGroup;
  63036. },
  63037. /**
  63038. * @override
  63039. */
  63040. render: function (legendModel, ecModel, api) {
  63041. var isFirstRender = this._isFirstRender;
  63042. this._isFirstRender = false;
  63043. this.resetInner();
  63044. if (!legendModel.get('show', true)) {
  63045. return;
  63046. }
  63047. var itemAlign = legendModel.get('align');
  63048. var orient = legendModel.get('orient');
  63049. if (!itemAlign || itemAlign === 'auto') {
  63050. itemAlign = legendModel.get('left') === 'right' && orient === 'vertical' ? 'right' : 'left';
  63051. }
  63052. var selector = legendModel.get('selector', true);
  63053. var selectorPosition = legendModel.get('selectorPosition', true);
  63054. if (selector && (!selectorPosition || selectorPosition === 'auto')) {
  63055. selectorPosition = orient === 'horizontal' ? 'end' : 'start';
  63056. }
  63057. this.renderInner(itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition); // Perform layout.
  63058. var positionInfo = legendModel.getBoxLayoutParams();
  63059. var viewportSize = {
  63060. width: api.getWidth(),
  63061. height: api.getHeight()
  63062. };
  63063. var padding = legendModel.get('padding');
  63064. var maxSize = getLayoutRect(positionInfo, viewportSize, padding);
  63065. var mainRect = this.layoutInner(legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition); // Place mainGroup, based on the calculated `mainRect`.
  63066. var layoutRect = getLayoutRect(defaults({
  63067. width: mainRect.width,
  63068. height: mainRect.height
  63069. }, positionInfo), viewportSize, padding);
  63070. this.group.attr('position', [layoutRect.x - mainRect.x, layoutRect.y - mainRect.y]); // Render background after group is layout.
  63071. this.group.add(this._backgroundEl = makeBackground(mainRect, legendModel));
  63072. },
  63073. /**
  63074. * @protected
  63075. */
  63076. resetInner: function () {
  63077. this.getContentGroup().removeAll();
  63078. this._backgroundEl && this.group.remove(this._backgroundEl);
  63079. this.getSelectorGroup().removeAll();
  63080. },
  63081. /**
  63082. * @protected
  63083. */
  63084. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  63085. var contentGroup = this.getContentGroup();
  63086. var legendDrawnMap = createHashMap();
  63087. var selectMode = legendModel.get('selectedMode');
  63088. var excludeSeriesId = [];
  63089. ecModel.eachRawSeries(function (seriesModel) {
  63090. !seriesModel.get('legendHoverLink') && excludeSeriesId.push(seriesModel.id);
  63091. });
  63092. each$16(legendModel.getData(), function (itemModel, dataIndex) {
  63093. var name = itemModel.get('name'); // Use empty string or \n as a newline string
  63094. if (!this.newlineDisabled && (name === '' || name === '\n')) {
  63095. contentGroup.add(new Group$3({
  63096. newline: true
  63097. }));
  63098. return;
  63099. } // Representitive series.
  63100. var seriesModel = ecModel.getSeriesByName(name)[0];
  63101. if (legendDrawnMap.get(name)) {
  63102. // Have been drawed
  63103. return;
  63104. } // Legend to control series.
  63105. if (seriesModel) {
  63106. var data = seriesModel.getData();
  63107. var color = data.getVisual('color');
  63108. var borderColor = data.getVisual('borderColor'); // If color is a callback function
  63109. if (typeof color === 'function') {
  63110. // Use the first data
  63111. color = color(seriesModel.getDataParams(0));
  63112. } // If borderColor is a callback function
  63113. if (typeof borderColor === 'function') {
  63114. // Use the first data
  63115. borderColor = borderColor(seriesModel.getDataParams(0));
  63116. } // Using rect symbol defaultly
  63117. var legendSymbolType = data.getVisual('legendSymbol') || 'roundRect';
  63118. var symbolType = data.getVisual('symbol');
  63119. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, selectMode);
  63120. itemGroup.on('click', curry$4(dispatchSelectAction, name, null, api, excludeSeriesId)).on('mouseover', curry$4(dispatchHighlightAction, seriesModel.name, null, api, excludeSeriesId)).on('mouseout', curry$4(dispatchDownplayAction, seriesModel.name, null, api, excludeSeriesId));
  63121. legendDrawnMap.set(name, true);
  63122. } else {
  63123. // Legend to control data. In pie and funnel.
  63124. ecModel.eachRawSeries(function (seriesModel) {
  63125. // In case multiple series has same data name
  63126. if (legendDrawnMap.get(name)) {
  63127. return;
  63128. }
  63129. if (seriesModel.legendVisualProvider) {
  63130. var provider = seriesModel.legendVisualProvider;
  63131. if (!provider.containName(name)) {
  63132. return;
  63133. }
  63134. var idx = provider.indexOfName(name);
  63135. var color = provider.getItemVisual(idx, 'color');
  63136. var borderColor = provider.getItemVisual(idx, 'borderColor');
  63137. var legendSymbolType = 'roundRect';
  63138. var itemGroup = this._createItem(name, dataIndex, itemModel, legendModel, legendSymbolType, null, itemAlign, color, borderColor, selectMode); // FIXME: consider different series has items with the same name.
  63139. itemGroup.on('click', curry$4(dispatchSelectAction, null, name, api, excludeSeriesId)) // Should not specify the series name, consider legend controls
  63140. // more than one pie series.
  63141. .on('mouseover', curry$4(dispatchHighlightAction, null, name, api, excludeSeriesId)).on('mouseout', curry$4(dispatchDownplayAction, null, name, api, excludeSeriesId));
  63142. legendDrawnMap.set(name, true);
  63143. }
  63144. }, this);
  63145. }
  63146. }, this);
  63147. if (selector) {
  63148. this._createSelector(selector, legendModel, api, orient, selectorPosition);
  63149. }
  63150. },
  63151. _createSelector: function (selector, legendModel, api, orient, selectorPosition) {
  63152. var selectorGroup = this.getSelectorGroup();
  63153. each$16(selector, function (selectorItem) {
  63154. createSelectorButton(selectorItem);
  63155. });
  63156. function createSelectorButton(selectorItem) {
  63157. var type = selectorItem.type;
  63158. var labelText = new Text({
  63159. style: {
  63160. x: 0,
  63161. y: 0,
  63162. align: 'center',
  63163. verticalAlign: 'middle'
  63164. },
  63165. onclick: function () {
  63166. api.dispatchAction({
  63167. type: type === 'all' ? 'legendAllSelect' : 'legendInverseSelect'
  63168. });
  63169. }
  63170. });
  63171. selectorGroup.add(labelText);
  63172. var labelModel = legendModel.getModel('selectorLabel');
  63173. var emphasisLabelModel = legendModel.getModel('emphasis.selectorLabel');
  63174. setLabelStyle(labelText.style, labelText.hoverStyle = {}, labelModel, emphasisLabelModel, {
  63175. defaultText: selectorItem.title,
  63176. isRectText: false
  63177. });
  63178. setHoverStyle(labelText);
  63179. }
  63180. },
  63181. _createItem: function (name, dataIndex, itemModel, legendModel, legendSymbolType, symbolType, itemAlign, color, borderColor, selectMode) {
  63182. var itemWidth = legendModel.get('itemWidth');
  63183. var itemHeight = legendModel.get('itemHeight');
  63184. var inactiveColor = legendModel.get('inactiveColor');
  63185. var inactiveBorderColor = legendModel.get('inactiveBorderColor');
  63186. var symbolKeepAspect = legendModel.get('symbolKeepAspect');
  63187. var legendModelItemStyle = legendModel.getModel('itemStyle');
  63188. var isSelected = legendModel.isSelected(name);
  63189. var itemGroup = new Group$3();
  63190. var textStyleModel = itemModel.getModel('textStyle');
  63191. var itemIcon = itemModel.get('icon');
  63192. var tooltipModel = itemModel.getModel('tooltip');
  63193. var legendGlobalTooltipModel = tooltipModel.parentModel; // Use user given icon first
  63194. legendSymbolType = itemIcon || legendSymbolType;
  63195. var legendSymbol = createSymbol(legendSymbolType, 0, 0, itemWidth, itemHeight, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  63196. symbolKeepAspect == null ? true : symbolKeepAspect);
  63197. itemGroup.add(setSymbolStyle(legendSymbol, legendSymbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected)); // Compose symbols
  63198. // PENDING
  63199. if (!itemIcon && symbolType // At least show one symbol, can't be all none
  63200. && (symbolType !== legendSymbolType || symbolType === 'none')) {
  63201. var size = itemHeight * 0.8;
  63202. if (symbolType === 'none') {
  63203. symbolType = 'circle';
  63204. }
  63205. var legendSymbolCenter = createSymbol(symbolType, (itemWidth - size) / 2, (itemHeight - size) / 2, size, size, isSelected ? color : inactiveColor, // symbolKeepAspect default true for legend
  63206. symbolKeepAspect == null ? true : symbolKeepAspect); // Put symbol in the center
  63207. itemGroup.add(setSymbolStyle(legendSymbolCenter, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected));
  63208. }
  63209. var textX = itemAlign === 'left' ? itemWidth + 5 : -5;
  63210. var textAlign = itemAlign;
  63211. var formatter = legendModel.get('formatter');
  63212. var content = name;
  63213. if (typeof formatter === 'string' && formatter) {
  63214. content = formatter.replace('{name}', name != null ? name : '');
  63215. } else if (typeof formatter === 'function') {
  63216. content = formatter(name);
  63217. }
  63218. itemGroup.add(new Text({
  63219. style: setTextStyle({}, textStyleModel, {
  63220. text: content,
  63221. x: textX,
  63222. y: itemHeight / 2,
  63223. textFill: isSelected ? textStyleModel.getTextColor() : inactiveColor,
  63224. textAlign: textAlign,
  63225. textVerticalAlign: 'middle'
  63226. })
  63227. })); // Add a invisible rect to increase the area of mouse hover
  63228. var hitRect = new Rect({
  63229. shape: itemGroup.getBoundingRect(),
  63230. invisible: true,
  63231. tooltip: tooltipModel.get('show') ? extend({
  63232. content: name,
  63233. // Defaul formatter
  63234. formatter: legendGlobalTooltipModel.get('formatter', true) || function () {
  63235. return name;
  63236. },
  63237. formatterParams: {
  63238. componentType: 'legend',
  63239. legendIndex: legendModel.componentIndex,
  63240. name: name,
  63241. $vars: ['name']
  63242. }
  63243. }, tooltipModel.option) : null
  63244. });
  63245. itemGroup.add(hitRect);
  63246. itemGroup.eachChild(function (child) {
  63247. child.silent = true;
  63248. });
  63249. hitRect.silent = !selectMode;
  63250. this.getContentGroup().add(itemGroup);
  63251. setHoverStyle(itemGroup);
  63252. itemGroup.__legendDataIndex = dataIndex;
  63253. return itemGroup;
  63254. },
  63255. /**
  63256. * @protected
  63257. */
  63258. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  63259. var contentGroup = this.getContentGroup();
  63260. var selectorGroup = this.getSelectorGroup(); // Place items in contentGroup.
  63261. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), maxSize.width, maxSize.height);
  63262. var contentRect = contentGroup.getBoundingRect();
  63263. var contentPos = [-contentRect.x, -contentRect.y];
  63264. if (selector) {
  63265. // Place buttons in selectorGroup
  63266. box( // Buttons in selectorGroup always layout horizontally
  63267. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  63268. var selectorRect = selectorGroup.getBoundingRect();
  63269. var selectorPos = [-selectorRect.x, -selectorRect.y];
  63270. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  63271. var orientIdx = legendModel.getOrient().index;
  63272. var wh = orientIdx === 0 ? 'width' : 'height';
  63273. var hw = orientIdx === 0 ? 'height' : 'width';
  63274. var yx = orientIdx === 0 ? 'y' : 'x';
  63275. if (selectorPosition === 'end') {
  63276. selectorPos[orientIdx] += contentRect[wh] + selectorButtonGap;
  63277. } else {
  63278. contentPos[orientIdx] += selectorRect[wh] + selectorButtonGap;
  63279. } //Always align selector to content as 'middle'
  63280. selectorPos[1 - orientIdx] += contentRect[hw] / 2 - selectorRect[hw] / 2;
  63281. selectorGroup.attr('position', selectorPos);
  63282. contentGroup.attr('position', contentPos);
  63283. var mainRect = {
  63284. x: 0,
  63285. y: 0
  63286. };
  63287. mainRect[wh] = contentRect[wh] + selectorButtonGap + selectorRect[wh];
  63288. mainRect[hw] = Math.max(contentRect[hw], selectorRect[hw]);
  63289. mainRect[yx] = Math.min(0, selectorRect[yx] + selectorPos[1 - orientIdx]);
  63290. return mainRect;
  63291. } else {
  63292. contentGroup.attr('position', contentPos);
  63293. return this.group.getBoundingRect();
  63294. }
  63295. },
  63296. /**
  63297. * @protected
  63298. */
  63299. remove: function () {
  63300. this.getContentGroup().removeAll();
  63301. this._isFirstRender = true;
  63302. }
  63303. });
  63304. function setSymbolStyle(symbol, symbolType, legendModelItemStyle, borderColor, inactiveBorderColor, isSelected) {
  63305. var itemStyle;
  63306. if (symbolType !== 'line' && symbolType.indexOf('empty') < 0) {
  63307. itemStyle = legendModelItemStyle.getItemStyle();
  63308. symbol.style.stroke = borderColor;
  63309. if (!isSelected) {
  63310. itemStyle.stroke = inactiveBorderColor;
  63311. }
  63312. } else {
  63313. itemStyle = legendModelItemStyle.getItemStyle(['borderWidth', 'borderColor']);
  63314. }
  63315. return symbol.setStyle(itemStyle);
  63316. }
  63317. function dispatchSelectAction(seriesName, dataName, api, excludeSeriesId) {
  63318. // downplay before unselect
  63319. dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId);
  63320. api.dispatchAction({
  63321. type: 'legendToggleSelect',
  63322. name: seriesName != null ? seriesName : dataName
  63323. }); // highlight after select
  63324. dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId);
  63325. }
  63326. function dispatchHighlightAction(seriesName, dataName, api, excludeSeriesId) {
  63327. // If element hover will move to a hoverLayer.
  63328. var el = api.getZr().storage.getDisplayList()[0];
  63329. if (!(el && el.useHoverLayer)) {
  63330. api.dispatchAction({
  63331. type: 'highlight',
  63332. seriesName: seriesName,
  63333. name: dataName,
  63334. excludeSeriesId: excludeSeriesId
  63335. });
  63336. }
  63337. }
  63338. function dispatchDownplayAction(seriesName, dataName, api, excludeSeriesId) {
  63339. // If element hover will move to a hoverLayer.
  63340. var el = api.getZr().storage.getDisplayList()[0];
  63341. if (!(el && el.useHoverLayer)) {
  63342. api.dispatchAction({
  63343. type: 'downplay',
  63344. seriesName: seriesName,
  63345. name: dataName,
  63346. excludeSeriesId: excludeSeriesId
  63347. });
  63348. }
  63349. }
  63350. /*
  63351. * Licensed to the Apache Software Foundation (ASF) under one
  63352. * or more contributor license agreements. See the NOTICE file
  63353. * distributed with this work for additional information
  63354. * regarding copyright ownership. The ASF licenses this file
  63355. * to you under the Apache License, Version 2.0 (the
  63356. * "License"); you may not use this file except in compliance
  63357. * with the License. You may obtain a copy of the License at
  63358. *
  63359. * http://www.apache.org/licenses/LICENSE-2.0
  63360. *
  63361. * Unless required by applicable law or agreed to in writing,
  63362. * software distributed under the License is distributed on an
  63363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63364. * KIND, either express or implied. See the License for the
  63365. * specific language governing permissions and limitations
  63366. * under the License.
  63367. */
  63368. var legendFilter = function (ecModel) {
  63369. var legendModels = ecModel.findComponents({
  63370. mainType: 'legend'
  63371. });
  63372. if (legendModels && legendModels.length) {
  63373. ecModel.filterSeries(function (series) {
  63374. // If in any legend component the status is not selected.
  63375. // Because in legend series is assumed selected when it is not in the legend data.
  63376. for (var i = 0; i < legendModels.length; i++) {
  63377. if (!legendModels[i].isSelected(series.name)) {
  63378. return false;
  63379. }
  63380. }
  63381. return true;
  63382. });
  63383. }
  63384. };
  63385. /*
  63386. * Licensed to the Apache Software Foundation (ASF) under one
  63387. * or more contributor license agreements. See the NOTICE file
  63388. * distributed with this work for additional information
  63389. * regarding copyright ownership. The ASF licenses this file
  63390. * to you under the Apache License, Version 2.0 (the
  63391. * "License"); you may not use this file except in compliance
  63392. * with the License. You may obtain a copy of the License at
  63393. *
  63394. * http://www.apache.org/licenses/LICENSE-2.0
  63395. *
  63396. * Unless required by applicable law or agreed to in writing,
  63397. * software distributed under the License is distributed on an
  63398. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63399. * KIND, either express or implied. See the License for the
  63400. * specific language governing permissions and limitations
  63401. * under the License.
  63402. */
  63403. // Do not contain scrollable legend, for sake of file size.
  63404. registerProcessor(PRIORITY.PROCESSOR.SERIES_FILTER, legendFilter);
  63405. ComponentModel.registerSubTypeDefaulter('legend', function () {
  63406. // Default 'plain' when no type specified.
  63407. return 'plain';
  63408. });
  63409. /*
  63410. * Licensed to the Apache Software Foundation (ASF) under one
  63411. * or more contributor license agreements. See the NOTICE file
  63412. * distributed with this work for additional information
  63413. * regarding copyright ownership. The ASF licenses this file
  63414. * to you under the Apache License, Version 2.0 (the
  63415. * "License"); you may not use this file except in compliance
  63416. * with the License. You may obtain a copy of the License at
  63417. *
  63418. * http://www.apache.org/licenses/LICENSE-2.0
  63419. *
  63420. * Unless required by applicable law or agreed to in writing,
  63421. * software distributed under the License is distributed on an
  63422. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63423. * KIND, either express or implied. See the License for the
  63424. * specific language governing permissions and limitations
  63425. * under the License.
  63426. */
  63427. var ScrollableLegendModel = LegendModel.extend({
  63428. type: 'legend.scroll',
  63429. /**
  63430. * @param {number} scrollDataIndex
  63431. */
  63432. setScrollDataIndex: function (scrollDataIndex) {
  63433. this.option.scrollDataIndex = scrollDataIndex;
  63434. },
  63435. defaultOption: {
  63436. scrollDataIndex: 0,
  63437. pageButtonItemGap: 5,
  63438. pageButtonGap: null,
  63439. pageButtonPosition: 'end',
  63440. // 'start' or 'end'
  63441. pageFormatter: '{current}/{total}',
  63442. // If null/undefined, do not show page.
  63443. pageIcons: {
  63444. horizontal: ['M0,0L12,-10L12,10z', 'M0,0L-12,-10L-12,10z'],
  63445. vertical: ['M0,0L20,0L10,-20z', 'M0,0L20,0L10,20z']
  63446. },
  63447. pageIconColor: '#2f4554',
  63448. pageIconInactiveColor: '#aaa',
  63449. pageIconSize: 15,
  63450. // Can be [10, 3], which represents [width, height]
  63451. pageTextStyle: {
  63452. color: '#333'
  63453. },
  63454. animationDurationUpdate: 800
  63455. },
  63456. /**
  63457. * @override
  63458. */
  63459. init: function (option, parentModel, ecModel, extraOpt) {
  63460. var inputPositionParams = getLayoutParams(option);
  63461. ScrollableLegendModel.superCall(this, 'init', option, parentModel, ecModel, extraOpt);
  63462. mergeAndNormalizeLayoutParams$1(this, option, inputPositionParams);
  63463. },
  63464. /**
  63465. * @override
  63466. */
  63467. mergeOption: function (option, extraOpt) {
  63468. ScrollableLegendModel.superCall(this, 'mergeOption', option, extraOpt);
  63469. mergeAndNormalizeLayoutParams$1(this, this.option, option);
  63470. }
  63471. }); // Do not `ignoreSize` to enable setting {left: 10, right: 10}.
  63472. function mergeAndNormalizeLayoutParams$1(legendModel, target, raw) {
  63473. var orient = legendModel.getOrient();
  63474. var ignoreSize = [1, 1];
  63475. ignoreSize[orient.index] = 0;
  63476. mergeLayoutParam(target, raw, {
  63477. type: 'box',
  63478. ignoreSize: ignoreSize
  63479. });
  63480. }
  63481. /*
  63482. * Licensed to the Apache Software Foundation (ASF) under one
  63483. * or more contributor license agreements. See the NOTICE file
  63484. * distributed with this work for additional information
  63485. * regarding copyright ownership. The ASF licenses this file
  63486. * to you under the Apache License, Version 2.0 (the
  63487. * "License"); you may not use this file except in compliance
  63488. * with the License. You may obtain a copy of the License at
  63489. *
  63490. * http://www.apache.org/licenses/LICENSE-2.0
  63491. *
  63492. * Unless required by applicable law or agreed to in writing,
  63493. * software distributed under the License is distributed on an
  63494. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63495. * KIND, either express or implied. See the License for the
  63496. * specific language governing permissions and limitations
  63497. * under the License.
  63498. */
  63499. /**
  63500. * Separate legend and scrollable legend to reduce package size.
  63501. */
  63502. var Group$4 = Group;
  63503. var WH$1 = ['width', 'height'];
  63504. var XY$1 = ['x', 'y'];
  63505. var ScrollableLegendView = LegendView.extend({
  63506. type: 'legend.scroll',
  63507. newlineDisabled: true,
  63508. init: function () {
  63509. ScrollableLegendView.superCall(this, 'init');
  63510. /**
  63511. * @private
  63512. * @type {number} For `scroll`.
  63513. */
  63514. this._currentIndex = 0;
  63515. /**
  63516. * @private
  63517. * @type {module:zrender/container/Group}
  63518. */
  63519. this.group.add(this._containerGroup = new Group$4());
  63520. this._containerGroup.add(this.getContentGroup());
  63521. /**
  63522. * @private
  63523. * @type {module:zrender/container/Group}
  63524. */
  63525. this.group.add(this._controllerGroup = new Group$4());
  63526. /**
  63527. *
  63528. * @private
  63529. */
  63530. this._showController;
  63531. },
  63532. /**
  63533. * @override
  63534. */
  63535. resetInner: function () {
  63536. ScrollableLegendView.superCall(this, 'resetInner');
  63537. this._controllerGroup.removeAll();
  63538. this._containerGroup.removeClipPath();
  63539. this._containerGroup.__rectSize = null;
  63540. },
  63541. /**
  63542. * @override
  63543. */
  63544. renderInner: function (itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition) {
  63545. var me = this; // Render content items.
  63546. ScrollableLegendView.superCall(this, 'renderInner', itemAlign, legendModel, ecModel, api, selector, orient, selectorPosition);
  63547. var controllerGroup = this._controllerGroup; // FIXME: support be 'auto' adapt to size number text length,
  63548. // e.g., '3/12345' should not overlap with the control arrow button.
  63549. var pageIconSize = legendModel.get('pageIconSize', true);
  63550. if (!isArray(pageIconSize)) {
  63551. pageIconSize = [pageIconSize, pageIconSize];
  63552. }
  63553. createPageButton('pagePrev', 0);
  63554. var pageTextStyleModel = legendModel.getModel('pageTextStyle');
  63555. controllerGroup.add(new Text({
  63556. name: 'pageText',
  63557. style: {
  63558. textFill: pageTextStyleModel.getTextColor(),
  63559. font: pageTextStyleModel.getFont(),
  63560. textVerticalAlign: 'middle',
  63561. textAlign: 'center'
  63562. },
  63563. silent: true
  63564. }));
  63565. createPageButton('pageNext', 1);
  63566. function createPageButton(name, iconIdx) {
  63567. var pageDataIndexName = name + 'DataIndex';
  63568. var icon = createIcon(legendModel.get('pageIcons', true)[legendModel.getOrient().name][iconIdx], {
  63569. // Buttons will be created in each render, so we do not need
  63570. // to worry about avoiding using legendModel kept in scope.
  63571. onclick: bind(me._pageGo, me, pageDataIndexName, legendModel, api)
  63572. }, {
  63573. x: -pageIconSize[0] / 2,
  63574. y: -pageIconSize[1] / 2,
  63575. width: pageIconSize[0],
  63576. height: pageIconSize[1]
  63577. });
  63578. icon.name = name;
  63579. controllerGroup.add(icon);
  63580. }
  63581. },
  63582. /**
  63583. * @override
  63584. */
  63585. layoutInner: function (legendModel, itemAlign, maxSize, isFirstRender, selector, selectorPosition) {
  63586. var selectorGroup = this.getSelectorGroup();
  63587. var orientIdx = legendModel.getOrient().index;
  63588. var wh = WH$1[orientIdx];
  63589. var xy = XY$1[orientIdx];
  63590. var hw = WH$1[1 - orientIdx];
  63591. var yx = XY$1[1 - orientIdx];
  63592. selector && box( // Buttons in selectorGroup always layout horizontally
  63593. 'horizontal', selectorGroup, legendModel.get('selectorItemGap', true));
  63594. var selectorButtonGap = legendModel.get('selectorButtonGap', true);
  63595. var selectorRect = selectorGroup.getBoundingRect();
  63596. var selectorPos = [-selectorRect.x, -selectorRect.y];
  63597. var processMaxSize = clone(maxSize);
  63598. selector && (processMaxSize[wh] = maxSize[wh] - selectorRect[wh] - selectorButtonGap);
  63599. var mainRect = this._layoutContentAndController(legendModel, isFirstRender, processMaxSize, orientIdx, wh, hw, yx);
  63600. if (selector) {
  63601. if (selectorPosition === 'end') {
  63602. selectorPos[orientIdx] += mainRect[wh] + selectorButtonGap;
  63603. } else {
  63604. var offset = selectorRect[wh] + selectorButtonGap;
  63605. selectorPos[orientIdx] -= offset;
  63606. mainRect[xy] -= offset;
  63607. }
  63608. mainRect[wh] += selectorRect[wh] + selectorButtonGap;
  63609. selectorPos[1 - orientIdx] += mainRect[yx] + mainRect[hw] / 2 - selectorRect[hw] / 2;
  63610. mainRect[hw] = Math.max(mainRect[hw], selectorRect[hw]);
  63611. mainRect[yx] = Math.min(mainRect[yx], selectorRect[yx] + selectorPos[1 - orientIdx]);
  63612. selectorGroup.attr('position', selectorPos);
  63613. }
  63614. return mainRect;
  63615. },
  63616. _layoutContentAndController: function (legendModel, isFirstRender, maxSize, orientIdx, wh, hw, yx) {
  63617. var contentGroup = this.getContentGroup();
  63618. var containerGroup = this._containerGroup;
  63619. var controllerGroup = this._controllerGroup; // Place items in contentGroup.
  63620. box(legendModel.get('orient'), contentGroup, legendModel.get('itemGap'), !orientIdx ? null : maxSize.width, orientIdx ? null : maxSize.height);
  63621. box( // Buttons in controller are layout always horizontally.
  63622. 'horizontal', controllerGroup, legendModel.get('pageButtonItemGap', true));
  63623. var contentRect = contentGroup.getBoundingRect();
  63624. var controllerRect = controllerGroup.getBoundingRect();
  63625. var showController = this._showController = contentRect[wh] > maxSize[wh];
  63626. var contentPos = [-contentRect.x, -contentRect.y]; // Remain contentPos when scroll animation perfroming.
  63627. // If first rendering, `contentGroup.position` is [0, 0], which
  63628. // does not make sense and may cause unexepcted animation if adopted.
  63629. if (!isFirstRender) {
  63630. contentPos[orientIdx] = contentGroup.position[orientIdx];
  63631. } // Layout container group based on 0.
  63632. var containerPos = [0, 0];
  63633. var controllerPos = [-controllerRect.x, -controllerRect.y];
  63634. var pageButtonGap = retrieve2(legendModel.get('pageButtonGap', true), legendModel.get('itemGap', true)); // Place containerGroup and controllerGroup and contentGroup.
  63635. if (showController) {
  63636. var pageButtonPosition = legendModel.get('pageButtonPosition', true); // controller is on the right / bottom.
  63637. if (pageButtonPosition === 'end') {
  63638. controllerPos[orientIdx] += maxSize[wh] - controllerRect[wh];
  63639. } // controller is on the left / top.
  63640. else {
  63641. containerPos[orientIdx] += controllerRect[wh] + pageButtonGap;
  63642. }
  63643. } // Always align controller to content as 'middle'.
  63644. controllerPos[1 - orientIdx] += contentRect[hw] / 2 - controllerRect[hw] / 2;
  63645. contentGroup.attr('position', contentPos);
  63646. containerGroup.attr('position', containerPos);
  63647. controllerGroup.attr('position', controllerPos); // Calculate `mainRect` and set `clipPath`.
  63648. // mainRect should not be calculated by `this.group.getBoundingRect()`
  63649. // for sake of the overflow.
  63650. var mainRect = {
  63651. x: 0,
  63652. y: 0
  63653. }; // Consider content may be overflow (should be clipped).
  63654. mainRect[wh] = showController ? maxSize[wh] : contentRect[wh];
  63655. mainRect[hw] = Math.max(contentRect[hw], controllerRect[hw]); // `containerRect[yx] + containerPos[1 - orientIdx]` is 0.
  63656. mainRect[yx] = Math.min(0, controllerRect[yx] + controllerPos[1 - orientIdx]);
  63657. containerGroup.__rectSize = maxSize[wh];
  63658. if (showController) {
  63659. var clipShape = {
  63660. x: 0,
  63661. y: 0
  63662. };
  63663. clipShape[wh] = Math.max(maxSize[wh] - controllerRect[wh] - pageButtonGap, 0);
  63664. clipShape[hw] = mainRect[hw];
  63665. containerGroup.setClipPath(new Rect({
  63666. shape: clipShape
  63667. })); // Consider content may be larger than container, container rect
  63668. // can not be obtained from `containerGroup.getBoundingRect()`.
  63669. containerGroup.__rectSize = clipShape[wh];
  63670. } else {
  63671. // Do not remove or ignore controller. Keep them set as placeholders.
  63672. controllerGroup.eachChild(function (child) {
  63673. child.attr({
  63674. invisible: true,
  63675. silent: true
  63676. });
  63677. });
  63678. } // Content translate animation.
  63679. var pageInfo = this._getPageInfo(legendModel);
  63680. pageInfo.pageIndex != null && updateProps(contentGroup, {
  63681. position: pageInfo.contentPosition
  63682. }, // When switch from "show controller" to "not show controller", view should be
  63683. // updated immediately without animation, otherwise causes weird effect.
  63684. showController ? legendModel : false);
  63685. this._updatePageInfoView(legendModel, pageInfo);
  63686. return mainRect;
  63687. },
  63688. _pageGo: function (to, legendModel, api) {
  63689. var scrollDataIndex = this._getPageInfo(legendModel)[to];
  63690. scrollDataIndex != null && api.dispatchAction({
  63691. type: 'legendScroll',
  63692. scrollDataIndex: scrollDataIndex,
  63693. legendId: legendModel.id
  63694. });
  63695. },
  63696. _updatePageInfoView: function (legendModel, pageInfo) {
  63697. var controllerGroup = this._controllerGroup;
  63698. each$1(['pagePrev', 'pageNext'], function (name) {
  63699. var canJump = pageInfo[name + 'DataIndex'] != null;
  63700. var icon = controllerGroup.childOfName(name);
  63701. if (icon) {
  63702. icon.setStyle('fill', canJump ? legendModel.get('pageIconColor', true) : legendModel.get('pageIconInactiveColor', true));
  63703. icon.cursor = canJump ? 'pointer' : 'default';
  63704. }
  63705. });
  63706. var pageText = controllerGroup.childOfName('pageText');
  63707. var pageFormatter = legendModel.get('pageFormatter');
  63708. var pageIndex = pageInfo.pageIndex;
  63709. var current = pageIndex != null ? pageIndex + 1 : 0;
  63710. var total = pageInfo.pageCount;
  63711. pageText && pageFormatter && pageText.setStyle('text', isString(pageFormatter) ? pageFormatter.replace('{current}', current).replace('{total}', total) : pageFormatter({
  63712. current: current,
  63713. total: total
  63714. }));
  63715. },
  63716. /**
  63717. * @param {module:echarts/model/Model} legendModel
  63718. * @return {Object} {
  63719. * contentPosition: Array.<number>, null when data item not found.
  63720. * pageIndex: number, null when data item not found.
  63721. * pageCount: number, always be a number, can be 0.
  63722. * pagePrevDataIndex: number, null when no previous page.
  63723. * pageNextDataIndex: number, null when no next page.
  63724. * }
  63725. */
  63726. _getPageInfo: function (legendModel) {
  63727. var scrollDataIndex = legendModel.get('scrollDataIndex', true);
  63728. var contentGroup = this.getContentGroup();
  63729. var containerRectSize = this._containerGroup.__rectSize;
  63730. var orientIdx = legendModel.getOrient().index;
  63731. var wh = WH$1[orientIdx];
  63732. var xy = XY$1[orientIdx];
  63733. var targetItemIndex = this._findTargetItemIndex(scrollDataIndex);
  63734. var children = contentGroup.children();
  63735. var targetItem = children[targetItemIndex];
  63736. var itemCount = children.length;
  63737. var pCount = !itemCount ? 0 : 1;
  63738. var result = {
  63739. contentPosition: contentGroup.position.slice(),
  63740. pageCount: pCount,
  63741. pageIndex: pCount - 1,
  63742. pagePrevDataIndex: null,
  63743. pageNextDataIndex: null
  63744. };
  63745. if (!targetItem) {
  63746. return result;
  63747. }
  63748. var targetItemInfo = getItemInfo(targetItem);
  63749. result.contentPosition[orientIdx] = -targetItemInfo.s; // Strategy:
  63750. // (1) Always align based on the left/top most item.
  63751. // (2) It is user-friendly that the last item shown in the
  63752. // current window is shown at the begining of next window.
  63753. // Otherwise if half of the last item is cut by the window,
  63754. // it will have no chance to display entirely.
  63755. // (3) Consider that item size probably be different, we
  63756. // have calculate pageIndex by size rather than item index,
  63757. // and we can not get page index directly by division.
  63758. // (4) The window is to narrow to contain more than
  63759. // one item, we should make sure that the page can be fliped.
  63760. for (var i = targetItemIndex + 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i <= itemCount; ++i) {
  63761. currItemInfo = getItemInfo(children[i]);
  63762. if ( // Half of the last item is out of the window.
  63763. !currItemInfo && winEndItemInfo.e > winStartItemInfo.s + containerRectSize || // If the current item does not intersect with the window, the new page
  63764. // can be started at the current item or the last item.
  63765. currItemInfo && !intersect(currItemInfo, winStartItemInfo.s)) {
  63766. if (winEndItemInfo.i > winStartItemInfo.i) {
  63767. winStartItemInfo = winEndItemInfo;
  63768. } else {
  63769. // e.g., when page size is smaller than item size.
  63770. winStartItemInfo = currItemInfo;
  63771. }
  63772. if (winStartItemInfo) {
  63773. if (result.pageNextDataIndex == null) {
  63774. result.pageNextDataIndex = winStartItemInfo.i;
  63775. }
  63776. ++result.pageCount;
  63777. }
  63778. }
  63779. winEndItemInfo = currItemInfo;
  63780. }
  63781. for (var i = targetItemIndex - 1, winStartItemInfo = targetItemInfo, winEndItemInfo = targetItemInfo, currItemInfo = null; i >= -1; --i) {
  63782. currItemInfo = getItemInfo(children[i]);
  63783. if ( // If the the end item does not intersect with the window started
  63784. // from the current item, a page can be settled.
  63785. (!currItemInfo || !intersect(winEndItemInfo, currItemInfo.s)) && // e.g., when page size is smaller than item size.
  63786. winStartItemInfo.i < winEndItemInfo.i) {
  63787. winEndItemInfo = winStartItemInfo;
  63788. if (result.pagePrevDataIndex == null) {
  63789. result.pagePrevDataIndex = winStartItemInfo.i;
  63790. }
  63791. ++result.pageCount;
  63792. ++result.pageIndex;
  63793. }
  63794. winStartItemInfo = currItemInfo;
  63795. }
  63796. return result;
  63797. function getItemInfo(el) {
  63798. if (el) {
  63799. var itemRect = el.getBoundingRect();
  63800. var start = itemRect[xy] + el.position[orientIdx];
  63801. return {
  63802. s: start,
  63803. e: start + itemRect[wh],
  63804. i: el.__legendDataIndex
  63805. };
  63806. }
  63807. }
  63808. function intersect(itemInfo, winStart) {
  63809. return itemInfo.e >= winStart && itemInfo.s <= winStart + containerRectSize;
  63810. }
  63811. },
  63812. _findTargetItemIndex: function (targetDataIndex) {
  63813. if (!this._showController) {
  63814. return 0;
  63815. }
  63816. var index;
  63817. var contentGroup = this.getContentGroup();
  63818. var defaultIndex;
  63819. contentGroup.eachChild(function (child, idx) {
  63820. var legendDataIdx = child.__legendDataIndex; // FIXME
  63821. // If the given targetDataIndex (from model) is illegal,
  63822. // we use defualtIndex. But the index on the legend model and
  63823. // action payload is still illegal. That case will not be
  63824. // changed until some scenario requires.
  63825. if (defaultIndex == null && legendDataIdx != null) {
  63826. defaultIndex = idx;
  63827. }
  63828. if (legendDataIdx === targetDataIndex) {
  63829. index = idx;
  63830. }
  63831. });
  63832. return index != null ? index : defaultIndex;
  63833. }
  63834. });
  63835. /*
  63836. * Licensed to the Apache Software Foundation (ASF) under one
  63837. * or more contributor license agreements. See the NOTICE file
  63838. * distributed with this work for additional information
  63839. * regarding copyright ownership. The ASF licenses this file
  63840. * to you under the Apache License, Version 2.0 (the
  63841. * "License"); you may not use this file except in compliance
  63842. * with the License. You may obtain a copy of the License at
  63843. *
  63844. * http://www.apache.org/licenses/LICENSE-2.0
  63845. *
  63846. * Unless required by applicable law or agreed to in writing,
  63847. * software distributed under the License is distributed on an
  63848. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63849. * KIND, either express or implied. See the License for the
  63850. * specific language governing permissions and limitations
  63851. * under the License.
  63852. */
  63853. /**
  63854. * @event legendScroll
  63855. * @type {Object}
  63856. * @property {string} type 'legendScroll'
  63857. * @property {string} scrollDataIndex
  63858. */
  63859. registerAction('legendScroll', 'legendscroll', function (payload, ecModel) {
  63860. var scrollDataIndex = payload.scrollDataIndex;
  63861. scrollDataIndex != null && ecModel.eachComponent({
  63862. mainType: 'legend',
  63863. subType: 'scroll',
  63864. query: payload
  63865. }, function (legendModel) {
  63866. legendModel.setScrollDataIndex(scrollDataIndex);
  63867. });
  63868. });
  63869. /*
  63870. * Licensed to the Apache Software Foundation (ASF) under one
  63871. * or more contributor license agreements. See the NOTICE file
  63872. * distributed with this work for additional information
  63873. * regarding copyright ownership. The ASF licenses this file
  63874. * to you under the Apache License, Version 2.0 (the
  63875. * "License"); you may not use this file except in compliance
  63876. * with the License. You may obtain a copy of the License at
  63877. *
  63878. * http://www.apache.org/licenses/LICENSE-2.0
  63879. *
  63880. * Unless required by applicable law or agreed to in writing,
  63881. * software distributed under the License is distributed on an
  63882. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63883. * KIND, either express or implied. See the License for the
  63884. * specific language governing permissions and limitations
  63885. * under the License.
  63886. */
  63887. /**
  63888. * Legend component entry file8
  63889. */
  63890. /*
  63891. * Licensed to the Apache Software Foundation (ASF) under one
  63892. * or more contributor license agreements. See the NOTICE file
  63893. * distributed with this work for additional information
  63894. * regarding copyright ownership. The ASF licenses this file
  63895. * to you under the Apache License, Version 2.0 (the
  63896. * "License"); you may not use this file except in compliance
  63897. * with the License. You may obtain a copy of the License at
  63898. *
  63899. * http://www.apache.org/licenses/LICENSE-2.0
  63900. *
  63901. * Unless required by applicable law or agreed to in writing,
  63902. * software distributed under the License is distributed on an
  63903. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  63904. * KIND, either express or implied. See the License for the
  63905. * specific language governing permissions and limitations
  63906. * under the License.
  63907. */
  63908. extendComponentModel({
  63909. type: 'tooltip',
  63910. dependencies: ['axisPointer'],
  63911. defaultOption: {
  63912. zlevel: 0,
  63913. z: 60,
  63914. show: true,
  63915. // tooltip主体内容
  63916. showContent: true,
  63917. // 'trigger' only works on coordinate system.
  63918. // 'item' | 'axis' | 'none'
  63919. trigger: 'item',
  63920. // 'click' | 'mousemove' | 'none'
  63921. triggerOn: 'mousemove|click',
  63922. alwaysShowContent: false,
  63923. displayMode: 'single',
  63924. // 'single' | 'multipleByCoordSys'
  63925. renderMode: 'auto',
  63926. // 'auto' | 'html' | 'richText'
  63927. // 'auto': use html by default, and use non-html if `document` is not defined
  63928. // 'html': use html for tooltip
  63929. // 'richText': use canvas, svg, and etc. for tooltip
  63930. // 位置 {Array} | {Function}
  63931. // position: null
  63932. // Consider triggered from axisPointer handle, verticalAlign should be 'middle'
  63933. // align: null,
  63934. // verticalAlign: null,
  63935. // 是否约束 content 在 viewRect 中。默认 false 是为了兼容以前版本。
  63936. confine: false,
  63937. // 内容格式器:{string}(Template) ¦ {Function}
  63938. // formatter: null
  63939. showDelay: 0,
  63940. // 隐藏延迟,单位ms
  63941. hideDelay: 100,
  63942. // 动画变换时间,单位s
  63943. transitionDuration: 0.4,
  63944. enterable: false,
  63945. // 提示背景颜色,默认为透明度为0.7的黑色
  63946. backgroundColor: 'rgba(50,50,50,0.7)',
  63947. // 提示边框颜色
  63948. borderColor: '#333',
  63949. // 提示边框圆角,单位px,默认为4
  63950. borderRadius: 4,
  63951. // 提示边框线宽,单位px,默认为0(无边框)
  63952. borderWidth: 0,
  63953. // 提示内边距,单位px,默认各方向内边距为5,
  63954. // 接受数组分别设定上右下左边距,同css
  63955. padding: 5,
  63956. // Extra css text
  63957. extraCssText: '',
  63958. // 坐标轴指示器,坐标轴触发有效
  63959. axisPointer: {
  63960. // 默认为直线
  63961. // 可选为:'line' | 'shadow' | 'cross'
  63962. type: 'line',
  63963. // type 为 line 的时候有效,指定 tooltip line 所在的轴,可选
  63964. // 可选 'x' | 'y' | 'angle' | 'radius' | 'auto'
  63965. // 默认 'auto',会选择类型为 category 的轴,对于双数值轴,笛卡尔坐标系会默认选择 x 轴
  63966. // 极坐标系会默认选择 angle 轴
  63967. axis: 'auto',
  63968. animation: 'auto',
  63969. animationDurationUpdate: 200,
  63970. animationEasingUpdate: 'exponentialOut',
  63971. crossStyle: {
  63972. color: '#999',
  63973. width: 1,
  63974. type: 'dashed',
  63975. // TODO formatter
  63976. textStyle: {} // lineStyle and shadowStyle should not be specified here,
  63977. // otherwise it will always override those styles on option.axisPointer.
  63978. }
  63979. },
  63980. textStyle: {
  63981. color: '#fff',
  63982. fontSize: 14
  63983. }
  63984. }
  63985. });
  63986. /*
  63987. * Licensed to the Apache Software Foundation (ASF) under one
  63988. * or more contributor license agreements. See the NOTICE file
  63989. * distributed with this work for additional information
  63990. * regarding copyright ownership. The ASF licenses this file
  63991. * to you under the Apache License, Version 2.0 (the
  63992. * "License"); you may not use this file except in compliance
  63993. * with the License. You may obtain a copy of the License at
  63994. *
  63995. * http://www.apache.org/licenses/LICENSE-2.0
  63996. *
  63997. * Unless required by applicable law or agreed to in writing,
  63998. * software distributed under the License is distributed on an
  63999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64000. * KIND, either express or implied. See the License for the
  64001. * specific language governing permissions and limitations
  64002. * under the License.
  64003. */
  64004. var each$18 = each$1;
  64005. var toCamelCase$1 = toCamelCase;
  64006. var vendors = ['', '-webkit-', '-moz-', '-o-'];
  64007. var gCssText = 'position:absolute;display:block;border-style:solid;white-space:nowrap;z-index:9999999;';
  64008. /**
  64009. * @param {number} duration
  64010. * @return {string}
  64011. * @inner
  64012. */
  64013. function assembleTransition(duration) {
  64014. var transitionCurve = 'cubic-bezier(0.23, 1, 0.32, 1)';
  64015. var transitionText = 'left ' + duration + 's ' + transitionCurve + ',' + 'top ' + duration + 's ' + transitionCurve;
  64016. return map(vendors, function (vendorPrefix) {
  64017. return vendorPrefix + 'transition:' + transitionText;
  64018. }).join(';');
  64019. }
  64020. /**
  64021. * @param {Object} textStyle
  64022. * @return {string}
  64023. * @inner
  64024. */
  64025. function assembleFont(textStyleModel) {
  64026. var cssText = [];
  64027. var fontSize = textStyleModel.get('fontSize');
  64028. var color = textStyleModel.getTextColor();
  64029. color && cssText.push('color:' + color);
  64030. cssText.push('font:' + textStyleModel.getFont());
  64031. fontSize && cssText.push('line-height:' + Math.round(fontSize * 3 / 2) + 'px');
  64032. each$18(['decoration', 'align'], function (name) {
  64033. var val = textStyleModel.get(name);
  64034. val && cssText.push('text-' + name + ':' + val);
  64035. });
  64036. return cssText.join(';');
  64037. }
  64038. /**
  64039. * @param {Object} tooltipModel
  64040. * @return {string}
  64041. * @inner
  64042. */
  64043. function assembleCssText(tooltipModel) {
  64044. var cssText = [];
  64045. var transitionDuration = tooltipModel.get('transitionDuration');
  64046. var backgroundColor = tooltipModel.get('backgroundColor');
  64047. var textStyleModel = tooltipModel.getModel('textStyle');
  64048. var padding = tooltipModel.get('padding'); // Animation transition. Do not animate when transitionDuration is 0.
  64049. transitionDuration && cssText.push(assembleTransition(transitionDuration));
  64050. if (backgroundColor) {
  64051. if (env$1.canvasSupported) {
  64052. cssText.push('background-Color:' + backgroundColor);
  64053. } else {
  64054. // for ie
  64055. cssText.push('background-Color:#' + toHex(backgroundColor));
  64056. cssText.push('filter:alpha(opacity=70)');
  64057. }
  64058. } // Border style
  64059. each$18(['width', 'color', 'radius'], function (name) {
  64060. var borderName = 'border-' + name;
  64061. var camelCase = toCamelCase$1(borderName);
  64062. var val = tooltipModel.get(camelCase);
  64063. val != null && cssText.push(borderName + ':' + val + (name === 'color' ? '' : 'px'));
  64064. }); // Text style
  64065. cssText.push(assembleFont(textStyleModel)); // Padding
  64066. if (padding != null) {
  64067. cssText.push('padding:' + normalizeCssArray$1(padding).join('px ') + 'px');
  64068. }
  64069. return cssText.join(';') + ';';
  64070. } // If not able to make, do not modify the input `out`.
  64071. function makeStyleCoord(out, zr, appendToBody, zrX, zrY) {
  64072. var zrPainter = zr && zr.painter;
  64073. if (appendToBody) {
  64074. var zrViewportRoot = zrPainter && zrPainter.getViewportRoot();
  64075. if (zrViewportRoot) {
  64076. // Some APPs might use scale on body, so we support CSS transform here.
  64077. transformLocalCoord(out, zrViewportRoot, document.body, zrX, zrY);
  64078. }
  64079. } else {
  64080. out[0] = zrX;
  64081. out[1] = zrY; // xy should be based on canvas root. But tooltipContent is
  64082. // the sibling of canvas root. So padding of ec container
  64083. // should be considered here.
  64084. var viewportRootOffset = zrPainter && zrPainter.getViewportRootOffset();
  64085. if (viewportRootOffset) {
  64086. out[0] += viewportRootOffset.offsetLeft;
  64087. out[1] += viewportRootOffset.offsetTop;
  64088. }
  64089. }
  64090. }
  64091. /**
  64092. * @alias module:echarts/component/tooltip/TooltipContent
  64093. * @param {HTMLElement} container
  64094. * @param {ExtensionAPI} api
  64095. * @param {Object} [opt]
  64096. * @param {boolean} [opt.appendToBody]
  64097. * `false`: the DOM element will be inside the container. Default value.
  64098. * `true`: the DOM element will be appended to HTML body, which avoid
  64099. * some overflow clip but intrude outside of the container.
  64100. * @constructor
  64101. */
  64102. function TooltipContent(container, api, opt) {
  64103. if (env$1.wxa) {
  64104. return null;
  64105. }
  64106. var el = document.createElement('div');
  64107. el.domBelongToZr = true;
  64108. this.el = el;
  64109. var zr = this._zr = api.getZr();
  64110. var appendToBody = this._appendToBody = opt && opt.appendToBody;
  64111. this._styleCoord = [0, 0];
  64112. makeStyleCoord(this._styleCoord, zr, appendToBody, api.getWidth() / 2, api.getHeight() / 2);
  64113. if (appendToBody) {
  64114. document.body.appendChild(el);
  64115. } else {
  64116. container.appendChild(el);
  64117. }
  64118. this._container = container;
  64119. this._show = false;
  64120. /**
  64121. * @private
  64122. */
  64123. this._hideTimeout; // FIXME
  64124. // Is it needed to trigger zr event manually if
  64125. // the browser do not support `pointer-events: none`.
  64126. var self = this;
  64127. el.onmouseenter = function () {
  64128. // clear the timeout in hideLater and keep showing tooltip
  64129. if (self._enterable) {
  64130. clearTimeout(self._hideTimeout);
  64131. self._show = true;
  64132. }
  64133. self._inContent = true;
  64134. };
  64135. el.onmousemove = function (e) {
  64136. e = e || window.event;
  64137. if (!self._enterable) {
  64138. // `pointer-events: none` is set to tooltip content div
  64139. // if `enterable` is set as `false`, and `el.onmousemove`
  64140. // can not be triggered. But in browser that do not
  64141. // support `pointer-events`, we need to do this:
  64142. // Try trigger zrender event to avoid mouse
  64143. // in and out shape too frequently
  64144. var handler = zr.handler;
  64145. var zrViewportRoot = zr.painter.getViewportRoot();
  64146. normalizeEvent(zrViewportRoot, e, true);
  64147. handler.dispatch('mousemove', e);
  64148. }
  64149. };
  64150. el.onmouseleave = function () {
  64151. if (self._enterable) {
  64152. if (self._show) {
  64153. self.hideLater(self._hideDelay);
  64154. }
  64155. }
  64156. self._inContent = false;
  64157. };
  64158. }
  64159. TooltipContent.prototype = {
  64160. constructor: TooltipContent,
  64161. /**
  64162. * @private
  64163. * @type {boolean}
  64164. */
  64165. _enterable: true,
  64166. /**
  64167. * Update when tooltip is rendered
  64168. */
  64169. update: function () {
  64170. // FIXME
  64171. // Move this logic to ec main?
  64172. var container = this._container;
  64173. var stl = container.currentStyle || document.defaultView.getComputedStyle(container);
  64174. var domStyle = container.style;
  64175. if (domStyle.position !== 'absolute' && stl.position !== 'absolute') {
  64176. domStyle.position = 'relative';
  64177. } // Hide the tooltip
  64178. // PENDING
  64179. // this.hide();
  64180. },
  64181. show: function (tooltipModel) {
  64182. clearTimeout(this._hideTimeout);
  64183. var el = this.el;
  64184. var styleCoord = this._styleCoord;
  64185. el.style.cssText = gCssText + assembleCssText(tooltipModel) // Because of the reason described in:
  64186. // http://stackoverflow.com/questions/21125587/css3-transition-not-working-in-chrome-anymore
  64187. // we should set initial value to `left` and `top`.
  64188. + ';left:' + styleCoord[0] + 'px;top:' + styleCoord[1] + 'px;' + (tooltipModel.get('extraCssText') || '');
  64189. el.style.display = el.innerHTML ? 'block' : 'none'; // If mouse occsionally move over the tooltip, a mouseout event will be
  64190. // triggered by canvas, and cuase some unexpectable result like dragging
  64191. // stop, "unfocusAdjacency". Here `pointer-events: none` is used to solve
  64192. // it. Although it is not suppored by IE8~IE10, fortunately it is a rare
  64193. // scenario.
  64194. el.style.pointerEvents = this._enterable ? 'auto' : 'none';
  64195. this._show = true;
  64196. },
  64197. setContent: function (content) {
  64198. this.el.innerHTML = content == null ? '' : content;
  64199. },
  64200. setEnterable: function (enterable) {
  64201. this._enterable = enterable;
  64202. },
  64203. getSize: function () {
  64204. var el = this.el;
  64205. return [el.clientWidth, el.clientHeight];
  64206. },
  64207. moveTo: function (zrX, zrY) {
  64208. var styleCoord = this._styleCoord;
  64209. makeStyleCoord(styleCoord, this._zr, this._appendToBody, zrX, zrY);
  64210. var style = this.el.style;
  64211. style.left = styleCoord[0] + 'px';
  64212. style.top = styleCoord[1] + 'px';
  64213. },
  64214. hide: function () {
  64215. this.el.style.display = 'none';
  64216. this._show = false;
  64217. },
  64218. hideLater: function (time) {
  64219. if (this._show && !(this._inContent && this._enterable)) {
  64220. if (time) {
  64221. this._hideDelay = time; // Set show false to avoid invoke hideLater mutiple times
  64222. this._show = false;
  64223. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  64224. } else {
  64225. this.hide();
  64226. }
  64227. }
  64228. },
  64229. isShow: function () {
  64230. return this._show;
  64231. },
  64232. dispose: function () {
  64233. this.el.parentNode.removeChild(this.el);
  64234. },
  64235. getOuterSize: function () {
  64236. var width = this.el.clientWidth;
  64237. var height = this.el.clientHeight; // Consider browser compatibility.
  64238. // IE8 does not support getComputedStyle.
  64239. if (document.defaultView && document.defaultView.getComputedStyle) {
  64240. var stl = document.defaultView.getComputedStyle(this.el);
  64241. if (stl) {
  64242. width += parseInt(stl.borderLeftWidth, 10) + parseInt(stl.borderRightWidth, 10);
  64243. height += parseInt(stl.borderTopWidth, 10) + parseInt(stl.borderBottomWidth, 10);
  64244. }
  64245. }
  64246. return {
  64247. width: width,
  64248. height: height
  64249. };
  64250. }
  64251. };
  64252. /*
  64253. * Licensed to the Apache Software Foundation (ASF) under one
  64254. * or more contributor license agreements. See the NOTICE file
  64255. * distributed with this work for additional information
  64256. * regarding copyright ownership. The ASF licenses this file
  64257. * to you under the Apache License, Version 2.0 (the
  64258. * "License"); you may not use this file except in compliance
  64259. * with the License. You may obtain a copy of the License at
  64260. *
  64261. * http://www.apache.org/licenses/LICENSE-2.0
  64262. *
  64263. * Unless required by applicable law or agreed to in writing,
  64264. * software distributed under the License is distributed on an
  64265. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64266. * KIND, either express or implied. See the License for the
  64267. * specific language governing permissions and limitations
  64268. * under the License.
  64269. */
  64270. /**
  64271. * @alias module:echarts/component/tooltip/TooltipRichContent
  64272. * @constructor
  64273. */
  64274. function TooltipRichContent(api) {
  64275. this._zr = api.getZr();
  64276. this._show = false;
  64277. /**
  64278. * @private
  64279. */
  64280. this._hideTimeout;
  64281. }
  64282. TooltipRichContent.prototype = {
  64283. constructor: TooltipRichContent,
  64284. /**
  64285. * @private
  64286. * @type {boolean}
  64287. */
  64288. _enterable: true,
  64289. /**
  64290. * Update when tooltip is rendered
  64291. */
  64292. update: function () {// noop
  64293. },
  64294. show: function (tooltipModel) {
  64295. if (this._hideTimeout) {
  64296. clearTimeout(this._hideTimeout);
  64297. }
  64298. this.el.attr('show', true);
  64299. this._show = true;
  64300. },
  64301. /**
  64302. * Set tooltip content
  64303. *
  64304. * @param {string} content rich text string of content
  64305. * @param {Object} markerRich rich text style
  64306. * @param {Object} tooltipModel tooltip model
  64307. */
  64308. setContent: function (content, markerRich, tooltipModel) {
  64309. if (this.el) {
  64310. this._zr.remove(this.el);
  64311. }
  64312. var markers = {};
  64313. var text = content;
  64314. var prefix = '{marker';
  64315. var suffix = '|}';
  64316. var startId = text.indexOf(prefix);
  64317. while (startId >= 0) {
  64318. var endId = text.indexOf(suffix);
  64319. var name = text.substr(startId + prefix.length, endId - startId - prefix.length);
  64320. if (name.indexOf('sub') > -1) {
  64321. markers['marker' + name] = {
  64322. textWidth: 4,
  64323. textHeight: 4,
  64324. textBorderRadius: 2,
  64325. textBackgroundColor: markerRich[name],
  64326. // TODO: textOffset is not implemented for rich text
  64327. textOffset: [3, 0]
  64328. };
  64329. } else {
  64330. markers['marker' + name] = {
  64331. textWidth: 10,
  64332. textHeight: 10,
  64333. textBorderRadius: 5,
  64334. textBackgroundColor: markerRich[name]
  64335. };
  64336. }
  64337. text = text.substr(endId + 1);
  64338. startId = text.indexOf('{marker');
  64339. }
  64340. this.el = new Text({
  64341. style: {
  64342. rich: markers,
  64343. text: content,
  64344. textLineHeight: 20,
  64345. textBackgroundColor: tooltipModel.get('backgroundColor'),
  64346. textBorderRadius: tooltipModel.get('borderRadius'),
  64347. textFill: tooltipModel.get('textStyle.color'),
  64348. textPadding: tooltipModel.get('padding')
  64349. },
  64350. z: tooltipModel.get('z')
  64351. });
  64352. this._zr.add(this.el);
  64353. var self = this;
  64354. this.el.on('mouseover', function () {
  64355. // clear the timeout in hideLater and keep showing tooltip
  64356. if (self._enterable) {
  64357. clearTimeout(self._hideTimeout);
  64358. self._show = true;
  64359. }
  64360. self._inContent = true;
  64361. });
  64362. this.el.on('mouseout', function () {
  64363. if (self._enterable) {
  64364. if (self._show) {
  64365. self.hideLater(self._hideDelay);
  64366. }
  64367. }
  64368. self._inContent = false;
  64369. });
  64370. },
  64371. setEnterable: function (enterable) {
  64372. this._enterable = enterable;
  64373. },
  64374. getSize: function () {
  64375. var bounding = this.el.getBoundingRect();
  64376. return [bounding.width, bounding.height];
  64377. },
  64378. moveTo: function (x, y) {
  64379. if (this.el) {
  64380. this.el.attr('position', [x, y]);
  64381. }
  64382. },
  64383. hide: function () {
  64384. if (this.el) {
  64385. this.el.hide();
  64386. }
  64387. this._show = false;
  64388. },
  64389. hideLater: function (time) {
  64390. if (this._show && !(this._inContent && this._enterable)) {
  64391. if (time) {
  64392. this._hideDelay = time; // Set show false to avoid invoke hideLater mutiple times
  64393. this._show = false;
  64394. this._hideTimeout = setTimeout(bind(this.hide, this), time);
  64395. } else {
  64396. this.hide();
  64397. }
  64398. }
  64399. },
  64400. isShow: function () {
  64401. return this._show;
  64402. },
  64403. getOuterSize: function () {
  64404. var size = this.getSize();
  64405. return {
  64406. width: size[0],
  64407. height: size[1]
  64408. };
  64409. }
  64410. };
  64411. /*
  64412. * Licensed to the Apache Software Foundation (ASF) under one
  64413. * or more contributor license agreements. See the NOTICE file
  64414. * distributed with this work for additional information
  64415. * regarding copyright ownership. The ASF licenses this file
  64416. * to you under the Apache License, Version 2.0 (the
  64417. * "License"); you may not use this file except in compliance
  64418. * with the License. You may obtain a copy of the License at
  64419. *
  64420. * http://www.apache.org/licenses/LICENSE-2.0
  64421. *
  64422. * Unless required by applicable law or agreed to in writing,
  64423. * software distributed under the License is distributed on an
  64424. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  64425. * KIND, either express or implied. See the License for the
  64426. * specific language governing permissions and limitations
  64427. * under the License.
  64428. */
  64429. var bind$3 = bind;
  64430. var each$17 = each$1;
  64431. var parsePercent$2 = parsePercent$1;
  64432. var proxyRect = new Rect({
  64433. shape: {
  64434. x: -1,
  64435. y: -1,
  64436. width: 2,
  64437. height: 2
  64438. }
  64439. });
  64440. extendComponentView({
  64441. type: 'tooltip',
  64442. init: function (ecModel, api) {
  64443. if (env$1.node) {
  64444. return;
  64445. }
  64446. var tooltipModel = ecModel.getComponent('tooltip');
  64447. var renderMode = tooltipModel.get('renderMode');
  64448. this._renderMode = getTooltipRenderMode(renderMode);
  64449. var tooltipContent;
  64450. if (this._renderMode === 'html') {
  64451. tooltipContent = new TooltipContent(api.getDom(), api, {
  64452. appendToBody: tooltipModel.get('appendToBody', true)
  64453. });
  64454. this._newLine = '<br/>';
  64455. } else {
  64456. tooltipContent = new TooltipRichContent(api);
  64457. this._newLine = '\n';
  64458. }
  64459. this._tooltipContent = tooltipContent;
  64460. },
  64461. render: function (tooltipModel, ecModel, api) {
  64462. if (env$1.node) {
  64463. return;
  64464. } // Reset
  64465. this.group.removeAll();
  64466. /**
  64467. * @private
  64468. * @type {module:echarts/component/tooltip/TooltipModel}
  64469. */
  64470. this._tooltipModel = tooltipModel;
  64471. /**
  64472. * @private
  64473. * @type {module:echarts/model/Global}
  64474. */
  64475. this._ecModel = ecModel;
  64476. /**
  64477. * @private
  64478. * @type {module:echarts/ExtensionAPI}
  64479. */
  64480. this._api = api;
  64481. /**
  64482. * Should be cleaned when render.
  64483. * @private
  64484. * @type {Array.<Array.<Object>>}
  64485. */
  64486. this._lastDataByCoordSys = null;
  64487. /**
  64488. * @private
  64489. * @type {boolean}
  64490. */
  64491. this._alwaysShowContent = tooltipModel.get('alwaysShowContent');
  64492. var tooltipContent = this._tooltipContent;
  64493. tooltipContent.update();
  64494. tooltipContent.setEnterable(tooltipModel.get('enterable'));
  64495. this._initGlobalListener();
  64496. this._keepShow();
  64497. },
  64498. _initGlobalListener: function () {
  64499. var tooltipModel = this._tooltipModel;
  64500. var triggerOn = tooltipModel.get('triggerOn');
  64501. register('itemTooltip', this._api, bind$3(function (currTrigger, e, dispatchAction) {
  64502. // If 'none', it is not controlled by mouse totally.
  64503. if (triggerOn !== 'none') {
  64504. if (triggerOn.indexOf(currTrigger) >= 0) {
  64505. this._tryShow(e, dispatchAction);
  64506. } else if (currTrigger === 'leave') {
  64507. this._hide(dispatchAction);
  64508. }
  64509. }
  64510. }, this));
  64511. },
  64512. _keepShow: function () {
  64513. var tooltipModel = this._tooltipModel;
  64514. var ecModel = this._ecModel;
  64515. var api = this._api; // Try to keep the tooltip show when refreshing
  64516. if (this._lastX != null && this._lastY != null // When user is willing to control tooltip totally using API,
  64517. // self.manuallyShowTip({x, y}) might cause tooltip hide,
  64518. // which is not expected.
  64519. && tooltipModel.get('triggerOn') !== 'none') {
  64520. var self = this;
  64521. clearTimeout(this._refreshUpdateTimeout);
  64522. this._refreshUpdateTimeout = setTimeout(function () {
  64523. // Show tip next tick after other charts are rendered
  64524. // In case highlight action has wrong result
  64525. // FIXME
  64526. !api.isDisposed() && self.manuallyShowTip(tooltipModel, ecModel, api, {
  64527. x: self._lastX,
  64528. y: self._lastY
  64529. });
  64530. });
  64531. }
  64532. },
  64533. /**
  64534. * Show tip manually by
  64535. * dispatchAction({
  64536. * type: 'showTip',
  64537. * x: 10,
  64538. * y: 10
  64539. * });
  64540. * Or
  64541. * dispatchAction({
  64542. * type: 'showTip',
  64543. * seriesIndex: 0,
  64544. * dataIndex or dataIndexInside or name
  64545. * });
  64546. *
  64547. * TODO Batch
  64548. */
  64549. manuallyShowTip: function (tooltipModel, ecModel, api, payload) {
  64550. if (payload.from === this.uid || env$1.node) {
  64551. return;
  64552. }
  64553. var dispatchAction = makeDispatchAction$1(payload, api); // Reset ticket
  64554. this._ticket = ''; // When triggered from axisPointer.
  64555. var dataByCoordSys = payload.dataByCoordSys;
  64556. if (payload.tooltip && payload.x != null && payload.y != null) {
  64557. var el = proxyRect;
  64558. el.position = [payload.x, payload.y];
  64559. el.update();
  64560. el.tooltip = payload.tooltip; // Manually show tooltip while view is not using zrender elements.
  64561. this._tryShow({
  64562. offsetX: payload.x,
  64563. offsetY: payload.y,
  64564. target: el
  64565. }, dispatchAction);
  64566. } else if (dataByCoordSys) {
  64567. this._tryShow({
  64568. offsetX: payload.x,
  64569. offsetY: payload.y,
  64570. position: payload.position,
  64571. dataByCoordSys: payload.dataByCoordSys,
  64572. tooltipOption: payload.tooltipOption
  64573. }, dispatchAction);
  64574. } else if (payload.seriesIndex != null) {
  64575. if (this._manuallyAxisShowTip(tooltipModel, ecModel, api, payload)) {
  64576. return;
  64577. }
  64578. var pointInfo = findPointFromSeries(payload, ecModel);
  64579. var cx = pointInfo.point[0];
  64580. var cy = pointInfo.point[1];
  64581. if (cx != null && cy != null) {
  64582. this._tryShow({
  64583. offsetX: cx,
  64584. offsetY: cy,
  64585. position: payload.position,
  64586. target: pointInfo.el
  64587. }, dispatchAction);
  64588. }
  64589. } else if (payload.x != null && payload.y != null) {
  64590. // FIXME
  64591. // should wrap dispatchAction like `axisPointer/globalListener` ?
  64592. api.dispatchAction({
  64593. type: 'updateAxisPointer',
  64594. x: payload.x,
  64595. y: payload.y
  64596. });
  64597. this._tryShow({
  64598. offsetX: payload.x,
  64599. offsetY: payload.y,
  64600. position: payload.position,
  64601. target: api.getZr().findHover(payload.x, payload.y).target
  64602. }, dispatchAction);
  64603. }
  64604. },
  64605. manuallyHideTip: function (tooltipModel, ecModel, api, payload) {
  64606. var tooltipContent = this._tooltipContent;
  64607. if (!this._alwaysShowContent && this._tooltipModel) {
  64608. tooltipContent.hideLater(this._tooltipModel.get('hideDelay'));
  64609. }
  64610. this._lastX = this._lastY = null;
  64611. if (payload.from !== this.uid) {
  64612. this._hide(makeDispatchAction$1(payload, api));
  64613. }
  64614. },
  64615. // Be compatible with previous design, that is, when tooltip.type is 'axis' and
  64616. // dispatchAction 'showTip' with seriesIndex and dataIndex will trigger axis pointer
  64617. // and tooltip.
  64618. _manuallyAxisShowTip: function (tooltipModel, ecModel, api, payload) {
  64619. var seriesIndex = payload.seriesIndex;
  64620. var dataIndex = payload.dataIndex;
  64621. var coordSysAxesInfo = ecModel.getComponent('axisPointer').coordSysAxesInfo;
  64622. if (seriesIndex == null || dataIndex == null || coordSysAxesInfo == null) {
  64623. return;
  64624. }
  64625. var seriesModel = ecModel.getSeriesByIndex(seriesIndex);
  64626. if (!seriesModel) {
  64627. return;
  64628. }
  64629. var data = seriesModel.getData();
  64630. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), seriesModel, (seriesModel.coordinateSystem || {}).model, tooltipModel]);
  64631. if (tooltipModel.get('trigger') !== 'axis') {
  64632. return;
  64633. }
  64634. api.dispatchAction({
  64635. type: 'updateAxisPointer',
  64636. seriesIndex: seriesIndex,
  64637. dataIndex: dataIndex,
  64638. position: payload.position
  64639. });
  64640. return true;
  64641. },
  64642. _tryShow: function (e, dispatchAction) {
  64643. var el = e.target;
  64644. var tooltipModel = this._tooltipModel;
  64645. if (!tooltipModel) {
  64646. return;
  64647. } // Save mouse x, mouse y. So we can try to keep showing the tip if chart is refreshed
  64648. this._lastX = e.offsetX;
  64649. this._lastY = e.offsetY;
  64650. var dataByCoordSys = e.dataByCoordSys;
  64651. if (dataByCoordSys && dataByCoordSys.length) {
  64652. this._showAxisTooltip(dataByCoordSys, e);
  64653. } // Always show item tooltip if mouse is on the element with dataIndex
  64654. else if (el && el.dataIndex != null) {
  64655. this._lastDataByCoordSys = null;
  64656. this._showSeriesItemTooltip(e, el, dispatchAction);
  64657. } // Tooltip provided directly. Like legend.
  64658. else if (el && el.tooltip) {
  64659. this._lastDataByCoordSys = null;
  64660. this._showComponentItemTooltip(e, el, dispatchAction);
  64661. } else {
  64662. this._lastDataByCoordSys = null;
  64663. this._hide(dispatchAction);
  64664. }
  64665. },
  64666. _showOrMove: function (tooltipModel, cb) {
  64667. // showDelay is used in this case: tooltip.enterable is set
  64668. // as true. User intent to move mouse into tooltip and click
  64669. // something. `showDelay` makes it easyer to enter the content
  64670. // but tooltip do not move immediately.
  64671. var delay = tooltipModel.get('showDelay');
  64672. cb = bind(cb, this);
  64673. clearTimeout(this._showTimout);
  64674. delay > 0 ? this._showTimout = setTimeout(cb, delay) : cb();
  64675. },
  64676. _showAxisTooltip: function (dataByCoordSys, e) {
  64677. var ecModel = this._ecModel;
  64678. var globalTooltipModel = this._tooltipModel;
  64679. var point = [e.offsetX, e.offsetY];
  64680. var singleDefaultHTML = [];
  64681. var singleParamsList = [];
  64682. var singleTooltipModel = buildTooltipModel([e.tooltipOption, globalTooltipModel]);
  64683. var renderMode = this._renderMode;
  64684. var newLine = this._newLine;
  64685. var markers = {};
  64686. each$17(dataByCoordSys, function (itemCoordSys) {
  64687. // var coordParamList = [];
  64688. // var coordDefaultHTML = [];
  64689. // var coordTooltipModel = buildTooltipModel([
  64690. // e.tooltipOption,
  64691. // itemCoordSys.tooltipOption,
  64692. // ecModel.getComponent(itemCoordSys.coordSysMainType, itemCoordSys.coordSysIndex),
  64693. // globalTooltipModel
  64694. // ]);
  64695. // var displayMode = coordTooltipModel.get('displayMode');
  64696. // var paramsList = displayMode === 'single' ? singleParamsList : [];
  64697. each$17(itemCoordSys.dataByAxis, function (item) {
  64698. var axisModel = ecModel.getComponent(item.axisDim + 'Axis', item.axisIndex);
  64699. var axisValue = item.value;
  64700. var seriesDefaultHTML = [];
  64701. if (!axisModel || axisValue == null) {
  64702. return;
  64703. }
  64704. var valueLabel = getValueLabel(axisValue, axisModel.axis, ecModel, item.seriesDataIndices, item.valueLabelOpt);
  64705. each$1(item.seriesDataIndices, function (idxItem) {
  64706. var series = ecModel.getSeriesByIndex(idxItem.seriesIndex);
  64707. var dataIndex = idxItem.dataIndexInside;
  64708. var dataParams = series && series.getDataParams(dataIndex);
  64709. dataParams.axisDim = item.axisDim;
  64710. dataParams.axisIndex = item.axisIndex;
  64711. dataParams.axisType = item.axisType;
  64712. dataParams.axisId = item.axisId;
  64713. dataParams.axisValue = getAxisRawValue(axisModel.axis, axisValue);
  64714. dataParams.axisValueLabel = valueLabel;
  64715. if (dataParams) {
  64716. singleParamsList.push(dataParams);
  64717. var seriesTooltip = series.formatTooltip(dataIndex, true, null, renderMode);
  64718. var html;
  64719. if (isObject$1(seriesTooltip)) {
  64720. html = seriesTooltip.html;
  64721. var newMarkers = seriesTooltip.markers;
  64722. merge(markers, newMarkers);
  64723. } else {
  64724. html = seriesTooltip;
  64725. }
  64726. seriesDefaultHTML.push(html);
  64727. }
  64728. }); // Default tooltip content
  64729. // FIXME
  64730. // (1) shold be the first data which has name?
  64731. // (2) themeRiver, firstDataIndex is array, and first line is unnecessary.
  64732. var firstLine = valueLabel;
  64733. if (renderMode !== 'html') {
  64734. singleDefaultHTML.push(seriesDefaultHTML.join(newLine));
  64735. } else {
  64736. singleDefaultHTML.push((firstLine ? encodeHTML(firstLine) + newLine : '') + seriesDefaultHTML.join(newLine));
  64737. }
  64738. });
  64739. }, this); // In most case, the second axis is shown upper than the first one.
  64740. singleDefaultHTML.reverse();
  64741. singleDefaultHTML = singleDefaultHTML.join(this._newLine + this._newLine);
  64742. var positionExpr = e.position;
  64743. this._showOrMove(singleTooltipModel, function () {
  64744. if (this._updateContentNotChangedOnAxis(dataByCoordSys)) {
  64745. this._updatePosition(singleTooltipModel, positionExpr, point[0], point[1], this._tooltipContent, singleParamsList);
  64746. } else {
  64747. this._showTooltipContent(singleTooltipModel, singleDefaultHTML, singleParamsList, Math.random(), point[0], point[1], positionExpr, undefined, markers);
  64748. }
  64749. }); // Do not trigger events here, because this branch only be entered
  64750. // from dispatchAction.
  64751. },
  64752. _showSeriesItemTooltip: function (e, el, dispatchAction) {
  64753. var ecModel = this._ecModel; // Use dataModel in element if possible
  64754. // Used when mouseover on a element like markPoint or edge
  64755. // In which case, the data is not main data in series.
  64756. var seriesIndex = el.seriesIndex;
  64757. var seriesModel = ecModel.getSeriesByIndex(seriesIndex); // For example, graph link.
  64758. var dataModel = el.dataModel || seriesModel;
  64759. var dataIndex = el.dataIndex;
  64760. var dataType = el.dataType;
  64761. var data = dataModel.getData(dataType);
  64762. var tooltipModel = buildTooltipModel([data.getItemModel(dataIndex), dataModel, seriesModel && (seriesModel.coordinateSystem || {}).model, this._tooltipModel]);
  64763. var tooltipTrigger = tooltipModel.get('trigger');
  64764. if (tooltipTrigger != null && tooltipTrigger !== 'item') {
  64765. return;
  64766. }
  64767. var params = dataModel.getDataParams(dataIndex, dataType);
  64768. var seriesTooltip = dataModel.formatTooltip(dataIndex, false, dataType, this._renderMode);
  64769. var defaultHtml;
  64770. var markers;
  64771. if (isObject$1(seriesTooltip)) {
  64772. defaultHtml = seriesTooltip.html;
  64773. markers = seriesTooltip.markers;
  64774. } else {
  64775. defaultHtml = seriesTooltip;
  64776. markers = null;
  64777. }
  64778. var asyncTicket = 'item_' + dataModel.name + '_' + dataIndex;
  64779. this._showOrMove(tooltipModel, function () {
  64780. this._showTooltipContent(tooltipModel, defaultHtml, params, asyncTicket, e.offsetX, e.offsetY, e.position, e.target, markers);
  64781. }); // FIXME
  64782. // duplicated showtip if manuallyShowTip is called from dispatchAction.
  64783. dispatchAction({
  64784. type: 'showTip',
  64785. dataIndexInside: dataIndex,
  64786. dataIndex: data.getRawIndex(dataIndex),
  64787. seriesIndex: seriesIndex,
  64788. from: this.uid
  64789. });
  64790. },
  64791. _showComponentItemTooltip: function (e, el, dispatchAction) {
  64792. var tooltipOpt = el.tooltip;
  64793. if (typeof tooltipOpt === 'string') {
  64794. var content = tooltipOpt;
  64795. tooltipOpt = {
  64796. content: content,
  64797. // Fixed formatter
  64798. formatter: content
  64799. };
  64800. }
  64801. var subTooltipModel = new Model(tooltipOpt, this._tooltipModel, this._ecModel);
  64802. var defaultHtml = subTooltipModel.get('content');
  64803. var asyncTicket = Math.random(); // Do not check whether `trigger` is 'none' here, because `trigger`
  64804. // only works on cooridinate system. In fact, we have not found case
  64805. // that requires setting `trigger` nothing on component yet.
  64806. this._showOrMove(subTooltipModel, function () {
  64807. this._showTooltipContent(subTooltipModel, defaultHtml, subTooltipModel.get('formatterParams') || {}, asyncTicket, e.offsetX, e.offsetY, e.position, el);
  64808. }); // If not dispatch showTip, tip may be hide triggered by axis.
  64809. dispatchAction({
  64810. type: 'showTip',
  64811. from: this.uid
  64812. });
  64813. },
  64814. _showTooltipContent: function (tooltipModel, defaultHtml, params, asyncTicket, x, y, positionExpr, el, markers) {
  64815. // Reset ticket
  64816. this._ticket = '';
  64817. if (!tooltipModel.get('showContent') || !tooltipModel.get('show')) {
  64818. return;
  64819. }
  64820. var tooltipContent = this._tooltipContent;
  64821. var formatter = tooltipModel.get('formatter');
  64822. positionExpr = positionExpr || tooltipModel.get('position');
  64823. var html = defaultHtml;
  64824. if (formatter && typeof formatter === 'string') {
  64825. html = formatTpl(formatter, params, true);
  64826. } else if (typeof formatter === 'function') {
  64827. var callback = bind$3(function (cbTicket, html) {
  64828. if (cbTicket === this._ticket) {
  64829. tooltipContent.setContent(html, markers, tooltipModel);
  64830. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  64831. }
  64832. }, this);
  64833. this._ticket = asyncTicket;
  64834. html = formatter(params, asyncTicket, callback);
  64835. }
  64836. tooltipContent.setContent(html, markers, tooltipModel);
  64837. tooltipContent.show(tooltipModel);
  64838. this._updatePosition(tooltipModel, positionExpr, x, y, tooltipContent, params, el);
  64839. },
  64840. /**
  64841. * @param {string|Function|Array.<number>|Object} positionExpr
  64842. * @param {number} x Mouse x
  64843. * @param {number} y Mouse y
  64844. * @param {boolean} confine Whether confine tooltip content in view rect.
  64845. * @param {Object|<Array.<Object>} params
  64846. * @param {module:zrender/Element} el target element
  64847. * @param {module:echarts/ExtensionAPI} api
  64848. * @return {Array.<number>}
  64849. */
  64850. _updatePosition: function (tooltipModel, positionExpr, x, y, content, params, el) {
  64851. var viewWidth = this._api.getWidth();
  64852. var viewHeight = this._api.getHeight();
  64853. positionExpr = positionExpr || tooltipModel.get('position');
  64854. var contentSize = content.getSize();
  64855. var align = tooltipModel.get('align');
  64856. var vAlign = tooltipModel.get('verticalAlign');
  64857. var rect = el && el.getBoundingRect().clone();
  64858. el && rect.applyTransform(el.transform);
  64859. if (typeof positionExpr === 'function') {
  64860. // Callback of position can be an array or a string specify the position
  64861. positionExpr = positionExpr([x, y], params, content.el, rect, {
  64862. viewSize: [viewWidth, viewHeight],
  64863. contentSize: contentSize.slice()
  64864. });
  64865. }
  64866. if (isArray(positionExpr)) {
  64867. x = parsePercent$2(positionExpr[0], viewWidth);
  64868. y = parsePercent$2(positionExpr[1], viewHeight);
  64869. } else if (isObject$1(positionExpr)) {
  64870. positionExpr.width = contentSize[0];
  64871. positionExpr.height = contentSize[1];
  64872. var layoutRect = getLayoutRect(positionExpr, {
  64873. width: viewWidth,
  64874. height: viewHeight
  64875. });
  64876. x = layoutRect.x;
  64877. y = layoutRect.y;
  64878. align = null; // When positionExpr is left/top/right/bottom,
  64879. // align and verticalAlign will not work.
  64880. vAlign = null;
  64881. } // Specify tooltip position by string 'top' 'bottom' 'left' 'right' around graphic element
  64882. else if (typeof positionExpr === 'string' && el) {
  64883. var pos = calcTooltipPosition(positionExpr, rect, contentSize);
  64884. x = pos[0];
  64885. y = pos[1];
  64886. } else {
  64887. var pos = refixTooltipPosition(x, y, content, viewWidth, viewHeight, align ? null : 20, vAlign ? null : 20);
  64888. x = pos[0];
  64889. y = pos[1];
  64890. }
  64891. align && (x -= isCenterAlign(align) ? contentSize[0] / 2 : align === 'right' ? contentSize[0] : 0);
  64892. vAlign && (y -= isCenterAlign(vAlign) ? contentSize[1] / 2 : vAlign === 'bottom' ? contentSize[1] : 0);
  64893. if (tooltipModel.get('confine')) {
  64894. var pos = confineTooltipPosition(x, y, content, viewWidth, viewHeight);
  64895. x = pos[0];
  64896. y = pos[1];
  64897. }
  64898. content.moveTo(x, y);
  64899. },
  64900. // FIXME
  64901. // Should we remove this but leave this to user?
  64902. _updateContentNotChangedOnAxis: function (dataByCoordSys) {
  64903. var lastCoordSys = this._lastDataByCoordSys;
  64904. var contentNotChanged = !!lastCoordSys && lastCoordSys.length === dataByCoordSys.length;
  64905. contentNotChanged && each$17(lastCoordSys, function (lastItemCoordSys, indexCoordSys) {
  64906. var lastDataByAxis = lastItemCoordSys.dataByAxis || {};
  64907. var thisItemCoordSys = dataByCoordSys[indexCoordSys] || {};
  64908. var thisDataByAxis = thisItemCoordSys.dataByAxis || [];
  64909. contentNotChanged &= lastDataByAxis.length === thisDataByAxis.length;
  64910. contentNotChanged && each$17(lastDataByAxis, function (lastItem, indexAxis) {
  64911. var thisItem = thisDataByAxis[indexAxis] || {};
  64912. var lastIndices = lastItem.seriesDataIndices || [];
  64913. var newIndices = thisItem.seriesDataIndices || [];
  64914. contentNotChanged &= lastItem.value === thisItem.value && lastItem.axisType === thisItem.axisType && lastItem.axisId === thisItem.axisId && lastIndices.length === newIndices.length;
  64915. contentNotChanged && each$17(lastIndices, function (lastIdxItem, j) {
  64916. var newIdxItem = newIndices[j];
  64917. contentNotChanged &= lastIdxItem.seriesIndex === newIdxItem.seriesIndex && lastIdxItem.dataIndex === newIdxItem.dataIndex;
  64918. });
  64919. });
  64920. });
  64921. this._lastDataByCoordSys = dataByCoordSys;
  64922. return !!contentNotChanged;
  64923. },
  64924. _hide: function (dispatchAction) {
  64925. // Do not directly hideLater here, because this behavior may be prevented
  64926. // in dispatchAction when showTip is dispatched.
  64927. // FIXME
  64928. // duplicated hideTip if manuallyHideTip is called from dispatchAction.
  64929. this._lastDataByCoordSys = null;
  64930. dispatchAction({
  64931. type: 'hideTip',
  64932. from: this.uid
  64933. });
  64934. },
  64935. dispose: function (ecModel, api) {
  64936. if (env$1.node) {
  64937. return;
  64938. }
  64939. this._tooltipContent.dispose();
  64940. unregister('itemTooltip', api);
  64941. }
  64942. });
  64943. /**
  64944. * @param {Array.<Object|module:echarts/model/Model>} modelCascade
  64945. * From top to bottom. (the last one should be globalTooltipModel);
  64946. */
  64947. function buildTooltipModel(modelCascade) {
  64948. var resultModel = modelCascade.pop();
  64949. while (modelCascade.length) {
  64950. var tooltipOpt = modelCascade.pop();
  64951. if (tooltipOpt) {
  64952. if (Model.isInstance(tooltipOpt)) {
  64953. tooltipOpt = tooltipOpt.get('tooltip', true);
  64954. } // In each data item tooltip can be simply write:
  64955. // {
  64956. // value: 10,
  64957. // tooltip: 'Something you need to know'
  64958. // }
  64959. if (typeof tooltipOpt === 'string') {
  64960. tooltipOpt = {
  64961. formatter: tooltipOpt
  64962. };
  64963. }
  64964. resultModel = new Model(tooltipOpt, resultModel, resultModel.ecModel);
  64965. }
  64966. }
  64967. return resultModel;
  64968. }
  64969. function makeDispatchAction$1(payload, api) {
  64970. return payload.dispatchAction || bind(api.dispatchAction, api);
  64971. }
  64972. function refixTooltipPosition(x, y, content, viewWidth, viewHeight, gapH, gapV) {
  64973. var size = content.getOuterSize();
  64974. var width = size.width;
  64975. var height = size.height;
  64976. if (gapH != null) {
  64977. if (x + width + gapH > viewWidth) {
  64978. x -= width + gapH;
  64979. } else {
  64980. x += gapH;
  64981. }
  64982. }
  64983. if (gapV != null) {
  64984. if (y + height + gapV > viewHeight) {
  64985. y -= height + gapV;
  64986. } else {
  64987. y += gapV;
  64988. }
  64989. }
  64990. return [x, y];
  64991. }
  64992. function confineTooltipPosition(x, y, content, viewWidth, viewHeight) {
  64993. var size = content.getOuterSize();
  64994. var width = size.width;
  64995. var height = size.height;
  64996. x = Math.min(x + width, viewWidth) - width;
  64997. y = Math.min(y + height, viewHeight) - height;
  64998. x = Math.max(x, 0);
  64999. y = Math.max(y, 0);
  65000. return [x, y];
  65001. }
  65002. function calcTooltipPosition(position, rect, contentSize) {
  65003. var domWidth = contentSize[0];
  65004. var domHeight = contentSize[1];
  65005. var gap = 5;
  65006. var x = 0;
  65007. var y = 0;
  65008. var rectWidth = rect.width;
  65009. var rectHeight = rect.height;
  65010. switch (position) {
  65011. case 'inside':
  65012. x = rect.x + rectWidth / 2 - domWidth / 2;
  65013. y = rect.y + rectHeight / 2 - domHeight / 2;
  65014. break;
  65015. case 'top':
  65016. x = rect.x + rectWidth / 2 - domWidth / 2;
  65017. y = rect.y - domHeight - gap;
  65018. break;
  65019. case 'bottom':
  65020. x = rect.x + rectWidth / 2 - domWidth / 2;
  65021. y = rect.y + rectHeight + gap;
  65022. break;
  65023. case 'left':
  65024. x = rect.x - domWidth - gap;
  65025. y = rect.y + rectHeight / 2 - domHeight / 2;
  65026. break;
  65027. case 'right':
  65028. x = rect.x + rectWidth + gap;
  65029. y = rect.y + rectHeight / 2 - domHeight / 2;
  65030. }
  65031. return [x, y];
  65032. }
  65033. function isCenterAlign(align) {
  65034. return align === 'center' || align === 'middle';
  65035. }
  65036. /*
  65037. * Licensed to the Apache Software Foundation (ASF) under one
  65038. * or more contributor license agreements. See the NOTICE file
  65039. * distributed with this work for additional information
  65040. * regarding copyright ownership. The ASF licenses this file
  65041. * to you under the Apache License, Version 2.0 (the
  65042. * "License"); you may not use this file except in compliance
  65043. * with the License. You may obtain a copy of the License at
  65044. *
  65045. * http://www.apache.org/licenses/LICENSE-2.0
  65046. *
  65047. * Unless required by applicable law or agreed to in writing,
  65048. * software distributed under the License is distributed on an
  65049. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65050. * KIND, either express or implied. See the License for the
  65051. * specific language governing permissions and limitations
  65052. * under the License.
  65053. */
  65054. // FIXME Better way to pack data in graphic element
  65055. /**
  65056. * @action
  65057. * @property {string} type
  65058. * @property {number} seriesIndex
  65059. * @property {number} dataIndex
  65060. * @property {number} [x]
  65061. * @property {number} [y]
  65062. */
  65063. registerAction({
  65064. type: 'showTip',
  65065. event: 'showTip',
  65066. update: 'tooltip:manuallyShowTip'
  65067. }, // noop
  65068. function () {});
  65069. registerAction({
  65070. type: 'hideTip',
  65071. event: 'hideTip',
  65072. update: 'tooltip:manuallyHideTip'
  65073. }, // noop
  65074. function () {});
  65075. /*
  65076. * Licensed to the Apache Software Foundation (ASF) under one
  65077. * or more contributor license agreements. See the NOTICE file
  65078. * distributed with this work for additional information
  65079. * regarding copyright ownership. The ASF licenses this file
  65080. * to you under the Apache License, Version 2.0 (the
  65081. * "License"); you may not use this file except in compliance
  65082. * with the License. You may obtain a copy of the License at
  65083. *
  65084. * http://www.apache.org/licenses/LICENSE-2.0
  65085. *
  65086. * Unless required by applicable law or agreed to in writing,
  65087. * software distributed under the License is distributed on an
  65088. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65089. * KIND, either express or implied. See the License for the
  65090. * specific language governing permissions and limitations
  65091. * under the License.
  65092. */
  65093. var addCommas$1 = addCommas;
  65094. var encodeHTML$1 = encodeHTML;
  65095. function fillLabel(opt) {
  65096. defaultEmphasis(opt, 'label', ['show']);
  65097. }
  65098. var MarkerModel = extendComponentModel({
  65099. type: 'marker',
  65100. dependencies: ['series', 'grid', 'polar', 'geo'],
  65101. /**
  65102. * @overrite
  65103. */
  65104. init: function (option, parentModel, ecModel) {
  65105. this.mergeDefaultAndTheme(option, ecModel);
  65106. this._mergeOption(option, ecModel, false, true);
  65107. },
  65108. /**
  65109. * @return {boolean}
  65110. */
  65111. isAnimationEnabled: function () {
  65112. if (env$1.node) {
  65113. return false;
  65114. }
  65115. var hostSeries = this.__hostSeries;
  65116. return this.getShallow('animation') && hostSeries && hostSeries.isAnimationEnabled();
  65117. },
  65118. /**
  65119. * @overrite
  65120. */
  65121. mergeOption: function (newOpt, ecModel) {
  65122. this._mergeOption(newOpt, ecModel, false, false);
  65123. },
  65124. _mergeOption: function (newOpt, ecModel, createdBySelf, isInit) {
  65125. var MarkerModel = this.constructor;
  65126. var modelPropName = this.mainType + 'Model';
  65127. if (!createdBySelf) {
  65128. ecModel.eachSeries(function (seriesModel) {
  65129. var markerOpt = seriesModel.get(this.mainType, true);
  65130. var markerModel = seriesModel[modelPropName];
  65131. if (!markerOpt || !markerOpt.data) {
  65132. seriesModel[modelPropName] = null;
  65133. return;
  65134. }
  65135. if (!markerModel) {
  65136. if (isInit) {
  65137. // Default label emphasis `position` and `show`
  65138. fillLabel(markerOpt);
  65139. }
  65140. each$1(markerOpt.data, function (item) {
  65141. // FIXME Overwrite fillLabel method ?
  65142. if (item instanceof Array) {
  65143. fillLabel(item[0]);
  65144. fillLabel(item[1]);
  65145. } else {
  65146. fillLabel(item);
  65147. }
  65148. });
  65149. markerModel = new MarkerModel(markerOpt, this, ecModel);
  65150. extend(markerModel, {
  65151. mainType: this.mainType,
  65152. // Use the same series index and name
  65153. seriesIndex: seriesModel.seriesIndex,
  65154. name: seriesModel.name,
  65155. createdBySelf: true
  65156. });
  65157. markerModel.__hostSeries = seriesModel;
  65158. } else {
  65159. markerModel._mergeOption(markerOpt, ecModel, true);
  65160. }
  65161. seriesModel[modelPropName] = markerModel;
  65162. }, this);
  65163. }
  65164. },
  65165. formatTooltip: function (dataIndex) {
  65166. var data = this.getData();
  65167. var value = this.getRawValue(dataIndex);
  65168. var formattedValue = isArray(value) ? map(value, addCommas$1).join(', ') : addCommas$1(value);
  65169. var name = data.getName(dataIndex);
  65170. var html = encodeHTML$1(this.name);
  65171. if (value != null || name) {
  65172. html += '<br />';
  65173. }
  65174. if (name) {
  65175. html += encodeHTML$1(name);
  65176. if (value != null) {
  65177. html += ' : ';
  65178. }
  65179. }
  65180. if (value != null) {
  65181. html += encodeHTML$1(formattedValue);
  65182. }
  65183. return html;
  65184. },
  65185. getData: function () {
  65186. return this._data;
  65187. },
  65188. setData: function (data) {
  65189. this._data = data;
  65190. }
  65191. });
  65192. mixin(MarkerModel, dataFormatMixin);
  65193. /*
  65194. * Licensed to the Apache Software Foundation (ASF) under one
  65195. * or more contributor license agreements. See the NOTICE file
  65196. * distributed with this work for additional information
  65197. * regarding copyright ownership. The ASF licenses this file
  65198. * to you under the Apache License, Version 2.0 (the
  65199. * "License"); you may not use this file except in compliance
  65200. * with the License. You may obtain a copy of the License at
  65201. *
  65202. * http://www.apache.org/licenses/LICENSE-2.0
  65203. *
  65204. * Unless required by applicable law or agreed to in writing,
  65205. * software distributed under the License is distributed on an
  65206. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65207. * KIND, either express or implied. See the License for the
  65208. * specific language governing permissions and limitations
  65209. * under the License.
  65210. */
  65211. MarkerModel.extend({
  65212. type: 'markPoint',
  65213. defaultOption: {
  65214. zlevel: 0,
  65215. z: 5,
  65216. symbol: 'pin',
  65217. symbolSize: 50,
  65218. //symbolRotate: 0,
  65219. //symbolOffset: [0, 0]
  65220. tooltip: {
  65221. trigger: 'item'
  65222. },
  65223. label: {
  65224. show: true,
  65225. position: 'inside'
  65226. },
  65227. itemStyle: {
  65228. borderWidth: 2
  65229. },
  65230. emphasis: {
  65231. label: {
  65232. show: true
  65233. }
  65234. }
  65235. }
  65236. });
  65237. /*
  65238. * Licensed to the Apache Software Foundation (ASF) under one
  65239. * or more contributor license agreements. See the NOTICE file
  65240. * distributed with this work for additional information
  65241. * regarding copyright ownership. The ASF licenses this file
  65242. * to you under the Apache License, Version 2.0 (the
  65243. * "License"); you may not use this file except in compliance
  65244. * with the License. You may obtain a copy of the License at
  65245. *
  65246. * http://www.apache.org/licenses/LICENSE-2.0
  65247. *
  65248. * Unless required by applicable law or agreed to in writing,
  65249. * software distributed under the License is distributed on an
  65250. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65251. * KIND, either express or implied. See the License for the
  65252. * specific language governing permissions and limitations
  65253. * under the License.
  65254. */
  65255. var indexOf$1 = indexOf;
  65256. function hasXOrY(item) {
  65257. return !(isNaN(parseFloat(item.x)) && isNaN(parseFloat(item.y)));
  65258. }
  65259. function hasXAndY(item) {
  65260. return !isNaN(parseFloat(item.x)) && !isNaN(parseFloat(item.y));
  65261. } // Make it simple, do not visit all stacked value to count precision.
  65262. // function getPrecision(data, valueAxisDim, dataIndex) {
  65263. // var precision = -1;
  65264. // var stackedDim = data.mapDimension(valueAxisDim);
  65265. // do {
  65266. // precision = Math.max(
  65267. // numberUtil.getPrecision(data.get(stackedDim, dataIndex)),
  65268. // precision
  65269. // );
  65270. // var stackedOnSeries = data.getCalculationInfo('stackedOnSeries');
  65271. // if (stackedOnSeries) {
  65272. // var byValue = data.get(data.getCalculationInfo('stackedByDimension'), dataIndex);
  65273. // data = stackedOnSeries.getData();
  65274. // dataIndex = data.indexOf(data.getCalculationInfo('stackedByDimension'), byValue);
  65275. // stackedDim = data.getCalculationInfo('stackedDimension');
  65276. // }
  65277. // else {
  65278. // data = null;
  65279. // }
  65280. // } while (data);
  65281. // return precision;
  65282. // }
  65283. function markerTypeCalculatorWithExtent(mlType, data, otherDataDim, targetDataDim, otherCoordIndex, targetCoordIndex) {
  65284. var coordArr = [];
  65285. var stacked = isDimensionStacked(data, targetDataDim
  65286. /*, otherDataDim*/
  65287. );
  65288. var calcDataDim = stacked ? data.getCalculationInfo('stackResultDimension') : targetDataDim;
  65289. var value = numCalculate(data, calcDataDim, mlType);
  65290. var dataIndex = data.indicesOfNearest(calcDataDim, value)[0];
  65291. coordArr[otherCoordIndex] = data.get(otherDataDim, dataIndex);
  65292. coordArr[targetCoordIndex] = data.get(calcDataDim, dataIndex);
  65293. var coordArrValue = data.get(targetDataDim, dataIndex); // Make it simple, do not visit all stacked value to count precision.
  65294. var precision = getPrecision(data.get(targetDataDim, dataIndex));
  65295. precision = Math.min(precision, 20);
  65296. if (precision >= 0) {
  65297. coordArr[targetCoordIndex] = +coordArr[targetCoordIndex].toFixed(precision);
  65298. }
  65299. return [coordArr, coordArrValue];
  65300. }
  65301. var curry$5 = curry; // TODO Specified percent
  65302. var markerTypeCalculator = {
  65303. /**
  65304. * @method
  65305. * @param {module:echarts/data/List} data
  65306. * @param {string} baseAxisDim
  65307. * @param {string} valueAxisDim
  65308. */
  65309. min: curry$5(markerTypeCalculatorWithExtent, 'min'),
  65310. /**
  65311. * @method
  65312. * @param {module:echarts/data/List} data
  65313. * @param {string} baseAxisDim
  65314. * @param {string} valueAxisDim
  65315. */
  65316. max: curry$5(markerTypeCalculatorWithExtent, 'max'),
  65317. /**
  65318. * @method
  65319. * @param {module:echarts/data/List} data
  65320. * @param {string} baseAxisDim
  65321. * @param {string} valueAxisDim
  65322. */
  65323. average: curry$5(markerTypeCalculatorWithExtent, 'average')
  65324. };
  65325. /**
  65326. * Transform markPoint data item to format used in List by do the following
  65327. * 1. Calculate statistic like `max`, `min`, `average`
  65328. * 2. Convert `item.xAxis`, `item.yAxis` to `item.coord` array
  65329. * @param {module:echarts/model/Series} seriesModel
  65330. * @param {module:echarts/coord/*} [coordSys]
  65331. * @param {Object} item
  65332. * @return {Object}
  65333. */
  65334. function dataTransform(seriesModel, item) {
  65335. var data = seriesModel.getData();
  65336. var coordSys = seriesModel.coordinateSystem; // 1. If not specify the position with pixel directly
  65337. // 2. If `coord` is not a data array. Which uses `xAxis`,
  65338. // `yAxis` to specify the coord on each dimension
  65339. // parseFloat first because item.x and item.y can be percent string like '20%'
  65340. if (item && !hasXAndY(item) && !isArray(item.coord) && coordSys) {
  65341. var dims = coordSys.dimensions;
  65342. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel); // Clone the option
  65343. // Transform the properties xAxis, yAxis, radiusAxis, angleAxis, geoCoord to value
  65344. item = clone(item);
  65345. if (item.type && markerTypeCalculator[item.type] && axisInfo.baseAxis && axisInfo.valueAxis) {
  65346. var otherCoordIndex = indexOf$1(dims, axisInfo.baseAxis.dim);
  65347. var targetCoordIndex = indexOf$1(dims, axisInfo.valueAxis.dim);
  65348. var coordInfo = markerTypeCalculator[item.type](data, axisInfo.baseDataDim, axisInfo.valueDataDim, otherCoordIndex, targetCoordIndex);
  65349. item.coord = coordInfo[0]; // Force to use the value of calculated value.
  65350. // let item use the value without stack.
  65351. item.value = coordInfo[1];
  65352. } else {
  65353. // FIXME Only has one of xAxis and yAxis.
  65354. var coord = [item.xAxis != null ? item.xAxis : item.radiusAxis, item.yAxis != null ? item.yAxis : item.angleAxis]; // Each coord support max, min, average
  65355. for (var i = 0; i < 2; i++) {
  65356. if (markerTypeCalculator[coord[i]]) {
  65357. coord[i] = numCalculate(data, data.mapDimension(dims[i]), coord[i]);
  65358. }
  65359. }
  65360. item.coord = coord;
  65361. }
  65362. }
  65363. return item;
  65364. }
  65365. function getAxisInfo$1(item, data, coordSys, seriesModel) {
  65366. var ret = {};
  65367. if (item.valueIndex != null || item.valueDim != null) {
  65368. ret.valueDataDim = item.valueIndex != null ? data.getDimension(item.valueIndex) : item.valueDim;
  65369. ret.valueAxis = coordSys.getAxis(dataDimToCoordDim(seriesModel, ret.valueDataDim));
  65370. ret.baseAxis = coordSys.getOtherAxis(ret.valueAxis);
  65371. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  65372. } else {
  65373. ret.baseAxis = seriesModel.getBaseAxis();
  65374. ret.valueAxis = coordSys.getOtherAxis(ret.baseAxis);
  65375. ret.baseDataDim = data.mapDimension(ret.baseAxis.dim);
  65376. ret.valueDataDim = data.mapDimension(ret.valueAxis.dim);
  65377. }
  65378. return ret;
  65379. }
  65380. function dataDimToCoordDim(seriesModel, dataDim) {
  65381. var data = seriesModel.getData();
  65382. var dimensions = data.dimensions;
  65383. dataDim = data.getDimension(dataDim);
  65384. for (var i = 0; i < dimensions.length; i++) {
  65385. var dimItem = data.getDimensionInfo(dimensions[i]);
  65386. if (dimItem.name === dataDim) {
  65387. return dimItem.coordDim;
  65388. }
  65389. }
  65390. }
  65391. /**
  65392. * Filter data which is out of coordinateSystem range
  65393. * [dataFilter description]
  65394. * @param {module:echarts/coord/*} [coordSys]
  65395. * @param {Object} item
  65396. * @return {boolean}
  65397. */
  65398. function dataFilter$1(coordSys, item) {
  65399. // Alwalys return true if there is no coordSys
  65400. return coordSys && coordSys.containData && item.coord && !hasXOrY(item) ? coordSys.containData(item.coord) : true;
  65401. }
  65402. function dimValueGetter(item, dimName, dataIndex, dimIndex) {
  65403. // x, y, radius, angle
  65404. if (dimIndex < 2) {
  65405. return item.coord && item.coord[dimIndex];
  65406. }
  65407. return item.value;
  65408. }
  65409. function numCalculate(data, valueDataDim, type) {
  65410. if (type === 'average') {
  65411. var sum = 0;
  65412. var count = 0;
  65413. data.each(valueDataDim, function (val, idx) {
  65414. if (!isNaN(val)) {
  65415. sum += val;
  65416. count++;
  65417. }
  65418. });
  65419. return sum / count;
  65420. } else if (type === 'median') {
  65421. return data.getMedian(valueDataDim);
  65422. } else {
  65423. // max & min
  65424. return data.getDataExtent(valueDataDim, true)[type === 'max' ? 1 : 0];
  65425. }
  65426. }
  65427. /*
  65428. * Licensed to the Apache Software Foundation (ASF) under one
  65429. * or more contributor license agreements. See the NOTICE file
  65430. * distributed with this work for additional information
  65431. * regarding copyright ownership. The ASF licenses this file
  65432. * to you under the Apache License, Version 2.0 (the
  65433. * "License"); you may not use this file except in compliance
  65434. * with the License. You may obtain a copy of the License at
  65435. *
  65436. * http://www.apache.org/licenses/LICENSE-2.0
  65437. *
  65438. * Unless required by applicable law or agreed to in writing,
  65439. * software distributed under the License is distributed on an
  65440. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65441. * KIND, either express or implied. See the License for the
  65442. * specific language governing permissions and limitations
  65443. * under the License.
  65444. */
  65445. var MarkerView = extendComponentView({
  65446. type: 'marker',
  65447. init: function () {
  65448. /**
  65449. * Markline grouped by series
  65450. * @private
  65451. * @type {module:zrender/core/util.HashMap}
  65452. */
  65453. this.markerGroupMap = createHashMap();
  65454. },
  65455. render: function (markerModel, ecModel, api) {
  65456. var markerGroupMap = this.markerGroupMap;
  65457. markerGroupMap.each(function (item) {
  65458. item.__keep = false;
  65459. });
  65460. var markerModelKey = this.type + 'Model';
  65461. ecModel.eachSeries(function (seriesModel) {
  65462. var markerModel = seriesModel[markerModelKey];
  65463. markerModel && this.renderSeries(seriesModel, markerModel, ecModel, api);
  65464. }, this);
  65465. markerGroupMap.each(function (item) {
  65466. !item.__keep && this.group.remove(item.group);
  65467. }, this);
  65468. },
  65469. renderSeries: function () {}
  65470. });
  65471. /*
  65472. * Licensed to the Apache Software Foundation (ASF) under one
  65473. * or more contributor license agreements. See the NOTICE file
  65474. * distributed with this work for additional information
  65475. * regarding copyright ownership. The ASF licenses this file
  65476. * to you under the Apache License, Version 2.0 (the
  65477. * "License"); you may not use this file except in compliance
  65478. * with the License. You may obtain a copy of the License at
  65479. *
  65480. * http://www.apache.org/licenses/LICENSE-2.0
  65481. *
  65482. * Unless required by applicable law or agreed to in writing,
  65483. * software distributed under the License is distributed on an
  65484. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65485. * KIND, either express or implied. See the License for the
  65486. * specific language governing permissions and limitations
  65487. * under the License.
  65488. */
  65489. function updateMarkerLayout(mpData, seriesModel, api) {
  65490. var coordSys = seriesModel.coordinateSystem;
  65491. mpData.each(function (idx) {
  65492. var itemModel = mpData.getItemModel(idx);
  65493. var point;
  65494. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  65495. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  65496. if (!isNaN(xPx) && !isNaN(yPx)) {
  65497. point = [xPx, yPx];
  65498. } // Chart like bar may have there own marker positioning logic
  65499. else if (seriesModel.getMarkerPosition) {
  65500. // Use the getMarkerPoisition
  65501. point = seriesModel.getMarkerPosition(mpData.getValues(mpData.dimensions, idx));
  65502. } else if (coordSys) {
  65503. var x = mpData.get(coordSys.dimensions[0], idx);
  65504. var y = mpData.get(coordSys.dimensions[1], idx);
  65505. point = coordSys.dataToPoint([x, y]);
  65506. } // Use x, y if has any
  65507. if (!isNaN(xPx)) {
  65508. point[0] = xPx;
  65509. }
  65510. if (!isNaN(yPx)) {
  65511. point[1] = yPx;
  65512. }
  65513. mpData.setItemLayout(idx, point);
  65514. });
  65515. }
  65516. MarkerView.extend({
  65517. type: 'markPoint',
  65518. // updateLayout: function (markPointModel, ecModel, api) {
  65519. // ecModel.eachSeries(function (seriesModel) {
  65520. // var mpModel = seriesModel.markPointModel;
  65521. // if (mpModel) {
  65522. // updateMarkerLayout(mpModel.getData(), seriesModel, api);
  65523. // this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  65524. // }
  65525. // }, this);
  65526. // },
  65527. updateTransform: function (markPointModel, ecModel, api) {
  65528. ecModel.eachSeries(function (seriesModel) {
  65529. var mpModel = seriesModel.markPointModel;
  65530. if (mpModel) {
  65531. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  65532. this.markerGroupMap.get(seriesModel.id).updateLayout(mpModel);
  65533. }
  65534. }, this);
  65535. },
  65536. renderSeries: function (seriesModel, mpModel, ecModel, api) {
  65537. var coordSys = seriesModel.coordinateSystem;
  65538. var seriesId = seriesModel.id;
  65539. var seriesData = seriesModel.getData();
  65540. var symbolDrawMap = this.markerGroupMap;
  65541. var symbolDraw = symbolDrawMap.get(seriesId) || symbolDrawMap.set(seriesId, new SymbolDraw());
  65542. var mpData = createList$1(coordSys, seriesModel, mpModel); // FIXME
  65543. mpModel.setData(mpData);
  65544. updateMarkerLayout(mpModel.getData(), seriesModel, api);
  65545. mpData.each(function (idx) {
  65546. var itemModel = mpData.getItemModel(idx);
  65547. var symbol = itemModel.getShallow('symbol');
  65548. var symbolSize = itemModel.getShallow('symbolSize');
  65549. var isFnSymbol = isFunction$1(symbol);
  65550. var isFnSymbolSize = isFunction$1(symbolSize);
  65551. if (isFnSymbol || isFnSymbolSize) {
  65552. var rawIdx = mpModel.getRawValue(idx);
  65553. var dataParams = mpModel.getDataParams(idx);
  65554. if (isFnSymbol) {
  65555. symbol = symbol(rawIdx, dataParams);
  65556. }
  65557. if (isFnSymbolSize) {
  65558. // FIXME 这里不兼容 ECharts 2.x,2.x 貌似参数是整个数据?
  65559. symbolSize = symbolSize(rawIdx, dataParams);
  65560. }
  65561. }
  65562. mpData.setItemVisual(idx, {
  65563. symbol: symbol,
  65564. symbolSize: symbolSize,
  65565. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  65566. });
  65567. }); // TODO Text are wrong
  65568. symbolDraw.updateData(mpData);
  65569. this.group.add(symbolDraw.group); // Set host model for tooltip
  65570. // FIXME
  65571. mpData.eachItemGraphicEl(function (el) {
  65572. el.traverse(function (child) {
  65573. child.dataModel = mpModel;
  65574. });
  65575. });
  65576. symbolDraw.__keep = true;
  65577. symbolDraw.group.silent = mpModel.get('silent') || seriesModel.get('silent');
  65578. }
  65579. });
  65580. /**
  65581. * @inner
  65582. * @param {module:echarts/coord/*} [coordSys]
  65583. * @param {module:echarts/model/Series} seriesModel
  65584. * @param {module:echarts/model/Model} mpModel
  65585. */
  65586. function createList$1(coordSys, seriesModel, mpModel) {
  65587. var coordDimsInfos;
  65588. if (coordSys) {
  65589. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  65590. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  65591. return defaults({
  65592. name: coordDim
  65593. }, info);
  65594. });
  65595. } else {
  65596. coordDimsInfos = [{
  65597. name: 'value',
  65598. type: 'float'
  65599. }];
  65600. }
  65601. var mpData = new List(coordDimsInfos, mpModel);
  65602. var dataOpt = map(mpModel.get('data'), curry(dataTransform, seriesModel));
  65603. if (coordSys) {
  65604. dataOpt = filter(dataOpt, curry(dataFilter$1, coordSys));
  65605. }
  65606. mpData.initData(dataOpt, null, coordSys ? dimValueGetter : function (item) {
  65607. return item.value;
  65608. });
  65609. return mpData;
  65610. }
  65611. /*
  65612. * Licensed to the Apache Software Foundation (ASF) under one
  65613. * or more contributor license agreements. See the NOTICE file
  65614. * distributed with this work for additional information
  65615. * regarding copyright ownership. The ASF licenses this file
  65616. * to you under the Apache License, Version 2.0 (the
  65617. * "License"); you may not use this file except in compliance
  65618. * with the License. You may obtain a copy of the License at
  65619. *
  65620. * http://www.apache.org/licenses/LICENSE-2.0
  65621. *
  65622. * Unless required by applicable law or agreed to in writing,
  65623. * software distributed under the License is distributed on an
  65624. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65625. * KIND, either express or implied. See the License for the
  65626. * specific language governing permissions and limitations
  65627. * under the License.
  65628. */
  65629. // HINT Markpoint can't be used too much
  65630. registerPreprocessor(function (opt) {
  65631. // Make sure markPoint component is enabled
  65632. opt.markPoint = opt.markPoint || {};
  65633. });
  65634. /*
  65635. * Licensed to the Apache Software Foundation (ASF) under one
  65636. * or more contributor license agreements. See the NOTICE file
  65637. * distributed with this work for additional information
  65638. * regarding copyright ownership. The ASF licenses this file
  65639. * to you under the Apache License, Version 2.0 (the
  65640. * "License"); you may not use this file except in compliance
  65641. * with the License. You may obtain a copy of the License at
  65642. *
  65643. * http://www.apache.org/licenses/LICENSE-2.0
  65644. *
  65645. * Unless required by applicable law or agreed to in writing,
  65646. * software distributed under the License is distributed on an
  65647. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65648. * KIND, either express or implied. See the License for the
  65649. * specific language governing permissions and limitations
  65650. * under the License.
  65651. */
  65652. MarkerModel.extend({
  65653. type: 'markLine',
  65654. defaultOption: {
  65655. zlevel: 0,
  65656. z: 5,
  65657. symbol: ['circle', 'arrow'],
  65658. symbolSize: [8, 16],
  65659. //symbolRotate: 0,
  65660. precision: 2,
  65661. tooltip: {
  65662. trigger: 'item'
  65663. },
  65664. label: {
  65665. show: true,
  65666. position: 'end',
  65667. distance: 5
  65668. },
  65669. lineStyle: {
  65670. type: 'dashed'
  65671. },
  65672. emphasis: {
  65673. label: {
  65674. show: true
  65675. },
  65676. lineStyle: {
  65677. width: 3
  65678. }
  65679. },
  65680. animationEasing: 'linear'
  65681. }
  65682. });
  65683. /*
  65684. * Licensed to the Apache Software Foundation (ASF) under one
  65685. * or more contributor license agreements. See the NOTICE file
  65686. * distributed with this work for additional information
  65687. * regarding copyright ownership. The ASF licenses this file
  65688. * to you under the Apache License, Version 2.0 (the
  65689. * "License"); you may not use this file except in compliance
  65690. * with the License. You may obtain a copy of the License at
  65691. *
  65692. * http://www.apache.org/licenses/LICENSE-2.0
  65693. *
  65694. * Unless required by applicable law or agreed to in writing,
  65695. * software distributed under the License is distributed on an
  65696. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65697. * KIND, either express or implied. See the License for the
  65698. * specific language governing permissions and limitations
  65699. * under the License.
  65700. */
  65701. var markLineTransform = function (seriesModel, coordSys, mlModel, item) {
  65702. var data = seriesModel.getData(); // Special type markLine like 'min', 'max', 'average', 'median'
  65703. var mlType = item.type;
  65704. if (!isArray(item) && (mlType === 'min' || mlType === 'max' || mlType === 'average' || mlType === 'median' // In case
  65705. // data: [{
  65706. // yAxis: 10
  65707. // }]
  65708. || item.xAxis != null || item.yAxis != null)) {
  65709. var valueAxis;
  65710. var value;
  65711. if (item.yAxis != null || item.xAxis != null) {
  65712. valueAxis = coordSys.getAxis(item.yAxis != null ? 'y' : 'x');
  65713. value = retrieve(item.yAxis, item.xAxis);
  65714. } else {
  65715. var axisInfo = getAxisInfo$1(item, data, coordSys, seriesModel);
  65716. valueAxis = axisInfo.valueAxis;
  65717. var valueDataDim = getStackedDimension(data, axisInfo.valueDataDim);
  65718. value = numCalculate(data, valueDataDim, mlType);
  65719. }
  65720. var valueIndex = valueAxis.dim === 'x' ? 0 : 1;
  65721. var baseIndex = 1 - valueIndex;
  65722. var mlFrom = clone(item);
  65723. var mlTo = {};
  65724. mlFrom.type = null;
  65725. mlFrom.coord = [];
  65726. mlTo.coord = [];
  65727. mlFrom.coord[baseIndex] = -Infinity;
  65728. mlTo.coord[baseIndex] = Infinity;
  65729. var precision = mlModel.get('precision');
  65730. if (precision >= 0 && typeof value === 'number') {
  65731. value = +value.toFixed(Math.min(precision, 20));
  65732. }
  65733. mlFrom.coord[valueIndex] = mlTo.coord[valueIndex] = value;
  65734. item = [mlFrom, mlTo, {
  65735. // Extra option for tooltip and label
  65736. type: mlType,
  65737. valueIndex: item.valueIndex,
  65738. // Force to use the value of calculated value.
  65739. value: value
  65740. }];
  65741. }
  65742. item = [dataTransform(seriesModel, item[0]), dataTransform(seriesModel, item[1]), extend({}, item[2])]; // Avoid line data type is extended by from(to) data type
  65743. item[2].type = item[2].type || ''; // Merge from option and to option into line option
  65744. merge(item[2], item[0]);
  65745. merge(item[2], item[1]);
  65746. return item;
  65747. };
  65748. function isInifinity(val) {
  65749. return !isNaN(val) && !isFinite(val);
  65750. } // If a markLine has one dim
  65751. function ifMarkLineHasOnlyDim(dimIndex, fromCoord, toCoord, coordSys) {
  65752. var otherDimIndex = 1 - dimIndex;
  65753. var dimName = coordSys.dimensions[dimIndex];
  65754. return isInifinity(fromCoord[otherDimIndex]) && isInifinity(toCoord[otherDimIndex]) && fromCoord[dimIndex] === toCoord[dimIndex] && coordSys.getAxis(dimName).containData(fromCoord[dimIndex]);
  65755. }
  65756. function markLineFilter(coordSys, item) {
  65757. if (coordSys.type === 'cartesian2d') {
  65758. var fromCoord = item[0].coord;
  65759. var toCoord = item[1].coord; // In case
  65760. // {
  65761. // markLine: {
  65762. // data: [{ yAxis: 2 }]
  65763. // }
  65764. // }
  65765. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim(0, fromCoord, toCoord, coordSys))) {
  65766. return true;
  65767. }
  65768. }
  65769. return dataFilter$1(coordSys, item[0]) && dataFilter$1(coordSys, item[1]);
  65770. }
  65771. function updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api) {
  65772. var coordSys = seriesModel.coordinateSystem;
  65773. var itemModel = data.getItemModel(idx);
  65774. var point;
  65775. var xPx = parsePercent$1(itemModel.get('x'), api.getWidth());
  65776. var yPx = parsePercent$1(itemModel.get('y'), api.getHeight());
  65777. if (!isNaN(xPx) && !isNaN(yPx)) {
  65778. point = [xPx, yPx];
  65779. } else {
  65780. // Chart like bar may have there own marker positioning logic
  65781. if (seriesModel.getMarkerPosition) {
  65782. // Use the getMarkerPoisition
  65783. point = seriesModel.getMarkerPosition(data.getValues(data.dimensions, idx));
  65784. } else {
  65785. var dims = coordSys.dimensions;
  65786. var x = data.get(dims[0], idx);
  65787. var y = data.get(dims[1], idx);
  65788. point = coordSys.dataToPoint([x, y]);
  65789. } // Expand line to the edge of grid if value on one axis is Inifnity
  65790. // In case
  65791. // markLine: {
  65792. // data: [{
  65793. // yAxis: 2
  65794. // // or
  65795. // type: 'average'
  65796. // }]
  65797. // }
  65798. if (coordSys.type === 'cartesian2d') {
  65799. var xAxis = coordSys.getAxis('x');
  65800. var yAxis = coordSys.getAxis('y');
  65801. var dims = coordSys.dimensions;
  65802. if (isInifinity(data.get(dims[0], idx))) {
  65803. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[isFrom ? 0 : 1]);
  65804. } else if (isInifinity(data.get(dims[1], idx))) {
  65805. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[isFrom ? 0 : 1]);
  65806. }
  65807. } // Use x, y if has any
  65808. if (!isNaN(xPx)) {
  65809. point[0] = xPx;
  65810. }
  65811. if (!isNaN(yPx)) {
  65812. point[1] = yPx;
  65813. }
  65814. }
  65815. data.setItemLayout(idx, point);
  65816. }
  65817. MarkerView.extend({
  65818. type: 'markLine',
  65819. // updateLayout: function (markLineModel, ecModel, api) {
  65820. // ecModel.eachSeries(function (seriesModel) {
  65821. // var mlModel = seriesModel.markLineModel;
  65822. // if (mlModel) {
  65823. // var mlData = mlModel.getData();
  65824. // var fromData = mlModel.__from;
  65825. // var toData = mlModel.__to;
  65826. // // Update visual and layout of from symbol and to symbol
  65827. // fromData.each(function (idx) {
  65828. // updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  65829. // updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  65830. // });
  65831. // // Update layout of line
  65832. // mlData.each(function (idx) {
  65833. // mlData.setItemLayout(idx, [
  65834. // fromData.getItemLayout(idx),
  65835. // toData.getItemLayout(idx)
  65836. // ]);
  65837. // });
  65838. // this.markerGroupMap.get(seriesModel.id).updateLayout();
  65839. // }
  65840. // }, this);
  65841. // },
  65842. updateTransform: function (markLineModel, ecModel, api) {
  65843. ecModel.eachSeries(function (seriesModel) {
  65844. var mlModel = seriesModel.markLineModel;
  65845. if (mlModel) {
  65846. var mlData = mlModel.getData();
  65847. var fromData = mlModel.__from;
  65848. var toData = mlModel.__to; // Update visual and layout of from symbol and to symbol
  65849. fromData.each(function (idx) {
  65850. updateSingleMarkerEndLayout(fromData, idx, true, seriesModel, api);
  65851. updateSingleMarkerEndLayout(toData, idx, false, seriesModel, api);
  65852. }); // Update layout of line
  65853. mlData.each(function (idx) {
  65854. mlData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  65855. });
  65856. this.markerGroupMap.get(seriesModel.id).updateLayout();
  65857. }
  65858. }, this);
  65859. },
  65860. renderSeries: function (seriesModel, mlModel, ecModel, api) {
  65861. var coordSys = seriesModel.coordinateSystem;
  65862. var seriesId = seriesModel.id;
  65863. var seriesData = seriesModel.getData();
  65864. var lineDrawMap = this.markerGroupMap;
  65865. var lineDraw = lineDrawMap.get(seriesId) || lineDrawMap.set(seriesId, new LineDraw());
  65866. this.group.add(lineDraw.group);
  65867. var mlData = createList$2(coordSys, seriesModel, mlModel);
  65868. var fromData = mlData.from;
  65869. var toData = mlData.to;
  65870. var lineData = mlData.line;
  65871. mlModel.__from = fromData;
  65872. mlModel.__to = toData; // Line data for tooltip and formatter
  65873. mlModel.setData(lineData);
  65874. var symbolType = mlModel.get('symbol');
  65875. var symbolSize = mlModel.get('symbolSize');
  65876. if (!isArray(symbolType)) {
  65877. symbolType = [symbolType, symbolType];
  65878. }
  65879. if (typeof symbolSize === 'number') {
  65880. symbolSize = [symbolSize, symbolSize];
  65881. } // Update visual and layout of from symbol and to symbol
  65882. mlData.from.each(function (idx) {
  65883. updateDataVisualAndLayout(fromData, idx, true);
  65884. updateDataVisualAndLayout(toData, idx, false);
  65885. }); // Update visual and layout of line
  65886. lineData.each(function (idx) {
  65887. var lineColor = lineData.getItemModel(idx).get('lineStyle.color');
  65888. lineData.setItemVisual(idx, {
  65889. color: lineColor || fromData.getItemVisual(idx, 'color')
  65890. });
  65891. lineData.setItemLayout(idx, [fromData.getItemLayout(idx), toData.getItemLayout(idx)]);
  65892. lineData.setItemVisual(idx, {
  65893. 'fromSymbolSize': fromData.getItemVisual(idx, 'symbolSize'),
  65894. 'fromSymbol': fromData.getItemVisual(idx, 'symbol'),
  65895. 'toSymbolSize': toData.getItemVisual(idx, 'symbolSize'),
  65896. 'toSymbol': toData.getItemVisual(idx, 'symbol')
  65897. });
  65898. });
  65899. lineDraw.updateData(lineData); // Set host model for tooltip
  65900. // FIXME
  65901. mlData.line.eachItemGraphicEl(function (el, idx) {
  65902. el.traverse(function (child) {
  65903. child.dataModel = mlModel;
  65904. });
  65905. });
  65906. function updateDataVisualAndLayout(data, idx, isFrom) {
  65907. var itemModel = data.getItemModel(idx);
  65908. updateSingleMarkerEndLayout(data, idx, isFrom, seriesModel, api);
  65909. data.setItemVisual(idx, {
  65910. symbolSize: itemModel.get('symbolSize') || symbolSize[isFrom ? 0 : 1],
  65911. symbol: itemModel.get('symbol', true) || symbolType[isFrom ? 0 : 1],
  65912. color: itemModel.get('itemStyle.color') || seriesData.getVisual('color')
  65913. });
  65914. }
  65915. lineDraw.__keep = true;
  65916. lineDraw.group.silent = mlModel.get('silent') || seriesModel.get('silent');
  65917. }
  65918. });
  65919. /**
  65920. * @inner
  65921. * @param {module:echarts/coord/*} coordSys
  65922. * @param {module:echarts/model/Series} seriesModel
  65923. * @param {module:echarts/model/Model} mpModel
  65924. */
  65925. function createList$2(coordSys, seriesModel, mlModel) {
  65926. var coordDimsInfos;
  65927. if (coordSys) {
  65928. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  65929. var info = seriesModel.getData().getDimensionInfo(seriesModel.getData().mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  65930. return defaults({
  65931. name: coordDim
  65932. }, info);
  65933. });
  65934. } else {
  65935. coordDimsInfos = [{
  65936. name: 'value',
  65937. type: 'float'
  65938. }];
  65939. }
  65940. var fromData = new List(coordDimsInfos, mlModel);
  65941. var toData = new List(coordDimsInfos, mlModel); // No dimensions
  65942. var lineData = new List([], mlModel);
  65943. var optData = map(mlModel.get('data'), curry(markLineTransform, seriesModel, coordSys, mlModel));
  65944. if (coordSys) {
  65945. optData = filter(optData, curry(markLineFilter, coordSys));
  65946. }
  65947. var dimValueGetter$$1 = coordSys ? dimValueGetter : function (item) {
  65948. return item.value;
  65949. };
  65950. fromData.initData(map(optData, function (item) {
  65951. return item[0];
  65952. }), null, dimValueGetter$$1);
  65953. toData.initData(map(optData, function (item) {
  65954. return item[1];
  65955. }), null, dimValueGetter$$1);
  65956. lineData.initData(map(optData, function (item) {
  65957. return item[2];
  65958. }));
  65959. lineData.hasItemOption = true;
  65960. return {
  65961. from: fromData,
  65962. to: toData,
  65963. line: lineData
  65964. };
  65965. }
  65966. /*
  65967. * Licensed to the Apache Software Foundation (ASF) under one
  65968. * or more contributor license agreements. See the NOTICE file
  65969. * distributed with this work for additional information
  65970. * regarding copyright ownership. The ASF licenses this file
  65971. * to you under the Apache License, Version 2.0 (the
  65972. * "License"); you may not use this file except in compliance
  65973. * with the License. You may obtain a copy of the License at
  65974. *
  65975. * http://www.apache.org/licenses/LICENSE-2.0
  65976. *
  65977. * Unless required by applicable law or agreed to in writing,
  65978. * software distributed under the License is distributed on an
  65979. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  65980. * KIND, either express or implied. See the License for the
  65981. * specific language governing permissions and limitations
  65982. * under the License.
  65983. */
  65984. registerPreprocessor(function (opt) {
  65985. // Make sure markLine component is enabled
  65986. opt.markLine = opt.markLine || {};
  65987. });
  65988. /*
  65989. * Licensed to the Apache Software Foundation (ASF) under one
  65990. * or more contributor license agreements. See the NOTICE file
  65991. * distributed with this work for additional information
  65992. * regarding copyright ownership. The ASF licenses this file
  65993. * to you under the Apache License, Version 2.0 (the
  65994. * "License"); you may not use this file except in compliance
  65995. * with the License. You may obtain a copy of the License at
  65996. *
  65997. * http://www.apache.org/licenses/LICENSE-2.0
  65998. *
  65999. * Unless required by applicable law or agreed to in writing,
  66000. * software distributed under the License is distributed on an
  66001. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66002. * KIND, either express or implied. See the License for the
  66003. * specific language governing permissions and limitations
  66004. * under the License.
  66005. */
  66006. MarkerModel.extend({
  66007. type: 'markArea',
  66008. defaultOption: {
  66009. zlevel: 0,
  66010. // PENDING
  66011. z: 1,
  66012. tooltip: {
  66013. trigger: 'item'
  66014. },
  66015. // markArea should fixed on the coordinate system
  66016. animation: false,
  66017. label: {
  66018. show: true,
  66019. position: 'top'
  66020. },
  66021. itemStyle: {
  66022. // color and borderColor default to use color from series
  66023. // color: 'auto'
  66024. // borderColor: 'auto'
  66025. borderWidth: 0
  66026. },
  66027. emphasis: {
  66028. label: {
  66029. show: true,
  66030. position: 'top'
  66031. }
  66032. }
  66033. }
  66034. });
  66035. /*
  66036. * Licensed to the Apache Software Foundation (ASF) under one
  66037. * or more contributor license agreements. See the NOTICE file
  66038. * distributed with this work for additional information
  66039. * regarding copyright ownership. The ASF licenses this file
  66040. * to you under the Apache License, Version 2.0 (the
  66041. * "License"); you may not use this file except in compliance
  66042. * with the License. You may obtain a copy of the License at
  66043. *
  66044. * http://www.apache.org/licenses/LICENSE-2.0
  66045. *
  66046. * Unless required by applicable law or agreed to in writing,
  66047. * software distributed under the License is distributed on an
  66048. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66049. * KIND, either express or implied. See the License for the
  66050. * specific language governing permissions and limitations
  66051. * under the License.
  66052. */
  66053. // TODO Better on polar
  66054. var markAreaTransform = function (seriesModel, coordSys, maModel, item) {
  66055. var lt = dataTransform(seriesModel, item[0]);
  66056. var rb = dataTransform(seriesModel, item[1]);
  66057. var retrieve$$1 = retrieve; // FIXME make sure lt is less than rb
  66058. var ltCoord = lt.coord;
  66059. var rbCoord = rb.coord;
  66060. ltCoord[0] = retrieve$$1(ltCoord[0], -Infinity);
  66061. ltCoord[1] = retrieve$$1(ltCoord[1], -Infinity);
  66062. rbCoord[0] = retrieve$$1(rbCoord[0], Infinity);
  66063. rbCoord[1] = retrieve$$1(rbCoord[1], Infinity); // Merge option into one
  66064. var result = mergeAll([{}, lt, rb]);
  66065. result.coord = [lt.coord, rb.coord];
  66066. result.x0 = lt.x;
  66067. result.y0 = lt.y;
  66068. result.x1 = rb.x;
  66069. result.y1 = rb.y;
  66070. return result;
  66071. };
  66072. function isInifinity$1(val) {
  66073. return !isNaN(val) && !isFinite(val);
  66074. } // If a markArea has one dim
  66075. function ifMarkLineHasOnlyDim$1(dimIndex, fromCoord, toCoord, coordSys) {
  66076. var otherDimIndex = 1 - dimIndex;
  66077. return isInifinity$1(fromCoord[otherDimIndex]) && isInifinity$1(toCoord[otherDimIndex]);
  66078. }
  66079. function markAreaFilter(coordSys, item) {
  66080. var fromCoord = item.coord[0];
  66081. var toCoord = item.coord[1];
  66082. if (coordSys.type === 'cartesian2d') {
  66083. // In case
  66084. // {
  66085. // markArea: {
  66086. // data: [{ yAxis: 2 }]
  66087. // }
  66088. // }
  66089. if (fromCoord && toCoord && (ifMarkLineHasOnlyDim$1(1, fromCoord, toCoord, coordSys) || ifMarkLineHasOnlyDim$1(0, fromCoord, toCoord, coordSys))) {
  66090. return true;
  66091. }
  66092. }
  66093. return dataFilter$1(coordSys, {
  66094. coord: fromCoord,
  66095. x: item.x0,
  66096. y: item.y0
  66097. }) || dataFilter$1(coordSys, {
  66098. coord: toCoord,
  66099. x: item.x1,
  66100. y: item.y1
  66101. });
  66102. } // dims can be ['x0', 'y0'], ['x1', 'y1'], ['x0', 'y1'], ['x1', 'y0']
  66103. function getSingleMarkerEndPoint(data, idx, dims, seriesModel, api) {
  66104. var coordSys = seriesModel.coordinateSystem;
  66105. var itemModel = data.getItemModel(idx);
  66106. var point;
  66107. var xPx = parsePercent$1(itemModel.get(dims[0]), api.getWidth());
  66108. var yPx = parsePercent$1(itemModel.get(dims[1]), api.getHeight());
  66109. if (!isNaN(xPx) && !isNaN(yPx)) {
  66110. point = [xPx, yPx];
  66111. } else {
  66112. // Chart like bar may have there own marker positioning logic
  66113. if (seriesModel.getMarkerPosition) {
  66114. // Use the getMarkerPoisition
  66115. point = seriesModel.getMarkerPosition(data.getValues(dims, idx));
  66116. } else {
  66117. var x = data.get(dims[0], idx);
  66118. var y = data.get(dims[1], idx);
  66119. var pt = [x, y];
  66120. coordSys.clampData && coordSys.clampData(pt, pt);
  66121. point = coordSys.dataToPoint(pt, true);
  66122. }
  66123. if (coordSys.type === 'cartesian2d') {
  66124. var xAxis = coordSys.getAxis('x');
  66125. var yAxis = coordSys.getAxis('y');
  66126. var x = data.get(dims[0], idx);
  66127. var y = data.get(dims[1], idx);
  66128. if (isInifinity$1(x)) {
  66129. point[0] = xAxis.toGlobalCoord(xAxis.getExtent()[dims[0] === 'x0' ? 0 : 1]);
  66130. } else if (isInifinity$1(y)) {
  66131. point[1] = yAxis.toGlobalCoord(yAxis.getExtent()[dims[1] === 'y0' ? 0 : 1]);
  66132. }
  66133. } // Use x, y if has any
  66134. if (!isNaN(xPx)) {
  66135. point[0] = xPx;
  66136. }
  66137. if (!isNaN(yPx)) {
  66138. point[1] = yPx;
  66139. }
  66140. }
  66141. return point;
  66142. }
  66143. var dimPermutations = [['x0', 'y0'], ['x1', 'y0'], ['x1', 'y1'], ['x0', 'y1']];
  66144. MarkerView.extend({
  66145. type: 'markArea',
  66146. // updateLayout: function (markAreaModel, ecModel, api) {
  66147. // ecModel.eachSeries(function (seriesModel) {
  66148. // var maModel = seriesModel.markAreaModel;
  66149. // if (maModel) {
  66150. // var areaData = maModel.getData();
  66151. // areaData.each(function (idx) {
  66152. // var points = zrUtil.map(dimPermutations, function (dim) {
  66153. // return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  66154. // });
  66155. // // Layout
  66156. // areaData.setItemLayout(idx, points);
  66157. // var el = areaData.getItemGraphicEl(idx);
  66158. // el.setShape('points', points);
  66159. // });
  66160. // }
  66161. // }, this);
  66162. // },
  66163. updateTransform: function (markAreaModel, ecModel, api) {
  66164. ecModel.eachSeries(function (seriesModel) {
  66165. var maModel = seriesModel.markAreaModel;
  66166. if (maModel) {
  66167. var areaData = maModel.getData();
  66168. areaData.each(function (idx) {
  66169. var points = map(dimPermutations, function (dim) {
  66170. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  66171. }); // Layout
  66172. areaData.setItemLayout(idx, points);
  66173. var el = areaData.getItemGraphicEl(idx);
  66174. el.setShape('points', points);
  66175. });
  66176. }
  66177. }, this);
  66178. },
  66179. renderSeries: function (seriesModel, maModel, ecModel, api) {
  66180. var coordSys = seriesModel.coordinateSystem;
  66181. var seriesId = seriesModel.id;
  66182. var seriesData = seriesModel.getData();
  66183. var areaGroupMap = this.markerGroupMap;
  66184. var polygonGroup = areaGroupMap.get(seriesId) || areaGroupMap.set(seriesId, {
  66185. group: new Group()
  66186. });
  66187. this.group.add(polygonGroup.group);
  66188. polygonGroup.__keep = true;
  66189. var areaData = createList$3(coordSys, seriesModel, maModel); // Line data for tooltip and formatter
  66190. maModel.setData(areaData); // Update visual and layout of line
  66191. areaData.each(function (idx) {
  66192. // Layout
  66193. areaData.setItemLayout(idx, map(dimPermutations, function (dim) {
  66194. return getSingleMarkerEndPoint(areaData, idx, dim, seriesModel, api);
  66195. })); // Visual
  66196. areaData.setItemVisual(idx, {
  66197. color: seriesData.getVisual('color')
  66198. });
  66199. });
  66200. areaData.diff(polygonGroup.__data).add(function (idx) {
  66201. var polygon = new Polygon({
  66202. shape: {
  66203. points: areaData.getItemLayout(idx)
  66204. }
  66205. });
  66206. areaData.setItemGraphicEl(idx, polygon);
  66207. polygonGroup.group.add(polygon);
  66208. }).update(function (newIdx, oldIdx) {
  66209. var polygon = polygonGroup.__data.getItemGraphicEl(oldIdx);
  66210. updateProps(polygon, {
  66211. shape: {
  66212. points: areaData.getItemLayout(newIdx)
  66213. }
  66214. }, maModel, newIdx);
  66215. polygonGroup.group.add(polygon);
  66216. areaData.setItemGraphicEl(newIdx, polygon);
  66217. }).remove(function (idx) {
  66218. var polygon = polygonGroup.__data.getItemGraphicEl(idx);
  66219. polygonGroup.group.remove(polygon);
  66220. }).execute();
  66221. areaData.eachItemGraphicEl(function (polygon, idx) {
  66222. var itemModel = areaData.getItemModel(idx);
  66223. var labelModel = itemModel.getModel('label');
  66224. var labelHoverModel = itemModel.getModel('emphasis.label');
  66225. var color = areaData.getItemVisual(idx, 'color');
  66226. polygon.useStyle(defaults(itemModel.getModel('itemStyle').getItemStyle(), {
  66227. fill: modifyAlpha(color, 0.4),
  66228. stroke: color
  66229. }));
  66230. polygon.hoverStyle = itemModel.getModel('emphasis.itemStyle').getItemStyle();
  66231. setLabelStyle(polygon.style, polygon.hoverStyle, labelModel, labelHoverModel, {
  66232. labelFetcher: maModel,
  66233. labelDataIndex: idx,
  66234. defaultText: areaData.getName(idx) || '',
  66235. isRectText: true,
  66236. autoColor: color
  66237. });
  66238. setHoverStyle(polygon, {});
  66239. polygon.dataModel = maModel;
  66240. });
  66241. polygonGroup.__data = areaData;
  66242. polygonGroup.group.silent = maModel.get('silent') || seriesModel.get('silent');
  66243. }
  66244. });
  66245. /**
  66246. * @inner
  66247. * @param {module:echarts/coord/*} coordSys
  66248. * @param {module:echarts/model/Series} seriesModel
  66249. * @param {module:echarts/model/Model} mpModel
  66250. */
  66251. function createList$3(coordSys, seriesModel, maModel) {
  66252. var coordDimsInfos;
  66253. var areaData;
  66254. var dims = ['x0', 'y0', 'x1', 'y1'];
  66255. if (coordSys) {
  66256. coordDimsInfos = map(coordSys && coordSys.dimensions, function (coordDim) {
  66257. var data = seriesModel.getData();
  66258. var info = data.getDimensionInfo(data.mapDimension(coordDim)) || {}; // In map series data don't have lng and lat dimension. Fallback to same with coordSys
  66259. return defaults({
  66260. name: coordDim
  66261. }, info);
  66262. });
  66263. areaData = new List(map(dims, function (dim, idx) {
  66264. return {
  66265. name: dim,
  66266. type: coordDimsInfos[idx % 2].type
  66267. };
  66268. }), maModel);
  66269. } else {
  66270. coordDimsInfos = [{
  66271. name: 'value',
  66272. type: 'float'
  66273. }];
  66274. areaData = new List(coordDimsInfos, maModel);
  66275. }
  66276. var optData = map(maModel.get('data'), curry(markAreaTransform, seriesModel, coordSys, maModel));
  66277. if (coordSys) {
  66278. optData = filter(optData, curry(markAreaFilter, coordSys));
  66279. }
  66280. var dimValueGetter$$1 = coordSys ? function (item, dimName, dataIndex, dimIndex) {
  66281. return item.coord[Math.floor(dimIndex / 2)][dimIndex % 2];
  66282. } : function (item) {
  66283. return item.value;
  66284. };
  66285. areaData.initData(optData, null, dimValueGetter$$1);
  66286. areaData.hasItemOption = true;
  66287. return areaData;
  66288. }
  66289. /*
  66290. * Licensed to the Apache Software Foundation (ASF) under one
  66291. * or more contributor license agreements. See the NOTICE file
  66292. * distributed with this work for additional information
  66293. * regarding copyright ownership. The ASF licenses this file
  66294. * to you under the Apache License, Version 2.0 (the
  66295. * "License"); you may not use this file except in compliance
  66296. * with the License. You may obtain a copy of the License at
  66297. *
  66298. * http://www.apache.org/licenses/LICENSE-2.0
  66299. *
  66300. * Unless required by applicable law or agreed to in writing,
  66301. * software distributed under the License is distributed on an
  66302. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66303. * KIND, either express or implied. See the License for the
  66304. * specific language governing permissions and limitations
  66305. * under the License.
  66306. */
  66307. registerPreprocessor(function (opt) {
  66308. // Make sure markArea component is enabled
  66309. opt.markArea = opt.markArea || {};
  66310. });
  66311. /*
  66312. * Licensed to the Apache Software Foundation (ASF) under one
  66313. * or more contributor license agreements. See the NOTICE file
  66314. * distributed with this work for additional information
  66315. * regarding copyright ownership. The ASF licenses this file
  66316. * to you under the Apache License, Version 2.0 (the
  66317. * "License"); you may not use this file except in compliance
  66318. * with the License. You may obtain a copy of the License at
  66319. *
  66320. * http://www.apache.org/licenses/LICENSE-2.0
  66321. *
  66322. * Unless required by applicable law or agreed to in writing,
  66323. * software distributed under the License is distributed on an
  66324. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66325. * KIND, either express or implied. See the License for the
  66326. * specific language governing permissions and limitations
  66327. * under the License.
  66328. */
  66329. var preprocessor$1 = function (option) {
  66330. var timelineOpt = option && option.timeline;
  66331. if (!isArray(timelineOpt)) {
  66332. timelineOpt = timelineOpt ? [timelineOpt] : [];
  66333. }
  66334. each$1(timelineOpt, function (opt) {
  66335. if (!opt) {
  66336. return;
  66337. }
  66338. compatibleEC2(opt);
  66339. });
  66340. };
  66341. function compatibleEC2(opt) {
  66342. var type = opt.type;
  66343. var ec2Types = {
  66344. 'number': 'value',
  66345. 'time': 'time'
  66346. }; // Compatible with ec2
  66347. if (ec2Types[type]) {
  66348. opt.axisType = ec2Types[type];
  66349. delete opt.type;
  66350. }
  66351. transferItem(opt);
  66352. if (has$1(opt, 'controlPosition')) {
  66353. var controlStyle = opt.controlStyle || (opt.controlStyle = {});
  66354. if (!has$1(controlStyle, 'position')) {
  66355. controlStyle.position = opt.controlPosition;
  66356. }
  66357. if (controlStyle.position === 'none' && !has$1(controlStyle, 'show')) {
  66358. controlStyle.show = false;
  66359. delete controlStyle.position;
  66360. }
  66361. delete opt.controlPosition;
  66362. }
  66363. each$1(opt.data || [], function (dataItem) {
  66364. if (isObject$1(dataItem) && !isArray(dataItem)) {
  66365. if (!has$1(dataItem, 'value') && has$1(dataItem, 'name')) {
  66366. // In ec2, using name as value.
  66367. dataItem.value = dataItem.name;
  66368. }
  66369. transferItem(dataItem);
  66370. }
  66371. });
  66372. }
  66373. function transferItem(opt) {
  66374. var itemStyle = opt.itemStyle || (opt.itemStyle = {});
  66375. var itemStyleEmphasis = itemStyle.emphasis || (itemStyle.emphasis = {}); // Transfer label out
  66376. var label = opt.label || opt.label || {};
  66377. var labelNormal = label.normal || (label.normal = {});
  66378. var excludeLabelAttr = {
  66379. normal: 1,
  66380. emphasis: 1
  66381. };
  66382. each$1(label, function (value, name) {
  66383. if (!excludeLabelAttr[name] && !has$1(labelNormal, name)) {
  66384. labelNormal[name] = value;
  66385. }
  66386. });
  66387. if (itemStyleEmphasis.label && !has$1(label, 'emphasis')) {
  66388. label.emphasis = itemStyleEmphasis.label;
  66389. delete itemStyleEmphasis.label;
  66390. }
  66391. }
  66392. function has$1(obj, attr) {
  66393. return obj.hasOwnProperty(attr);
  66394. }
  66395. /*
  66396. * Licensed to the Apache Software Foundation (ASF) under one
  66397. * or more contributor license agreements. See the NOTICE file
  66398. * distributed with this work for additional information
  66399. * regarding copyright ownership. The ASF licenses this file
  66400. * to you under the Apache License, Version 2.0 (the
  66401. * "License"); you may not use this file except in compliance
  66402. * with the License. You may obtain a copy of the License at
  66403. *
  66404. * http://www.apache.org/licenses/LICENSE-2.0
  66405. *
  66406. * Unless required by applicable law or agreed to in writing,
  66407. * software distributed under the License is distributed on an
  66408. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66409. * KIND, either express or implied. See the License for the
  66410. * specific language governing permissions and limitations
  66411. * under the License.
  66412. */
  66413. ComponentModel.registerSubTypeDefaulter('timeline', function () {
  66414. // Only slider now.
  66415. return 'slider';
  66416. });
  66417. /*
  66418. * Licensed to the Apache Software Foundation (ASF) under one
  66419. * or more contributor license agreements. See the NOTICE file
  66420. * distributed with this work for additional information
  66421. * regarding copyright ownership. The ASF licenses this file
  66422. * to you under the Apache License, Version 2.0 (the
  66423. * "License"); you may not use this file except in compliance
  66424. * with the License. You may obtain a copy of the License at
  66425. *
  66426. * http://www.apache.org/licenses/LICENSE-2.0
  66427. *
  66428. * Unless required by applicable law or agreed to in writing,
  66429. * software distributed under the License is distributed on an
  66430. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66431. * KIND, either express or implied. See the License for the
  66432. * specific language governing permissions and limitations
  66433. * under the License.
  66434. */
  66435. registerAction({
  66436. type: 'timelineChange',
  66437. event: 'timelineChanged',
  66438. update: 'prepareAndUpdate'
  66439. }, function (payload, ecModel) {
  66440. var timelineModel = ecModel.getComponent('timeline');
  66441. if (timelineModel && payload.currentIndex != null) {
  66442. timelineModel.setCurrentIndex(payload.currentIndex);
  66443. if (!timelineModel.get('loop', true) && timelineModel.isIndexMax()) {
  66444. timelineModel.setPlayState(false);
  66445. }
  66446. } // Set normalized currentIndex to payload.
  66447. ecModel.resetOption('timeline');
  66448. return defaults({
  66449. currentIndex: timelineModel.option.currentIndex
  66450. }, payload);
  66451. });
  66452. registerAction({
  66453. type: 'timelinePlayChange',
  66454. event: 'timelinePlayChanged',
  66455. update: 'update'
  66456. }, function (payload, ecModel) {
  66457. var timelineModel = ecModel.getComponent('timeline');
  66458. if (timelineModel && payload.playState != null) {
  66459. timelineModel.setPlayState(payload.playState);
  66460. }
  66461. });
  66462. /*
  66463. * Licensed to the Apache Software Foundation (ASF) under one
  66464. * or more contributor license agreements. See the NOTICE file
  66465. * distributed with this work for additional information
  66466. * regarding copyright ownership. The ASF licenses this file
  66467. * to you under the Apache License, Version 2.0 (the
  66468. * "License"); you may not use this file except in compliance
  66469. * with the License. You may obtain a copy of the License at
  66470. *
  66471. * http://www.apache.org/licenses/LICENSE-2.0
  66472. *
  66473. * Unless required by applicable law or agreed to in writing,
  66474. * software distributed under the License is distributed on an
  66475. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66476. * KIND, either express or implied. See the License for the
  66477. * specific language governing permissions and limitations
  66478. * under the License.
  66479. */
  66480. var TimelineModel = ComponentModel.extend({
  66481. type: 'timeline',
  66482. layoutMode: 'box',
  66483. /**
  66484. * @protected
  66485. */
  66486. defaultOption: {
  66487. zlevel: 0,
  66488. // 一级层叠
  66489. z: 4,
  66490. // 二级层叠
  66491. show: true,
  66492. axisType: 'time',
  66493. // 模式是时间类型,支持 value, category
  66494. realtime: true,
  66495. left: '20%',
  66496. top: null,
  66497. right: '20%',
  66498. bottom: 0,
  66499. width: null,
  66500. height: 40,
  66501. padding: 5,
  66502. controlPosition: 'left',
  66503. // 'left' 'right' 'top' 'bottom' 'none'
  66504. autoPlay: false,
  66505. rewind: false,
  66506. // 反向播放
  66507. loop: true,
  66508. playInterval: 2000,
  66509. // 播放时间间隔,单位ms
  66510. currentIndex: 0,
  66511. itemStyle: {},
  66512. label: {
  66513. color: '#000'
  66514. },
  66515. data: []
  66516. },
  66517. /**
  66518. * @override
  66519. */
  66520. init: function (option, parentModel, ecModel) {
  66521. /**
  66522. * @private
  66523. * @type {module:echarts/data/List}
  66524. */
  66525. this._data;
  66526. /**
  66527. * @private
  66528. * @type {Array.<string>}
  66529. */
  66530. this._names;
  66531. this.mergeDefaultAndTheme(option, ecModel);
  66532. this._initData();
  66533. },
  66534. /**
  66535. * @override
  66536. */
  66537. mergeOption: function (option) {
  66538. TimelineModel.superApply(this, 'mergeOption', arguments);
  66539. this._initData();
  66540. },
  66541. /**
  66542. * @param {number} [currentIndex]
  66543. */
  66544. setCurrentIndex: function (currentIndex) {
  66545. if (currentIndex == null) {
  66546. currentIndex = this.option.currentIndex;
  66547. }
  66548. var count = this._data.count();
  66549. if (this.option.loop) {
  66550. currentIndex = (currentIndex % count + count) % count;
  66551. } else {
  66552. currentIndex >= count && (currentIndex = count - 1);
  66553. currentIndex < 0 && (currentIndex = 0);
  66554. }
  66555. this.option.currentIndex = currentIndex;
  66556. },
  66557. /**
  66558. * @return {number} currentIndex
  66559. */
  66560. getCurrentIndex: function () {
  66561. return this.option.currentIndex;
  66562. },
  66563. /**
  66564. * @return {boolean}
  66565. */
  66566. isIndexMax: function () {
  66567. return this.getCurrentIndex() >= this._data.count() - 1;
  66568. },
  66569. /**
  66570. * @param {boolean} state true: play, false: stop
  66571. */
  66572. setPlayState: function (state) {
  66573. this.option.autoPlay = !!state;
  66574. },
  66575. /**
  66576. * @return {boolean} true: play, false: stop
  66577. */
  66578. getPlayState: function () {
  66579. return !!this.option.autoPlay;
  66580. },
  66581. /**
  66582. * @private
  66583. */
  66584. _initData: function () {
  66585. var thisOption = this.option;
  66586. var dataArr = thisOption.data || [];
  66587. var axisType = thisOption.axisType;
  66588. var names = this._names = [];
  66589. if (axisType === 'category') {
  66590. var idxArr = [];
  66591. each$1(dataArr, function (item, index) {
  66592. var value = getDataItemValue(item);
  66593. var newItem;
  66594. if (isObject$1(item)) {
  66595. newItem = clone(item);
  66596. newItem.value = index;
  66597. } else {
  66598. newItem = index;
  66599. }
  66600. idxArr.push(newItem);
  66601. if (!isString(value) && (value == null || isNaN(value))) {
  66602. value = '';
  66603. }
  66604. names.push(value + '');
  66605. });
  66606. dataArr = idxArr;
  66607. }
  66608. var dimType = {
  66609. category: 'ordinal',
  66610. time: 'time'
  66611. }[axisType] || 'number';
  66612. var data = this._data = new List([{
  66613. name: 'value',
  66614. type: dimType
  66615. }], this);
  66616. data.initData(dataArr, names);
  66617. },
  66618. getData: function () {
  66619. return this._data;
  66620. },
  66621. /**
  66622. * @public
  66623. * @return {Array.<string>} categoreis
  66624. */
  66625. getCategories: function () {
  66626. if (this.get('axisType') === 'category') {
  66627. return this._names.slice();
  66628. }
  66629. }
  66630. });
  66631. /*
  66632. * Licensed to the Apache Software Foundation (ASF) under one
  66633. * or more contributor license agreements. See the NOTICE file
  66634. * distributed with this work for additional information
  66635. * regarding copyright ownership. The ASF licenses this file
  66636. * to you under the Apache License, Version 2.0 (the
  66637. * "License"); you may not use this file except in compliance
  66638. * with the License. You may obtain a copy of the License at
  66639. *
  66640. * http://www.apache.org/licenses/LICENSE-2.0
  66641. *
  66642. * Unless required by applicable law or agreed to in writing,
  66643. * software distributed under the License is distributed on an
  66644. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66645. * KIND, either express or implied. See the License for the
  66646. * specific language governing permissions and limitations
  66647. * under the License.
  66648. */
  66649. var SliderTimelineModel = TimelineModel.extend({
  66650. type: 'timeline.slider',
  66651. /**
  66652. * @protected
  66653. */
  66654. defaultOption: {
  66655. backgroundColor: 'rgba(0,0,0,0)',
  66656. // 时间轴背景颜色
  66657. borderColor: '#ccc',
  66658. // 时间轴边框颜色
  66659. borderWidth: 0,
  66660. // 时间轴边框线宽,单位px,默认为0(无边框)
  66661. orient: 'horizontal',
  66662. // 'vertical'
  66663. inverse: false,
  66664. tooltip: {
  66665. // boolean or Object
  66666. trigger: 'item' // data item may also have tootip attr.
  66667. },
  66668. symbol: 'emptyCircle',
  66669. symbolSize: 10,
  66670. lineStyle: {
  66671. show: true,
  66672. width: 2,
  66673. color: '#304654'
  66674. },
  66675. label: {
  66676. // 文本标签
  66677. position: 'auto',
  66678. // auto left right top bottom
  66679. // When using number, label position is not
  66680. // restricted by viewRect.
  66681. // positive: right/bottom, negative: left/top
  66682. show: true,
  66683. interval: 'auto',
  66684. rotate: 0,
  66685. // formatter: null,
  66686. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  66687. color: '#304654'
  66688. },
  66689. itemStyle: {
  66690. color: '#304654',
  66691. borderWidth: 1
  66692. },
  66693. checkpointStyle: {
  66694. symbol: 'circle',
  66695. symbolSize: 13,
  66696. color: '#c23531',
  66697. borderWidth: 5,
  66698. borderColor: 'rgba(194,53,49, 0.5)',
  66699. animation: true,
  66700. animationDuration: 300,
  66701. animationEasing: 'quinticInOut'
  66702. },
  66703. controlStyle: {
  66704. show: true,
  66705. showPlayBtn: true,
  66706. showPrevBtn: true,
  66707. showNextBtn: true,
  66708. itemSize: 22,
  66709. itemGap: 12,
  66710. position: 'left',
  66711. // 'left' 'right' 'top' 'bottom'
  66712. 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',
  66713. // jshint ignore:line
  66714. 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',
  66715. // jshint ignore:line
  66716. 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',
  66717. // jshint ignore:line
  66718. 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',
  66719. // jshint ignore:line
  66720. color: '#304654',
  66721. borderColor: '#304654',
  66722. borderWidth: 1
  66723. },
  66724. emphasis: {
  66725. label: {
  66726. show: true,
  66727. // 其余属性默认使用全局文本样式,详见TEXTSTYLE
  66728. color: '#c23531'
  66729. },
  66730. itemStyle: {
  66731. color: '#c23531'
  66732. },
  66733. controlStyle: {
  66734. color: '#c23531',
  66735. borderColor: '#c23531',
  66736. borderWidth: 2
  66737. }
  66738. },
  66739. data: []
  66740. }
  66741. });
  66742. mixin(SliderTimelineModel, dataFormatMixin);
  66743. /*
  66744. * Licensed to the Apache Software Foundation (ASF) under one
  66745. * or more contributor license agreements. See the NOTICE file
  66746. * distributed with this work for additional information
  66747. * regarding copyright ownership. The ASF licenses this file
  66748. * to you under the Apache License, Version 2.0 (the
  66749. * "License"); you may not use this file except in compliance
  66750. * with the License. You may obtain a copy of the License at
  66751. *
  66752. * http://www.apache.org/licenses/LICENSE-2.0
  66753. *
  66754. * Unless required by applicable law or agreed to in writing,
  66755. * software distributed under the License is distributed on an
  66756. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66757. * KIND, either express or implied. See the License for the
  66758. * specific language governing permissions and limitations
  66759. * under the License.
  66760. */
  66761. var TimelineView = Component$1.extend({
  66762. type: 'timeline'
  66763. });
  66764. /*
  66765. * Licensed to the Apache Software Foundation (ASF) under one
  66766. * or more contributor license agreements. See the NOTICE file
  66767. * distributed with this work for additional information
  66768. * regarding copyright ownership. The ASF licenses this file
  66769. * to you under the Apache License, Version 2.0 (the
  66770. * "License"); you may not use this file except in compliance
  66771. * with the License. You may obtain a copy of the License at
  66772. *
  66773. * http://www.apache.org/licenses/LICENSE-2.0
  66774. *
  66775. * Unless required by applicable law or agreed to in writing,
  66776. * software distributed under the License is distributed on an
  66777. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66778. * KIND, either express or implied. See the License for the
  66779. * specific language governing permissions and limitations
  66780. * under the License.
  66781. */
  66782. /**
  66783. * Extend axis 2d
  66784. * @constructor module:echarts/coord/cartesian/Axis2D
  66785. * @extends {module:echarts/coord/cartesian/Axis}
  66786. * @param {string} dim
  66787. * @param {*} scale
  66788. * @param {Array.<number>} coordExtent
  66789. * @param {string} axisType
  66790. * @param {string} position
  66791. */
  66792. var TimelineAxis = function (dim, scale, coordExtent, axisType) {
  66793. Axis.call(this, dim, scale, coordExtent);
  66794. /**
  66795. * Axis type
  66796. * - 'category'
  66797. * - 'value'
  66798. * - 'time'
  66799. * - 'log'
  66800. * @type {string}
  66801. */
  66802. this.type = axisType || 'value';
  66803. /**
  66804. * Axis model
  66805. * @param {module:echarts/component/TimelineModel}
  66806. */
  66807. this.model = null;
  66808. };
  66809. TimelineAxis.prototype = {
  66810. constructor: TimelineAxis,
  66811. /**
  66812. * @override
  66813. */
  66814. getLabelModel: function () {
  66815. return this.model.getModel('label');
  66816. },
  66817. /**
  66818. * @override
  66819. */
  66820. isHorizontal: function () {
  66821. return this.model.get('orient') === 'horizontal';
  66822. }
  66823. };
  66824. inherits(TimelineAxis, Axis);
  66825. /*
  66826. * Licensed to the Apache Software Foundation (ASF) under one
  66827. * or more contributor license agreements. See the NOTICE file
  66828. * distributed with this work for additional information
  66829. * regarding copyright ownership. The ASF licenses this file
  66830. * to you under the Apache License, Version 2.0 (the
  66831. * "License"); you may not use this file except in compliance
  66832. * with the License. You may obtain a copy of the License at
  66833. *
  66834. * http://www.apache.org/licenses/LICENSE-2.0
  66835. *
  66836. * Unless required by applicable law or agreed to in writing,
  66837. * software distributed under the License is distributed on an
  66838. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  66839. * KIND, either express or implied. See the License for the
  66840. * specific language governing permissions and limitations
  66841. * under the License.
  66842. */
  66843. var bind$4 = bind;
  66844. var each$19 = each$1;
  66845. var PI$5 = Math.PI;
  66846. TimelineView.extend({
  66847. type: 'timeline.slider',
  66848. init: function (ecModel, api) {
  66849. this.api = api;
  66850. /**
  66851. * @private
  66852. * @type {module:echarts/component/timeline/TimelineAxis}
  66853. */
  66854. this._axis;
  66855. /**
  66856. * @private
  66857. * @type {module:zrender/core/BoundingRect}
  66858. */
  66859. this._viewRect;
  66860. /**
  66861. * @type {number}
  66862. */
  66863. this._timer;
  66864. /**
  66865. * @type {module:zrender/Element}
  66866. */
  66867. this._currentPointer;
  66868. /**
  66869. * @type {module:zrender/container/Group}
  66870. */
  66871. this._mainGroup;
  66872. /**
  66873. * @type {module:zrender/container/Group}
  66874. */
  66875. this._labelGroup;
  66876. },
  66877. /**
  66878. * @override
  66879. */
  66880. render: function (timelineModel, ecModel, api, payload) {
  66881. this.model = timelineModel;
  66882. this.api = api;
  66883. this.ecModel = ecModel;
  66884. this.group.removeAll();
  66885. if (timelineModel.get('show', true)) {
  66886. var layoutInfo = this._layout(timelineModel, api);
  66887. var mainGroup = this._createGroup('mainGroup');
  66888. var labelGroup = this._createGroup('labelGroup');
  66889. /**
  66890. * @private
  66891. * @type {module:echarts/component/timeline/TimelineAxis}
  66892. */
  66893. var axis = this._axis = this._createAxis(layoutInfo, timelineModel);
  66894. timelineModel.formatTooltip = function (dataIndex) {
  66895. return encodeHTML(axis.scale.getLabel(dataIndex));
  66896. };
  66897. each$19(['AxisLine', 'AxisTick', 'Control', 'CurrentPointer'], function (name) {
  66898. this['_render' + name](layoutInfo, mainGroup, axis, timelineModel);
  66899. }, this);
  66900. this._renderAxisLabel(layoutInfo, labelGroup, axis, timelineModel);
  66901. this._position(layoutInfo, timelineModel);
  66902. }
  66903. this._doPlayStop();
  66904. },
  66905. /**
  66906. * @override
  66907. */
  66908. remove: function () {
  66909. this._clearTimer();
  66910. this.group.removeAll();
  66911. },
  66912. /**
  66913. * @override
  66914. */
  66915. dispose: function () {
  66916. this._clearTimer();
  66917. },
  66918. _layout: function (timelineModel, api) {
  66919. var labelPosOpt = timelineModel.get('label.position');
  66920. var orient = timelineModel.get('orient');
  66921. var viewRect = getViewRect$5(timelineModel, api); // Auto label offset.
  66922. if (labelPosOpt == null || labelPosOpt === 'auto') {
  66923. labelPosOpt = orient === 'horizontal' ? viewRect.y + viewRect.height / 2 < api.getHeight() / 2 ? '-' : '+' : viewRect.x + viewRect.width / 2 < api.getWidth() / 2 ? '+' : '-';
  66924. } else if (isNaN(labelPosOpt)) {
  66925. labelPosOpt = {
  66926. horizontal: {
  66927. top: '-',
  66928. bottom: '+'
  66929. },
  66930. vertical: {
  66931. left: '-',
  66932. right: '+'
  66933. }
  66934. }[orient][labelPosOpt];
  66935. }
  66936. var labelAlignMap = {
  66937. horizontal: 'center',
  66938. vertical: labelPosOpt >= 0 || labelPosOpt === '+' ? 'left' : 'right'
  66939. };
  66940. var labelBaselineMap = {
  66941. horizontal: labelPosOpt >= 0 || labelPosOpt === '+' ? 'top' : 'bottom',
  66942. vertical: 'middle'
  66943. };
  66944. var rotationMap = {
  66945. horizontal: 0,
  66946. vertical: PI$5 / 2
  66947. }; // Position
  66948. var mainLength = orient === 'vertical' ? viewRect.height : viewRect.width;
  66949. var controlModel = timelineModel.getModel('controlStyle');
  66950. var showControl = controlModel.get('show', true);
  66951. var controlSize = showControl ? controlModel.get('itemSize') : 0;
  66952. var controlGap = showControl ? controlModel.get('itemGap') : 0;
  66953. var sizePlusGap = controlSize + controlGap; // Special label rotate.
  66954. var labelRotation = timelineModel.get('label.rotate') || 0;
  66955. labelRotation = labelRotation * PI$5 / 180; // To radian.
  66956. var playPosition;
  66957. var prevBtnPosition;
  66958. var nextBtnPosition;
  66959. var axisExtent;
  66960. var controlPosition = controlModel.get('position', true);
  66961. var showPlayBtn = showControl && controlModel.get('showPlayBtn', true);
  66962. var showPrevBtn = showControl && controlModel.get('showPrevBtn', true);
  66963. var showNextBtn = showControl && controlModel.get('showNextBtn', true);
  66964. var xLeft = 0;
  66965. var xRight = mainLength; // position[0] means left, position[1] means middle.
  66966. if (controlPosition === 'left' || controlPosition === 'bottom') {
  66967. showPlayBtn && (playPosition = [0, 0], xLeft += sizePlusGap);
  66968. showPrevBtn && (prevBtnPosition = [xLeft, 0], xLeft += sizePlusGap);
  66969. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  66970. } else {
  66971. // 'top' 'right'
  66972. showPlayBtn && (playPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  66973. showPrevBtn && (prevBtnPosition = [0, 0], xLeft += sizePlusGap);
  66974. showNextBtn && (nextBtnPosition = [xRight - controlSize, 0], xRight -= sizePlusGap);
  66975. }
  66976. axisExtent = [xLeft, xRight];
  66977. if (timelineModel.get('inverse')) {
  66978. axisExtent.reverse();
  66979. }
  66980. return {
  66981. viewRect: viewRect,
  66982. mainLength: mainLength,
  66983. orient: orient,
  66984. rotation: rotationMap[orient],
  66985. labelRotation: labelRotation,
  66986. labelPosOpt: labelPosOpt,
  66987. labelAlign: timelineModel.get('label.align') || labelAlignMap[orient],
  66988. labelBaseline: timelineModel.get('label.verticalAlign') || timelineModel.get('label.baseline') || labelBaselineMap[orient],
  66989. // Based on mainGroup.
  66990. playPosition: playPosition,
  66991. prevBtnPosition: prevBtnPosition,
  66992. nextBtnPosition: nextBtnPosition,
  66993. axisExtent: axisExtent,
  66994. controlSize: controlSize,
  66995. controlGap: controlGap
  66996. };
  66997. },
  66998. _position: function (layoutInfo, timelineModel) {
  66999. // Position is be called finally, because bounding rect is needed for
  67000. // adapt content to fill viewRect (auto adapt offset).
  67001. // Timeline may be not all in the viewRect when 'offset' is specified
  67002. // as a number, because it is more appropriate that label aligns at
  67003. // 'offset' but not the other edge defined by viewRect.
  67004. var mainGroup = this._mainGroup;
  67005. var labelGroup = this._labelGroup;
  67006. var viewRect = layoutInfo.viewRect;
  67007. if (layoutInfo.orient === 'vertical') {
  67008. // transform to horizontal, inverse rotate by left-top point.
  67009. var m = create$1();
  67010. var rotateOriginX = viewRect.x;
  67011. var rotateOriginY = viewRect.y + viewRect.height;
  67012. translate(m, m, [-rotateOriginX, -rotateOriginY]);
  67013. rotate(m, m, -PI$5 / 2);
  67014. translate(m, m, [rotateOriginX, rotateOriginY]);
  67015. viewRect = viewRect.clone();
  67016. viewRect.applyTransform(m);
  67017. }
  67018. var viewBound = getBound(viewRect);
  67019. var mainBound = getBound(mainGroup.getBoundingRect());
  67020. var labelBound = getBound(labelGroup.getBoundingRect());
  67021. var mainPosition = mainGroup.position;
  67022. var labelsPosition = labelGroup.position;
  67023. labelsPosition[0] = mainPosition[0] = viewBound[0][0];
  67024. var labelPosOpt = layoutInfo.labelPosOpt;
  67025. if (isNaN(labelPosOpt)) {
  67026. // '+' or '-'
  67027. var mainBoundIdx = labelPosOpt === '+' ? 0 : 1;
  67028. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  67029. toBound(labelsPosition, labelBound, viewBound, 1, 1 - mainBoundIdx);
  67030. } else {
  67031. var mainBoundIdx = labelPosOpt >= 0 ? 0 : 1;
  67032. toBound(mainPosition, mainBound, viewBound, 1, mainBoundIdx);
  67033. labelsPosition[1] = mainPosition[1] + labelPosOpt;
  67034. }
  67035. mainGroup.attr('position', mainPosition);
  67036. labelGroup.attr('position', labelsPosition);
  67037. mainGroup.rotation = labelGroup.rotation = layoutInfo.rotation;
  67038. setOrigin(mainGroup);
  67039. setOrigin(labelGroup);
  67040. function setOrigin(targetGroup) {
  67041. var pos = targetGroup.position;
  67042. targetGroup.origin = [viewBound[0][0] - pos[0], viewBound[1][0] - pos[1]];
  67043. }
  67044. function getBound(rect) {
  67045. // [[xmin, xmax], [ymin, ymax]]
  67046. return [[rect.x, rect.x + rect.width], [rect.y, rect.y + rect.height]];
  67047. }
  67048. function toBound(fromPos, from, to, dimIdx, boundIdx) {
  67049. fromPos[dimIdx] += to[dimIdx][boundIdx] - from[dimIdx][boundIdx];
  67050. }
  67051. },
  67052. _createAxis: function (layoutInfo, timelineModel) {
  67053. var data = timelineModel.getData();
  67054. var axisType = timelineModel.get('axisType');
  67055. var scale = createScaleByModel(timelineModel, axisType); // Customize scale. The `tickValue` is `dataIndex`.
  67056. scale.getTicks = function () {
  67057. return data.mapArray(['value'], function (value) {
  67058. return value;
  67059. });
  67060. };
  67061. var dataExtent = data.getDataExtent('value');
  67062. scale.setExtent(dataExtent[0], dataExtent[1]);
  67063. scale.niceTicks();
  67064. var axis = new TimelineAxis('value', scale, layoutInfo.axisExtent, axisType);
  67065. axis.model = timelineModel;
  67066. return axis;
  67067. },
  67068. _createGroup: function (name) {
  67069. var newGroup = this['_' + name] = new Group();
  67070. this.group.add(newGroup);
  67071. return newGroup;
  67072. },
  67073. _renderAxisLine: function (layoutInfo, group, axis, timelineModel) {
  67074. var axisExtent = axis.getExtent();
  67075. if (!timelineModel.get('lineStyle.show')) {
  67076. return;
  67077. }
  67078. group.add(new Line({
  67079. shape: {
  67080. x1: axisExtent[0],
  67081. y1: 0,
  67082. x2: axisExtent[1],
  67083. y2: 0
  67084. },
  67085. style: extend({
  67086. lineCap: 'round'
  67087. }, timelineModel.getModel('lineStyle').getLineStyle()),
  67088. silent: true,
  67089. z2: 1
  67090. }));
  67091. },
  67092. /**
  67093. * @private
  67094. */
  67095. _renderAxisTick: function (layoutInfo, group, axis, timelineModel) {
  67096. var data = timelineModel.getData(); // Show all ticks, despite ignoring strategy.
  67097. var ticks = axis.scale.getTicks(); // The value is dataIndex, see the costomized scale.
  67098. each$19(ticks, function (value) {
  67099. var tickCoord = axis.dataToCoord(value);
  67100. var itemModel = data.getItemModel(value);
  67101. var itemStyleModel = itemModel.getModel('itemStyle');
  67102. var hoverStyleModel = itemModel.getModel('emphasis.itemStyle');
  67103. var symbolOpt = {
  67104. position: [tickCoord, 0],
  67105. onclick: bind$4(this._changeTimeline, this, value)
  67106. };
  67107. var el = giveSymbol(itemModel, itemStyleModel, group, symbolOpt);
  67108. setHoverStyle(el, hoverStyleModel.getItemStyle());
  67109. if (itemModel.get('tooltip')) {
  67110. el.dataIndex = value;
  67111. el.dataModel = timelineModel;
  67112. } else {
  67113. el.dataIndex = el.dataModel = null;
  67114. }
  67115. }, this);
  67116. },
  67117. /**
  67118. * @private
  67119. */
  67120. _renderAxisLabel: function (layoutInfo, group, axis, timelineModel) {
  67121. var labelModel = axis.getLabelModel();
  67122. if (!labelModel.get('show')) {
  67123. return;
  67124. }
  67125. var data = timelineModel.getData();
  67126. var labels = axis.getViewLabels();
  67127. each$19(labels, function (labelItem) {
  67128. // The tickValue is dataIndex, see the costomized scale.
  67129. var dataIndex = labelItem.tickValue;
  67130. var itemModel = data.getItemModel(dataIndex);
  67131. var normalLabelModel = itemModel.getModel('label');
  67132. var hoverLabelModel = itemModel.getModel('emphasis.label');
  67133. var tickCoord = axis.dataToCoord(labelItem.tickValue);
  67134. var textEl = new Text({
  67135. position: [tickCoord, 0],
  67136. rotation: layoutInfo.labelRotation - layoutInfo.rotation,
  67137. onclick: bind$4(this._changeTimeline, this, dataIndex),
  67138. silent: false
  67139. });
  67140. setTextStyle(textEl.style, normalLabelModel, {
  67141. text: labelItem.formattedLabel,
  67142. textAlign: layoutInfo.labelAlign,
  67143. textVerticalAlign: layoutInfo.labelBaseline
  67144. });
  67145. group.add(textEl);
  67146. setHoverStyle(textEl, setTextStyle({}, hoverLabelModel));
  67147. }, this);
  67148. },
  67149. /**
  67150. * @private
  67151. */
  67152. _renderControl: function (layoutInfo, group, axis, timelineModel) {
  67153. var controlSize = layoutInfo.controlSize;
  67154. var rotation = layoutInfo.rotation;
  67155. var itemStyle = timelineModel.getModel('controlStyle').getItemStyle();
  67156. var hoverStyle = timelineModel.getModel('emphasis.controlStyle').getItemStyle();
  67157. var rect = [0, -controlSize / 2, controlSize, controlSize];
  67158. var playState = timelineModel.getPlayState();
  67159. var inverse = timelineModel.get('inverse', true);
  67160. makeBtn(layoutInfo.nextBtnPosition, 'controlStyle.nextIcon', bind$4(this._changeTimeline, this, inverse ? '-' : '+'));
  67161. makeBtn(layoutInfo.prevBtnPosition, 'controlStyle.prevIcon', bind$4(this._changeTimeline, this, inverse ? '+' : '-'));
  67162. makeBtn(layoutInfo.playPosition, 'controlStyle.' + (playState ? 'stopIcon' : 'playIcon'), bind$4(this._handlePlayClick, this, !playState), true);
  67163. function makeBtn(position, iconPath, onclick, willRotate) {
  67164. if (!position) {
  67165. return;
  67166. }
  67167. var opt = {
  67168. position: position,
  67169. origin: [controlSize / 2, 0],
  67170. rotation: willRotate ? -rotation : 0,
  67171. rectHover: true,
  67172. style: itemStyle,
  67173. onclick: onclick
  67174. };
  67175. var btn = makeIcon(timelineModel, iconPath, rect, opt);
  67176. group.add(btn);
  67177. setHoverStyle(btn, hoverStyle);
  67178. }
  67179. },
  67180. _renderCurrentPointer: function (layoutInfo, group, axis, timelineModel) {
  67181. var data = timelineModel.getData();
  67182. var currentIndex = timelineModel.getCurrentIndex();
  67183. var pointerModel = data.getItemModel(currentIndex).getModel('checkpointStyle');
  67184. var me = this;
  67185. var callback = {
  67186. onCreate: function (pointer) {
  67187. pointer.draggable = true;
  67188. pointer.drift = bind$4(me._handlePointerDrag, me);
  67189. pointer.ondragend = bind$4(me._handlePointerDragend, me);
  67190. pointerMoveTo(pointer, currentIndex, axis, timelineModel, true);
  67191. },
  67192. onUpdate: function (pointer) {
  67193. pointerMoveTo(pointer, currentIndex, axis, timelineModel);
  67194. }
  67195. }; // Reuse when exists, for animation and drag.
  67196. this._currentPointer = giveSymbol(pointerModel, pointerModel, this._mainGroup, {}, this._currentPointer, callback);
  67197. },
  67198. _handlePlayClick: function (nextState) {
  67199. this._clearTimer();
  67200. this.api.dispatchAction({
  67201. type: 'timelinePlayChange',
  67202. playState: nextState,
  67203. from: this.uid
  67204. });
  67205. },
  67206. _handlePointerDrag: function (dx, dy, e) {
  67207. this._clearTimer();
  67208. this._pointerChangeTimeline([e.offsetX, e.offsetY]);
  67209. },
  67210. _handlePointerDragend: function (e) {
  67211. this._pointerChangeTimeline([e.offsetX, e.offsetY], true);
  67212. },
  67213. _pointerChangeTimeline: function (mousePos, trigger) {
  67214. var toCoord = this._toAxisCoord(mousePos)[0];
  67215. var axis = this._axis;
  67216. var axisExtent = asc(axis.getExtent().slice());
  67217. toCoord > axisExtent[1] && (toCoord = axisExtent[1]);
  67218. toCoord < axisExtent[0] && (toCoord = axisExtent[0]);
  67219. this._currentPointer.position[0] = toCoord;
  67220. this._currentPointer.dirty();
  67221. var targetDataIndex = this._findNearestTick(toCoord);
  67222. var timelineModel = this.model;
  67223. if (trigger || targetDataIndex !== timelineModel.getCurrentIndex() && timelineModel.get('realtime')) {
  67224. this._changeTimeline(targetDataIndex);
  67225. }
  67226. },
  67227. _doPlayStop: function () {
  67228. this._clearTimer();
  67229. if (this.model.getPlayState()) {
  67230. this._timer = setTimeout(bind$4(handleFrame, this), this.model.get('playInterval'));
  67231. }
  67232. function handleFrame() {
  67233. // Do not cache
  67234. var timelineModel = this.model;
  67235. this._changeTimeline(timelineModel.getCurrentIndex() + (timelineModel.get('rewind', true) ? -1 : 1));
  67236. }
  67237. },
  67238. _toAxisCoord: function (vertex) {
  67239. var trans = this._mainGroup.getLocalTransform();
  67240. return applyTransform$1(vertex, trans, true);
  67241. },
  67242. _findNearestTick: function (axisCoord) {
  67243. var data = this.model.getData();
  67244. var dist = Infinity;
  67245. var targetDataIndex;
  67246. var axis = this._axis;
  67247. data.each(['value'], function (value, dataIndex) {
  67248. var coord = axis.dataToCoord(value);
  67249. var d = Math.abs(coord - axisCoord);
  67250. if (d < dist) {
  67251. dist = d;
  67252. targetDataIndex = dataIndex;
  67253. }
  67254. });
  67255. return targetDataIndex;
  67256. },
  67257. _clearTimer: function () {
  67258. if (this._timer) {
  67259. clearTimeout(this._timer);
  67260. this._timer = null;
  67261. }
  67262. },
  67263. _changeTimeline: function (nextIndex) {
  67264. var currentIndex = this.model.getCurrentIndex();
  67265. if (nextIndex === '+') {
  67266. nextIndex = currentIndex + 1;
  67267. } else if (nextIndex === '-') {
  67268. nextIndex = currentIndex - 1;
  67269. }
  67270. this.api.dispatchAction({
  67271. type: 'timelineChange',
  67272. currentIndex: nextIndex,
  67273. from: this.uid
  67274. });
  67275. }
  67276. });
  67277. function getViewRect$5(model, api) {
  67278. return getLayoutRect(model.getBoxLayoutParams(), {
  67279. width: api.getWidth(),
  67280. height: api.getHeight()
  67281. }, model.get('padding'));
  67282. }
  67283. function makeIcon(timelineModel, objPath, rect, opts) {
  67284. var icon = makePath(timelineModel.get(objPath).replace(/^path:\/\//, ''), clone(opts || {}), new BoundingRect(rect[0], rect[1], rect[2], rect[3]), 'center');
  67285. return icon;
  67286. }
  67287. /**
  67288. * Create symbol or update symbol
  67289. * opt: basic position and event handlers
  67290. */
  67291. function giveSymbol(hostModel, itemStyleModel, group, opt, symbol, callback) {
  67292. var color = itemStyleModel.get('color');
  67293. if (!symbol) {
  67294. var symbolType = hostModel.get('symbol');
  67295. symbol = createSymbol(symbolType, -1, -1, 2, 2, color);
  67296. symbol.setStyle('strokeNoScale', true);
  67297. group.add(symbol);
  67298. callback && callback.onCreate(symbol);
  67299. } else {
  67300. symbol.setColor(color);
  67301. group.add(symbol); // Group may be new, also need to add.
  67302. callback && callback.onUpdate(symbol);
  67303. } // Style
  67304. var itemStyle = itemStyleModel.getItemStyle(['color', 'symbol', 'symbolSize']);
  67305. symbol.setStyle(itemStyle); // Transform and events.
  67306. opt = merge({
  67307. rectHover: true,
  67308. z2: 100
  67309. }, opt, true);
  67310. var symbolSize = hostModel.get('symbolSize');
  67311. symbolSize = symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize];
  67312. symbolSize[0] /= 2;
  67313. symbolSize[1] /= 2;
  67314. opt.scale = symbolSize;
  67315. var symbolOffset = hostModel.get('symbolOffset');
  67316. if (symbolOffset) {
  67317. var pos = opt.position = opt.position || [0, 0];
  67318. pos[0] += parsePercent$1(symbolOffset[0], symbolSize[0]);
  67319. pos[1] += parsePercent$1(symbolOffset[1], symbolSize[1]);
  67320. }
  67321. var symbolRotate = hostModel.get('symbolRotate');
  67322. opt.rotation = (symbolRotate || 0) * Math.PI / 180 || 0;
  67323. symbol.attr(opt); // FIXME
  67324. // (1) When symbol.style.strokeNoScale is true and updateTransform is not performed,
  67325. // getBoundingRect will return wrong result.
  67326. // (This is supposed to be resolved in zrender, but it is a little difficult to
  67327. // leverage performance and auto updateTransform)
  67328. // (2) All of ancesters of symbol do not scale, so we can just updateTransform symbol.
  67329. symbol.updateTransform();
  67330. return symbol;
  67331. }
  67332. function pointerMoveTo(pointer, dataIndex, axis, timelineModel, noAnimation) {
  67333. if (pointer.dragging) {
  67334. return;
  67335. }
  67336. var pointerModel = timelineModel.getModel('checkpointStyle');
  67337. var toCoord = axis.dataToCoord(timelineModel.getData().get(['value'], dataIndex));
  67338. if (noAnimation || !pointerModel.get('animation', true)) {
  67339. pointer.attr({
  67340. position: [toCoord, 0]
  67341. });
  67342. } else {
  67343. pointer.stopAnimation(true);
  67344. pointer.animateTo({
  67345. position: [toCoord, 0]
  67346. }, pointerModel.get('animationDuration', true), pointerModel.get('animationEasing', true));
  67347. }
  67348. }
  67349. /*
  67350. * Licensed to the Apache Software Foundation (ASF) under one
  67351. * or more contributor license agreements. See the NOTICE file
  67352. * distributed with this work for additional information
  67353. * regarding copyright ownership. The ASF licenses this file
  67354. * to you under the Apache License, Version 2.0 (the
  67355. * "License"); you may not use this file except in compliance
  67356. * with the License. You may obtain a copy of the License at
  67357. *
  67358. * http://www.apache.org/licenses/LICENSE-2.0
  67359. *
  67360. * Unless required by applicable law or agreed to in writing,
  67361. * software distributed under the License is distributed on an
  67362. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67363. * KIND, either express or implied. See the License for the
  67364. * specific language governing permissions and limitations
  67365. * under the License.
  67366. */
  67367. /**
  67368. * DataZoom component entry
  67369. */
  67370. registerPreprocessor(preprocessor$1);
  67371. /*
  67372. * Licensed to the Apache Software Foundation (ASF) under one
  67373. * or more contributor license agreements. See the NOTICE file
  67374. * distributed with this work for additional information
  67375. * regarding copyright ownership. The ASF licenses this file
  67376. * to you under the Apache License, Version 2.0 (the
  67377. * "License"); you may not use this file except in compliance
  67378. * with the License. You may obtain a copy of the License at
  67379. *
  67380. * http://www.apache.org/licenses/LICENSE-2.0
  67381. *
  67382. * Unless required by applicable law or agreed to in writing,
  67383. * software distributed under the License is distributed on an
  67384. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67385. * KIND, either express or implied. See the License for the
  67386. * specific language governing permissions and limitations
  67387. * under the License.
  67388. */
  67389. ComponentModel.registerSubTypeDefaulter('dataZoom', function () {
  67390. // Default 'slider' when no type specified.
  67391. return 'slider';
  67392. });
  67393. /*
  67394. * Licensed to the Apache Software Foundation (ASF) under one
  67395. * or more contributor license agreements. See the NOTICE file
  67396. * distributed with this work for additional information
  67397. * regarding copyright ownership. The ASF licenses this file
  67398. * to you under the Apache License, Version 2.0 (the
  67399. * "License"); you may not use this file except in compliance
  67400. * with the License. You may obtain a copy of the License at
  67401. *
  67402. * http://www.apache.org/licenses/LICENSE-2.0
  67403. *
  67404. * Unless required by applicable law or agreed to in writing,
  67405. * software distributed under the License is distributed on an
  67406. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67407. * KIND, either express or implied. See the License for the
  67408. * specific language governing permissions and limitations
  67409. * under the License.
  67410. */
  67411. var AXIS_DIMS = ['x', 'y', 'z', 'radius', 'angle', 'single']; // Supported coords.
  67412. var COORDS = ['cartesian2d', 'polar', 'singleAxis'];
  67413. /**
  67414. * @param {string} coordType
  67415. * @return {boolean}
  67416. */
  67417. function isCoordSupported(coordType) {
  67418. return indexOf(COORDS, coordType) >= 0;
  67419. }
  67420. /**
  67421. * Create "each" method to iterate names.
  67422. *
  67423. * @pubilc
  67424. * @param {Array.<string>} names
  67425. * @param {Array.<string>=} attrs
  67426. * @return {Function}
  67427. */
  67428. function createNameEach(names, attrs) {
  67429. names = names.slice();
  67430. var capitalNames = map(names, capitalFirst);
  67431. attrs = (attrs || []).slice();
  67432. var capitalAttrs = map(attrs, capitalFirst);
  67433. return function (callback, context) {
  67434. each$1(names, function (name, index) {
  67435. var nameObj = {
  67436. name: name,
  67437. capital: capitalNames[index]
  67438. };
  67439. for (var j = 0; j < attrs.length; j++) {
  67440. nameObj[attrs[j]] = name + capitalAttrs[j];
  67441. }
  67442. callback.call(context, nameObj);
  67443. });
  67444. };
  67445. }
  67446. /**
  67447. * Iterate each dimension name.
  67448. *
  67449. * @public
  67450. * @param {Function} callback The parameter is like:
  67451. * {
  67452. * name: 'angle',
  67453. * capital: 'Angle',
  67454. * axis: 'angleAxis',
  67455. * axisIndex: 'angleAixs',
  67456. * index: 'angleIndex'
  67457. * }
  67458. * @param {Object} context
  67459. */
  67460. var eachAxisDim$1 = createNameEach(AXIS_DIMS, ['axisIndex', 'axis', 'index', 'id']);
  67461. /**
  67462. * If tow dataZoomModels has the same axis controlled, we say that they are 'linked'.
  67463. * dataZoomModels and 'links' make up one or more graphics.
  67464. * This function finds the graphic where the source dataZoomModel is in.
  67465. *
  67466. * @public
  67467. * @param {Function} forEachNode Node iterator.
  67468. * @param {Function} forEachEdgeType edgeType iterator
  67469. * @param {Function} edgeIdGetter Giving node and edgeType, return an array of edge id.
  67470. * @return {Function} Input: sourceNode, Output: Like {nodes: [], dims: {}}
  67471. */
  67472. function createLinkedNodesFinder(forEachNode, forEachEdgeType, edgeIdGetter) {
  67473. return function (sourceNode) {
  67474. var result = {
  67475. nodes: [],
  67476. records: {} // key: edgeType.name, value: Object (key: edge id, value: boolean).
  67477. };
  67478. forEachEdgeType(function (edgeType) {
  67479. result.records[edgeType.name] = {};
  67480. });
  67481. if (!sourceNode) {
  67482. return result;
  67483. }
  67484. absorb(sourceNode, result);
  67485. var existsLink;
  67486. do {
  67487. existsLink = false;
  67488. forEachNode(processSingleNode);
  67489. } while (existsLink);
  67490. function processSingleNode(node) {
  67491. if (!isNodeAbsorded(node, result) && isLinked(node, result)) {
  67492. absorb(node, result);
  67493. existsLink = true;
  67494. }
  67495. }
  67496. return result;
  67497. };
  67498. function isNodeAbsorded(node, result) {
  67499. return indexOf(result.nodes, node) >= 0;
  67500. }
  67501. function isLinked(node, result) {
  67502. var hasLink = false;
  67503. forEachEdgeType(function (edgeType) {
  67504. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  67505. result.records[edgeType.name][edgeId] && (hasLink = true);
  67506. });
  67507. });
  67508. return hasLink;
  67509. }
  67510. function absorb(node, result) {
  67511. result.nodes.push(node);
  67512. forEachEdgeType(function (edgeType) {
  67513. each$1(edgeIdGetter(node, edgeType) || [], function (edgeId) {
  67514. result.records[edgeType.name][edgeId] = true;
  67515. });
  67516. });
  67517. }
  67518. }
  67519. /*
  67520. * Licensed to the Apache Software Foundation (ASF) under one
  67521. * or more contributor license agreements. See the NOTICE file
  67522. * distributed with this work for additional information
  67523. * regarding copyright ownership. The ASF licenses this file
  67524. * to you under the Apache License, Version 2.0 (the
  67525. * "License"); you may not use this file except in compliance
  67526. * with the License. You may obtain a copy of the License at
  67527. *
  67528. * http://www.apache.org/licenses/LICENSE-2.0
  67529. *
  67530. * Unless required by applicable law or agreed to in writing,
  67531. * software distributed under the License is distributed on an
  67532. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67533. * KIND, either express or implied. See the License for the
  67534. * specific language governing permissions and limitations
  67535. * under the License.
  67536. */
  67537. var each$21 = each$1;
  67538. var asc$1 = asc;
  67539. /**
  67540. * Operate single axis.
  67541. * One axis can only operated by one axis operator.
  67542. * Different dataZoomModels may be defined to operate the same axis.
  67543. * (i.e. 'inside' data zoom and 'slider' data zoom components)
  67544. * So dataZoomModels share one axisProxy in that case.
  67545. *
  67546. * @class
  67547. */
  67548. var AxisProxy = function (dimName, axisIndex, dataZoomModel, ecModel) {
  67549. /**
  67550. * @private
  67551. * @type {string}
  67552. */
  67553. this._dimName = dimName;
  67554. /**
  67555. * @private
  67556. */
  67557. this._axisIndex = axisIndex;
  67558. /**
  67559. * @private
  67560. * @type {Array.<number>}
  67561. */
  67562. this._valueWindow;
  67563. /**
  67564. * @private
  67565. * @type {Array.<number>}
  67566. */
  67567. this._percentWindow;
  67568. /**
  67569. * @private
  67570. * @type {Array.<number>}
  67571. */
  67572. this._dataExtent;
  67573. /**
  67574. * {minSpan, maxSpan, minValueSpan, maxValueSpan}
  67575. * @private
  67576. * @type {Object}
  67577. */
  67578. this._minMaxSpan;
  67579. /**
  67580. * @readOnly
  67581. * @type {module: echarts/model/Global}
  67582. */
  67583. this.ecModel = ecModel;
  67584. /**
  67585. * @private
  67586. * @type {module: echarts/component/dataZoom/DataZoomModel}
  67587. */
  67588. this._dataZoomModel = dataZoomModel; // /**
  67589. // * @readOnly
  67590. // * @private
  67591. // */
  67592. // this.hasSeriesStacked;
  67593. };
  67594. AxisProxy.prototype = {
  67595. constructor: AxisProxy,
  67596. /**
  67597. * Whether the axisProxy is hosted by dataZoomModel.
  67598. *
  67599. * @public
  67600. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  67601. * @return {boolean}
  67602. */
  67603. hostedBy: function (dataZoomModel) {
  67604. return this._dataZoomModel === dataZoomModel;
  67605. },
  67606. /**
  67607. * @return {Array.<number>} Value can only be NaN or finite value.
  67608. */
  67609. getDataValueWindow: function () {
  67610. return this._valueWindow.slice();
  67611. },
  67612. /**
  67613. * @return {Array.<number>}
  67614. */
  67615. getDataPercentWindow: function () {
  67616. return this._percentWindow.slice();
  67617. },
  67618. /**
  67619. * @public
  67620. * @param {number} axisIndex
  67621. * @return {Array} seriesModels
  67622. */
  67623. getTargetSeriesModels: function () {
  67624. var seriesModels = [];
  67625. var ecModel = this.ecModel;
  67626. ecModel.eachSeries(function (seriesModel) {
  67627. if (isCoordSupported(seriesModel.get('coordinateSystem'))) {
  67628. var dimName = this._dimName;
  67629. var axisModel = ecModel.queryComponents({
  67630. mainType: dimName + 'Axis',
  67631. index: seriesModel.get(dimName + 'AxisIndex'),
  67632. id: seriesModel.get(dimName + 'AxisId')
  67633. })[0];
  67634. if (this._axisIndex === (axisModel && axisModel.componentIndex)) {
  67635. seriesModels.push(seriesModel);
  67636. }
  67637. }
  67638. }, this);
  67639. return seriesModels;
  67640. },
  67641. getAxisModel: function () {
  67642. return this.ecModel.getComponent(this._dimName + 'Axis', this._axisIndex);
  67643. },
  67644. getOtherAxisModel: function () {
  67645. var axisDim = this._dimName;
  67646. var ecModel = this.ecModel;
  67647. var axisModel = this.getAxisModel();
  67648. var isCartesian = axisDim === 'x' || axisDim === 'y';
  67649. var otherAxisDim;
  67650. var coordSysIndexName;
  67651. if (isCartesian) {
  67652. coordSysIndexName = 'gridIndex';
  67653. otherAxisDim = axisDim === 'x' ? 'y' : 'x';
  67654. } else {
  67655. coordSysIndexName = 'polarIndex';
  67656. otherAxisDim = axisDim === 'angle' ? 'radius' : 'angle';
  67657. }
  67658. var foundOtherAxisModel;
  67659. ecModel.eachComponent(otherAxisDim + 'Axis', function (otherAxisModel) {
  67660. if ((otherAxisModel.get(coordSysIndexName) || 0) === (axisModel.get(coordSysIndexName) || 0)) {
  67661. foundOtherAxisModel = otherAxisModel;
  67662. }
  67663. });
  67664. return foundOtherAxisModel;
  67665. },
  67666. getMinMaxSpan: function () {
  67667. return clone(this._minMaxSpan);
  67668. },
  67669. /**
  67670. * Only calculate by given range and this._dataExtent, do not change anything.
  67671. *
  67672. * @param {Object} opt
  67673. * @param {number} [opt.start]
  67674. * @param {number} [opt.end]
  67675. * @param {number} [opt.startValue]
  67676. * @param {number} [opt.endValue]
  67677. */
  67678. calculateDataWindow: function (opt) {
  67679. var dataExtent = this._dataExtent;
  67680. var axisModel = this.getAxisModel();
  67681. var scale = axisModel.axis.scale;
  67682. var rangePropMode = this._dataZoomModel.getRangePropMode();
  67683. var percentExtent = [0, 100];
  67684. var percentWindow = [];
  67685. var valueWindow = [];
  67686. var hasPropModeValue;
  67687. each$21(['start', 'end'], function (prop, idx) {
  67688. var boundPercent = opt[prop];
  67689. var boundValue = opt[prop + 'Value']; // Notice: dataZoom is based either on `percentProp` ('start', 'end') or
  67690. // on `valueProp` ('startValue', 'endValue'). (They are based on the data extent
  67691. // but not min/max of axis, which will be calculated by data window then).
  67692. // The former one is suitable for cases that a dataZoom component controls multiple
  67693. // axes with different unit or extent, and the latter one is suitable for accurate
  67694. // zoom by pixel (e.g., in dataZoomSelect).
  67695. // we use `getRangePropMode()` to mark which prop is used. `rangePropMode` is updated
  67696. // only when setOption or dispatchAction, otherwise it remains its original value.
  67697. // (Why not only record `percentProp` and always map to `valueProp`? Because
  67698. // the map `valueProp` -> `percentProp` -> `valueProp` probably not the original
  67699. // `valueProp`. consider two axes constrolled by one dataZoom. They have different
  67700. // data extent. All of values that are overflow the `dataExtent` will be calculated
  67701. // to percent '100%').
  67702. if (rangePropMode[idx] === 'percent') {
  67703. boundPercent == null && (boundPercent = percentExtent[idx]); // Use scale.parse to math round for category or time axis.
  67704. boundValue = scale.parse(linearMap(boundPercent, percentExtent, dataExtent));
  67705. } else {
  67706. hasPropModeValue = true;
  67707. boundValue = boundValue == null ? dataExtent[idx] : scale.parse(boundValue); // Calculating `percent` from `value` may be not accurate, because
  67708. // This calculation can not be inversed, because all of values that
  67709. // are overflow the `dataExtent` will be calculated to percent '100%'
  67710. boundPercent = linearMap(boundValue, dataExtent, percentExtent);
  67711. } // valueWindow[idx] = round(boundValue);
  67712. // percentWindow[idx] = round(boundPercent);
  67713. valueWindow[idx] = boundValue;
  67714. percentWindow[idx] = boundPercent;
  67715. });
  67716. asc$1(valueWindow);
  67717. asc$1(percentWindow); // The windows from user calling of `dispatchAction` might be out of the extent,
  67718. // or do not obey the `min/maxSpan`, `min/maxValueSpan`. But we dont restrict window
  67719. // by `zoomLock` here, because we see `zoomLock` just as a interaction constraint,
  67720. // where API is able to initialize/modify the window size even though `zoomLock`
  67721. // specified.
  67722. var spans = this._minMaxSpan;
  67723. hasPropModeValue ? restrictSet(valueWindow, percentWindow, dataExtent, percentExtent, false) : restrictSet(percentWindow, valueWindow, percentExtent, dataExtent, true);
  67724. function restrictSet(fromWindow, toWindow, fromExtent, toExtent, toValue) {
  67725. var suffix = toValue ? 'Span' : 'ValueSpan';
  67726. sliderMove(0, fromWindow, fromExtent, 'all', spans['min' + suffix], spans['max' + suffix]);
  67727. for (var i = 0; i < 2; i++) {
  67728. toWindow[i] = linearMap(fromWindow[i], fromExtent, toExtent, true);
  67729. toValue && (toWindow[i] = scale.parse(toWindow[i]));
  67730. }
  67731. }
  67732. return {
  67733. valueWindow: valueWindow,
  67734. percentWindow: percentWindow
  67735. };
  67736. },
  67737. /**
  67738. * Notice: reset should not be called before series.restoreData() called,
  67739. * so it is recommanded to be called in "process stage" but not "model init
  67740. * stage".
  67741. *
  67742. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  67743. */
  67744. reset: function (dataZoomModel) {
  67745. if (dataZoomModel !== this._dataZoomModel) {
  67746. return;
  67747. }
  67748. var targetSeries = this.getTargetSeriesModels(); // Culculate data window and data extent, and record them.
  67749. this._dataExtent = calculateDataExtent(this, this._dimName, targetSeries); // this.hasSeriesStacked = false;
  67750. // each(targetSeries, function (series) {
  67751. // var data = series.getData();
  67752. // var dataDim = data.mapDimension(this._dimName);
  67753. // var stackedDimension = data.getCalculationInfo('stackedDimension');
  67754. // if (stackedDimension && stackedDimension === dataDim) {
  67755. // this.hasSeriesStacked = true;
  67756. // }
  67757. // }, this);
  67758. // `calculateDataWindow` uses min/maxSpan.
  67759. setMinMaxSpan(this);
  67760. var dataWindow = this.calculateDataWindow(dataZoomModel.settledOption);
  67761. this._valueWindow = dataWindow.valueWindow;
  67762. this._percentWindow = dataWindow.percentWindow; // Update axis setting then.
  67763. setAxisModel(this);
  67764. },
  67765. /**
  67766. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  67767. */
  67768. restore: function (dataZoomModel) {
  67769. if (dataZoomModel !== this._dataZoomModel) {
  67770. return;
  67771. }
  67772. this._valueWindow = this._percentWindow = null;
  67773. setAxisModel(this, true);
  67774. },
  67775. /**
  67776. * @param {module: echarts/component/dataZoom/DataZoomModel} dataZoomModel
  67777. */
  67778. filterData: function (dataZoomModel, api) {
  67779. if (dataZoomModel !== this._dataZoomModel) {
  67780. return;
  67781. }
  67782. var axisDim = this._dimName;
  67783. var seriesModels = this.getTargetSeriesModels();
  67784. var filterMode = dataZoomModel.get('filterMode');
  67785. var valueWindow = this._valueWindow;
  67786. if (filterMode === 'none') {
  67787. return;
  67788. } // FIXME
  67789. // Toolbox may has dataZoom injected. And if there are stacked bar chart
  67790. // with NaN data, NaN will be filtered and stack will be wrong.
  67791. // So we need to force the mode to be set empty.
  67792. // In fect, it is not a big deal that do not support filterMode-'filter'
  67793. // when using toolbox#dataZoom, utill tooltip#dataZoom support "single axis
  67794. // selection" some day, which might need "adapt to data extent on the
  67795. // otherAxis", which is disabled by filterMode-'empty'.
  67796. // But currently, stack has been fixed to based on value but not index,
  67797. // so this is not an issue any more.
  67798. // var otherAxisModel = this.getOtherAxisModel();
  67799. // if (dataZoomModel.get('$fromToolbox')
  67800. // && otherAxisModel
  67801. // && otherAxisModel.hasSeriesStacked
  67802. // ) {
  67803. // filterMode = 'empty';
  67804. // }
  67805. // TODO
  67806. // filterMode 'weakFilter' and 'empty' is not optimized for huge data yet.
  67807. each$21(seriesModels, function (seriesModel) {
  67808. var seriesData = seriesModel.getData();
  67809. var dataDims = seriesData.mapDimension(axisDim, true);
  67810. if (!dataDims.length) {
  67811. return;
  67812. }
  67813. if (filterMode === 'weakFilter') {
  67814. seriesData.filterSelf(function (dataIndex) {
  67815. var leftOut;
  67816. var rightOut;
  67817. var hasValue;
  67818. for (var i = 0; i < dataDims.length; i++) {
  67819. var value = seriesData.get(dataDims[i], dataIndex);
  67820. var thisHasValue = !isNaN(value);
  67821. var thisLeftOut = value < valueWindow[0];
  67822. var thisRightOut = value > valueWindow[1];
  67823. if (thisHasValue && !thisLeftOut && !thisRightOut) {
  67824. return true;
  67825. }
  67826. thisHasValue && (hasValue = true);
  67827. thisLeftOut && (leftOut = true);
  67828. thisRightOut && (rightOut = true);
  67829. } // If both left out and right out, do not filter.
  67830. return hasValue && leftOut && rightOut;
  67831. });
  67832. } else {
  67833. each$21(dataDims, function (dim) {
  67834. if (filterMode === 'empty') {
  67835. seriesModel.setData(seriesData = seriesData.map(dim, function (value) {
  67836. return !isInWindow(value) ? NaN : value;
  67837. }));
  67838. } else {
  67839. var range = {};
  67840. range[dim] = valueWindow; // console.time('select');
  67841. seriesData.selectRange(range); // console.timeEnd('select');
  67842. }
  67843. });
  67844. }
  67845. each$21(dataDims, function (dim) {
  67846. seriesData.setApproximateExtent(valueWindow, dim);
  67847. });
  67848. });
  67849. function isInWindow(value) {
  67850. return value >= valueWindow[0] && value <= valueWindow[1];
  67851. }
  67852. }
  67853. };
  67854. function calculateDataExtent(axisProxy, axisDim, seriesModels) {
  67855. var dataExtent = [Infinity, -Infinity];
  67856. each$21(seriesModels, function (seriesModel) {
  67857. var seriesData = seriesModel.getData();
  67858. if (seriesData) {
  67859. each$21(seriesData.mapDimension(axisDim, true), function (dim) {
  67860. var seriesExtent = seriesData.getApproximateExtent(dim);
  67861. seriesExtent[0] < dataExtent[0] && (dataExtent[0] = seriesExtent[0]);
  67862. seriesExtent[1] > dataExtent[1] && (dataExtent[1] = seriesExtent[1]);
  67863. });
  67864. }
  67865. });
  67866. if (dataExtent[1] < dataExtent[0]) {
  67867. dataExtent = [NaN, NaN];
  67868. } // It is important to get "consistent" extent when more then one axes is
  67869. // controlled by a `dataZoom`, otherwise those axes will not be synchronized
  67870. // when zooming. But it is difficult to know what is "consistent", considering
  67871. // axes have different type or even different meanings (For example, two
  67872. // time axes are used to compare data of the same date in different years).
  67873. // So basically dataZoom just obtains extent by series.data (in category axis
  67874. // extent can be obtained from axis.data).
  67875. // Nevertheless, user can set min/max/scale on axes to make extent of axes
  67876. // consistent.
  67877. fixExtentByAxis(axisProxy, dataExtent);
  67878. return dataExtent;
  67879. }
  67880. function fixExtentByAxis(axisProxy, dataExtent) {
  67881. var axisModel = axisProxy.getAxisModel();
  67882. var min = axisModel.getMin(true); // For category axis, if min/max/scale are not set, extent is determined
  67883. // by axis.data by default.
  67884. var isCategoryAxis = axisModel.get('type') === 'category';
  67885. var axisDataLen = isCategoryAxis && axisModel.getCategories().length;
  67886. if (min != null && min !== 'dataMin' && typeof min !== 'function') {
  67887. dataExtent[0] = min;
  67888. } else if (isCategoryAxis) {
  67889. dataExtent[0] = axisDataLen > 0 ? 0 : NaN;
  67890. }
  67891. var max = axisModel.getMax(true);
  67892. if (max != null && max !== 'dataMax' && typeof max !== 'function') {
  67893. dataExtent[1] = max;
  67894. } else if (isCategoryAxis) {
  67895. dataExtent[1] = axisDataLen > 0 ? axisDataLen - 1 : NaN;
  67896. }
  67897. if (!axisModel.get('scale', true)) {
  67898. dataExtent[0] > 0 && (dataExtent[0] = 0);
  67899. dataExtent[1] < 0 && (dataExtent[1] = 0);
  67900. } // For value axis, if min/max/scale are not set, we just use the extent obtained
  67901. // by series data, which may be a little different from the extent calculated by
  67902. // `axisHelper.getScaleExtent`. But the different just affects the experience a
  67903. // little when zooming. So it will not be fixed until some users require it strongly.
  67904. return dataExtent;
  67905. }
  67906. function setAxisModel(axisProxy, isRestore) {
  67907. var axisModel = axisProxy.getAxisModel();
  67908. var percentWindow = axisProxy._percentWindow;
  67909. var valueWindow = axisProxy._valueWindow;
  67910. if (!percentWindow) {
  67911. return;
  67912. } // [0, 500]: arbitrary value, guess axis extent.
  67913. var precision = getPixelPrecision(valueWindow, [0, 500]);
  67914. precision = Math.min(precision, 20); // isRestore or isFull
  67915. var useOrigin = isRestore || percentWindow[0] === 0 && percentWindow[1] === 100;
  67916. axisModel.setRange(useOrigin ? null : +valueWindow[0].toFixed(precision), useOrigin ? null : +valueWindow[1].toFixed(precision));
  67917. }
  67918. function setMinMaxSpan(axisProxy) {
  67919. var minMaxSpan = axisProxy._minMaxSpan = {};
  67920. var dataZoomModel = axisProxy._dataZoomModel;
  67921. var dataExtent = axisProxy._dataExtent;
  67922. each$21(['min', 'max'], function (minMax) {
  67923. var percentSpan = dataZoomModel.get(minMax + 'Span');
  67924. var valueSpan = dataZoomModel.get(minMax + 'ValueSpan');
  67925. valueSpan != null && (valueSpan = axisProxy.getAxisModel().axis.scale.parse(valueSpan)); // minValueSpan and maxValueSpan has higher priority than minSpan and maxSpan
  67926. if (valueSpan != null) {
  67927. percentSpan = linearMap(dataExtent[0] + valueSpan, dataExtent, [0, 100], true);
  67928. } else if (percentSpan != null) {
  67929. valueSpan = linearMap(percentSpan, [0, 100], dataExtent, true) - dataExtent[0];
  67930. }
  67931. minMaxSpan[minMax + 'Span'] = percentSpan;
  67932. minMaxSpan[minMax + 'ValueSpan'] = valueSpan;
  67933. });
  67934. }
  67935. /*
  67936. * Licensed to the Apache Software Foundation (ASF) under one
  67937. * or more contributor license agreements. See the NOTICE file
  67938. * distributed with this work for additional information
  67939. * regarding copyright ownership. The ASF licenses this file
  67940. * to you under the Apache License, Version 2.0 (the
  67941. * "License"); you may not use this file except in compliance
  67942. * with the License. You may obtain a copy of the License at
  67943. *
  67944. * http://www.apache.org/licenses/LICENSE-2.0
  67945. *
  67946. * Unless required by applicable law or agreed to in writing,
  67947. * software distributed under the License is distributed on an
  67948. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  67949. * KIND, either express or implied. See the License for the
  67950. * specific language governing permissions and limitations
  67951. * under the License.
  67952. */
  67953. var each$20 = each$1;
  67954. var eachAxisDim = eachAxisDim$1;
  67955. var DataZoomModel = extendComponentModel({
  67956. type: 'dataZoom',
  67957. dependencies: ['xAxis', 'yAxis', 'zAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'series'],
  67958. /**
  67959. * @protected
  67960. */
  67961. defaultOption: {
  67962. zlevel: 0,
  67963. z: 4,
  67964. // Higher than normal component (z: 2).
  67965. orient: null,
  67966. // Default auto by axisIndex. Possible value: 'horizontal', 'vertical'.
  67967. xAxisIndex: null,
  67968. // Default the first horizontal category axis.
  67969. yAxisIndex: null,
  67970. // Default the first vertical category axis.
  67971. filterMode: 'filter',
  67972. // Possible values: 'filter' or 'empty' or 'weakFilter'.
  67973. // 'filter': data items which are out of window will be removed. This option is
  67974. // applicable when filtering outliers. For each data item, it will be
  67975. // filtered if one of the relevant dimensions is out of the window.
  67976. // 'weakFilter': data items which are out of window will be removed. This option
  67977. // is applicable when filtering outliers. For each data item, it will be
  67978. // filtered only if all of the relevant dimensions are out of the same
  67979. // side of the window.
  67980. // 'empty': data items which are out of window will be set to empty.
  67981. // This option is applicable when user should not neglect
  67982. // that there are some data items out of window.
  67983. // 'none': Do not filter.
  67984. // Taking line chart as an example, line will be broken in
  67985. // the filtered points when filterModel is set to 'empty', but
  67986. // be connected when set to 'filter'.
  67987. throttle: null,
  67988. // Dispatch action by the fixed rate, avoid frequency.
  67989. // default 100. Do not throttle when use null/undefined.
  67990. // If animation === true and animationDurationUpdate > 0,
  67991. // default value is 100, otherwise 20.
  67992. start: 0,
  67993. // Start percent. 0 ~ 100
  67994. end: 100,
  67995. // End percent. 0 ~ 100
  67996. startValue: null,
  67997. // Start value. If startValue specified, start is ignored.
  67998. endValue: null,
  67999. // End value. If endValue specified, end is ignored.
  68000. minSpan: null,
  68001. // 0 ~ 100
  68002. maxSpan: null,
  68003. // 0 ~ 100
  68004. minValueSpan: null,
  68005. // The range of dataZoom can not be smaller than that.
  68006. maxValueSpan: null,
  68007. // The range of dataZoom can not be larger than that.
  68008. rangeMode: null // Array, can be 'value' or 'percent'.
  68009. },
  68010. /**
  68011. * @override
  68012. */
  68013. init: function (option, parentModel, ecModel) {
  68014. /**
  68015. * key like x_0, y_1
  68016. * @private
  68017. * @type {Object}
  68018. */
  68019. this._dataIntervalByAxis = {};
  68020. /**
  68021. * @private
  68022. */
  68023. this._dataInfo = {};
  68024. /**
  68025. * key like x_0, y_1
  68026. * @private
  68027. */
  68028. this._axisProxies = {};
  68029. /**
  68030. * @readOnly
  68031. */
  68032. this.textStyleModel;
  68033. /**
  68034. * @private
  68035. */
  68036. this._autoThrottle = true;
  68037. /**
  68038. * It is `[rangeModeForMin, rangeModeForMax]`.
  68039. * The optional values for `rangeMode`:
  68040. * + `'value'` mode: the axis extent will always be determined by
  68041. * `dataZoom.startValue` and `dataZoom.endValue`, despite
  68042. * how data like and how `axis.min` and `axis.max` are.
  68043. * + `'percent'` mode: `100` represents 100% of the `[dMin, dMax]`,
  68044. * where `dMin` is `axis.min` if `axis.min` specified, otherwise `data.extent[0]`,
  68045. * and `dMax` is `axis.max` if `axis.max` specified, otherwise `data.extent[1]`.
  68046. * Axis extent will be determined by the result of the percent of `[dMin, dMax]`.
  68047. *
  68048. * For example, when users are using dynamic data (update data periodically via `setOption`),
  68049. * if in `'value`' mode, the window will be kept in a fixed value range despite how
  68050. * data are appended, while if in `'percent'` mode, whe window range will be changed alone with
  68051. * the appended data (suppose `axis.min` and `axis.max` are not specified).
  68052. *
  68053. * @private
  68054. */
  68055. this._rangePropMode = ['percent', 'percent'];
  68056. var inputRawOption = retrieveRawOption(option);
  68057. /**
  68058. * Suppose a "main process" start at the point that model prepared (that is,
  68059. * model initialized or merged or method called in `action`).
  68060. * We should keep the `main process` idempotent, that is, given a set of values
  68061. * on `option`, we get the same result.
  68062. *
  68063. * But sometimes, values on `option` will be updated for providing users
  68064. * a "final calculated value" (`dataZoomProcessor` will do that). Those value
  68065. * should not be the base/input of the `main process`.
  68066. *
  68067. * So in that case we should save and keep the input of the `main process`
  68068. * separately, called `settledOption`.
  68069. *
  68070. * For example, consider the case:
  68071. * (Step_1) brush zoom the grid by `toolbox.dataZoom`,
  68072. * where the original input `option.startValue`, `option.endValue` are earsed by
  68073. * calculated value.
  68074. * (Step)2) click the legend to hide and show a series,
  68075. * where the new range is calculated by the earsed `startValue` and `endValue`,
  68076. * which brings incorrect result.
  68077. *
  68078. * @readOnly
  68079. */
  68080. this.settledOption = inputRawOption;
  68081. this.mergeDefaultAndTheme(option, ecModel);
  68082. this.doInit(inputRawOption);
  68083. },
  68084. /**
  68085. * @override
  68086. */
  68087. mergeOption: function (newOption) {
  68088. var inputRawOption = retrieveRawOption(newOption); //FIX #2591
  68089. merge(this.option, newOption, true);
  68090. merge(this.settledOption, inputRawOption, true);
  68091. this.doInit(inputRawOption);
  68092. },
  68093. /**
  68094. * @protected
  68095. */
  68096. doInit: function (inputRawOption) {
  68097. var thisOption = this.option; // Disable realtime view update if canvas is not supported.
  68098. if (!env$1.canvasSupported) {
  68099. thisOption.realtime = false;
  68100. }
  68101. this._setDefaultThrottle(inputRawOption);
  68102. updateRangeUse(this, inputRawOption);
  68103. var settledOption = this.settledOption;
  68104. each$20([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  68105. // start/end has higher priority over startValue/endValue if they
  68106. // both set, but we should make chart.setOption({endValue: 1000})
  68107. // effective, rather than chart.setOption({endValue: 1000, end: null}).
  68108. if (this._rangePropMode[index] === 'value') {
  68109. thisOption[names[0]] = settledOption[names[0]] = null;
  68110. } // Otherwise do nothing and use the merge result.
  68111. }, this);
  68112. this.textStyleModel = this.getModel('textStyle');
  68113. this._resetTarget();
  68114. this._giveAxisProxies();
  68115. },
  68116. /**
  68117. * @private
  68118. */
  68119. _giveAxisProxies: function () {
  68120. var axisProxies = this._axisProxies;
  68121. this.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel, ecModel) {
  68122. var axisModel = this.dependentModels[dimNames.axis][axisIndex]; // If exists, share axisProxy with other dataZoomModels.
  68123. var axisProxy = axisModel.__dzAxisProxy || ( // Use the first dataZoomModel as the main model of axisProxy.
  68124. axisModel.__dzAxisProxy = new AxisProxy(dimNames.name, axisIndex, this, ecModel)); // FIXME
  68125. // dispose __dzAxisProxy
  68126. axisProxies[dimNames.name + '_' + axisIndex] = axisProxy;
  68127. }, this);
  68128. },
  68129. /**
  68130. * @private
  68131. */
  68132. _resetTarget: function () {
  68133. var thisOption = this.option;
  68134. var autoMode = this._judgeAutoMode();
  68135. eachAxisDim(function (dimNames) {
  68136. var axisIndexName = dimNames.axisIndex;
  68137. thisOption[axisIndexName] = normalizeToArray(thisOption[axisIndexName]);
  68138. }, this);
  68139. if (autoMode === 'axisIndex') {
  68140. this._autoSetAxisIndex();
  68141. } else if (autoMode === 'orient') {
  68142. this._autoSetOrient();
  68143. }
  68144. },
  68145. /**
  68146. * @private
  68147. */
  68148. _judgeAutoMode: function () {
  68149. // Auto set only works for setOption at the first time.
  68150. // The following is user's reponsibility. So using merged
  68151. // option is OK.
  68152. var thisOption = this.option;
  68153. var hasIndexSpecified = false;
  68154. eachAxisDim(function (dimNames) {
  68155. // When user set axisIndex as a empty array, we think that user specify axisIndex
  68156. // but do not want use auto mode. Because empty array may be encountered when
  68157. // some error occured.
  68158. if (thisOption[dimNames.axisIndex] != null) {
  68159. hasIndexSpecified = true;
  68160. }
  68161. }, this);
  68162. var orient = thisOption.orient;
  68163. if (orient == null && hasIndexSpecified) {
  68164. return 'orient';
  68165. } else if (!hasIndexSpecified) {
  68166. if (orient == null) {
  68167. thisOption.orient = 'horizontal';
  68168. }
  68169. return 'axisIndex';
  68170. }
  68171. },
  68172. /**
  68173. * @private
  68174. */
  68175. _autoSetAxisIndex: function () {
  68176. var autoAxisIndex = true;
  68177. var orient = this.get('orient', true);
  68178. var thisOption = this.option;
  68179. var dependentModels = this.dependentModels;
  68180. if (autoAxisIndex) {
  68181. // Find axis that parallel to dataZoom as default.
  68182. var dimName = orient === 'vertical' ? 'y' : 'x';
  68183. if (dependentModels[dimName + 'Axis'].length) {
  68184. thisOption[dimName + 'AxisIndex'] = [0];
  68185. autoAxisIndex = false;
  68186. } else {
  68187. each$20(dependentModels.singleAxis, function (singleAxisModel) {
  68188. if (autoAxisIndex && singleAxisModel.get('orient', true) === orient) {
  68189. thisOption.singleAxisIndex = [singleAxisModel.componentIndex];
  68190. autoAxisIndex = false;
  68191. }
  68192. });
  68193. }
  68194. }
  68195. if (autoAxisIndex) {
  68196. // Find the first category axis as default. (consider polar)
  68197. eachAxisDim(function (dimNames) {
  68198. if (!autoAxisIndex) {
  68199. return;
  68200. }
  68201. var axisIndices = [];
  68202. var axisModels = this.dependentModels[dimNames.axis];
  68203. if (axisModels.length && !axisIndices.length) {
  68204. for (var i = 0, len = axisModels.length; i < len; i++) {
  68205. if (axisModels[i].get('type') === 'category') {
  68206. axisIndices.push(i);
  68207. }
  68208. }
  68209. }
  68210. thisOption[dimNames.axisIndex] = axisIndices;
  68211. if (axisIndices.length) {
  68212. autoAxisIndex = false;
  68213. }
  68214. }, this);
  68215. }
  68216. if (autoAxisIndex) {
  68217. // FIXME
  68218. // 这里是兼容ec2的写法(没指定xAxisIndex和yAxisIndex时把scatter和双数值轴折柱纳入dataZoom控制),
  68219. // 但是实际是否需要Grid.js#getScaleByOption来判断(考虑time,log等axis type)?
  68220. // If both dataZoom.xAxisIndex and dataZoom.yAxisIndex is not specified,
  68221. // dataZoom component auto adopts series that reference to
  68222. // both xAxis and yAxis which type is 'value'.
  68223. this.ecModel.eachSeries(function (seriesModel) {
  68224. if (this._isSeriesHasAllAxesTypeOf(seriesModel, 'value')) {
  68225. eachAxisDim(function (dimNames) {
  68226. var axisIndices = thisOption[dimNames.axisIndex];
  68227. var axisIndex = seriesModel.get(dimNames.axisIndex);
  68228. var axisId = seriesModel.get(dimNames.axisId);
  68229. var axisModel = seriesModel.ecModel.queryComponents({
  68230. mainType: dimNames.axis,
  68231. index: axisIndex,
  68232. id: axisId
  68233. })[0];
  68234. axisIndex = axisModel.componentIndex;
  68235. if (indexOf(axisIndices, axisIndex) < 0) {
  68236. axisIndices.push(axisIndex);
  68237. }
  68238. });
  68239. }
  68240. }, this);
  68241. }
  68242. },
  68243. /**
  68244. * @private
  68245. */
  68246. _autoSetOrient: function () {
  68247. var dim; // Find the first axis
  68248. this.eachTargetAxis(function (dimNames) {
  68249. !dim && (dim = dimNames.name);
  68250. }, this);
  68251. this.option.orient = dim === 'y' ? 'vertical' : 'horizontal';
  68252. },
  68253. /**
  68254. * @private
  68255. */
  68256. _isSeriesHasAllAxesTypeOf: function (seriesModel, axisType) {
  68257. // FIXME
  68258. // 需要series的xAxisIndex和yAxisIndex都首先自动设置上。
  68259. // 例如series.type === scatter时。
  68260. var is = true;
  68261. eachAxisDim(function (dimNames) {
  68262. var seriesAxisIndex = seriesModel.get(dimNames.axisIndex);
  68263. var axisModel = this.dependentModels[dimNames.axis][seriesAxisIndex];
  68264. if (!axisModel || axisModel.get('type') !== axisType) {
  68265. is = false;
  68266. }
  68267. }, this);
  68268. return is;
  68269. },
  68270. /**
  68271. * @private
  68272. */
  68273. _setDefaultThrottle: function (inputRawOption) {
  68274. // When first time user set throttle, auto throttle ends.
  68275. if (inputRawOption.hasOwnProperty('throttle')) {
  68276. this._autoThrottle = false;
  68277. }
  68278. if (this._autoThrottle) {
  68279. var globalOption = this.ecModel.option;
  68280. this.option.throttle = globalOption.animation && globalOption.animationDurationUpdate > 0 ? 100 : 20;
  68281. }
  68282. },
  68283. /**
  68284. * @public
  68285. */
  68286. getFirstTargetAxisModel: function () {
  68287. var firstAxisModel;
  68288. eachAxisDim(function (dimNames) {
  68289. if (firstAxisModel == null) {
  68290. var indices = this.get(dimNames.axisIndex);
  68291. if (indices.length) {
  68292. firstAxisModel = this.dependentModels[dimNames.axis][indices[0]];
  68293. }
  68294. }
  68295. }, this);
  68296. return firstAxisModel;
  68297. },
  68298. /**
  68299. * @public
  68300. * @param {Function} callback param: axisModel, dimNames, axisIndex, dataZoomModel, ecModel
  68301. */
  68302. eachTargetAxis: function (callback, context) {
  68303. var ecModel = this.ecModel;
  68304. eachAxisDim(function (dimNames) {
  68305. each$20(this.get(dimNames.axisIndex), function (axisIndex) {
  68306. callback.call(context, dimNames, axisIndex, this, ecModel);
  68307. }, this);
  68308. }, this);
  68309. },
  68310. /**
  68311. * @param {string} dimName
  68312. * @param {number} axisIndex
  68313. * @return {module:echarts/component/dataZoom/AxisProxy} If not found, return null/undefined.
  68314. */
  68315. getAxisProxy: function (dimName, axisIndex) {
  68316. return this._axisProxies[dimName + '_' + axisIndex];
  68317. },
  68318. /**
  68319. * @param {string} dimName
  68320. * @param {number} axisIndex
  68321. * @return {module:echarts/model/Model} If not found, return null/undefined.
  68322. */
  68323. getAxisModel: function (dimName, axisIndex) {
  68324. var axisProxy = this.getAxisProxy(dimName, axisIndex);
  68325. return axisProxy && axisProxy.getAxisModel();
  68326. },
  68327. /**
  68328. * If not specified, set to undefined.
  68329. *
  68330. * @public
  68331. * @param {Object} opt
  68332. * @param {number} [opt.start]
  68333. * @param {number} [opt.end]
  68334. * @param {number} [opt.startValue]
  68335. * @param {number} [opt.endValue]
  68336. */
  68337. setRawRange: function (opt) {
  68338. var thisOption = this.option;
  68339. var settledOption = this.settledOption;
  68340. each$20([['start', 'startValue'], ['end', 'endValue']], function (names) {
  68341. // Consider the pair <start, startValue>:
  68342. // If one has value and the other one is `null/undefined`, we both set them
  68343. // to `settledOption`. This strategy enables the feature to clear the original
  68344. // value in `settledOption` to `null/undefined`.
  68345. // But if both of them are `null/undefined`, we do not set them to `settledOption`
  68346. // and keep `settledOption` with the original value. This strategy enables users to
  68347. // only set <end or endValue> but not set <start or startValue> when calling
  68348. // `dispatchAction`.
  68349. // The pair <end, endValue> is treated in the same way.
  68350. if (opt[names[0]] != null || opt[names[1]] != null) {
  68351. thisOption[names[0]] = settledOption[names[0]] = opt[names[0]];
  68352. thisOption[names[1]] = settledOption[names[1]] = opt[names[1]];
  68353. }
  68354. }, this);
  68355. updateRangeUse(this, opt);
  68356. },
  68357. /**
  68358. * @public
  68359. * @param {Object} opt
  68360. * @param {number} [opt.start]
  68361. * @param {number} [opt.end]
  68362. * @param {number} [opt.startValue]
  68363. * @param {number} [opt.endValue]
  68364. */
  68365. setCalculatedRange: function (opt) {
  68366. var option = this.option;
  68367. each$20(['start', 'startValue', 'end', 'endValue'], function (name) {
  68368. option[name] = opt[name];
  68369. });
  68370. },
  68371. /**
  68372. * @public
  68373. * @return {Array.<number>} [startPercent, endPercent]
  68374. */
  68375. getPercentRange: function () {
  68376. var axisProxy = this.findRepresentativeAxisProxy();
  68377. if (axisProxy) {
  68378. return axisProxy.getDataPercentWindow();
  68379. }
  68380. },
  68381. /**
  68382. * @public
  68383. * For example, chart.getModel().getComponent('dataZoom').getValueRange('y', 0);
  68384. *
  68385. * @param {string} [axisDimName]
  68386. * @param {number} [axisIndex]
  68387. * @return {Array.<number>} [startValue, endValue] value can only be '-' or finite number.
  68388. */
  68389. getValueRange: function (axisDimName, axisIndex) {
  68390. if (axisDimName == null && axisIndex == null) {
  68391. var axisProxy = this.findRepresentativeAxisProxy();
  68392. if (axisProxy) {
  68393. return axisProxy.getDataValueWindow();
  68394. }
  68395. } else {
  68396. return this.getAxisProxy(axisDimName, axisIndex).getDataValueWindow();
  68397. }
  68398. },
  68399. /**
  68400. * @public
  68401. * @param {module:echarts/model/Model} [axisModel] If axisModel given, find axisProxy
  68402. * corresponding to the axisModel
  68403. * @return {module:echarts/component/dataZoom/AxisProxy}
  68404. */
  68405. findRepresentativeAxisProxy: function (axisModel) {
  68406. if (axisModel) {
  68407. return axisModel.__dzAxisProxy;
  68408. } // Find the first hosted axisProxy
  68409. var axisProxies = this._axisProxies;
  68410. for (var key in axisProxies) {
  68411. if (axisProxies.hasOwnProperty(key) && axisProxies[key].hostedBy(this)) {
  68412. return axisProxies[key];
  68413. }
  68414. } // If no hosted axis find not hosted axisProxy.
  68415. // Consider this case: dataZoomModel1 and dataZoomModel2 control the same axis,
  68416. // and the option.start or option.end settings are different. The percentRange
  68417. // should follow axisProxy.
  68418. // (We encounter this problem in toolbox data zoom.)
  68419. for (var key in axisProxies) {
  68420. if (axisProxies.hasOwnProperty(key) && !axisProxies[key].hostedBy(this)) {
  68421. return axisProxies[key];
  68422. }
  68423. }
  68424. },
  68425. /**
  68426. * @return {Array.<string>}
  68427. */
  68428. getRangePropMode: function () {
  68429. return this._rangePropMode.slice();
  68430. }
  68431. });
  68432. /**
  68433. * Retrieve the those raw params from option, which will be cached separately.
  68434. * becasue they will be overwritten by normalized/calculated values in the main
  68435. * process.
  68436. */
  68437. function retrieveRawOption(option) {
  68438. var ret = {};
  68439. each$20(['start', 'end', 'startValue', 'endValue', 'throttle'], function (name) {
  68440. option.hasOwnProperty(name) && (ret[name] = option[name]);
  68441. });
  68442. return ret;
  68443. }
  68444. function updateRangeUse(dataZoomModel, inputRawOption) {
  68445. var rangePropMode = dataZoomModel._rangePropMode;
  68446. var rangeModeInOption = dataZoomModel.get('rangeMode');
  68447. each$20([['start', 'startValue'], ['end', 'endValue']], function (names, index) {
  68448. var percentSpecified = inputRawOption[names[0]] != null;
  68449. var valueSpecified = inputRawOption[names[1]] != null;
  68450. if (percentSpecified && !valueSpecified) {
  68451. rangePropMode[index] = 'percent';
  68452. } else if (!percentSpecified && valueSpecified) {
  68453. rangePropMode[index] = 'value';
  68454. } else if (rangeModeInOption) {
  68455. rangePropMode[index] = rangeModeInOption[index];
  68456. } else if (percentSpecified) {
  68457. // percentSpecified && valueSpecified
  68458. rangePropMode[index] = 'percent';
  68459. } // else remain its original setting.
  68460. });
  68461. }
  68462. /*
  68463. * Licensed to the Apache Software Foundation (ASF) under one
  68464. * or more contributor license agreements. See the NOTICE file
  68465. * distributed with this work for additional information
  68466. * regarding copyright ownership. The ASF licenses this file
  68467. * to you under the Apache License, Version 2.0 (the
  68468. * "License"); you may not use this file except in compliance
  68469. * with the License. You may obtain a copy of the License at
  68470. *
  68471. * http://www.apache.org/licenses/LICENSE-2.0
  68472. *
  68473. * Unless required by applicable law or agreed to in writing,
  68474. * software distributed under the License is distributed on an
  68475. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68476. * KIND, either express or implied. See the License for the
  68477. * specific language governing permissions and limitations
  68478. * under the License.
  68479. */
  68480. var DataZoomView = Component$1.extend({
  68481. type: 'dataZoom',
  68482. render: function (dataZoomModel, ecModel, api, payload) {
  68483. this.dataZoomModel = dataZoomModel;
  68484. this.ecModel = ecModel;
  68485. this.api = api;
  68486. },
  68487. /**
  68488. * Find the first target coordinate system.
  68489. *
  68490. * @protected
  68491. * @return {Object} {
  68492. * grid: [
  68493. * {model: coord0, axisModels: [axis1, axis3], coordIndex: 1},
  68494. * {model: coord1, axisModels: [axis0, axis2], coordIndex: 0},
  68495. * ...
  68496. * ], // cartesians must not be null/undefined.
  68497. * polar: [
  68498. * {model: coord0, axisModels: [axis4], coordIndex: 0},
  68499. * ...
  68500. * ], // polars must not be null/undefined.
  68501. * singleAxis: [
  68502. * {model: coord0, axisModels: [], coordIndex: 0}
  68503. * ]
  68504. */
  68505. getTargetCoordInfo: function () {
  68506. var dataZoomModel = this.dataZoomModel;
  68507. var ecModel = this.ecModel;
  68508. var coordSysLists = {};
  68509. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  68510. var axisModel = ecModel.getComponent(dimNames.axis, axisIndex);
  68511. if (axisModel) {
  68512. var coordModel = axisModel.getCoordSysModel();
  68513. coordModel && save(coordModel, axisModel, coordSysLists[coordModel.mainType] || (coordSysLists[coordModel.mainType] = []), coordModel.componentIndex);
  68514. }
  68515. }, this);
  68516. function save(coordModel, axisModel, store, coordIndex) {
  68517. var item;
  68518. for (var i = 0; i < store.length; i++) {
  68519. if (store[i].model === coordModel) {
  68520. item = store[i];
  68521. break;
  68522. }
  68523. }
  68524. if (!item) {
  68525. store.push(item = {
  68526. model: coordModel,
  68527. axisModels: [],
  68528. coordIndex: coordIndex
  68529. });
  68530. }
  68531. item.axisModels.push(axisModel);
  68532. }
  68533. return coordSysLists;
  68534. }
  68535. });
  68536. /*
  68537. * Licensed to the Apache Software Foundation (ASF) under one
  68538. * or more contributor license agreements. See the NOTICE file
  68539. * distributed with this work for additional information
  68540. * regarding copyright ownership. The ASF licenses this file
  68541. * to you under the Apache License, Version 2.0 (the
  68542. * "License"); you may not use this file except in compliance
  68543. * with the License. You may obtain a copy of the License at
  68544. *
  68545. * http://www.apache.org/licenses/LICENSE-2.0
  68546. *
  68547. * Unless required by applicable law or agreed to in writing,
  68548. * software distributed under the License is distributed on an
  68549. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68550. * KIND, either express or implied. See the License for the
  68551. * specific language governing permissions and limitations
  68552. * under the License.
  68553. */
  68554. var SliderZoomModel = DataZoomModel.extend({
  68555. type: 'dataZoom.slider',
  68556. layoutMode: 'box',
  68557. /**
  68558. * @protected
  68559. */
  68560. defaultOption: {
  68561. show: true,
  68562. // ph => placeholder. Using placehoder here because
  68563. // deault value can only be drived in view stage.
  68564. right: 'ph',
  68565. // Default align to grid rect.
  68566. top: 'ph',
  68567. // Default align to grid rect.
  68568. width: 'ph',
  68569. // Default align to grid rect.
  68570. height: 'ph',
  68571. // Default align to grid rect.
  68572. left: null,
  68573. // Default align to grid rect.
  68574. bottom: null,
  68575. // Default align to grid rect.
  68576. backgroundColor: 'rgba(47,69,84,0)',
  68577. // Background of slider zoom component.
  68578. // dataBackgroundColor: '#ddd', // Background coor of data shadow and border of box,
  68579. // highest priority, remain for compatibility of
  68580. // previous version, but not recommended any more.
  68581. dataBackground: {
  68582. lineStyle: {
  68583. color: '#2f4554',
  68584. width: 0.5,
  68585. opacity: 0.3
  68586. },
  68587. areaStyle: {
  68588. color: 'rgba(47,69,84,0.3)',
  68589. opacity: 0.3
  68590. }
  68591. },
  68592. borderColor: '#ddd',
  68593. // border color of the box. For compatibility,
  68594. // if dataBackgroundColor is set, borderColor
  68595. // is ignored.
  68596. fillerColor: 'rgba(167,183,204,0.4)',
  68597. // Color of selected area.
  68598. // handleColor: 'rgba(89,170,216,0.95)', // Color of handle.
  68599. // 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',
  68600. /* eslint-disable */
  68601. 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',
  68602. /* eslint-enable */
  68603. // Percent of the slider height
  68604. handleSize: '100%',
  68605. handleStyle: {
  68606. color: '#a7b7cc'
  68607. },
  68608. labelPrecision: null,
  68609. labelFormatter: null,
  68610. showDetail: true,
  68611. showDataShadow: 'auto',
  68612. // Default auto decision.
  68613. realtime: true,
  68614. zoomLock: false,
  68615. // Whether disable zoom.
  68616. textStyle: {
  68617. color: '#333'
  68618. }
  68619. }
  68620. });
  68621. /*
  68622. * Licensed to the Apache Software Foundation (ASF) under one
  68623. * or more contributor license agreements. See the NOTICE file
  68624. * distributed with this work for additional information
  68625. * regarding copyright ownership. The ASF licenses this file
  68626. * to you under the Apache License, Version 2.0 (the
  68627. * "License"); you may not use this file except in compliance
  68628. * with the License. You may obtain a copy of the License at
  68629. *
  68630. * http://www.apache.org/licenses/LICENSE-2.0
  68631. *
  68632. * Unless required by applicable law or agreed to in writing,
  68633. * software distributed under the License is distributed on an
  68634. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  68635. * KIND, either express or implied. See the License for the
  68636. * specific language governing permissions and limitations
  68637. * under the License.
  68638. */
  68639. var Rect$2 = Rect;
  68640. var linearMap$1 = linearMap;
  68641. var asc$2 = asc;
  68642. var bind$5 = bind;
  68643. var each$22 = each$1; // Constants
  68644. var DEFAULT_LOCATION_EDGE_GAP = 7;
  68645. var DEFAULT_FRAME_BORDER_WIDTH = 1;
  68646. var DEFAULT_FILLER_SIZE = 30;
  68647. var HORIZONTAL = 'horizontal';
  68648. var VERTICAL = 'vertical';
  68649. var LABEL_GAP = 5;
  68650. var SHOW_DATA_SHADOW_SERIES_TYPE = ['line', 'bar', 'candlestick', 'scatter'];
  68651. var SliderZoomView = DataZoomView.extend({
  68652. type: 'dataZoom.slider',
  68653. init: function (ecModel, api) {
  68654. /**
  68655. * @private
  68656. * @type {Object}
  68657. */
  68658. this._displayables = {};
  68659. /**
  68660. * @private
  68661. * @type {string}
  68662. */
  68663. this._orient;
  68664. /**
  68665. * [0, 100]
  68666. * @private
  68667. */
  68668. this._range;
  68669. /**
  68670. * [coord of the first handle, coord of the second handle]
  68671. * @private
  68672. */
  68673. this._handleEnds;
  68674. /**
  68675. * [length, thick]
  68676. * @private
  68677. * @type {Array.<number>}
  68678. */
  68679. this._size;
  68680. /**
  68681. * @private
  68682. * @type {number}
  68683. */
  68684. this._handleWidth;
  68685. /**
  68686. * @private
  68687. * @type {number}
  68688. */
  68689. this._handleHeight;
  68690. /**
  68691. * @private
  68692. */
  68693. this._location;
  68694. /**
  68695. * @private
  68696. */
  68697. this._dragging;
  68698. /**
  68699. * @private
  68700. */
  68701. this._dataShadowInfo;
  68702. this.api = api;
  68703. },
  68704. /**
  68705. * @override
  68706. */
  68707. render: function (dataZoomModel, ecModel, api, payload) {
  68708. SliderZoomView.superApply(this, 'render', arguments);
  68709. createOrUpdate(this, '_dispatchZoomAction', this.dataZoomModel.get('throttle'), 'fixRate');
  68710. this._orient = dataZoomModel.get('orient');
  68711. if (this.dataZoomModel.get('show') === false) {
  68712. this.group.removeAll();
  68713. return;
  68714. } // Notice: this._resetInterval() should not be executed when payload.type
  68715. // is 'dataZoom', origin this._range should be maintained, otherwise 'pan'
  68716. // or 'zoom' info will be missed because of 'throttle' of this.dispatchAction,
  68717. if (!payload || payload.type !== 'dataZoom' || payload.from !== this.uid) {
  68718. this._buildView();
  68719. }
  68720. this._updateView();
  68721. },
  68722. /**
  68723. * @override
  68724. */
  68725. remove: function () {
  68726. SliderZoomView.superApply(this, 'remove', arguments);
  68727. clear(this, '_dispatchZoomAction');
  68728. },
  68729. /**
  68730. * @override
  68731. */
  68732. dispose: function () {
  68733. SliderZoomView.superApply(this, 'dispose', arguments);
  68734. clear(this, '_dispatchZoomAction');
  68735. },
  68736. _buildView: function () {
  68737. var thisGroup = this.group;
  68738. thisGroup.removeAll();
  68739. this._resetLocation();
  68740. this._resetInterval();
  68741. var barGroup = this._displayables.barGroup = new Group();
  68742. this._renderBackground();
  68743. this._renderHandle();
  68744. this._renderDataShadow();
  68745. thisGroup.add(barGroup);
  68746. this._positionGroup();
  68747. },
  68748. /**
  68749. * @private
  68750. */
  68751. _resetLocation: function () {
  68752. var dataZoomModel = this.dataZoomModel;
  68753. var api = this.api; // If some of x/y/width/height are not specified,
  68754. // auto-adapt according to target grid.
  68755. var coordRect = this._findCoordRect();
  68756. var ecSize = {
  68757. width: api.getWidth(),
  68758. height: api.getHeight()
  68759. }; // Default align by coordinate system rect.
  68760. var positionInfo = this._orient === HORIZONTAL ? {
  68761. // Why using 'right', because right should be used in vertical,
  68762. // and it is better to be consistent for dealing with position param merge.
  68763. right: ecSize.width - coordRect.x - coordRect.width,
  68764. top: ecSize.height - DEFAULT_FILLER_SIZE - DEFAULT_LOCATION_EDGE_GAP,
  68765. width: coordRect.width,
  68766. height: DEFAULT_FILLER_SIZE
  68767. } : {
  68768. // vertical
  68769. right: DEFAULT_LOCATION_EDGE_GAP,
  68770. top: coordRect.y,
  68771. width: DEFAULT_FILLER_SIZE,
  68772. height: coordRect.height
  68773. }; // Do not write back to option and replace value 'ph', because
  68774. // the 'ph' value should be recalculated when resize.
  68775. var layoutParams = getLayoutParams(dataZoomModel.option); // Replace the placeholder value.
  68776. each$1(['right', 'top', 'width', 'height'], function (name) {
  68777. if (layoutParams[name] === 'ph') {
  68778. layoutParams[name] = positionInfo[name];
  68779. }
  68780. });
  68781. var layoutRect = getLayoutRect(layoutParams, ecSize, dataZoomModel.padding);
  68782. this._location = {
  68783. x: layoutRect.x,
  68784. y: layoutRect.y
  68785. };
  68786. this._size = [layoutRect.width, layoutRect.height];
  68787. this._orient === VERTICAL && this._size.reverse();
  68788. },
  68789. /**
  68790. * @private
  68791. */
  68792. _positionGroup: function () {
  68793. var thisGroup = this.group;
  68794. var location = this._location;
  68795. var orient = this._orient; // Just use the first axis to determine mapping.
  68796. var targetAxisModel = this.dataZoomModel.getFirstTargetAxisModel();
  68797. var inverse = targetAxisModel && targetAxisModel.get('inverse');
  68798. var barGroup = this._displayables.barGroup;
  68799. var otherAxisInverse = (this._dataShadowInfo || {}).otherAxisInverse; // Transform barGroup.
  68800. barGroup.attr(orient === HORIZONTAL && !inverse ? {
  68801. scale: otherAxisInverse ? [1, 1] : [1, -1]
  68802. } : orient === HORIZONTAL && inverse ? {
  68803. scale: otherAxisInverse ? [-1, 1] : [-1, -1]
  68804. } : orient === VERTICAL && !inverse ? {
  68805. scale: otherAxisInverse ? [1, -1] : [1, 1],
  68806. rotation: Math.PI / 2 // Dont use Math.PI, considering shadow direction.
  68807. } : {
  68808. scale: otherAxisInverse ? [-1, -1] : [-1, 1],
  68809. rotation: Math.PI / 2
  68810. }); // Position barGroup
  68811. var rect = thisGroup.getBoundingRect([barGroup]);
  68812. thisGroup.attr('position', [location.x - rect.x, location.y - rect.y]);
  68813. },
  68814. /**
  68815. * @private
  68816. */
  68817. _getViewExtent: function () {
  68818. return [0, this._size[0]];
  68819. },
  68820. _renderBackground: function () {
  68821. var dataZoomModel = this.dataZoomModel;
  68822. var size = this._size;
  68823. var barGroup = this._displayables.barGroup;
  68824. barGroup.add(new Rect$2({
  68825. silent: true,
  68826. shape: {
  68827. x: 0,
  68828. y: 0,
  68829. width: size[0],
  68830. height: size[1]
  68831. },
  68832. style: {
  68833. fill: dataZoomModel.get('backgroundColor')
  68834. },
  68835. z2: -40
  68836. })); // Click panel, over shadow, below handles.
  68837. barGroup.add(new Rect$2({
  68838. shape: {
  68839. x: 0,
  68840. y: 0,
  68841. width: size[0],
  68842. height: size[1]
  68843. },
  68844. style: {
  68845. fill: 'transparent'
  68846. },
  68847. z2: 0,
  68848. onclick: bind(this._onClickPanelClick, this)
  68849. }));
  68850. },
  68851. _renderDataShadow: function () {
  68852. var info = this._dataShadowInfo = this._prepareDataShadowInfo();
  68853. if (!info) {
  68854. return;
  68855. }
  68856. var size = this._size;
  68857. var seriesModel = info.series;
  68858. var data = seriesModel.getRawData();
  68859. var otherDim = seriesModel.getShadowDim ? seriesModel.getShadowDim() // @see candlestick
  68860. : info.otherDim;
  68861. if (otherDim == null) {
  68862. return;
  68863. }
  68864. var otherDataExtent = data.getDataExtent(otherDim); // Nice extent.
  68865. var otherOffset = (otherDataExtent[1] - otherDataExtent[0]) * 0.3;
  68866. otherDataExtent = [otherDataExtent[0] - otherOffset, otherDataExtent[1] + otherOffset];
  68867. var otherShadowExtent = [0, size[1]];
  68868. var thisShadowExtent = [0, size[0]];
  68869. var areaPoints = [[size[0], 0], [0, 0]];
  68870. var linePoints = [];
  68871. var step = thisShadowExtent[1] / (data.count() - 1);
  68872. var thisCoord = 0; // Optimize for large data shadow
  68873. var stride = Math.round(data.count() / size[0]);
  68874. var lastIsEmpty;
  68875. data.each([otherDim], function (value, index) {
  68876. if (stride > 0 && index % stride) {
  68877. thisCoord += step;
  68878. return;
  68879. } // FIXME
  68880. // Should consider axis.min/axis.max when drawing dataShadow.
  68881. // FIXME
  68882. // 应该使用统一的空判断?还是在list里进行空判断?
  68883. var isEmpty = value == null || isNaN(value) || value === ''; // See #4235.
  68884. var otherCoord = isEmpty ? 0 : linearMap$1(value, otherDataExtent, otherShadowExtent, true); // Attempt to draw data shadow precisely when there are empty value.
  68885. if (isEmpty && !lastIsEmpty && index) {
  68886. areaPoints.push([areaPoints[areaPoints.length - 1][0], 0]);
  68887. linePoints.push([linePoints[linePoints.length - 1][0], 0]);
  68888. } else if (!isEmpty && lastIsEmpty) {
  68889. areaPoints.push([thisCoord, 0]);
  68890. linePoints.push([thisCoord, 0]);
  68891. }
  68892. areaPoints.push([thisCoord, otherCoord]);
  68893. linePoints.push([thisCoord, otherCoord]);
  68894. thisCoord += step;
  68895. lastIsEmpty = isEmpty;
  68896. });
  68897. var dataZoomModel = this.dataZoomModel; // var dataBackgroundModel = dataZoomModel.getModel('dataBackground');
  68898. this._displayables.barGroup.add(new Polygon({
  68899. shape: {
  68900. points: areaPoints
  68901. },
  68902. style: defaults({
  68903. fill: dataZoomModel.get('dataBackgroundColor')
  68904. }, dataZoomModel.getModel('dataBackground.areaStyle').getAreaStyle()),
  68905. silent: true,
  68906. z2: -20
  68907. }));
  68908. this._displayables.barGroup.add(new Polyline({
  68909. shape: {
  68910. points: linePoints
  68911. },
  68912. style: dataZoomModel.getModel('dataBackground.lineStyle').getLineStyle(),
  68913. silent: true,
  68914. z2: -19
  68915. }));
  68916. },
  68917. _prepareDataShadowInfo: function () {
  68918. var dataZoomModel = this.dataZoomModel;
  68919. var showDataShadow = dataZoomModel.get('showDataShadow');
  68920. if (showDataShadow === false) {
  68921. return;
  68922. } // Find a representative series.
  68923. var result;
  68924. var ecModel = this.ecModel;
  68925. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex) {
  68926. var seriesModels = dataZoomModel.getAxisProxy(dimNames.name, axisIndex).getTargetSeriesModels();
  68927. each$1(seriesModels, function (seriesModel) {
  68928. if (result) {
  68929. return;
  68930. }
  68931. if (showDataShadow !== true && indexOf(SHOW_DATA_SHADOW_SERIES_TYPE, seriesModel.get('type')) < 0) {
  68932. return;
  68933. }
  68934. var thisAxis = ecModel.getComponent(dimNames.axis, axisIndex).axis;
  68935. var otherDim = getOtherDim(dimNames.name);
  68936. var otherAxisInverse;
  68937. var coordSys = seriesModel.coordinateSystem;
  68938. if (otherDim != null && coordSys.getOtherAxis) {
  68939. otherAxisInverse = coordSys.getOtherAxis(thisAxis).inverse;
  68940. }
  68941. otherDim = seriesModel.getData().mapDimension(otherDim);
  68942. result = {
  68943. thisAxis: thisAxis,
  68944. series: seriesModel,
  68945. thisDim: dimNames.name,
  68946. otherDim: otherDim,
  68947. otherAxisInverse: otherAxisInverse
  68948. };
  68949. }, this);
  68950. }, this);
  68951. return result;
  68952. },
  68953. _renderHandle: function () {
  68954. var displaybles = this._displayables;
  68955. var handles = displaybles.handles = [];
  68956. var handleLabels = displaybles.handleLabels = [];
  68957. var barGroup = this._displayables.barGroup;
  68958. var size = this._size;
  68959. var dataZoomModel = this.dataZoomModel;
  68960. barGroup.add(displaybles.filler = new Rect$2({
  68961. draggable: true,
  68962. cursor: getCursor(this._orient),
  68963. drift: bind$5(this._onDragMove, this, 'all'),
  68964. ondragstart: bind$5(this._showDataInfo, this, true),
  68965. ondragend: bind$5(this._onDragEnd, this),
  68966. onmouseover: bind$5(this._showDataInfo, this, true),
  68967. onmouseout: bind$5(this._showDataInfo, this, false),
  68968. style: {
  68969. fill: dataZoomModel.get('fillerColor'),
  68970. textPosition: 'inside'
  68971. }
  68972. })); // Frame border.
  68973. barGroup.add(new Rect$2({
  68974. silent: true,
  68975. subPixelOptimize: true,
  68976. shape: {
  68977. x: 0,
  68978. y: 0,
  68979. width: size[0],
  68980. height: size[1]
  68981. },
  68982. style: {
  68983. stroke: dataZoomModel.get('dataBackgroundColor') || dataZoomModel.get('borderColor'),
  68984. lineWidth: DEFAULT_FRAME_BORDER_WIDTH,
  68985. fill: 'rgba(0,0,0,0)'
  68986. }
  68987. }));
  68988. each$22([0, 1], function (handleIndex) {
  68989. var path = createIcon(dataZoomModel.get('handleIcon'), {
  68990. cursor: getCursor(this._orient),
  68991. draggable: true,
  68992. drift: bind$5(this._onDragMove, this, handleIndex),
  68993. ondragend: bind$5(this._onDragEnd, this),
  68994. onmouseover: bind$5(this._showDataInfo, this, true),
  68995. onmouseout: bind$5(this._showDataInfo, this, false)
  68996. }, {
  68997. x: -1,
  68998. y: 0,
  68999. width: 2,
  69000. height: 2
  69001. });
  69002. var bRect = path.getBoundingRect();
  69003. this._handleHeight = parsePercent$1(dataZoomModel.get('handleSize'), this._size[1]);
  69004. this._handleWidth = bRect.width / bRect.height * this._handleHeight;
  69005. path.setStyle(dataZoomModel.getModel('handleStyle').getItemStyle());
  69006. var handleColor = dataZoomModel.get('handleColor'); // Compatitable with previous version
  69007. if (handleColor != null) {
  69008. path.style.fill = handleColor;
  69009. }
  69010. barGroup.add(handles[handleIndex] = path);
  69011. var textStyleModel = dataZoomModel.textStyleModel;
  69012. this.group.add(handleLabels[handleIndex] = new Text({
  69013. silent: true,
  69014. invisible: true,
  69015. style: {
  69016. x: 0,
  69017. y: 0,
  69018. text: '',
  69019. textVerticalAlign: 'middle',
  69020. textAlign: 'center',
  69021. textFill: textStyleModel.getTextColor(),
  69022. textFont: textStyleModel.getFont()
  69023. },
  69024. z2: 10
  69025. }));
  69026. }, this);
  69027. },
  69028. /**
  69029. * @private
  69030. */
  69031. _resetInterval: function () {
  69032. var range = this._range = this.dataZoomModel.getPercentRange();
  69033. var viewExtent = this._getViewExtent();
  69034. this._handleEnds = [linearMap$1(range[0], [0, 100], viewExtent, true), linearMap$1(range[1], [0, 100], viewExtent, true)];
  69035. },
  69036. /**
  69037. * @private
  69038. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  69039. * @param {number} delta
  69040. * @return {boolean} changed
  69041. */
  69042. _updateInterval: function (handleIndex, delta) {
  69043. var dataZoomModel = this.dataZoomModel;
  69044. var handleEnds = this._handleEnds;
  69045. var viewExtend = this._getViewExtent();
  69046. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  69047. var percentExtent = [0, 100];
  69048. sliderMove(delta, handleEnds, viewExtend, dataZoomModel.get('zoomLock') ? 'all' : handleIndex, minMaxSpan.minSpan != null ? linearMap$1(minMaxSpan.minSpan, percentExtent, viewExtend, true) : null, minMaxSpan.maxSpan != null ? linearMap$1(minMaxSpan.maxSpan, percentExtent, viewExtend, true) : null);
  69049. var lastRange = this._range;
  69050. var range = this._range = asc$2([linearMap$1(handleEnds[0], viewExtend, percentExtent, true), linearMap$1(handleEnds[1], viewExtend, percentExtent, true)]);
  69051. return !lastRange || lastRange[0] !== range[0] || lastRange[1] !== range[1];
  69052. },
  69053. /**
  69054. * @private
  69055. */
  69056. _updateView: function (nonRealtime) {
  69057. var displaybles = this._displayables;
  69058. var handleEnds = this._handleEnds;
  69059. var handleInterval = asc$2(handleEnds.slice());
  69060. var size = this._size;
  69061. each$22([0, 1], function (handleIndex) {
  69062. // Handles
  69063. var handle = displaybles.handles[handleIndex];
  69064. var handleHeight = this._handleHeight;
  69065. handle.attr({
  69066. scale: [handleHeight / 2, handleHeight / 2],
  69067. position: [handleEnds[handleIndex], size[1] / 2 - handleHeight / 2]
  69068. });
  69069. }, this); // Filler
  69070. displaybles.filler.setShape({
  69071. x: handleInterval[0],
  69072. y: 0,
  69073. width: handleInterval[1] - handleInterval[0],
  69074. height: size[1]
  69075. });
  69076. this._updateDataInfo(nonRealtime);
  69077. },
  69078. /**
  69079. * @private
  69080. */
  69081. _updateDataInfo: function (nonRealtime) {
  69082. var dataZoomModel = this.dataZoomModel;
  69083. var displaybles = this._displayables;
  69084. var handleLabels = displaybles.handleLabels;
  69085. var orient = this._orient;
  69086. var labelTexts = ['', '']; // FIXME
  69087. // date型,支持formatter,autoformatter(ec2 date.getAutoFormatter)
  69088. if (dataZoomModel.get('showDetail')) {
  69089. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  69090. if (axisProxy) {
  69091. var axis = axisProxy.getAxisModel().axis;
  69092. var range = this._range;
  69093. var dataInterval = nonRealtime // See #4434, data and axis are not processed and reset yet in non-realtime mode.
  69094. ? axisProxy.calculateDataWindow({
  69095. start: range[0],
  69096. end: range[1]
  69097. }).valueWindow : axisProxy.getDataValueWindow();
  69098. labelTexts = [this._formatLabel(dataInterval[0], axis), this._formatLabel(dataInterval[1], axis)];
  69099. }
  69100. }
  69101. var orderedHandleEnds = asc$2(this._handleEnds.slice());
  69102. setLabel.call(this, 0);
  69103. setLabel.call(this, 1);
  69104. function setLabel(handleIndex) {
  69105. // Label
  69106. // Text should not transform by barGroup.
  69107. // Ignore handlers transform
  69108. var barTransform = getTransform(displaybles.handles[handleIndex].parent, this.group);
  69109. var direction = transformDirection(handleIndex === 0 ? 'right' : 'left', barTransform);
  69110. var offset = this._handleWidth / 2 + LABEL_GAP;
  69111. var textPoint = applyTransform$1([orderedHandleEnds[handleIndex] + (handleIndex === 0 ? -offset : offset), this._size[1] / 2], barTransform);
  69112. handleLabels[handleIndex].setStyle({
  69113. x: textPoint[0],
  69114. y: textPoint[1],
  69115. textVerticalAlign: orient === HORIZONTAL ? 'middle' : direction,
  69116. textAlign: orient === HORIZONTAL ? direction : 'center',
  69117. text: labelTexts[handleIndex]
  69118. });
  69119. }
  69120. },
  69121. /**
  69122. * @private
  69123. */
  69124. _formatLabel: function (value, axis) {
  69125. var dataZoomModel = this.dataZoomModel;
  69126. var labelFormatter = dataZoomModel.get('labelFormatter');
  69127. var labelPrecision = dataZoomModel.get('labelPrecision');
  69128. if (labelPrecision == null || labelPrecision === 'auto') {
  69129. labelPrecision = axis.getPixelPrecision();
  69130. }
  69131. var valueStr = value == null || isNaN(value) ? '' // FIXME Glue code
  69132. : axis.type === 'category' || axis.type === 'time' ? axis.scale.getLabel(Math.round(value)) // param of toFixed should less then 20.
  69133. : value.toFixed(Math.min(labelPrecision, 20));
  69134. return isFunction$1(labelFormatter) ? labelFormatter(value, valueStr) : isString(labelFormatter) ? labelFormatter.replace('{value}', valueStr) : valueStr;
  69135. },
  69136. /**
  69137. * @private
  69138. * @param {boolean} showOrHide true: show, false: hide
  69139. */
  69140. _showDataInfo: function (showOrHide) {
  69141. // Always show when drgging.
  69142. showOrHide = this._dragging || showOrHide;
  69143. var handleLabels = this._displayables.handleLabels;
  69144. handleLabels[0].attr('invisible', !showOrHide);
  69145. handleLabels[1].attr('invisible', !showOrHide);
  69146. },
  69147. _onDragMove: function (handleIndex, dx, dy, event) {
  69148. this._dragging = true; // For mobile device, prevent screen slider on the button.
  69149. stop(event.event); // Transform dx, dy to bar coordination.
  69150. var barTransform = this._displayables.barGroup.getLocalTransform();
  69151. var vertex = applyTransform$1([dx, dy], barTransform, true);
  69152. var changed = this._updateInterval(handleIndex, vertex[0]);
  69153. var realtime = this.dataZoomModel.get('realtime');
  69154. this._updateView(!realtime); // Avoid dispatch dataZoom repeatly but range not changed,
  69155. // which cause bad visual effect when progressive enabled.
  69156. changed && realtime && this._dispatchZoomAction();
  69157. },
  69158. _onDragEnd: function () {
  69159. this._dragging = false;
  69160. this._showDataInfo(false); // While in realtime mode and stream mode, dispatch action when
  69161. // drag end will cause the whole view rerender, which is unnecessary.
  69162. var realtime = this.dataZoomModel.get('realtime');
  69163. !realtime && this._dispatchZoomAction();
  69164. },
  69165. _onClickPanelClick: function (e) {
  69166. var size = this._size;
  69167. var localPoint = this._displayables.barGroup.transformCoordToLocal(e.offsetX, e.offsetY);
  69168. if (localPoint[0] < 0 || localPoint[0] > size[0] || localPoint[1] < 0 || localPoint[1] > size[1]) {
  69169. return;
  69170. }
  69171. var handleEnds = this._handleEnds;
  69172. var center = (handleEnds[0] + handleEnds[1]) / 2;
  69173. var changed = this._updateInterval('all', localPoint[0] - center);
  69174. this._updateView();
  69175. changed && this._dispatchZoomAction();
  69176. },
  69177. /**
  69178. * This action will be throttled.
  69179. * @private
  69180. */
  69181. _dispatchZoomAction: function () {
  69182. var range = this._range;
  69183. this.api.dispatchAction({
  69184. type: 'dataZoom',
  69185. from: this.uid,
  69186. dataZoomId: this.dataZoomModel.id,
  69187. start: range[0],
  69188. end: range[1]
  69189. });
  69190. },
  69191. /**
  69192. * @private
  69193. */
  69194. _findCoordRect: function () {
  69195. // Find the grid coresponding to the first axis referred by dataZoom.
  69196. var rect;
  69197. each$22(this.getTargetCoordInfo(), function (coordInfoList) {
  69198. if (!rect && coordInfoList.length) {
  69199. var coordSys = coordInfoList[0].model.coordinateSystem;
  69200. rect = coordSys.getRect && coordSys.getRect();
  69201. }
  69202. });
  69203. if (!rect) {
  69204. var width = this.api.getWidth();
  69205. var height = this.api.getHeight();
  69206. rect = {
  69207. x: width * 0.2,
  69208. y: height * 0.2,
  69209. width: width * 0.6,
  69210. height: height * 0.6
  69211. };
  69212. }
  69213. return rect;
  69214. }
  69215. });
  69216. function getOtherDim(thisDim) {
  69217. // FIXME
  69218. // 这个逻辑和getOtherAxis里一致,但是写在这里是否不好
  69219. var map$$1 = {
  69220. x: 'y',
  69221. y: 'x',
  69222. radius: 'angle',
  69223. angle: 'radius'
  69224. };
  69225. return map$$1[thisDim];
  69226. }
  69227. function getCursor(orient) {
  69228. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  69229. }
  69230. /*
  69231. * Licensed to the Apache Software Foundation (ASF) under one
  69232. * or more contributor license agreements. See the NOTICE file
  69233. * distributed with this work for additional information
  69234. * regarding copyright ownership. The ASF licenses this file
  69235. * to you under the Apache License, Version 2.0 (the
  69236. * "License"); you may not use this file except in compliance
  69237. * with the License. You may obtain a copy of the License at
  69238. *
  69239. * http://www.apache.org/licenses/LICENSE-2.0
  69240. *
  69241. * Unless required by applicable law or agreed to in writing,
  69242. * software distributed under the License is distributed on an
  69243. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69244. * KIND, either express or implied. See the License for the
  69245. * specific language governing permissions and limitations
  69246. * under the License.
  69247. */
  69248. registerProcessor({
  69249. // `dataZoomProcessor` will only be performed in needed series. Consider if
  69250. // there is a line series and a pie series, it is better not to update the
  69251. // line series if only pie series is needed to be updated.
  69252. getTargetSeries: function (ecModel) {
  69253. var seriesModelMap = createHashMap();
  69254. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69255. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  69256. var axisProxy = dataZoomModel.getAxisProxy(dimNames.name, axisIndex);
  69257. each$1(axisProxy.getTargetSeriesModels(), function (seriesModel) {
  69258. seriesModelMap.set(seriesModel.uid, seriesModel);
  69259. });
  69260. });
  69261. });
  69262. return seriesModelMap;
  69263. },
  69264. modifyOutputEnd: true,
  69265. // Consider appendData, where filter should be performed. Because data process is
  69266. // in block mode currently, it is not need to worry about that the overallProgress
  69267. // execute every frame.
  69268. overallReset: function (ecModel, api) {
  69269. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69270. // We calculate window and reset axis here but not in model
  69271. // init stage and not after action dispatch handler, because
  69272. // reset should be called after seriesData.restoreData.
  69273. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  69274. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).reset(dataZoomModel, api);
  69275. }); // Caution: data zoom filtering is order sensitive when using
  69276. // percent range and no min/max/scale set on axis.
  69277. // For example, we have dataZoom definition:
  69278. // [
  69279. // {xAxisIndex: 0, start: 30, end: 70},
  69280. // {yAxisIndex: 0, start: 20, end: 80}
  69281. // ]
  69282. // In this case, [20, 80] of y-dataZoom should be based on data
  69283. // that have filtered by x-dataZoom using range of [30, 70],
  69284. // but should not be based on full raw data. Thus sliding
  69285. // x-dataZoom will change both ranges of xAxis and yAxis,
  69286. // while sliding y-dataZoom will only change the range of yAxis.
  69287. // So we should filter x-axis after reset x-axis immediately,
  69288. // and then reset y-axis and filter y-axis.
  69289. dataZoomModel.eachTargetAxis(function (dimNames, axisIndex, dataZoomModel) {
  69290. dataZoomModel.getAxisProxy(dimNames.name, axisIndex).filterData(dataZoomModel, api);
  69291. });
  69292. });
  69293. ecModel.eachComponent('dataZoom', function (dataZoomModel) {
  69294. // Fullfill all of the range props so that user
  69295. // is able to get them from chart.getOption().
  69296. var axisProxy = dataZoomModel.findRepresentativeAxisProxy();
  69297. var percentRange = axisProxy.getDataPercentWindow();
  69298. var valueRange = axisProxy.getDataValueWindow();
  69299. dataZoomModel.setCalculatedRange({
  69300. start: percentRange[0],
  69301. end: percentRange[1],
  69302. startValue: valueRange[0],
  69303. endValue: valueRange[1]
  69304. });
  69305. });
  69306. }
  69307. });
  69308. /*
  69309. * Licensed to the Apache Software Foundation (ASF) under one
  69310. * or more contributor license agreements. See the NOTICE file
  69311. * distributed with this work for additional information
  69312. * regarding copyright ownership. The ASF licenses this file
  69313. * to you under the Apache License, Version 2.0 (the
  69314. * "License"); you may not use this file except in compliance
  69315. * with the License. You may obtain a copy of the License at
  69316. *
  69317. * http://www.apache.org/licenses/LICENSE-2.0
  69318. *
  69319. * Unless required by applicable law or agreed to in writing,
  69320. * software distributed under the License is distributed on an
  69321. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69322. * KIND, either express or implied. See the License for the
  69323. * specific language governing permissions and limitations
  69324. * under the License.
  69325. */
  69326. registerAction('dataZoom', function (payload, ecModel) {
  69327. var linkedNodesFinder = createLinkedNodesFinder(bind(ecModel.eachComponent, ecModel, 'dataZoom'), eachAxisDim$1, function (model, dimNames) {
  69328. return model.get(dimNames.axisIndex);
  69329. });
  69330. var effectedModels = [];
  69331. ecModel.eachComponent({
  69332. mainType: 'dataZoom',
  69333. query: payload
  69334. }, function (model, index) {
  69335. effectedModels.push.apply(effectedModels, linkedNodesFinder(model).nodes);
  69336. });
  69337. each$1(effectedModels, function (dataZoomModel, index) {
  69338. dataZoomModel.setRawRange({
  69339. start: payload.start,
  69340. end: payload.end,
  69341. startValue: payload.startValue,
  69342. endValue: payload.endValue
  69343. });
  69344. });
  69345. });
  69346. /*
  69347. * Licensed to the Apache Software Foundation (ASF) under one
  69348. * or more contributor license agreements. See the NOTICE file
  69349. * distributed with this work for additional information
  69350. * regarding copyright ownership. The ASF licenses this file
  69351. * to you under the Apache License, Version 2.0 (the
  69352. * "License"); you may not use this file except in compliance
  69353. * with the License. You may obtain a copy of the License at
  69354. *
  69355. * http://www.apache.org/licenses/LICENSE-2.0
  69356. *
  69357. * Unless required by applicable law or agreed to in writing,
  69358. * software distributed under the License is distributed on an
  69359. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69360. * KIND, either express or implied. See the License for the
  69361. * specific language governing permissions and limitations
  69362. * under the License.
  69363. */
  69364. /*
  69365. * Licensed to the Apache Software Foundation (ASF) under one
  69366. * or more contributor license agreements. See the NOTICE file
  69367. * distributed with this work for additional information
  69368. * regarding copyright ownership. The ASF licenses this file
  69369. * to you under the Apache License, Version 2.0 (the
  69370. * "License"); you may not use this file except in compliance
  69371. * with the License. You may obtain a copy of the License at
  69372. *
  69373. * http://www.apache.org/licenses/LICENSE-2.0
  69374. *
  69375. * Unless required by applicable law or agreed to in writing,
  69376. * software distributed under the License is distributed on an
  69377. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69378. * KIND, either express or implied. See the License for the
  69379. * specific language governing permissions and limitations
  69380. * under the License.
  69381. */
  69382. DataZoomModel.extend({
  69383. type: 'dataZoom.inside',
  69384. /**
  69385. * @protected
  69386. */
  69387. defaultOption: {
  69388. disabled: false,
  69389. // Whether disable this inside zoom.
  69390. zoomLock: false,
  69391. // Whether disable zoom but only pan.
  69392. zoomOnMouseWheel: true,
  69393. // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  69394. moveOnMouseMove: true,
  69395. // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  69396. moveOnMouseWheel: false,
  69397. // Can be: true / false / 'shift' / 'ctrl' / 'alt'.
  69398. preventDefaultMouseMove: true
  69399. }
  69400. });
  69401. /*
  69402. * Licensed to the Apache Software Foundation (ASF) under one
  69403. * or more contributor license agreements. See the NOTICE file
  69404. * distributed with this work for additional information
  69405. * regarding copyright ownership. The ASF licenses this file
  69406. * to you under the Apache License, Version 2.0 (the
  69407. * "License"); you may not use this file except in compliance
  69408. * with the License. You may obtain a copy of the License at
  69409. *
  69410. * http://www.apache.org/licenses/LICENSE-2.0
  69411. *
  69412. * Unless required by applicable law or agreed to in writing,
  69413. * software distributed under the License is distributed on an
  69414. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69415. * KIND, either express or implied. See the License for the
  69416. * specific language governing permissions and limitations
  69417. * under the License.
  69418. */
  69419. // Only create one roam controller for each coordinate system.
  69420. // one roam controller might be refered by two inside data zoom
  69421. // components (for example, one for x and one for y). When user
  69422. // pan or zoom, only dispatch one action for those data zoom
  69423. // components.
  69424. var ATTR$1 = '\0_ec_dataZoom_roams';
  69425. /**
  69426. * @public
  69427. * @param {module:echarts/ExtensionAPI} api
  69428. * @param {Object} dataZoomInfo
  69429. * @param {string} dataZoomInfo.coordId
  69430. * @param {Function} dataZoomInfo.containsPoint
  69431. * @param {Array.<string>} dataZoomInfo.allCoordIds
  69432. * @param {string} dataZoomInfo.dataZoomId
  69433. * @param {Object} dataZoomInfo.getRange
  69434. * @param {Function} dataZoomInfo.getRange.pan
  69435. * @param {Function} dataZoomInfo.getRange.zoom
  69436. * @param {Function} dataZoomInfo.getRange.scrollMove
  69437. * @param {boolean} dataZoomInfo.dataZoomModel
  69438. */
  69439. function register$1(api, dataZoomInfo) {
  69440. var store = giveStore(api);
  69441. var theDataZoomId = dataZoomInfo.dataZoomId;
  69442. var theCoordId = dataZoomInfo.coordId; // Do clean when a dataZoom changes its target coordnate system.
  69443. // Avoid memory leak, dispose all not-used-registered.
  69444. each$1(store, function (record, coordId) {
  69445. var dataZoomInfos = record.dataZoomInfos;
  69446. if (dataZoomInfos[theDataZoomId] && indexOf(dataZoomInfo.allCoordIds, theCoordId) < 0) {
  69447. delete dataZoomInfos[theDataZoomId];
  69448. record.count--;
  69449. }
  69450. });
  69451. cleanStore(store);
  69452. var record = store[theCoordId]; // Create if needed.
  69453. if (!record) {
  69454. record = store[theCoordId] = {
  69455. coordId: theCoordId,
  69456. dataZoomInfos: {},
  69457. count: 0
  69458. };
  69459. record.controller = createController(api, record);
  69460. record.dispatchAction = curry(dispatchAction, api);
  69461. } // Update reference of dataZoom.
  69462. !record.dataZoomInfos[theDataZoomId] && record.count++;
  69463. record.dataZoomInfos[theDataZoomId] = dataZoomInfo;
  69464. var controllerParams = mergeControllerParams(record.dataZoomInfos);
  69465. record.controller.enable(controllerParams.controlType, controllerParams.opt); // Consider resize, area should be always updated.
  69466. record.controller.setPointerChecker(dataZoomInfo.containsPoint); // Update throttle.
  69467. createOrUpdate(record, 'dispatchAction', dataZoomInfo.dataZoomModel.get('throttle', true), 'fixRate');
  69468. }
  69469. /**
  69470. * @public
  69471. * @param {module:echarts/ExtensionAPI} api
  69472. * @param {string} dataZoomId
  69473. */
  69474. function unregister$1(api, dataZoomId) {
  69475. var store = giveStore(api);
  69476. each$1(store, function (record) {
  69477. record.controller.dispose();
  69478. var dataZoomInfos = record.dataZoomInfos;
  69479. if (dataZoomInfos[dataZoomId]) {
  69480. delete dataZoomInfos[dataZoomId];
  69481. record.count--;
  69482. }
  69483. });
  69484. cleanStore(store);
  69485. }
  69486. /**
  69487. * @public
  69488. */
  69489. function generateCoordId(coordModel) {
  69490. return coordModel.type + '\0_' + coordModel.id;
  69491. }
  69492. /**
  69493. * Key: coordId, value: {dataZoomInfos: [], count, controller}
  69494. * @type {Array.<Object>}
  69495. */
  69496. function giveStore(api) {
  69497. // Mount store on zrender instance, so that we do not
  69498. // need to worry about dispose.
  69499. var zr = api.getZr();
  69500. return zr[ATTR$1] || (zr[ATTR$1] = {});
  69501. }
  69502. function createController(api, newRecord) {
  69503. var controller = new RoamController(api.getZr());
  69504. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  69505. controller.on(eventName, function (event) {
  69506. var batch = [];
  69507. each$1(newRecord.dataZoomInfos, function (info) {
  69508. // Check whether the behaviors (zoomOnMouseWheel, moveOnMouseMove,
  69509. // moveOnMouseWheel, ...) enabled.
  69510. if (!event.isAvailableBehavior(info.dataZoomModel.option)) {
  69511. return;
  69512. }
  69513. var method = (info.getRange || {})[eventName];
  69514. var range = method && method(newRecord.controller, event);
  69515. !info.dataZoomModel.get('disabled', true) && range && batch.push({
  69516. dataZoomId: info.dataZoomId,
  69517. start: range[0],
  69518. end: range[1]
  69519. });
  69520. });
  69521. batch.length && newRecord.dispatchAction(batch);
  69522. });
  69523. });
  69524. return controller;
  69525. }
  69526. function cleanStore(store) {
  69527. each$1(store, function (record, coordId) {
  69528. if (!record.count) {
  69529. record.controller.dispose();
  69530. delete store[coordId];
  69531. }
  69532. });
  69533. }
  69534. /**
  69535. * This action will be throttled.
  69536. */
  69537. function dispatchAction(api, batch) {
  69538. api.dispatchAction({
  69539. type: 'dataZoom',
  69540. batch: batch
  69541. });
  69542. }
  69543. /**
  69544. * Merge roamController settings when multiple dataZooms share one roamController.
  69545. */
  69546. function mergeControllerParams(dataZoomInfos) {
  69547. var controlType; // DO NOT use reserved word (true, false, undefined) as key literally. Even if encapsulated
  69548. // as string, it is probably revert to reserved word by compress tool. See #7411.
  69549. var prefix = 'type_';
  69550. var typePriority = {
  69551. 'type_true': 2,
  69552. 'type_move': 1,
  69553. 'type_false': 0,
  69554. 'type_undefined': -1
  69555. };
  69556. var preventDefaultMouseMove = true;
  69557. each$1(dataZoomInfos, function (dataZoomInfo) {
  69558. var dataZoomModel = dataZoomInfo.dataZoomModel;
  69559. var oneType = dataZoomModel.get('disabled', true) ? false : dataZoomModel.get('zoomLock', true) ? 'move' : true;
  69560. if (typePriority[prefix + oneType] > typePriority[prefix + controlType]) {
  69561. controlType = oneType;
  69562. } // Prevent default move event by default. If one false, do not prevent. Otherwise
  69563. // users may be confused why it does not work when multiple insideZooms exist.
  69564. preventDefaultMouseMove &= dataZoomModel.get('preventDefaultMouseMove', true);
  69565. });
  69566. return {
  69567. controlType: controlType,
  69568. opt: {
  69569. // RoamController will enable all of these functionalities,
  69570. // and the final behavior is determined by its event listener
  69571. // provided by each inside zoom.
  69572. zoomOnMouseWheel: true,
  69573. moveOnMouseMove: true,
  69574. moveOnMouseWheel: true,
  69575. preventDefaultMouseMove: !!preventDefaultMouseMove
  69576. }
  69577. };
  69578. }
  69579. /*
  69580. * Licensed to the Apache Software Foundation (ASF) under one
  69581. * or more contributor license agreements. See the NOTICE file
  69582. * distributed with this work for additional information
  69583. * regarding copyright ownership. The ASF licenses this file
  69584. * to you under the Apache License, Version 2.0 (the
  69585. * "License"); you may not use this file except in compliance
  69586. * with the License. You may obtain a copy of the License at
  69587. *
  69588. * http://www.apache.org/licenses/LICENSE-2.0
  69589. *
  69590. * Unless required by applicable law or agreed to in writing,
  69591. * software distributed under the License is distributed on an
  69592. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69593. * KIND, either express or implied. See the License for the
  69594. * specific language governing permissions and limitations
  69595. * under the License.
  69596. */
  69597. var bind$6 = bind;
  69598. var InsideZoomView = DataZoomView.extend({
  69599. type: 'dataZoom.inside',
  69600. /**
  69601. * @override
  69602. */
  69603. init: function (ecModel, api) {
  69604. /**
  69605. * 'throttle' is used in this.dispatchAction, so we save range
  69606. * to avoid missing some 'pan' info.
  69607. * @private
  69608. * @type {Array.<number>}
  69609. */
  69610. this._range;
  69611. },
  69612. /**
  69613. * @override
  69614. */
  69615. render: function (dataZoomModel, ecModel, api, payload) {
  69616. InsideZoomView.superApply(this, 'render', arguments); // Hence the `throttle` util ensures to preserve command order,
  69617. // here simply updating range all the time will not cause missing
  69618. // any of the the roam change.
  69619. this._range = dataZoomModel.getPercentRange(); // Reset controllers.
  69620. each$1(this.getTargetCoordInfo(), function (coordInfoList, coordSysName) {
  69621. var allCoordIds = map(coordInfoList, function (coordInfo) {
  69622. return generateCoordId(coordInfo.model);
  69623. });
  69624. each$1(coordInfoList, function (coordInfo) {
  69625. var coordModel = coordInfo.model;
  69626. var getRange = {};
  69627. each$1(['pan', 'zoom', 'scrollMove'], function (eventName) {
  69628. getRange[eventName] = bind$6(roamHandlers[eventName], this, coordInfo, coordSysName);
  69629. }, this);
  69630. register$1(api, {
  69631. coordId: generateCoordId(coordModel),
  69632. allCoordIds: allCoordIds,
  69633. containsPoint: function (e, x, y) {
  69634. return coordModel.coordinateSystem.containPoint([x, y]);
  69635. },
  69636. dataZoomId: dataZoomModel.id,
  69637. dataZoomModel: dataZoomModel,
  69638. getRange: getRange
  69639. });
  69640. }, this);
  69641. }, this);
  69642. },
  69643. /**
  69644. * @override
  69645. */
  69646. dispose: function () {
  69647. unregister$1(this.api, this.dataZoomModel.id);
  69648. InsideZoomView.superApply(this, 'dispose', arguments);
  69649. this._range = null;
  69650. }
  69651. });
  69652. var roamHandlers = {
  69653. /**
  69654. * @this {module:echarts/component/dataZoom/InsideZoomView}
  69655. */
  69656. zoom: function (coordInfo, coordSysName, controller, e) {
  69657. var lastRange = this._range;
  69658. var range = lastRange.slice(); // Calculate transform by the first axis.
  69659. var axisModel = coordInfo.axisModels[0];
  69660. if (!axisModel) {
  69661. return;
  69662. }
  69663. var directionInfo = getDirectionInfo[coordSysName](null, [e.originX, e.originY], axisModel, controller, coordInfo);
  69664. var percentPoint = (directionInfo.signal > 0 ? directionInfo.pixelStart + directionInfo.pixelLength - directionInfo.pixel : directionInfo.pixel - directionInfo.pixelStart) / directionInfo.pixelLength * (range[1] - range[0]) + range[0];
  69665. var scale = Math.max(1 / e.scale, 0);
  69666. range[0] = (range[0] - percentPoint) * scale + percentPoint;
  69667. range[1] = (range[1] - percentPoint) * scale + percentPoint; // Restrict range.
  69668. var minMaxSpan = this.dataZoomModel.findRepresentativeAxisProxy().getMinMaxSpan();
  69669. sliderMove(0, range, [0, 100], 0, minMaxSpan.minSpan, minMaxSpan.maxSpan);
  69670. this._range = range;
  69671. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  69672. return range;
  69673. }
  69674. },
  69675. /**
  69676. * @this {module:echarts/component/dataZoom/InsideZoomView}
  69677. */
  69678. pan: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  69679. var directionInfo = getDirectionInfo[coordSysName]([e.oldX, e.oldY], [e.newX, e.newY], axisModel, controller, coordInfo);
  69680. return directionInfo.signal * (range[1] - range[0]) * directionInfo.pixel / directionInfo.pixelLength;
  69681. }),
  69682. /**
  69683. * @this {module:echarts/component/dataZoom/InsideZoomView}
  69684. */
  69685. scrollMove: makeMover(function (range, axisModel, coordInfo, coordSysName, controller, e) {
  69686. var directionInfo = getDirectionInfo[coordSysName]([0, 0], [e.scrollDelta, e.scrollDelta], axisModel, controller, coordInfo);
  69687. return directionInfo.signal * (range[1] - range[0]) * e.scrollDelta;
  69688. })
  69689. };
  69690. function makeMover(getPercentDelta) {
  69691. return function (coordInfo, coordSysName, controller, e) {
  69692. var lastRange = this._range;
  69693. var range = lastRange.slice(); // Calculate transform by the first axis.
  69694. var axisModel = coordInfo.axisModels[0];
  69695. if (!axisModel) {
  69696. return;
  69697. }
  69698. var percentDelta = getPercentDelta(range, axisModel, coordInfo, coordSysName, controller, e);
  69699. sliderMove(percentDelta, range, [0, 100], 'all');
  69700. this._range = range;
  69701. if (lastRange[0] !== range[0] || lastRange[1] !== range[1]) {
  69702. return range;
  69703. }
  69704. };
  69705. }
  69706. var getDirectionInfo = {
  69707. grid: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  69708. var axis = axisModel.axis;
  69709. var ret = {};
  69710. var rect = coordInfo.model.coordinateSystem.getRect();
  69711. oldPoint = oldPoint || [0, 0];
  69712. if (axis.dim === 'x') {
  69713. ret.pixel = newPoint[0] - oldPoint[0];
  69714. ret.pixelLength = rect.width;
  69715. ret.pixelStart = rect.x;
  69716. ret.signal = axis.inverse ? 1 : -1;
  69717. } else {
  69718. // axis.dim === 'y'
  69719. ret.pixel = newPoint[1] - oldPoint[1];
  69720. ret.pixelLength = rect.height;
  69721. ret.pixelStart = rect.y;
  69722. ret.signal = axis.inverse ? -1 : 1;
  69723. }
  69724. return ret;
  69725. },
  69726. polar: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  69727. var axis = axisModel.axis;
  69728. var ret = {};
  69729. var polar = coordInfo.model.coordinateSystem;
  69730. var radiusExtent = polar.getRadiusAxis().getExtent();
  69731. var angleExtent = polar.getAngleAxis().getExtent();
  69732. oldPoint = oldPoint ? polar.pointToCoord(oldPoint) : [0, 0];
  69733. newPoint = polar.pointToCoord(newPoint);
  69734. if (axisModel.mainType === 'radiusAxis') {
  69735. ret.pixel = newPoint[0] - oldPoint[0]; // ret.pixelLength = Math.abs(radiusExtent[1] - radiusExtent[0]);
  69736. // ret.pixelStart = Math.min(radiusExtent[0], radiusExtent[1]);
  69737. ret.pixelLength = radiusExtent[1] - radiusExtent[0];
  69738. ret.pixelStart = radiusExtent[0];
  69739. ret.signal = axis.inverse ? 1 : -1;
  69740. } else {
  69741. // 'angleAxis'
  69742. ret.pixel = newPoint[1] - oldPoint[1]; // ret.pixelLength = Math.abs(angleExtent[1] - angleExtent[0]);
  69743. // ret.pixelStart = Math.min(angleExtent[0], angleExtent[1]);
  69744. ret.pixelLength = angleExtent[1] - angleExtent[0];
  69745. ret.pixelStart = angleExtent[0];
  69746. ret.signal = axis.inverse ? -1 : 1;
  69747. }
  69748. return ret;
  69749. },
  69750. singleAxis: function (oldPoint, newPoint, axisModel, controller, coordInfo) {
  69751. var axis = axisModel.axis;
  69752. var rect = coordInfo.model.coordinateSystem.getRect();
  69753. var ret = {};
  69754. oldPoint = oldPoint || [0, 0];
  69755. if (axis.orient === 'horizontal') {
  69756. ret.pixel = newPoint[0] - oldPoint[0];
  69757. ret.pixelLength = rect.width;
  69758. ret.pixelStart = rect.x;
  69759. ret.signal = axis.inverse ? 1 : -1;
  69760. } else {
  69761. // 'vertical'
  69762. ret.pixel = newPoint[1] - oldPoint[1];
  69763. ret.pixelLength = rect.height;
  69764. ret.pixelStart = rect.y;
  69765. ret.signal = axis.inverse ? -1 : 1;
  69766. }
  69767. return ret;
  69768. }
  69769. };
  69770. /*
  69771. * Licensed to the Apache Software Foundation (ASF) under one
  69772. * or more contributor license agreements. See the NOTICE file
  69773. * distributed with this work for additional information
  69774. * regarding copyright ownership. The ASF licenses this file
  69775. * to you under the Apache License, Version 2.0 (the
  69776. * "License"); you may not use this file except in compliance
  69777. * with the License. You may obtain a copy of the License at
  69778. *
  69779. * http://www.apache.org/licenses/LICENSE-2.0
  69780. *
  69781. * Unless required by applicable law or agreed to in writing,
  69782. * software distributed under the License is distributed on an
  69783. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69784. * KIND, either express or implied. See the License for the
  69785. * specific language governing permissions and limitations
  69786. * under the License.
  69787. */
  69788. /*
  69789. * Licensed to the Apache Software Foundation (ASF) under one
  69790. * or more contributor license agreements. See the NOTICE file
  69791. * distributed with this work for additional information
  69792. * regarding copyright ownership. The ASF licenses this file
  69793. * to you under the Apache License, Version 2.0 (the
  69794. * "License"); you may not use this file except in compliance
  69795. * with the License. You may obtain a copy of the License at
  69796. *
  69797. * http://www.apache.org/licenses/LICENSE-2.0
  69798. *
  69799. * Unless required by applicable law or agreed to in writing,
  69800. * software distributed under the License is distributed on an
  69801. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69802. * KIND, either express or implied. See the License for the
  69803. * specific language governing permissions and limitations
  69804. * under the License.
  69805. */
  69806. // Do not include './dataZoomSelect',
  69807. // since it only work for toolbox dataZoom.
  69808. /*
  69809. * Licensed to the Apache Software Foundation (ASF) under one
  69810. * or more contributor license agreements. See the NOTICE file
  69811. * distributed with this work for additional information
  69812. * regarding copyright ownership. The ASF licenses this file
  69813. * to you under the Apache License, Version 2.0 (the
  69814. * "License"); you may not use this file except in compliance
  69815. * with the License. You may obtain a copy of the License at
  69816. *
  69817. * http://www.apache.org/licenses/LICENSE-2.0
  69818. *
  69819. * Unless required by applicable law or agreed to in writing,
  69820. * software distributed under the License is distributed on an
  69821. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69822. * KIND, either express or implied. See the License for the
  69823. * specific language governing permissions and limitations
  69824. * under the License.
  69825. */
  69826. var DEFAULT_TOOLBOX_BTNS = ['rect', 'polygon', 'keep', 'clear'];
  69827. var preprocessor$2 = function (option, isNew) {
  69828. var brushComponents = option && option.brush;
  69829. if (!isArray(brushComponents)) {
  69830. brushComponents = brushComponents ? [brushComponents] : [];
  69831. }
  69832. if (!brushComponents.length) {
  69833. return;
  69834. }
  69835. var brushComponentSpecifiedBtns = [];
  69836. each$1(brushComponents, function (brushOpt) {
  69837. var tbs = brushOpt.hasOwnProperty('toolbox') ? brushOpt.toolbox : [];
  69838. if (tbs instanceof Array) {
  69839. brushComponentSpecifiedBtns = brushComponentSpecifiedBtns.concat(tbs);
  69840. }
  69841. });
  69842. var toolbox = option && option.toolbox;
  69843. if (isArray(toolbox)) {
  69844. toolbox = toolbox[0];
  69845. }
  69846. if (!toolbox) {
  69847. toolbox = {
  69848. feature: {}
  69849. };
  69850. option.toolbox = [toolbox];
  69851. }
  69852. var toolboxFeature = toolbox.feature || (toolbox.feature = {});
  69853. var toolboxBrush = toolboxFeature.brush || (toolboxFeature.brush = {});
  69854. var brushTypes = toolboxBrush.type || (toolboxBrush.type = []);
  69855. brushTypes.push.apply(brushTypes, brushComponentSpecifiedBtns);
  69856. removeDuplicate(brushTypes);
  69857. if (isNew && !brushTypes.length) {
  69858. brushTypes.push.apply(brushTypes, DEFAULT_TOOLBOX_BTNS);
  69859. }
  69860. };
  69861. function removeDuplicate(arr) {
  69862. var map$$1 = {};
  69863. each$1(arr, function (val) {
  69864. map$$1[val] = 1;
  69865. });
  69866. arr.length = 0;
  69867. each$1(map$$1, function (flag, val) {
  69868. arr.push(val);
  69869. });
  69870. }
  69871. /*
  69872. * Licensed to the Apache Software Foundation (ASF) under one
  69873. * or more contributor license agreements. See the NOTICE file
  69874. * distributed with this work for additional information
  69875. * regarding copyright ownership. The ASF licenses this file
  69876. * to you under the Apache License, Version 2.0 (the
  69877. * "License"); you may not use this file except in compliance
  69878. * with the License. You may obtain a copy of the License at
  69879. *
  69880. * http://www.apache.org/licenses/LICENSE-2.0
  69881. *
  69882. * Unless required by applicable law or agreed to in writing,
  69883. * software distributed under the License is distributed on an
  69884. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  69885. * KIND, either express or implied. See the License for the
  69886. * specific language governing permissions and limitations
  69887. * under the License.
  69888. */
  69889. /**
  69890. * @file Visual solution, for consistent option specification.
  69891. */
  69892. var each$23 = each$1;
  69893. function hasKeys(obj) {
  69894. if (obj) {
  69895. for (var name in obj) {
  69896. if (obj.hasOwnProperty(name)) {
  69897. return true;
  69898. }
  69899. }
  69900. }
  69901. }
  69902. /**
  69903. * @param {Object} option
  69904. * @param {Array.<string>} stateList
  69905. * @param {Function} [supplementVisualOption]
  69906. * @return {Object} visualMappings <state, <visualType, module:echarts/visual/VisualMapping>>
  69907. */
  69908. function createVisualMappings(option, stateList, supplementVisualOption) {
  69909. var visualMappings = {};
  69910. each$23(stateList, function (state) {
  69911. var mappings = visualMappings[state] = createMappings();
  69912. each$23(option[state], function (visualData, visualType) {
  69913. if (!VisualMapping.isValidType(visualType)) {
  69914. return;
  69915. }
  69916. var mappingOption = {
  69917. type: visualType,
  69918. visual: visualData
  69919. };
  69920. supplementVisualOption && supplementVisualOption(mappingOption, state);
  69921. mappings[visualType] = new VisualMapping(mappingOption); // Prepare a alpha for opacity, for some case that opacity
  69922. // is not supported, such as rendering using gradient color.
  69923. if (visualType === 'opacity') {
  69924. mappingOption = clone(mappingOption);
  69925. mappingOption.type = 'colorAlpha';
  69926. mappings.__hidden.__alphaForOpacity = new VisualMapping(mappingOption);
  69927. }
  69928. });
  69929. });
  69930. return visualMappings;
  69931. function createMappings() {
  69932. var Creater = function () {}; // Make sure hidden fields will not be visited by
  69933. // object iteration (with hasOwnProperty checking).
  69934. Creater.prototype.__hidden = Creater.prototype;
  69935. var obj = new Creater();
  69936. return obj;
  69937. }
  69938. }
  69939. /**
  69940. * @param {Object} thisOption
  69941. * @param {Object} newOption
  69942. * @param {Array.<string>} keys
  69943. */
  69944. function replaceVisualOption(thisOption, newOption, keys) {
  69945. // Visual attributes merge is not supported, otherwise it
  69946. // brings overcomplicated merge logic. See #2853. So if
  69947. // newOption has anyone of these keys, all of these keys
  69948. // will be reset. Otherwise, all keys remain.
  69949. var has;
  69950. each$1(keys, function (key) {
  69951. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  69952. has = true;
  69953. }
  69954. });
  69955. has && each$1(keys, function (key) {
  69956. if (newOption.hasOwnProperty(key) && hasKeys(newOption[key])) {
  69957. thisOption[key] = clone(newOption[key]);
  69958. } else {
  69959. delete thisOption[key];
  69960. }
  69961. });
  69962. }
  69963. /**
  69964. * @param {Array.<string>} stateList
  69965. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  69966. * @param {module:echarts/data/List} list
  69967. * @param {Function} getValueState param: valueOrIndex, return: state.
  69968. * @param {object} [scope] Scope for getValueState
  69969. * @param {string} [dimension] Concrete dimension, if used.
  69970. */
  69971. // ???! handle brush?
  69972. function applyVisual(stateList, visualMappings, data, getValueState, scope, dimension) {
  69973. var visualTypesMap = {};
  69974. each$1(stateList, function (state) {
  69975. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  69976. visualTypesMap[state] = visualTypes;
  69977. });
  69978. var dataIndex;
  69979. function getVisual(key) {
  69980. return data.getItemVisual(dataIndex, key);
  69981. }
  69982. function setVisual(key, value) {
  69983. data.setItemVisual(dataIndex, key, value);
  69984. }
  69985. if (dimension == null) {
  69986. data.each(eachItem);
  69987. } else {
  69988. data.each([dimension], eachItem);
  69989. }
  69990. function eachItem(valueOrIndex, index) {
  69991. dataIndex = dimension == null ? valueOrIndex : index;
  69992. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  69993. if (rawDataItem && rawDataItem.visualMap === false) {
  69994. return;
  69995. }
  69996. var valueState = getValueState.call(scope, valueOrIndex);
  69997. var mappings = visualMappings[valueState];
  69998. var visualTypes = visualTypesMap[valueState];
  69999. for (var i = 0, len = visualTypes.length; i < len; i++) {
  70000. var type = visualTypes[i];
  70001. mappings[type] && mappings[type].applyVisual(valueOrIndex, getVisual, setVisual);
  70002. }
  70003. }
  70004. }
  70005. /**
  70006. * @param {module:echarts/data/List} data
  70007. * @param {Array.<string>} stateList
  70008. * @param {Object} visualMappings <state, Object.<visualType, module:echarts/visual/VisualMapping>>
  70009. * @param {Function} getValueState param: valueOrIndex, return: state.
  70010. * @param {number} [dim] dimension or dimension index.
  70011. */
  70012. function incrementalApplyVisual(stateList, visualMappings, getValueState, dim) {
  70013. var visualTypesMap = {};
  70014. each$1(stateList, function (state) {
  70015. var visualTypes = VisualMapping.prepareVisualTypes(visualMappings[state]);
  70016. visualTypesMap[state] = visualTypes;
  70017. });
  70018. function progress(params, data) {
  70019. if (dim != null) {
  70020. dim = data.getDimension(dim);
  70021. }
  70022. function getVisual(key) {
  70023. return data.getItemVisual(dataIndex, key);
  70024. }
  70025. function setVisual(key, value) {
  70026. data.setItemVisual(dataIndex, key, value);
  70027. }
  70028. var dataIndex;
  70029. while ((dataIndex = params.next()) != null) {
  70030. var rawDataItem = data.getRawDataItem(dataIndex); // Consider performance
  70031. if (rawDataItem && rawDataItem.visualMap === false) {
  70032. continue;
  70033. }
  70034. var value = dim != null ? data.get(dim, dataIndex, true) : dataIndex;
  70035. var valueState = getValueState(value);
  70036. var mappings = visualMappings[valueState];
  70037. var visualTypes = visualTypesMap[valueState];
  70038. for (var i = 0, len = visualTypes.length; i < len; i++) {
  70039. var type = visualTypes[i];
  70040. mappings[type] && mappings[type].applyVisual(value, getVisual, setVisual);
  70041. }
  70042. }
  70043. }
  70044. return {
  70045. progress: progress
  70046. };
  70047. }
  70048. /*
  70049. * Licensed to the Apache Software Foundation (ASF) under one
  70050. * or more contributor license agreements. See the NOTICE file
  70051. * distributed with this work for additional information
  70052. * regarding copyright ownership. The ASF licenses this file
  70053. * to you under the Apache License, Version 2.0 (the
  70054. * "License"); you may not use this file except in compliance
  70055. * with the License. You may obtain a copy of the License at
  70056. *
  70057. * http://www.apache.org/licenses/LICENSE-2.0
  70058. *
  70059. * Unless required by applicable law or agreed to in writing,
  70060. * software distributed under the License is distributed on an
  70061. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70062. * KIND, either express or implied. See the License for the
  70063. * specific language governing permissions and limitations
  70064. * under the License.
  70065. */
  70066. // Key of the second level is chart element type: `point`, `rect`.
  70067. // See moudule:echarts/component/helper/BrushController
  70068. // function param:
  70069. // {Object} itemLayout fetch from data.getItemLayout(dataIndex)
  70070. // {Object} selectors {point: selector, rect: selector, ...}
  70071. // {Object} area {range: [[], [], ..], boudingRect}
  70072. // function return:
  70073. // {boolean} Whether in the given brush.
  70074. var selector = {
  70075. lineX: getLineSelectors(0),
  70076. lineY: getLineSelectors(1),
  70077. rect: {
  70078. point: function (itemLayout, selectors, area) {
  70079. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]);
  70080. },
  70081. rect: function (itemLayout, selectors, area) {
  70082. return itemLayout && area.boundingRect.intersect(itemLayout);
  70083. }
  70084. },
  70085. polygon: {
  70086. point: function (itemLayout, selectors, area) {
  70087. return itemLayout && area.boundingRect.contain(itemLayout[0], itemLayout[1]) && contain$1(area.range, itemLayout[0], itemLayout[1]);
  70088. },
  70089. rect: function (itemLayout, selectors, area) {
  70090. var points = area.range;
  70091. if (!itemLayout || points.length <= 1) {
  70092. return false;
  70093. }
  70094. var x = itemLayout.x;
  70095. var y = itemLayout.y;
  70096. var width = itemLayout.width;
  70097. var height = itemLayout.height;
  70098. var p = points[0];
  70099. if (contain$1(points, x, y) || contain$1(points, x + width, y) || contain$1(points, x, y + height) || contain$1(points, x + width, y + height) || BoundingRect.create(itemLayout).contain(p[0], p[1]) || linePolygonIntersect(x, y, x + width, y, points) || linePolygonIntersect(x, y, x, y + height, points) || linePolygonIntersect(x + width, y, x + width, y + height, points) || linePolygonIntersect(x, y + height, x + width, y + height, points)) {
  70100. return true;
  70101. }
  70102. }
  70103. }
  70104. };
  70105. function getLineSelectors(xyIndex) {
  70106. var xy = ['x', 'y'];
  70107. var wh = ['width', 'height'];
  70108. return {
  70109. point: function (itemLayout, selectors, area) {
  70110. if (itemLayout) {
  70111. var range = area.range;
  70112. var p = itemLayout[xyIndex];
  70113. return inLineRange(p, range);
  70114. }
  70115. },
  70116. rect: function (itemLayout, selectors, area) {
  70117. if (itemLayout) {
  70118. var range = area.range;
  70119. var layoutRange = [itemLayout[xy[xyIndex]], itemLayout[xy[xyIndex]] + itemLayout[wh[xyIndex]]];
  70120. layoutRange[1] < layoutRange[0] && layoutRange.reverse();
  70121. return inLineRange(layoutRange[0], range) || inLineRange(layoutRange[1], range) || inLineRange(range[0], layoutRange) || inLineRange(range[1], layoutRange);
  70122. }
  70123. }
  70124. };
  70125. }
  70126. function inLineRange(p, range) {
  70127. return range[0] <= p && p <= range[1];
  70128. }
  70129. /*
  70130. * Licensed to the Apache Software Foundation (ASF) under one
  70131. * or more contributor license agreements. See the NOTICE file
  70132. * distributed with this work for additional information
  70133. * regarding copyright ownership. The ASF licenses this file
  70134. * to you under the Apache License, Version 2.0 (the
  70135. * "License"); you may not use this file except in compliance
  70136. * with the License. You may obtain a copy of the License at
  70137. *
  70138. * http://www.apache.org/licenses/LICENSE-2.0
  70139. *
  70140. * Unless required by applicable law or agreed to in writing,
  70141. * software distributed under the License is distributed on an
  70142. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70143. * KIND, either express or implied. See the License for the
  70144. * specific language governing permissions and limitations
  70145. * under the License.
  70146. */
  70147. var each$24 = each$1;
  70148. var indexOf$2 = indexOf;
  70149. var curry$6 = curry;
  70150. var COORD_CONVERTS = ['dataToPoint', 'pointToData']; // FIXME
  70151. // how to genarialize to more coordinate systems.
  70152. var INCLUDE_FINDER_MAIN_TYPES = ['grid', 'xAxis', 'yAxis', 'geo', 'graph', 'polar', 'radiusAxis', 'angleAxis', 'bmap'];
  70153. /**
  70154. * [option in constructor]:
  70155. * {
  70156. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  70157. * }
  70158. *
  70159. *
  70160. * [targetInfo]:
  70161. *
  70162. * There can be multiple axes in a single targetInfo. Consider the case
  70163. * of `grid` component, a targetInfo represents a grid which contains one or more
  70164. * cartesian and one or more axes. And consider the case of parallel system,
  70165. * which has multiple axes in a coordinate system.
  70166. * Can be {
  70167. * panelId: ...,
  70168. * coordSys: <a representitive cartesian in grid (first cartesian by default)>,
  70169. * coordSyses: all cartesians.
  70170. * gridModel: <grid component>
  70171. * xAxes: correspond to coordSyses on index
  70172. * yAxes: correspond to coordSyses on index
  70173. * }
  70174. * or {
  70175. * panelId: ...,
  70176. * coordSys: <geo coord sys>
  70177. * coordSyses: [<geo coord sys>]
  70178. * geoModel: <geo component>
  70179. * }
  70180. *
  70181. *
  70182. * [panelOpt]:
  70183. *
  70184. * Make from targetInfo. Input to BrushController.
  70185. * {
  70186. * panelId: ...,
  70187. * rect: ...
  70188. * }
  70189. *
  70190. *
  70191. * [area]:
  70192. *
  70193. * Generated by BrushController or user input.
  70194. * {
  70195. * panelId: Used to locate coordInfo directly. If user inpput, no panelId.
  70196. * brushType: determine how to convert to/from coord('rect' or 'polygon' or 'lineX/Y').
  70197. * Index/Id/Name of geo, xAxis, yAxis, grid: See util/model#parseFinder.
  70198. * range: pixel range.
  70199. * coordRange: representitive coord range (the first one of coordRanges).
  70200. * coordRanges: <Array> coord ranges, used in multiple cartesian in one grid.
  70201. * }
  70202. */
  70203. /**
  70204. * @param {Object} option contains Index/Id/Name of xAxis/yAxis/geo/grid
  70205. * Each can be {number|Array.<number>}. like: {xAxisIndex: [3, 4]}
  70206. * @param {module:echarts/model/Global} ecModel
  70207. * @param {Object} [opt]
  70208. * @param {Array.<string>} [opt.include] include coordinate system types.
  70209. */
  70210. function BrushTargetManager(option, ecModel, opt) {
  70211. /**
  70212. * @private
  70213. * @type {Array.<Object>}
  70214. */
  70215. var targetInfoList = this._targetInfoList = [];
  70216. var info = {};
  70217. var foundCpts = parseFinder$1(ecModel, option);
  70218. each$24(targetInfoBuilders, function (builder, type) {
  70219. if (!opt || !opt.include || indexOf$2(opt.include, type) >= 0) {
  70220. builder(foundCpts, targetInfoList, info);
  70221. }
  70222. });
  70223. }
  70224. var proto$2 = BrushTargetManager.prototype;
  70225. proto$2.setOutputRanges = function (areas, ecModel) {
  70226. this.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  70227. (area.coordRanges || (area.coordRanges = [])).push(coordRange); // area.coordRange is the first of area.coordRanges
  70228. if (!area.coordRange) {
  70229. area.coordRange = coordRange; // In 'category' axis, coord to pixel is not reversible, so we can not
  70230. // rebuild range by coordRange accrately, which may bring trouble when
  70231. // brushing only one item. So we use __rangeOffset to rebuilding range
  70232. // by coordRange. And this it only used in brush component so it is no
  70233. // need to be adapted to coordRanges.
  70234. var result = coordConvert[area.brushType](0, coordSys, coordRange);
  70235. area.__rangeOffset = {
  70236. offset: diffProcessor[area.brushType](result.values, area.range, [1, 1]),
  70237. xyMinMax: result.xyMinMax
  70238. };
  70239. }
  70240. });
  70241. };
  70242. proto$2.matchOutputRanges = function (areas, ecModel, cb) {
  70243. each$24(areas, function (area) {
  70244. var targetInfo = this.findTargetInfo(area, ecModel);
  70245. if (targetInfo && targetInfo !== true) {
  70246. each$1(targetInfo.coordSyses, function (coordSys) {
  70247. var result = coordConvert[area.brushType](1, coordSys, area.range);
  70248. cb(area, result.values, coordSys, ecModel);
  70249. });
  70250. }
  70251. }, this);
  70252. };
  70253. proto$2.setInputRanges = function (areas, ecModel) {
  70254. each$24(areas, function (area) {
  70255. var targetInfo = this.findTargetInfo(area, ecModel);
  70256. area.range = area.range || []; // convert coordRange to global range and set panelId.
  70257. if (targetInfo && targetInfo !== true) {
  70258. area.panelId = targetInfo.panelId; // (1) area.range shoule always be calculate from coordRange but does
  70259. // not keep its original value, for the sake of the dataZoom scenario,
  70260. // where area.coordRange remains unchanged but area.range may be changed.
  70261. // (2) Only support converting one coordRange to pixel range in brush
  70262. // component. So do not consider `coordRanges`.
  70263. // (3) About __rangeOffset, see comment above.
  70264. var result = coordConvert[area.brushType](0, targetInfo.coordSys, area.coordRange);
  70265. var rangeOffset = area.__rangeOffset;
  70266. area.range = rangeOffset ? diffProcessor[area.brushType](result.values, rangeOffset.offset, getScales(result.xyMinMax, rangeOffset.xyMinMax)) : result.values;
  70267. }
  70268. }, this);
  70269. };
  70270. proto$2.makePanelOpts = function (api, getDefaultBrushType) {
  70271. return map(this._targetInfoList, function (targetInfo) {
  70272. var rect = targetInfo.getPanelRect();
  70273. return {
  70274. panelId: targetInfo.panelId,
  70275. defaultBrushType: getDefaultBrushType && getDefaultBrushType(targetInfo),
  70276. clipPath: makeRectPanelClipPath(rect),
  70277. isTargetByCursor: makeRectIsTargetByCursor(rect, api, targetInfo.coordSysModel),
  70278. getLinearBrushOtherExtent: makeLinearBrushOtherExtent(rect)
  70279. };
  70280. });
  70281. };
  70282. proto$2.controlSeries = function (area, seriesModel, ecModel) {
  70283. // Check whether area is bound in coord, and series do not belong to that coord.
  70284. // If do not do this check, some brush (like lineX) will controll all axes.
  70285. var targetInfo = this.findTargetInfo(area, ecModel);
  70286. return targetInfo === true || targetInfo && indexOf$2(targetInfo.coordSyses, seriesModel.coordinateSystem) >= 0;
  70287. };
  70288. /**
  70289. * If return Object, a coord found.
  70290. * If reutrn true, global found.
  70291. * Otherwise nothing found.
  70292. *
  70293. * @param {Object} area
  70294. * @param {Array} targetInfoList
  70295. * @return {Object|boolean}
  70296. */
  70297. proto$2.findTargetInfo = function (area, ecModel) {
  70298. var targetInfoList = this._targetInfoList;
  70299. var foundCpts = parseFinder$1(ecModel, area);
  70300. for (var i = 0; i < targetInfoList.length; i++) {
  70301. var targetInfo = targetInfoList[i];
  70302. var areaPanelId = area.panelId;
  70303. if (areaPanelId) {
  70304. if (targetInfo.panelId === areaPanelId) {
  70305. return targetInfo;
  70306. }
  70307. } else {
  70308. for (var i = 0; i < targetInfoMatchers.length; i++) {
  70309. if (targetInfoMatchers[i](foundCpts, targetInfo)) {
  70310. return targetInfo;
  70311. }
  70312. }
  70313. }
  70314. }
  70315. return true;
  70316. };
  70317. function formatMinMax(minMax) {
  70318. minMax[0] > minMax[1] && minMax.reverse();
  70319. return minMax;
  70320. }
  70321. function parseFinder$1(ecModel, option) {
  70322. return parseFinder(ecModel, option, {
  70323. includeMainTypes: INCLUDE_FINDER_MAIN_TYPES
  70324. });
  70325. }
  70326. var targetInfoBuilders = {
  70327. grid: function (foundCpts, targetInfoList) {
  70328. var xAxisModels = foundCpts.xAxisModels;
  70329. var yAxisModels = foundCpts.yAxisModels;
  70330. var gridModels = foundCpts.gridModels; // Remove duplicated.
  70331. var gridModelMap = createHashMap();
  70332. var xAxesHas = {};
  70333. var yAxesHas = {};
  70334. if (!xAxisModels && !yAxisModels && !gridModels) {
  70335. return;
  70336. }
  70337. each$24(xAxisModels, function (axisModel) {
  70338. var gridModel = axisModel.axis.grid.model;
  70339. gridModelMap.set(gridModel.id, gridModel);
  70340. xAxesHas[gridModel.id] = true;
  70341. });
  70342. each$24(yAxisModels, function (axisModel) {
  70343. var gridModel = axisModel.axis.grid.model;
  70344. gridModelMap.set(gridModel.id, gridModel);
  70345. yAxesHas[gridModel.id] = true;
  70346. });
  70347. each$24(gridModels, function (gridModel) {
  70348. gridModelMap.set(gridModel.id, gridModel);
  70349. xAxesHas[gridModel.id] = true;
  70350. yAxesHas[gridModel.id] = true;
  70351. });
  70352. gridModelMap.each(function (gridModel) {
  70353. var grid = gridModel.coordinateSystem;
  70354. var cartesians = [];
  70355. each$24(grid.getCartesians(), function (cartesian, index) {
  70356. if (indexOf$2(xAxisModels, cartesian.getAxis('x').model) >= 0 || indexOf$2(yAxisModels, cartesian.getAxis('y').model) >= 0) {
  70357. cartesians.push(cartesian);
  70358. }
  70359. });
  70360. targetInfoList.push({
  70361. panelId: 'grid--' + gridModel.id,
  70362. gridModel: gridModel,
  70363. coordSysModel: gridModel,
  70364. // Use the first one as the representitive coordSys.
  70365. coordSys: cartesians[0],
  70366. coordSyses: cartesians,
  70367. getPanelRect: panelRectBuilder.grid,
  70368. xAxisDeclared: xAxesHas[gridModel.id],
  70369. yAxisDeclared: yAxesHas[gridModel.id]
  70370. });
  70371. });
  70372. },
  70373. geo: function (foundCpts, targetInfoList) {
  70374. each$24(foundCpts.geoModels, function (geoModel) {
  70375. var coordSys = geoModel.coordinateSystem;
  70376. targetInfoList.push({
  70377. panelId: 'geo--' + geoModel.id,
  70378. geoModel: geoModel,
  70379. coordSysModel: geoModel,
  70380. coordSys: coordSys,
  70381. coordSyses: [coordSys],
  70382. getPanelRect: panelRectBuilder.geo
  70383. });
  70384. });
  70385. }
  70386. };
  70387. var targetInfoMatchers = [// grid
  70388. function (foundCpts, targetInfo) {
  70389. var xAxisModel = foundCpts.xAxisModel;
  70390. var yAxisModel = foundCpts.yAxisModel;
  70391. var gridModel = foundCpts.gridModel;
  70392. !gridModel && xAxisModel && (gridModel = xAxisModel.axis.grid.model);
  70393. !gridModel && yAxisModel && (gridModel = yAxisModel.axis.grid.model);
  70394. return gridModel && gridModel === targetInfo.gridModel;
  70395. }, // geo
  70396. function (foundCpts, targetInfo) {
  70397. var geoModel = foundCpts.geoModel;
  70398. return geoModel && geoModel === targetInfo.geoModel;
  70399. }];
  70400. var panelRectBuilder = {
  70401. grid: function () {
  70402. // grid is not Transformable.
  70403. return this.coordSys.grid.getRect().clone();
  70404. },
  70405. geo: function () {
  70406. var coordSys = this.coordSys;
  70407. var rect = coordSys.getBoundingRect().clone(); // geo roam and zoom transform
  70408. rect.applyTransform(getTransform(coordSys));
  70409. return rect;
  70410. }
  70411. };
  70412. var coordConvert = {
  70413. lineX: curry$6(axisConvert, 0),
  70414. lineY: curry$6(axisConvert, 1),
  70415. rect: function (to, coordSys, rangeOrCoordRange) {
  70416. var xminymin = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][0], rangeOrCoordRange[1][0]]);
  70417. var xmaxymax = coordSys[COORD_CONVERTS[to]]([rangeOrCoordRange[0][1], rangeOrCoordRange[1][1]]);
  70418. var values = [formatMinMax([xminymin[0], xmaxymax[0]]), formatMinMax([xminymin[1], xmaxymax[1]])];
  70419. return {
  70420. values: values,
  70421. xyMinMax: values
  70422. };
  70423. },
  70424. polygon: function (to, coordSys, rangeOrCoordRange) {
  70425. var xyMinMax = [[Infinity, -Infinity], [Infinity, -Infinity]];
  70426. var values = map(rangeOrCoordRange, function (item) {
  70427. var p = coordSys[COORD_CONVERTS[to]](item);
  70428. xyMinMax[0][0] = Math.min(xyMinMax[0][0], p[0]);
  70429. xyMinMax[1][0] = Math.min(xyMinMax[1][0], p[1]);
  70430. xyMinMax[0][1] = Math.max(xyMinMax[0][1], p[0]);
  70431. xyMinMax[1][1] = Math.max(xyMinMax[1][1], p[1]);
  70432. return p;
  70433. });
  70434. return {
  70435. values: values,
  70436. xyMinMax: xyMinMax
  70437. };
  70438. }
  70439. };
  70440. function axisConvert(axisNameIndex, to, coordSys, rangeOrCoordRange) {
  70441. var axis = coordSys.getAxis(['x', 'y'][axisNameIndex]);
  70442. var values = formatMinMax(map([0, 1], function (i) {
  70443. return to ? axis.coordToData(axis.toLocalCoord(rangeOrCoordRange[i])) : axis.toGlobalCoord(axis.dataToCoord(rangeOrCoordRange[i]));
  70444. }));
  70445. var xyMinMax = [];
  70446. xyMinMax[axisNameIndex] = values;
  70447. xyMinMax[1 - axisNameIndex] = [NaN, NaN];
  70448. return {
  70449. values: values,
  70450. xyMinMax: xyMinMax
  70451. };
  70452. }
  70453. var diffProcessor = {
  70454. lineX: curry$6(axisDiffProcessor, 0),
  70455. lineY: curry$6(axisDiffProcessor, 1),
  70456. rect: function (values, refer, scales) {
  70457. return [[values[0][0] - scales[0] * refer[0][0], values[0][1] - scales[0] * refer[0][1]], [values[1][0] - scales[1] * refer[1][0], values[1][1] - scales[1] * refer[1][1]]];
  70458. },
  70459. polygon: function (values, refer, scales) {
  70460. return map(values, function (item, idx) {
  70461. return [item[0] - scales[0] * refer[idx][0], item[1] - scales[1] * refer[idx][1]];
  70462. });
  70463. }
  70464. };
  70465. function axisDiffProcessor(axisNameIndex, values, refer, scales) {
  70466. return [values[0] - scales[axisNameIndex] * refer[0], values[1] - scales[axisNameIndex] * refer[1]];
  70467. } // We have to process scale caused by dataZoom manually,
  70468. // although it might be not accurate.
  70469. function getScales(xyMinMaxCurr, xyMinMaxOrigin) {
  70470. var sizeCurr = getSize(xyMinMaxCurr);
  70471. var sizeOrigin = getSize(xyMinMaxOrigin);
  70472. var scales = [sizeCurr[0] / sizeOrigin[0], sizeCurr[1] / sizeOrigin[1]];
  70473. isNaN(scales[0]) && (scales[0] = 1);
  70474. isNaN(scales[1]) && (scales[1] = 1);
  70475. return scales;
  70476. }
  70477. function getSize(xyMinMax) {
  70478. return xyMinMax ? [xyMinMax[0][1] - xyMinMax[0][0], xyMinMax[1][1] - xyMinMax[1][0]] : [NaN, NaN];
  70479. }
  70480. /*
  70481. * Licensed to the Apache Software Foundation (ASF) under one
  70482. * or more contributor license agreements. See the NOTICE file
  70483. * distributed with this work for additional information
  70484. * regarding copyright ownership. The ASF licenses this file
  70485. * to you under the Apache License, Version 2.0 (the
  70486. * "License"); you may not use this file except in compliance
  70487. * with the License. You may obtain a copy of the License at
  70488. *
  70489. * http://www.apache.org/licenses/LICENSE-2.0
  70490. *
  70491. * Unless required by applicable law or agreed to in writing,
  70492. * software distributed under the License is distributed on an
  70493. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70494. * KIND, either express or implied. See the License for the
  70495. * specific language governing permissions and limitations
  70496. * under the License.
  70497. */
  70498. var STATE_LIST = ['inBrush', 'outOfBrush'];
  70499. var DISPATCH_METHOD = '__ecBrushSelect';
  70500. var DISPATCH_FLAG = '__ecInBrushSelectEvent';
  70501. var PRIORITY_BRUSH = PRIORITY.VISUAL.BRUSH;
  70502. /**
  70503. * Layout for visual, the priority higher than other layout, and before brush visual.
  70504. */
  70505. registerLayout(PRIORITY_BRUSH, function (ecModel, api, payload) {
  70506. ecModel.eachComponent({
  70507. mainType: 'brush'
  70508. }, function (brushModel) {
  70509. payload && payload.type === 'takeGlobalCursor' && brushModel.setBrushOption(payload.key === 'brush' ? payload.brushOption : {
  70510. brushType: false
  70511. });
  70512. });
  70513. layoutCovers(ecModel);
  70514. });
  70515. function layoutCovers(ecModel) {
  70516. ecModel.eachComponent({
  70517. mainType: 'brush'
  70518. }, function (brushModel) {
  70519. var brushTargetManager = brushModel.brushTargetManager = new BrushTargetManager(brushModel.option, ecModel);
  70520. brushTargetManager.setInputRanges(brushModel.areas, ecModel);
  70521. });
  70522. }
  70523. /**
  70524. * Register the visual encoding if this modules required.
  70525. */
  70526. registerVisual(PRIORITY_BRUSH, function (ecModel, api, payload) {
  70527. var brushSelected = [];
  70528. var throttleType;
  70529. var throttleDelay;
  70530. ecModel.eachComponent({
  70531. mainType: 'brush'
  70532. }, function (brushModel, brushIndex) {
  70533. var thisBrushSelected = {
  70534. brushId: brushModel.id,
  70535. brushIndex: brushIndex,
  70536. brushName: brushModel.name,
  70537. areas: clone(brushModel.areas),
  70538. selected: []
  70539. }; // Every brush component exists in event params, convenient
  70540. // for user to find by index.
  70541. brushSelected.push(thisBrushSelected);
  70542. var brushOption = brushModel.option;
  70543. var brushLink = brushOption.brushLink;
  70544. var linkedSeriesMap = [];
  70545. var selectedDataIndexForLink = [];
  70546. var rangeInfoBySeries = [];
  70547. var hasBrushExists = 0;
  70548. if (!brushIndex) {
  70549. // Only the first throttle setting works.
  70550. throttleType = brushOption.throttleType;
  70551. throttleDelay = brushOption.throttleDelay;
  70552. } // Add boundingRect and selectors to range.
  70553. var areas = map(brushModel.areas, function (area) {
  70554. return bindSelector(defaults({
  70555. boundingRect: boundingRectBuilders[area.brushType](area)
  70556. }, area));
  70557. });
  70558. var visualMappings = createVisualMappings(brushModel.option, STATE_LIST, function (mappingOption) {
  70559. mappingOption.mappingMethod = 'fixed';
  70560. });
  70561. isArray(brushLink) && each$1(brushLink, function (seriesIndex) {
  70562. linkedSeriesMap[seriesIndex] = 1;
  70563. });
  70564. function linkOthers(seriesIndex) {
  70565. return brushLink === 'all' || linkedSeriesMap[seriesIndex];
  70566. } // If no supported brush or no brush on the series,
  70567. // all visuals should be in original state.
  70568. function brushed(rangeInfoList) {
  70569. return !!rangeInfoList.length;
  70570. }
  70571. /**
  70572. * Logic for each series: (If the logic has to be modified one day, do it carefully!)
  70573. *
  70574. * ( brushed ┬ && ┬hasBrushExist ┬ && linkOthers ) => StepA: ┬record, ┬ StepB: ┬visualByRecord.
  70575. * !brushed┘ ├hasBrushExist ┤ └nothing,┘ ├visualByRecord.
  70576. * └!hasBrushExist┘ └nothing.
  70577. * ( !brushed && ┬hasBrushExist ┬ && linkOthers ) => StepA: nothing, StepB: ┬visualByRecord.
  70578. * └!hasBrushExist┘ └nothing.
  70579. * ( brushed ┬ && !linkOthers ) => StepA: nothing, StepB: ┬visualByCheck.
  70580. * !brushed┘ └nothing.
  70581. * ( !brushed && !linkOthers ) => StepA: nothing, StepB: nothing.
  70582. */
  70583. // Step A
  70584. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  70585. var rangeInfoList = rangeInfoBySeries[seriesIndex] = [];
  70586. seriesModel.subType === 'parallel' ? stepAParallel(seriesModel, seriesIndex, rangeInfoList) : stepAOthers(seriesModel, seriesIndex, rangeInfoList);
  70587. });
  70588. function stepAParallel(seriesModel, seriesIndex) {
  70589. var coordSys = seriesModel.coordinateSystem;
  70590. hasBrushExists |= coordSys.hasAxisBrushed();
  70591. linkOthers(seriesIndex) && coordSys.eachActiveState(seriesModel.getData(), function (activeState, dataIndex) {
  70592. activeState === 'active' && (selectedDataIndexForLink[dataIndex] = 1);
  70593. });
  70594. }
  70595. function stepAOthers(seriesModel, seriesIndex, rangeInfoList) {
  70596. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  70597. if (!selectorsByBrushType || brushModelNotControll(brushModel, seriesIndex)) {
  70598. return;
  70599. }
  70600. each$1(areas, function (area) {
  70601. selectorsByBrushType[area.brushType] && brushModel.brushTargetManager.controlSeries(area, seriesModel, ecModel) && rangeInfoList.push(area);
  70602. hasBrushExists |= brushed(rangeInfoList);
  70603. });
  70604. if (linkOthers(seriesIndex) && brushed(rangeInfoList)) {
  70605. var data = seriesModel.getData();
  70606. data.each(function (dataIndex) {
  70607. if (checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex)) {
  70608. selectedDataIndexForLink[dataIndex] = 1;
  70609. }
  70610. });
  70611. }
  70612. } // Step B
  70613. ecModel.eachSeries(function (seriesModel, seriesIndex) {
  70614. var seriesBrushSelected = {
  70615. seriesId: seriesModel.id,
  70616. seriesIndex: seriesIndex,
  70617. seriesName: seriesModel.name,
  70618. dataIndex: []
  70619. }; // Every series exists in event params, convenient
  70620. // for user to find series by seriesIndex.
  70621. thisBrushSelected.selected.push(seriesBrushSelected);
  70622. var selectorsByBrushType = getSelectorsByBrushType(seriesModel);
  70623. var rangeInfoList = rangeInfoBySeries[seriesIndex];
  70624. var data = seriesModel.getData();
  70625. var getValueState = linkOthers(seriesIndex) ? function (dataIndex) {
  70626. return selectedDataIndexForLink[dataIndex] ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  70627. } : function (dataIndex) {
  70628. return checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) ? (seriesBrushSelected.dataIndex.push(data.getRawIndex(dataIndex)), 'inBrush') : 'outOfBrush';
  70629. }; // If no supported brush or no brush, all visuals are in original state.
  70630. (linkOthers(seriesIndex) ? hasBrushExists : brushed(rangeInfoList)) && applyVisual(STATE_LIST, visualMappings, data, getValueState);
  70631. });
  70632. });
  70633. dispatchAction$1(api, throttleType, throttleDelay, brushSelected, payload);
  70634. });
  70635. function dispatchAction$1(api, throttleType, throttleDelay, brushSelected, payload) {
  70636. // This event will not be triggered when `setOpion`, otherwise dead lock may
  70637. // triggered when do `setOption` in event listener, which we do not find
  70638. // satisfactory way to solve yet. Some considered resolutions:
  70639. // (a) Diff with prevoius selected data ant only trigger event when changed.
  70640. // But store previous data and diff precisely (i.e., not only by dataIndex, but
  70641. // also detect value changes in selected data) might bring complexity or fragility.
  70642. // (b) Use spectial param like `silent` to suppress event triggering.
  70643. // But such kind of volatile param may be weird in `setOption`.
  70644. if (!payload) {
  70645. return;
  70646. }
  70647. var zr = api.getZr();
  70648. if (zr[DISPATCH_FLAG]) {
  70649. return;
  70650. }
  70651. if (!zr[DISPATCH_METHOD]) {
  70652. zr[DISPATCH_METHOD] = doDispatch;
  70653. }
  70654. var fn = createOrUpdate(zr, DISPATCH_METHOD, throttleDelay, throttleType);
  70655. fn(api, brushSelected);
  70656. }
  70657. function doDispatch(api, brushSelected) {
  70658. if (!api.isDisposed()) {
  70659. var zr = api.getZr();
  70660. zr[DISPATCH_FLAG] = true;
  70661. api.dispatchAction({
  70662. type: 'brushSelect',
  70663. batch: brushSelected
  70664. });
  70665. zr[DISPATCH_FLAG] = false;
  70666. }
  70667. }
  70668. function checkInRange(selectorsByBrushType, rangeInfoList, data, dataIndex) {
  70669. for (var i = 0, len = rangeInfoList.length; i < len; i++) {
  70670. var area = rangeInfoList[i];
  70671. if (selectorsByBrushType[area.brushType](dataIndex, data, area.selectors, area)) {
  70672. return true;
  70673. }
  70674. }
  70675. }
  70676. function getSelectorsByBrushType(seriesModel) {
  70677. var brushSelector = seriesModel.brushSelector;
  70678. if (isString(brushSelector)) {
  70679. var sels = [];
  70680. each$1(selector, function (selectorsByElementType, brushType) {
  70681. sels[brushType] = function (dataIndex, data, selectors, area) {
  70682. var itemLayout = data.getItemLayout(dataIndex);
  70683. return selectorsByElementType[brushSelector](itemLayout, selectors, area);
  70684. };
  70685. });
  70686. return sels;
  70687. } else if (isFunction$1(brushSelector)) {
  70688. var bSelector = {};
  70689. each$1(selector, function (sel, brushType) {
  70690. bSelector[brushType] = brushSelector;
  70691. });
  70692. return bSelector;
  70693. }
  70694. return brushSelector;
  70695. }
  70696. function brushModelNotControll(brushModel, seriesIndex) {
  70697. var seriesIndices = brushModel.option.seriesIndex;
  70698. return seriesIndices != null && seriesIndices !== 'all' && (isArray(seriesIndices) ? indexOf(seriesIndices, seriesIndex) < 0 : seriesIndex !== seriesIndices);
  70699. }
  70700. function bindSelector(area) {
  70701. var selectors = area.selectors = {};
  70702. each$1(selector[area.brushType], function (selFn, elType) {
  70703. // Do not use function binding or curry for performance.
  70704. selectors[elType] = function (itemLayout) {
  70705. return selFn(itemLayout, selectors, area);
  70706. };
  70707. });
  70708. return area;
  70709. }
  70710. var boundingRectBuilders = {
  70711. lineX: noop,
  70712. lineY: noop,
  70713. rect: function (area) {
  70714. return getBoundingRectFromMinMax(area.range);
  70715. },
  70716. polygon: function (area) {
  70717. var minMax;
  70718. var range = area.range;
  70719. for (var i = 0, len = range.length; i < len; i++) {
  70720. minMax = minMax || [[Infinity, -Infinity], [Infinity, -Infinity]];
  70721. var rg = range[i];
  70722. rg[0] < minMax[0][0] && (minMax[0][0] = rg[0]);
  70723. rg[0] > minMax[0][1] && (minMax[0][1] = rg[0]);
  70724. rg[1] < minMax[1][0] && (minMax[1][0] = rg[1]);
  70725. rg[1] > minMax[1][1] && (minMax[1][1] = rg[1]);
  70726. }
  70727. return minMax && getBoundingRectFromMinMax(minMax);
  70728. }
  70729. };
  70730. function getBoundingRectFromMinMax(minMax) {
  70731. return new BoundingRect(minMax[0][0], minMax[1][0], minMax[0][1] - minMax[0][0], minMax[1][1] - minMax[1][0]);
  70732. }
  70733. /*
  70734. * Licensed to the Apache Software Foundation (ASF) under one
  70735. * or more contributor license agreements. See the NOTICE file
  70736. * distributed with this work for additional information
  70737. * regarding copyright ownership. The ASF licenses this file
  70738. * to you under the Apache License, Version 2.0 (the
  70739. * "License"); you may not use this file except in compliance
  70740. * with the License. You may obtain a copy of the License at
  70741. *
  70742. * http://www.apache.org/licenses/LICENSE-2.0
  70743. *
  70744. * Unless required by applicable law or agreed to in writing,
  70745. * software distributed under the License is distributed on an
  70746. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70747. * KIND, either express or implied. See the License for the
  70748. * specific language governing permissions and limitations
  70749. * under the License.
  70750. */
  70751. var DEFAULT_OUT_OF_BRUSH_COLOR = ['#ddd'];
  70752. var BrushModel = extendComponentModel({
  70753. type: 'brush',
  70754. dependencies: ['geo', 'grid', 'xAxis', 'yAxis', 'parallel', 'series'],
  70755. /**
  70756. * @protected
  70757. */
  70758. defaultOption: {
  70759. // inBrush: null,
  70760. // outOfBrush: null,
  70761. toolbox: null,
  70762. // Default value see preprocessor.
  70763. brushLink: null,
  70764. // Series indices array, broadcast using dataIndex.
  70765. // or 'all', which means all series. 'none' or null means no series.
  70766. seriesIndex: 'all',
  70767. // seriesIndex array, specify series controlled by this brush component.
  70768. geoIndex: null,
  70769. //
  70770. xAxisIndex: null,
  70771. yAxisIndex: null,
  70772. brushType: 'rect',
  70773. // Default brushType, see BrushController.
  70774. brushMode: 'single',
  70775. // Default brushMode, 'single' or 'multiple'
  70776. transformable: true,
  70777. // Default transformable.
  70778. brushStyle: {
  70779. // Default brushStyle
  70780. borderWidth: 1,
  70781. color: 'rgba(120,140,180,0.3)',
  70782. borderColor: 'rgba(120,140,180,0.8)'
  70783. },
  70784. throttleType: 'fixRate',
  70785. // Throttle in brushSelected event. 'fixRate' or 'debounce'.
  70786. // If null, no throttle. Valid only in the first brush component
  70787. throttleDelay: 0,
  70788. // Unit: ms, 0 means every event will be triggered.
  70789. // FIXME
  70790. // 试验效果
  70791. removeOnClick: true,
  70792. z: 10000
  70793. },
  70794. /**
  70795. * @readOnly
  70796. * @type {Array.<Object>}
  70797. */
  70798. areas: [],
  70799. /**
  70800. * Current activated brush type.
  70801. * If null, brush is inactived.
  70802. * see module:echarts/component/helper/BrushController
  70803. * @readOnly
  70804. * @type {string}
  70805. */
  70806. brushType: null,
  70807. /**
  70808. * Current brush opt.
  70809. * see module:echarts/component/helper/BrushController
  70810. * @readOnly
  70811. * @type {Object}
  70812. */
  70813. brushOption: {},
  70814. /**
  70815. * @readOnly
  70816. * @type {Array.<Object>}
  70817. */
  70818. coordInfoList: [],
  70819. optionUpdated: function (newOption, isInit) {
  70820. var thisOption = this.option;
  70821. !isInit && replaceVisualOption(thisOption, newOption, ['inBrush', 'outOfBrush']);
  70822. var inBrush = thisOption.inBrush = thisOption.inBrush || {}; // Always give default visual, consider setOption at the second time.
  70823. thisOption.outOfBrush = thisOption.outOfBrush || {
  70824. color: DEFAULT_OUT_OF_BRUSH_COLOR
  70825. };
  70826. if (!inBrush.hasOwnProperty('liftZ')) {
  70827. // Bigger than the highlight z lift, otherwise it will
  70828. // be effected by the highlight z when brush.
  70829. inBrush.liftZ = 5;
  70830. }
  70831. },
  70832. /**
  70833. * If ranges is null/undefined, range state remain.
  70834. *
  70835. * @param {Array.<Object>} [ranges]
  70836. */
  70837. setAreas: function (areas) {
  70838. // If ranges is null/undefined, range state remain.
  70839. // This helps user to dispatchAction({type: 'brush'}) with no areas
  70840. // set but just want to get the current brush select info from a `brush` event.
  70841. if (!areas) {
  70842. return;
  70843. }
  70844. this.areas = map(areas, function (area) {
  70845. return generateBrushOption(this.option, area);
  70846. }, this);
  70847. },
  70848. /**
  70849. * see module:echarts/component/helper/BrushController
  70850. * @param {Object} brushOption
  70851. */
  70852. setBrushOption: function (brushOption) {
  70853. this.brushOption = generateBrushOption(this.option, brushOption);
  70854. this.brushType = this.brushOption.brushType;
  70855. }
  70856. });
  70857. function generateBrushOption(option, brushOption) {
  70858. return merge({
  70859. brushType: option.brushType,
  70860. brushMode: option.brushMode,
  70861. transformable: option.transformable,
  70862. brushStyle: new Model(option.brushStyle).getItemStyle(),
  70863. removeOnClick: option.removeOnClick,
  70864. z: option.z
  70865. }, brushOption, true);
  70866. }
  70867. /*
  70868. * Licensed to the Apache Software Foundation (ASF) under one
  70869. * or more contributor license agreements. See the NOTICE file
  70870. * distributed with this work for additional information
  70871. * regarding copyright ownership. The ASF licenses this file
  70872. * to you under the Apache License, Version 2.0 (the
  70873. * "License"); you may not use this file except in compliance
  70874. * with the License. You may obtain a copy of the License at
  70875. *
  70876. * http://www.apache.org/licenses/LICENSE-2.0
  70877. *
  70878. * Unless required by applicable law or agreed to in writing,
  70879. * software distributed under the License is distributed on an
  70880. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70881. * KIND, either express or implied. See the License for the
  70882. * specific language governing permissions and limitations
  70883. * under the License.
  70884. */
  70885. extendComponentView({
  70886. type: 'brush',
  70887. init: function (ecModel, api) {
  70888. /**
  70889. * @readOnly
  70890. * @type {module:echarts/model/Global}
  70891. */
  70892. this.ecModel = ecModel;
  70893. /**
  70894. * @readOnly
  70895. * @type {module:echarts/ExtensionAPI}
  70896. */
  70897. this.api = api;
  70898. /**
  70899. * @readOnly
  70900. * @type {module:echarts/component/brush/BrushModel}
  70901. */
  70902. this.model;
  70903. /**
  70904. * @private
  70905. * @type {module:echarts/component/helper/BrushController}
  70906. */
  70907. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  70908. },
  70909. /**
  70910. * @override
  70911. */
  70912. render: function (brushModel) {
  70913. this.model = brushModel;
  70914. return updateController.apply(this, arguments);
  70915. },
  70916. /**
  70917. * @override
  70918. */
  70919. updateTransform: function (brushModel, ecModel) {
  70920. // PENDING: `updateTransform` is a little tricky, whose layout need
  70921. // to be calculate mandatorily and other stages will not be performed.
  70922. // Take care the correctness of the logic. See #11754 .
  70923. layoutCovers(ecModel);
  70924. return updateController.apply(this, arguments);
  70925. },
  70926. /**
  70927. * @override
  70928. */
  70929. updateView: updateController,
  70930. // /**
  70931. // * @override
  70932. // */
  70933. // updateLayout: updateController,
  70934. // /**
  70935. // * @override
  70936. // */
  70937. // updateVisual: updateController,
  70938. /**
  70939. * @override
  70940. */
  70941. dispose: function () {
  70942. this._brushController.dispose();
  70943. },
  70944. /**
  70945. * @private
  70946. */
  70947. _onBrush: function (areas, opt) {
  70948. var modelId = this.model.id;
  70949. this.model.brushTargetManager.setOutputRanges(areas, this.ecModel); // Action is not dispatched on drag end, because the drag end
  70950. // emits the same params with the last drag move event, and
  70951. // may have some delay when using touch pad, which makes
  70952. // animation not smooth (when using debounce).
  70953. (!opt.isEnd || opt.removeOnClick) && this.api.dispatchAction({
  70954. type: 'brush',
  70955. brushId: modelId,
  70956. areas: clone(areas),
  70957. $from: modelId
  70958. });
  70959. opt.isEnd && this.api.dispatchAction({
  70960. type: 'brushEnd',
  70961. brushId: modelId,
  70962. areas: clone(areas),
  70963. $from: modelId
  70964. });
  70965. }
  70966. });
  70967. function updateController(brushModel, ecModel, api, payload) {
  70968. // Do not update controller when drawing.
  70969. (!payload || payload.$from !== brushModel.id) && this._brushController.setPanels(brushModel.brushTargetManager.makePanelOpts(api)).enableBrush(brushModel.brushOption).updateCovers(brushModel.areas.slice());
  70970. }
  70971. /*
  70972. * Licensed to the Apache Software Foundation (ASF) under one
  70973. * or more contributor license agreements. See the NOTICE file
  70974. * distributed with this work for additional information
  70975. * regarding copyright ownership. The ASF licenses this file
  70976. * to you under the Apache License, Version 2.0 (the
  70977. * "License"); you may not use this file except in compliance
  70978. * with the License. You may obtain a copy of the License at
  70979. *
  70980. * http://www.apache.org/licenses/LICENSE-2.0
  70981. *
  70982. * Unless required by applicable law or agreed to in writing,
  70983. * software distributed under the License is distributed on an
  70984. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  70985. * KIND, either express or implied. See the License for the
  70986. * specific language governing permissions and limitations
  70987. * under the License.
  70988. */
  70989. /**
  70990. * payload: {
  70991. * brushIndex: number, or,
  70992. * brushId: string, or,
  70993. * brushName: string,
  70994. * globalRanges: Array
  70995. * }
  70996. */
  70997. registerAction({
  70998. type: 'brush',
  70999. event: 'brush'
  71000. /*, update: 'updateView' */
  71001. }, function (payload, ecModel) {
  71002. ecModel.eachComponent({
  71003. mainType: 'brush',
  71004. query: payload
  71005. }, function (brushModel) {
  71006. brushModel.setAreas(payload.areas);
  71007. });
  71008. });
  71009. /**
  71010. * payload: {
  71011. * brushComponents: [
  71012. * {
  71013. * brushId,
  71014. * brushIndex,
  71015. * brushName,
  71016. * series: [
  71017. * {
  71018. * seriesId,
  71019. * seriesIndex,
  71020. * seriesName,
  71021. * rawIndices: [21, 34, ...]
  71022. * },
  71023. * ...
  71024. * ]
  71025. * },
  71026. * ...
  71027. * ]
  71028. * }
  71029. */
  71030. registerAction({
  71031. type: 'brushSelect',
  71032. event: 'brushSelected',
  71033. update: 'none'
  71034. }, function () {});
  71035. registerAction({
  71036. type: 'brushEnd',
  71037. event: 'brushEnd',
  71038. update: 'none'
  71039. }, function () {});
  71040. /*
  71041. * Licensed to the Apache Software Foundation (ASF) under one
  71042. * or more contributor license agreements. See the NOTICE file
  71043. * distributed with this work for additional information
  71044. * regarding copyright ownership. The ASF licenses this file
  71045. * to you under the Apache License, Version 2.0 (the
  71046. * "License"); you may not use this file except in compliance
  71047. * with the License. You may obtain a copy of the License at
  71048. *
  71049. * http://www.apache.org/licenses/LICENSE-2.0
  71050. *
  71051. * Unless required by applicable law or agreed to in writing,
  71052. * software distributed under the License is distributed on an
  71053. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71054. * KIND, either express or implied. See the License for the
  71055. * specific language governing permissions and limitations
  71056. * under the License.
  71057. */
  71058. var features = {};
  71059. function register$2(name, ctor) {
  71060. features[name] = ctor;
  71061. }
  71062. function get$1(name) {
  71063. return features[name];
  71064. }
  71065. /*
  71066. * Licensed to the Apache Software Foundation (ASF) under one
  71067. * or more contributor license agreements. See the NOTICE file
  71068. * distributed with this work for additional information
  71069. * regarding copyright ownership. The ASF licenses this file
  71070. * to you under the Apache License, Version 2.0 (the
  71071. * "License"); you may not use this file except in compliance
  71072. * with the License. You may obtain a copy of the License at
  71073. *
  71074. * http://www.apache.org/licenses/LICENSE-2.0
  71075. *
  71076. * Unless required by applicable law or agreed to in writing,
  71077. * software distributed under the License is distributed on an
  71078. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71079. * KIND, either express or implied. See the License for the
  71080. * specific language governing permissions and limitations
  71081. * under the License.
  71082. */
  71083. var brushLang = lang.toolbox.brush;
  71084. function Brush(model, ecModel, api) {
  71085. this.model = model;
  71086. this.ecModel = ecModel;
  71087. this.api = api;
  71088. /**
  71089. * @private
  71090. * @type {string}
  71091. */
  71092. this._brushType;
  71093. /**
  71094. * @private
  71095. * @type {string}
  71096. */
  71097. this._brushMode;
  71098. }
  71099. Brush.defaultOption = {
  71100. show: true,
  71101. type: ['rect', 'polygon', 'lineX', 'lineY', 'keep', 'clear'],
  71102. icon: {
  71103. /* eslint-disable */
  71104. 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',
  71105. // jshint ignore:line
  71106. 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',
  71107. // jshint ignore:line
  71108. 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',
  71109. // jshint ignore:line
  71110. 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',
  71111. // jshint ignore:line
  71112. 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',
  71113. // jshint ignore:line
  71114. 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
  71115. /* eslint-enable */
  71116. },
  71117. // `rect`, `polygon`, `lineX`, `lineY`, `keep`, `clear`
  71118. title: clone(brushLang.title)
  71119. };
  71120. var proto$3 = Brush.prototype; // proto.updateLayout = function (featureModel, ecModel, api) {
  71121. /* eslint-disable */
  71122. proto$3.render =
  71123. /* eslint-enable */
  71124. proto$3.updateView = function (featureModel, ecModel, api) {
  71125. var brushType;
  71126. var brushMode;
  71127. var isBrushed;
  71128. ecModel.eachComponent({
  71129. mainType: 'brush'
  71130. }, function (brushModel) {
  71131. brushType = brushModel.brushType;
  71132. brushMode = brushModel.brushOption.brushMode || 'single';
  71133. isBrushed |= brushModel.areas.length;
  71134. });
  71135. this._brushType = brushType;
  71136. this._brushMode = brushMode;
  71137. each$1(featureModel.get('type', true), function (type) {
  71138. featureModel.setIconStatus(type, (type === 'keep' ? brushMode === 'multiple' : type === 'clear' ? isBrushed : type === brushType) ? 'emphasis' : 'normal');
  71139. });
  71140. };
  71141. proto$3.getIcons = function () {
  71142. var model = this.model;
  71143. var availableIcons = model.get('icon', true);
  71144. var icons = {};
  71145. each$1(model.get('type', true), function (type) {
  71146. if (availableIcons[type]) {
  71147. icons[type] = availableIcons[type];
  71148. }
  71149. });
  71150. return icons;
  71151. };
  71152. proto$3.onclick = function (ecModel, api, type) {
  71153. var brushType = this._brushType;
  71154. var brushMode = this._brushMode;
  71155. if (type === 'clear') {
  71156. // Trigger parallel action firstly
  71157. api.dispatchAction({
  71158. type: 'axisAreaSelect',
  71159. intervals: []
  71160. });
  71161. api.dispatchAction({
  71162. type: 'brush',
  71163. command: 'clear',
  71164. // Clear all areas of all brush components.
  71165. areas: []
  71166. });
  71167. } else {
  71168. api.dispatchAction({
  71169. type: 'takeGlobalCursor',
  71170. key: 'brush',
  71171. brushOption: {
  71172. brushType: type === 'keep' ? brushType : brushType === type ? false : type,
  71173. brushMode: type === 'keep' ? brushMode === 'multiple' ? 'single' : 'multiple' : brushMode
  71174. }
  71175. });
  71176. }
  71177. };
  71178. register$2('brush', Brush);
  71179. /*
  71180. * Licensed to the Apache Software Foundation (ASF) under one
  71181. * or more contributor license agreements. See the NOTICE file
  71182. * distributed with this work for additional information
  71183. * regarding copyright ownership. The ASF licenses this file
  71184. * to you under the Apache License, Version 2.0 (the
  71185. * "License"); you may not use this file except in compliance
  71186. * with the License. You may obtain a copy of the License at
  71187. *
  71188. * http://www.apache.org/licenses/LICENSE-2.0
  71189. *
  71190. * Unless required by applicable law or agreed to in writing,
  71191. * software distributed under the License is distributed on an
  71192. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71193. * KIND, either express or implied. See the License for the
  71194. * specific language governing permissions and limitations
  71195. * under the License.
  71196. */
  71197. /**
  71198. * Brush component entry
  71199. */
  71200. registerPreprocessor(preprocessor$2);
  71201. /*
  71202. * Licensed to the Apache Software Foundation (ASF) under one
  71203. * or more contributor license agreements. See the NOTICE file
  71204. * distributed with this work for additional information
  71205. * regarding copyright ownership. The ASF licenses this file
  71206. * to you under the Apache License, Version 2.0 (the
  71207. * "License"); you may not use this file except in compliance
  71208. * with the License. You may obtain a copy of the License at
  71209. *
  71210. * http://www.apache.org/licenses/LICENSE-2.0
  71211. *
  71212. * Unless required by applicable law or agreed to in writing,
  71213. * software distributed under the License is distributed on an
  71214. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71215. * KIND, either express or implied. See the License for the
  71216. * specific language governing permissions and limitations
  71217. * under the License.
  71218. */
  71219. var each$25 = each$1;
  71220. var preprocessor$3 = function (option) {
  71221. var visualMap = option && option.visualMap;
  71222. if (!isArray(visualMap)) {
  71223. visualMap = visualMap ? [visualMap] : [];
  71224. }
  71225. each$25(visualMap, function (opt) {
  71226. if (!opt) {
  71227. return;
  71228. } // rename splitList to pieces
  71229. if (has$2(opt, 'splitList') && !has$2(opt, 'pieces')) {
  71230. opt.pieces = opt.splitList;
  71231. delete opt.splitList;
  71232. }
  71233. var pieces = opt.pieces;
  71234. if (pieces && isArray(pieces)) {
  71235. each$25(pieces, function (piece) {
  71236. if (isObject$1(piece)) {
  71237. if (has$2(piece, 'start') && !has$2(piece, 'min')) {
  71238. piece.min = piece.start;
  71239. }
  71240. if (has$2(piece, 'end') && !has$2(piece, 'max')) {
  71241. piece.max = piece.end;
  71242. }
  71243. }
  71244. });
  71245. }
  71246. });
  71247. };
  71248. function has$2(obj, name) {
  71249. return obj && obj.hasOwnProperty && obj.hasOwnProperty(name);
  71250. }
  71251. /*
  71252. * Licensed to the Apache Software Foundation (ASF) under one
  71253. * or more contributor license agreements. See the NOTICE file
  71254. * distributed with this work for additional information
  71255. * regarding copyright ownership. The ASF licenses this file
  71256. * to you under the Apache License, Version 2.0 (the
  71257. * "License"); you may not use this file except in compliance
  71258. * with the License. You may obtain a copy of the License at
  71259. *
  71260. * http://www.apache.org/licenses/LICENSE-2.0
  71261. *
  71262. * Unless required by applicable law or agreed to in writing,
  71263. * software distributed under the License is distributed on an
  71264. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71265. * KIND, either express or implied. See the License for the
  71266. * specific language governing permissions and limitations
  71267. * under the License.
  71268. */
  71269. ComponentModel.registerSubTypeDefaulter('visualMap', function (option) {
  71270. // Compatible with ec2, when splitNumber === 0, continuous visualMap will be used.
  71271. return !option.categories && (!(option.pieces ? option.pieces.length > 0 : option.splitNumber > 0) || option.calculable) ? 'continuous' : 'piecewise';
  71272. });
  71273. /*
  71274. * Licensed to the Apache Software Foundation (ASF) under one
  71275. * or more contributor license agreements. See the NOTICE file
  71276. * distributed with this work for additional information
  71277. * regarding copyright ownership. The ASF licenses this file
  71278. * to you under the Apache License, Version 2.0 (the
  71279. * "License"); you may not use this file except in compliance
  71280. * with the License. You may obtain a copy of the License at
  71281. *
  71282. * http://www.apache.org/licenses/LICENSE-2.0
  71283. *
  71284. * Unless required by applicable law or agreed to in writing,
  71285. * software distributed under the License is distributed on an
  71286. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71287. * KIND, either express or implied. See the License for the
  71288. * specific language governing permissions and limitations
  71289. * under the License.
  71290. */
  71291. var VISUAL_PRIORITY = PRIORITY.VISUAL.COMPONENT;
  71292. registerVisual(VISUAL_PRIORITY, {
  71293. createOnAllSeries: true,
  71294. reset: function (seriesModel, ecModel) {
  71295. var resetDefines = [];
  71296. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71297. var pipelineContext = seriesModel.pipelineContext;
  71298. if (!visualMapModel.isTargetSeries(seriesModel) || pipelineContext && pipelineContext.large) {
  71299. return;
  71300. }
  71301. resetDefines.push(incrementalApplyVisual(visualMapModel.stateList, visualMapModel.targetVisuals, bind(visualMapModel.getValueState, visualMapModel), visualMapModel.getDataDimension(seriesModel.getData())));
  71302. });
  71303. return resetDefines;
  71304. }
  71305. }); // Only support color.
  71306. registerVisual(VISUAL_PRIORITY, {
  71307. createOnAllSeries: true,
  71308. reset: function (seriesModel, ecModel) {
  71309. var data = seriesModel.getData();
  71310. var visualMetaList = [];
  71311. ecModel.eachComponent('visualMap', function (visualMapModel) {
  71312. if (visualMapModel.isTargetSeries(seriesModel)) {
  71313. var visualMeta = visualMapModel.getVisualMeta(bind(getColorVisual, null, seriesModel, visualMapModel)) || {
  71314. stops: [],
  71315. outerColors: []
  71316. };
  71317. var concreteDim = visualMapModel.getDataDimension(data);
  71318. var dimInfo = data.getDimensionInfo(concreteDim);
  71319. if (dimInfo != null) {
  71320. // visualMeta.dimension should be dimension index, but not concrete dimension.
  71321. visualMeta.dimension = dimInfo.index;
  71322. visualMetaList.push(visualMeta);
  71323. }
  71324. }
  71325. }); // console.log(JSON.stringify(visualMetaList.map(a => a.stops)));
  71326. seriesModel.getData().setVisual('visualMeta', visualMetaList);
  71327. }
  71328. }); // FIXME
  71329. // performance and export for heatmap?
  71330. // value can be Infinity or -Infinity
  71331. function getColorVisual(seriesModel, visualMapModel, value, valueState) {
  71332. var mappings = visualMapModel.targetVisuals[valueState];
  71333. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  71334. var resultVisual = {
  71335. color: seriesModel.getData().getVisual('color') // default color.
  71336. };
  71337. for (var i = 0, len = visualTypes.length; i < len; i++) {
  71338. var type = visualTypes[i];
  71339. var mapping = mappings[type === 'opacity' ? '__alphaForOpacity' : type];
  71340. mapping && mapping.applyVisual(value, getVisual, setVisual);
  71341. }
  71342. return resultVisual.color;
  71343. function getVisual(key) {
  71344. return resultVisual[key];
  71345. }
  71346. function setVisual(key, value) {
  71347. resultVisual[key] = value;
  71348. }
  71349. }
  71350. /*
  71351. * Licensed to the Apache Software Foundation (ASF) under one
  71352. * or more contributor license agreements. See the NOTICE file
  71353. * distributed with this work for additional information
  71354. * regarding copyright ownership. The ASF licenses this file
  71355. * to you under the Apache License, Version 2.0 (the
  71356. * "License"); you may not use this file except in compliance
  71357. * with the License. You may obtain a copy of the License at
  71358. *
  71359. * http://www.apache.org/licenses/LICENSE-2.0
  71360. *
  71361. * Unless required by applicable law or agreed to in writing,
  71362. * software distributed under the License is distributed on an
  71363. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71364. * KIND, either express or implied. See the License for the
  71365. * specific language governing permissions and limitations
  71366. * under the License.
  71367. */
  71368. /**
  71369. * @file Visual mapping.
  71370. */
  71371. var visualDefault = {
  71372. /**
  71373. * @public
  71374. */
  71375. get: function (visualType, key, isCategory) {
  71376. var value = clone((defaultOption$3[visualType] || {})[key]);
  71377. return isCategory ? isArray(value) ? value[value.length - 1] : value : value;
  71378. }
  71379. };
  71380. var defaultOption$3 = {
  71381. color: {
  71382. active: ['#006edd', '#e0ffff'],
  71383. inactive: ['rgba(0,0,0,0)']
  71384. },
  71385. colorHue: {
  71386. active: [0, 360],
  71387. inactive: [0, 0]
  71388. },
  71389. colorSaturation: {
  71390. active: [0.3, 1],
  71391. inactive: [0, 0]
  71392. },
  71393. colorLightness: {
  71394. active: [0.9, 0.5],
  71395. inactive: [0, 0]
  71396. },
  71397. colorAlpha: {
  71398. active: [0.3, 1],
  71399. inactive: [0, 0]
  71400. },
  71401. opacity: {
  71402. active: [0.3, 1],
  71403. inactive: [0, 0]
  71404. },
  71405. symbol: {
  71406. active: ['circle', 'roundRect', 'diamond'],
  71407. inactive: ['none']
  71408. },
  71409. symbolSize: {
  71410. active: [10, 50],
  71411. inactive: [0, 0]
  71412. }
  71413. };
  71414. /*
  71415. * Licensed to the Apache Software Foundation (ASF) under one
  71416. * or more contributor license agreements. See the NOTICE file
  71417. * distributed with this work for additional information
  71418. * regarding copyright ownership. The ASF licenses this file
  71419. * to you under the Apache License, Version 2.0 (the
  71420. * "License"); you may not use this file except in compliance
  71421. * with the License. You may obtain a copy of the License at
  71422. *
  71423. * http://www.apache.org/licenses/LICENSE-2.0
  71424. *
  71425. * Unless required by applicable law or agreed to in writing,
  71426. * software distributed under the License is distributed on an
  71427. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71428. * KIND, either express or implied. See the License for the
  71429. * specific language governing permissions and limitations
  71430. * under the License.
  71431. */
  71432. var mapVisual$2 = VisualMapping.mapVisual;
  71433. var eachVisual = VisualMapping.eachVisual;
  71434. var isArray$3 = isArray;
  71435. var each$26 = each$1;
  71436. var asc$3 = asc;
  71437. var linearMap$2 = linearMap;
  71438. var noop$2 = noop;
  71439. var VisualMapModel = extendComponentModel({
  71440. type: 'visualMap',
  71441. dependencies: ['series'],
  71442. /**
  71443. * @readOnly
  71444. * @type {Array.<string>}
  71445. */
  71446. stateList: ['inRange', 'outOfRange'],
  71447. /**
  71448. * @readOnly
  71449. * @type {Array.<string>}
  71450. */
  71451. replacableOptionKeys: ['inRange', 'outOfRange', 'target', 'controller', 'color'],
  71452. /**
  71453. * [lowerBound, upperBound]
  71454. *
  71455. * @readOnly
  71456. * @type {Array.<number>}
  71457. */
  71458. dataBound: [-Infinity, Infinity],
  71459. /**
  71460. * @readOnly
  71461. * @type {string|Object}
  71462. */
  71463. layoutMode: {
  71464. type: 'box',
  71465. ignoreSize: true
  71466. },
  71467. /**
  71468. * @protected
  71469. */
  71470. defaultOption: {
  71471. show: true,
  71472. zlevel: 0,
  71473. z: 4,
  71474. seriesIndex: 'all',
  71475. // 'all' or null/undefined: all series.
  71476. // A number or an array of number: the specified series.
  71477. // set min: 0, max: 200, only for campatible with ec2.
  71478. // In fact min max should not have default value.
  71479. min: 0,
  71480. // min value, must specified if pieces is not specified.
  71481. max: 200,
  71482. // max value, must specified if pieces is not specified.
  71483. dimension: null,
  71484. inRange: null,
  71485. // 'color', 'colorHue', 'colorSaturation', 'colorLightness', 'colorAlpha',
  71486. // 'symbol', 'symbolSize'
  71487. outOfRange: null,
  71488. // 'color', 'colorHue', 'colorSaturation',
  71489. // 'colorLightness', 'colorAlpha',
  71490. // 'symbol', 'symbolSize'
  71491. left: 0,
  71492. // 'center' ¦ 'left' ¦ 'right' ¦ {number} (px)
  71493. right: null,
  71494. // The same as left.
  71495. top: null,
  71496. // 'top' ¦ 'bottom' ¦ 'center' ¦ {number} (px)
  71497. bottom: 0,
  71498. // The same as top.
  71499. itemWidth: null,
  71500. itemHeight: null,
  71501. inverse: false,
  71502. orient: 'vertical',
  71503. // 'horizontal' ¦ 'vertical'
  71504. backgroundColor: 'rgba(0,0,0,0)',
  71505. borderColor: '#ccc',
  71506. // 值域边框颜色
  71507. contentColor: '#5793f3',
  71508. inactiveColor: '#aaa',
  71509. borderWidth: 0,
  71510. // 值域边框线宽,单位px,默认为0(无边框)
  71511. padding: 5,
  71512. // 值域内边距,单位px,默认各方向内边距为5,
  71513. // 接受数组分别设定上右下左边距,同css
  71514. textGap: 10,
  71515. //
  71516. precision: 0,
  71517. // 小数精度,默认为0,无小数点
  71518. color: null,
  71519. //颜色(deprecated,兼容ec2,顺序同pieces,不同于inRange/outOfRange)
  71520. formatter: null,
  71521. text: null,
  71522. // 文本,如['高', '低'],兼容ec2,text[0]对应高值,text[1]对应低值
  71523. textStyle: {
  71524. color: '#333' // 值域文字颜色
  71525. }
  71526. },
  71527. /**
  71528. * @protected
  71529. */
  71530. init: function (option, parentModel, ecModel) {
  71531. /**
  71532. * @private
  71533. * @type {Array.<number>}
  71534. */
  71535. this._dataExtent;
  71536. /**
  71537. * @readOnly
  71538. */
  71539. this.targetVisuals = {};
  71540. /**
  71541. * @readOnly
  71542. */
  71543. this.controllerVisuals = {};
  71544. /**
  71545. * @readOnly
  71546. */
  71547. this.textStyleModel;
  71548. /**
  71549. * [width, height]
  71550. * @readOnly
  71551. * @type {Array.<number>}
  71552. */
  71553. this.itemSize;
  71554. this.mergeDefaultAndTheme(option, ecModel);
  71555. },
  71556. /**
  71557. * @protected
  71558. */
  71559. optionUpdated: function (newOption, isInit) {
  71560. var thisOption = this.option; // FIXME
  71561. // necessary?
  71562. // Disable realtime view update if canvas is not supported.
  71563. if (!env$1.canvasSupported) {
  71564. thisOption.realtime = false;
  71565. }
  71566. !isInit && replaceVisualOption(thisOption, newOption, this.replacableOptionKeys);
  71567. this.textStyleModel = this.getModel('textStyle');
  71568. this.resetItemSize();
  71569. this.completeVisualOption();
  71570. },
  71571. /**
  71572. * @protected
  71573. */
  71574. resetVisual: function (supplementVisualOption) {
  71575. var stateList = this.stateList;
  71576. supplementVisualOption = bind(supplementVisualOption, this);
  71577. this.controllerVisuals = createVisualMappings(this.option.controller, stateList, supplementVisualOption);
  71578. this.targetVisuals = createVisualMappings(this.option.target, stateList, supplementVisualOption);
  71579. },
  71580. /**
  71581. * @protected
  71582. * @return {Array.<number>} An array of series indices.
  71583. */
  71584. getTargetSeriesIndices: function () {
  71585. var optionSeriesIndex = this.option.seriesIndex;
  71586. var seriesIndices = [];
  71587. if (optionSeriesIndex == null || optionSeriesIndex === 'all') {
  71588. this.ecModel.eachSeries(function (seriesModel, index) {
  71589. seriesIndices.push(index);
  71590. });
  71591. } else {
  71592. seriesIndices = normalizeToArray(optionSeriesIndex);
  71593. }
  71594. return seriesIndices;
  71595. },
  71596. /**
  71597. * @public
  71598. */
  71599. eachTargetSeries: function (callback, context) {
  71600. each$1(this.getTargetSeriesIndices(), function (seriesIndex) {
  71601. callback.call(context, this.ecModel.getSeriesByIndex(seriesIndex));
  71602. }, this);
  71603. },
  71604. /**
  71605. * @pubilc
  71606. */
  71607. isTargetSeries: function (seriesModel) {
  71608. var is = false;
  71609. this.eachTargetSeries(function (model) {
  71610. model === seriesModel && (is = true);
  71611. });
  71612. return is;
  71613. },
  71614. /**
  71615. * @example
  71616. * this.formatValueText(someVal); // format single numeric value to text.
  71617. * this.formatValueText(someVal, true); // format single category value to text.
  71618. * this.formatValueText([min, max]); // format numeric min-max to text.
  71619. * this.formatValueText([this.dataBound[0], max]); // using data lower bound.
  71620. * this.formatValueText([min, this.dataBound[1]]); // using data upper bound.
  71621. *
  71622. * @param {number|Array.<number>} value Real value, or this.dataBound[0 or 1].
  71623. * @param {boolean} [isCategory=false] Only available when value is number.
  71624. * @param {Array.<string>} edgeSymbols Open-close symbol when value is interval.
  71625. * @return {string}
  71626. * @protected
  71627. */
  71628. formatValueText: function (value, isCategory, edgeSymbols) {
  71629. var option = this.option;
  71630. var precision = option.precision;
  71631. var dataBound = this.dataBound;
  71632. var formatter = option.formatter;
  71633. var isMinMax;
  71634. var textValue;
  71635. edgeSymbols = edgeSymbols || ['<', '>'];
  71636. if (isArray(value)) {
  71637. value = value.slice();
  71638. isMinMax = true;
  71639. }
  71640. textValue = isCategory ? value : isMinMax ? [toFixed(value[0]), toFixed(value[1])] : toFixed(value);
  71641. if (isString(formatter)) {
  71642. return formatter.replace('{value}', isMinMax ? textValue[0] : textValue).replace('{value2}', isMinMax ? textValue[1] : textValue);
  71643. } else if (isFunction$1(formatter)) {
  71644. return isMinMax ? formatter(value[0], value[1]) : formatter(value);
  71645. }
  71646. if (isMinMax) {
  71647. if (value[0] === dataBound[0]) {
  71648. return edgeSymbols[0] + ' ' + textValue[1];
  71649. } else if (value[1] === dataBound[1]) {
  71650. return edgeSymbols[1] + ' ' + textValue[0];
  71651. } else {
  71652. return textValue[0] + ' - ' + textValue[1];
  71653. }
  71654. } else {
  71655. // Format single value (includes category case).
  71656. return textValue;
  71657. }
  71658. function toFixed(val) {
  71659. return val === dataBound[0] ? 'min' : val === dataBound[1] ? 'max' : (+val).toFixed(Math.min(precision, 20));
  71660. }
  71661. },
  71662. /**
  71663. * @protected
  71664. */
  71665. resetExtent: function () {
  71666. var thisOption = this.option; // Can not calculate data extent by data here.
  71667. // Because series and data may be modified in processing stage.
  71668. // So we do not support the feature "auto min/max".
  71669. var extent = asc$3([thisOption.min, thisOption.max]);
  71670. this._dataExtent = extent;
  71671. },
  71672. /**
  71673. * @public
  71674. * @param {module:echarts/data/List} list
  71675. * @return {string} Concrete dimention. If return null/undefined,
  71676. * no dimension used.
  71677. */
  71678. getDataDimension: function (list) {
  71679. var optDim = this.option.dimension;
  71680. var listDimensions = list.dimensions;
  71681. if (optDim == null && !listDimensions.length) {
  71682. return;
  71683. }
  71684. if (optDim != null) {
  71685. return list.getDimension(optDim);
  71686. }
  71687. var dimNames = list.dimensions;
  71688. for (var i = dimNames.length - 1; i >= 0; i--) {
  71689. var dimName = dimNames[i];
  71690. var dimInfo = list.getDimensionInfo(dimName);
  71691. if (!dimInfo.isCalculationCoord) {
  71692. return dimName;
  71693. }
  71694. }
  71695. },
  71696. /**
  71697. * @public
  71698. * @override
  71699. */
  71700. getExtent: function () {
  71701. return this._dataExtent.slice();
  71702. },
  71703. /**
  71704. * @protected
  71705. */
  71706. completeVisualOption: function () {
  71707. var ecModel = this.ecModel;
  71708. var thisOption = this.option;
  71709. var base = {
  71710. inRange: thisOption.inRange,
  71711. outOfRange: thisOption.outOfRange
  71712. };
  71713. var target = thisOption.target || (thisOption.target = {});
  71714. var controller = thisOption.controller || (thisOption.controller = {});
  71715. merge(target, base); // Do not override
  71716. merge(controller, base); // Do not override
  71717. var isCategory = this.isCategory();
  71718. completeSingle.call(this, target);
  71719. completeSingle.call(this, controller);
  71720. completeInactive.call(this, target, 'inRange', 'outOfRange'); // completeInactive.call(this, target, 'outOfRange', 'inRange');
  71721. completeController.call(this, controller);
  71722. function completeSingle(base) {
  71723. // Compatible with ec2 dataRange.color.
  71724. // The mapping order of dataRange.color is: [high value, ..., low value]
  71725. // whereas inRange.color and outOfRange.color is [low value, ..., high value]
  71726. // Notice: ec2 has no inverse.
  71727. if (isArray$3(thisOption.color) // If there has been inRange: {symbol: ...}, adding color is a mistake.
  71728. // So adding color only when no inRange defined.
  71729. && !base.inRange) {
  71730. base.inRange = {
  71731. color: thisOption.color.slice().reverse()
  71732. };
  71733. } // Compatible with previous logic, always give a defautl color, otherwise
  71734. // simple config with no inRange and outOfRange will not work.
  71735. // Originally we use visualMap.color as the default color, but setOption at
  71736. // the second time the default color will be erased. So we change to use
  71737. // constant DEFAULT_COLOR.
  71738. // If user do not want the defualt color, set inRange: {color: null}.
  71739. base.inRange = base.inRange || {
  71740. color: ecModel.get('gradientColor')
  71741. }; // If using shortcut like: {inRange: 'symbol'}, complete default value.
  71742. each$26(this.stateList, function (state) {
  71743. var visualType = base[state];
  71744. if (isString(visualType)) {
  71745. var defa = visualDefault.get(visualType, 'active', isCategory);
  71746. if (defa) {
  71747. base[state] = {};
  71748. base[state][visualType] = defa;
  71749. } else {
  71750. // Mark as not specified.
  71751. delete base[state];
  71752. }
  71753. }
  71754. }, this);
  71755. }
  71756. function completeInactive(base, stateExist, stateAbsent) {
  71757. var optExist = base[stateExist];
  71758. var optAbsent = base[stateAbsent];
  71759. if (optExist && !optAbsent) {
  71760. optAbsent = base[stateAbsent] = {};
  71761. each$26(optExist, function (visualData, visualType) {
  71762. if (!VisualMapping.isValidType(visualType)) {
  71763. return;
  71764. }
  71765. var defa = visualDefault.get(visualType, 'inactive', isCategory);
  71766. if (defa != null) {
  71767. optAbsent[visualType] = defa; // Compatibable with ec2:
  71768. // Only inactive color to rgba(0,0,0,0) can not
  71769. // make label transparent, so use opacity also.
  71770. if (visualType === 'color' && !optAbsent.hasOwnProperty('opacity') && !optAbsent.hasOwnProperty('colorAlpha')) {
  71771. optAbsent.opacity = [0, 0];
  71772. }
  71773. }
  71774. });
  71775. }
  71776. }
  71777. function completeController(controller) {
  71778. var symbolExists = (controller.inRange || {}).symbol || (controller.outOfRange || {}).symbol;
  71779. var symbolSizeExists = (controller.inRange || {}).symbolSize || (controller.outOfRange || {}).symbolSize;
  71780. var inactiveColor = this.get('inactiveColor');
  71781. each$26(this.stateList, function (state) {
  71782. var itemSize = this.itemSize;
  71783. var visuals = controller[state]; // Set inactive color for controller if no other color
  71784. // attr (like colorAlpha) specified.
  71785. if (!visuals) {
  71786. visuals = controller[state] = {
  71787. color: isCategory ? inactiveColor : [inactiveColor]
  71788. };
  71789. } // Consistent symbol and symbolSize if not specified.
  71790. if (visuals.symbol == null) {
  71791. visuals.symbol = symbolExists && clone(symbolExists) || (isCategory ? 'roundRect' : ['roundRect']);
  71792. }
  71793. if (visuals.symbolSize == null) {
  71794. visuals.symbolSize = symbolSizeExists && clone(symbolSizeExists) || (isCategory ? itemSize[0] : [itemSize[0], itemSize[0]]);
  71795. } // Filter square and none.
  71796. visuals.symbol = mapVisual$2(visuals.symbol, function (symbol) {
  71797. return symbol === 'none' || symbol === 'square' ? 'roundRect' : symbol;
  71798. }); // Normalize symbolSize
  71799. var symbolSize = visuals.symbolSize;
  71800. if (symbolSize != null) {
  71801. var max = -Infinity; // symbolSize can be object when categories defined.
  71802. eachVisual(symbolSize, function (value) {
  71803. value > max && (max = value);
  71804. });
  71805. visuals.symbolSize = mapVisual$2(symbolSize, function (value) {
  71806. return linearMap$2(value, [0, max], [0, itemSize[0]], true);
  71807. });
  71808. }
  71809. }, this);
  71810. }
  71811. },
  71812. /**
  71813. * @protected
  71814. */
  71815. resetItemSize: function () {
  71816. this.itemSize = [parseFloat(this.get('itemWidth')), parseFloat(this.get('itemHeight'))];
  71817. },
  71818. /**
  71819. * @public
  71820. */
  71821. isCategory: function () {
  71822. return !!this.option.categories;
  71823. },
  71824. /**
  71825. * @public
  71826. * @abstract
  71827. */
  71828. setSelected: noop$2,
  71829. /**
  71830. * @public
  71831. * @abstract
  71832. * @param {*|module:echarts/data/List} valueOrData
  71833. * @param {number} dataIndex
  71834. * @return {string} state See this.stateList
  71835. */
  71836. getValueState: noop$2,
  71837. /**
  71838. * FIXME
  71839. * Do not publish to thirt-part-dev temporarily
  71840. * util the interface is stable. (Should it return
  71841. * a function but not visual meta?)
  71842. *
  71843. * @pubilc
  71844. * @abstract
  71845. * @param {Function} getColorVisual
  71846. * params: value, valueState
  71847. * return: color
  71848. * @return {Object} visualMeta
  71849. * should includes {stops, outerColors}
  71850. * outerColor means [colorBeyondMinValue, colorBeyondMaxValue]
  71851. */
  71852. getVisualMeta: noop$2
  71853. });
  71854. /*
  71855. * Licensed to the Apache Software Foundation (ASF) under one
  71856. * or more contributor license agreements. See the NOTICE file
  71857. * distributed with this work for additional information
  71858. * regarding copyright ownership. The ASF licenses this file
  71859. * to you under the Apache License, Version 2.0 (the
  71860. * "License"); you may not use this file except in compliance
  71861. * with the License. You may obtain a copy of the License at
  71862. *
  71863. * http://www.apache.org/licenses/LICENSE-2.0
  71864. *
  71865. * Unless required by applicable law or agreed to in writing,
  71866. * software distributed under the License is distributed on an
  71867. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  71868. * KIND, either express or implied. See the License for the
  71869. * specific language governing permissions and limitations
  71870. * under the License.
  71871. */
  71872. var DEFAULT_BAR_BOUND = [20, 140];
  71873. var ContinuousModel = VisualMapModel.extend({
  71874. type: 'visualMap.continuous',
  71875. /**
  71876. * @protected
  71877. */
  71878. defaultOption: {
  71879. align: 'auto',
  71880. // 'auto', 'left', 'right', 'top', 'bottom'
  71881. calculable: false,
  71882. // This prop effect default component type determine,
  71883. // See echarts/component/visualMap/typeDefaulter.
  71884. range: null,
  71885. // selected range. In default case `range` is [min, max]
  71886. // and can auto change along with modification of min max,
  71887. // util use specifid a range.
  71888. realtime: true,
  71889. // Whether realtime update.
  71890. itemHeight: null,
  71891. // The length of the range control edge.
  71892. itemWidth: null,
  71893. // The length of the other side.
  71894. hoverLink: true,
  71895. // Enable hover highlight.
  71896. hoverLinkDataSize: null,
  71897. // The size of hovered data.
  71898. hoverLinkOnHandle: null // Whether trigger hoverLink when hover handle.
  71899. // If not specified, follow the value of `realtime`.
  71900. },
  71901. /**
  71902. * @override
  71903. */
  71904. optionUpdated: function (newOption, isInit) {
  71905. ContinuousModel.superApply(this, 'optionUpdated', arguments);
  71906. this.resetExtent();
  71907. this.resetVisual(function (mappingOption) {
  71908. mappingOption.mappingMethod = 'linear';
  71909. mappingOption.dataExtent = this.getExtent();
  71910. });
  71911. this._resetRange();
  71912. },
  71913. /**
  71914. * @protected
  71915. * @override
  71916. */
  71917. resetItemSize: function () {
  71918. ContinuousModel.superApply(this, 'resetItemSize', arguments);
  71919. var itemSize = this.itemSize;
  71920. this._orient === 'horizontal' && itemSize.reverse();
  71921. (itemSize[0] == null || isNaN(itemSize[0])) && (itemSize[0] = DEFAULT_BAR_BOUND[0]);
  71922. (itemSize[1] == null || isNaN(itemSize[1])) && (itemSize[1] = DEFAULT_BAR_BOUND[1]);
  71923. },
  71924. /**
  71925. * @private
  71926. */
  71927. _resetRange: function () {
  71928. var dataExtent = this.getExtent();
  71929. var range = this.option.range;
  71930. if (!range || range.auto) {
  71931. // `range` should always be array (so we dont use other
  71932. // value like 'auto') for user-friend. (consider getOption).
  71933. dataExtent.auto = 1;
  71934. this.option.range = dataExtent;
  71935. } else if (isArray(range)) {
  71936. if (range[0] > range[1]) {
  71937. range.reverse();
  71938. }
  71939. range[0] = Math.max(range[0], dataExtent[0]);
  71940. range[1] = Math.min(range[1], dataExtent[1]);
  71941. }
  71942. },
  71943. /**
  71944. * @protected
  71945. * @override
  71946. */
  71947. completeVisualOption: function () {
  71948. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  71949. each$1(this.stateList, function (state) {
  71950. var symbolSize = this.option.controller[state].symbolSize;
  71951. if (symbolSize && symbolSize[0] !== symbolSize[1]) {
  71952. symbolSize[0] = 0; // For good looking.
  71953. }
  71954. }, this);
  71955. },
  71956. /**
  71957. * @override
  71958. */
  71959. setSelected: function (selected) {
  71960. this.option.range = selected.slice();
  71961. this._resetRange();
  71962. },
  71963. /**
  71964. * @public
  71965. */
  71966. getSelected: function () {
  71967. var dataExtent = this.getExtent();
  71968. var dataInterval = asc((this.get('range') || []).slice()); // Clamp
  71969. dataInterval[0] > dataExtent[1] && (dataInterval[0] = dataExtent[1]);
  71970. dataInterval[1] > dataExtent[1] && (dataInterval[1] = dataExtent[1]);
  71971. dataInterval[0] < dataExtent[0] && (dataInterval[0] = dataExtent[0]);
  71972. dataInterval[1] < dataExtent[0] && (dataInterval[1] = dataExtent[0]);
  71973. return dataInterval;
  71974. },
  71975. /**
  71976. * @override
  71977. */
  71978. getValueState: function (value) {
  71979. var range = this.option.range;
  71980. var dataExtent = this.getExtent(); // When range[0] === dataExtent[0], any value larger than dataExtent[0] maps to 'inRange'.
  71981. // range[1] is processed likewise.
  71982. return (range[0] <= dataExtent[0] || range[0] <= value) && (range[1] >= dataExtent[1] || value <= range[1]) ? 'inRange' : 'outOfRange';
  71983. },
  71984. /**
  71985. * @params {Array.<number>} range target value: range[0] <= value && value <= range[1]
  71986. * @return {Array.<Object>} [{seriesId, dataIndices: <Array.<number>>}, ...]
  71987. */
  71988. findTargetDataIndices: function (range) {
  71989. var result = [];
  71990. this.eachTargetSeries(function (seriesModel) {
  71991. var dataIndices = [];
  71992. var data = seriesModel.getData();
  71993. data.each(this.getDataDimension(data), function (value, dataIndex) {
  71994. range[0] <= value && value <= range[1] && dataIndices.push(dataIndex);
  71995. }, this);
  71996. result.push({
  71997. seriesId: seriesModel.id,
  71998. dataIndex: dataIndices
  71999. });
  72000. }, this);
  72001. return result;
  72002. },
  72003. /**
  72004. * @implement
  72005. */
  72006. getVisualMeta: function (getColorVisual) {
  72007. var oVals = getColorStopValues(this, 'outOfRange', this.getExtent());
  72008. var iVals = getColorStopValues(this, 'inRange', this.option.range.slice());
  72009. var stops = [];
  72010. function setStop(value, valueState) {
  72011. stops.push({
  72012. value: value,
  72013. color: getColorVisual(value, valueState)
  72014. });
  72015. } // Format to: outOfRange -- inRange -- outOfRange.
  72016. var iIdx = 0;
  72017. var oIdx = 0;
  72018. var iLen = iVals.length;
  72019. var oLen = oVals.length;
  72020. for (; oIdx < oLen && (!iVals.length || oVals[oIdx] <= iVals[0]); oIdx++) {
  72021. // If oVal[oIdx] === iVals[iIdx], oVal[oIdx] should be ignored.
  72022. if (oVals[oIdx] < iVals[iIdx]) {
  72023. setStop(oVals[oIdx], 'outOfRange');
  72024. }
  72025. }
  72026. for (var first = 1; iIdx < iLen; iIdx++, first = 0) {
  72027. // If range is full, value beyond min, max will be clamped.
  72028. // make a singularity
  72029. first && stops.length && setStop(iVals[iIdx], 'outOfRange');
  72030. setStop(iVals[iIdx], 'inRange');
  72031. }
  72032. for (var first = 1; oIdx < oLen; oIdx++) {
  72033. if (!iVals.length || iVals[iVals.length - 1] < oVals[oIdx]) {
  72034. // make a singularity
  72035. if (first) {
  72036. stops.length && setStop(stops[stops.length - 1].value, 'outOfRange');
  72037. first = 0;
  72038. }
  72039. setStop(oVals[oIdx], 'outOfRange');
  72040. }
  72041. }
  72042. var stopsLen = stops.length;
  72043. return {
  72044. stops: stops,
  72045. outerColors: [stopsLen ? stops[0].color : 'transparent', stopsLen ? stops[stopsLen - 1].color : 'transparent']
  72046. };
  72047. }
  72048. });
  72049. function getColorStopValues(visualMapModel, valueState, dataExtent) {
  72050. if (dataExtent[0] === dataExtent[1]) {
  72051. return dataExtent.slice();
  72052. } // When using colorHue mapping, it is not linear color any more.
  72053. // Moreover, canvas gradient seems not to be accurate linear.
  72054. // FIXME
  72055. // Should be arbitrary value 100? or based on pixel size?
  72056. var count = 200;
  72057. var step = (dataExtent[1] - dataExtent[0]) / count;
  72058. var value = dataExtent[0];
  72059. var stopValues = [];
  72060. for (var i = 0; i <= count && value < dataExtent[1]; i++) {
  72061. stopValues.push(value);
  72062. value += step;
  72063. }
  72064. stopValues.push(dataExtent[1]);
  72065. return stopValues;
  72066. }
  72067. /*
  72068. * Licensed to the Apache Software Foundation (ASF) under one
  72069. * or more contributor license agreements. See the NOTICE file
  72070. * distributed with this work for additional information
  72071. * regarding copyright ownership. The ASF licenses this file
  72072. * to you under the Apache License, Version 2.0 (the
  72073. * "License"); you may not use this file except in compliance
  72074. * with the License. You may obtain a copy of the License at
  72075. *
  72076. * http://www.apache.org/licenses/LICENSE-2.0
  72077. *
  72078. * Unless required by applicable law or agreed to in writing,
  72079. * software distributed under the License is distributed on an
  72080. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72081. * KIND, either express or implied. See the License for the
  72082. * specific language governing permissions and limitations
  72083. * under the License.
  72084. */
  72085. var VisualMapView = extendComponentView({
  72086. type: 'visualMap',
  72087. /**
  72088. * @readOnly
  72089. * @type {Object}
  72090. */
  72091. autoPositionValues: {
  72092. left: 1,
  72093. right: 1,
  72094. top: 1,
  72095. bottom: 1
  72096. },
  72097. init: function (ecModel, api) {
  72098. /**
  72099. * @readOnly
  72100. * @type {module:echarts/model/Global}
  72101. */
  72102. this.ecModel = ecModel;
  72103. /**
  72104. * @readOnly
  72105. * @type {module:echarts/ExtensionAPI}
  72106. */
  72107. this.api = api;
  72108. /**
  72109. * @readOnly
  72110. * @type {module:echarts/component/visualMap/visualMapModel}
  72111. */
  72112. this.visualMapModel;
  72113. },
  72114. /**
  72115. * @protected
  72116. */
  72117. render: function (visualMapModel, ecModel, api, payload) {
  72118. this.visualMapModel = visualMapModel;
  72119. if (visualMapModel.get('show') === false) {
  72120. this.group.removeAll();
  72121. return;
  72122. }
  72123. this.doRender.apply(this, arguments);
  72124. },
  72125. /**
  72126. * @protected
  72127. */
  72128. renderBackground: function (group) {
  72129. var visualMapModel = this.visualMapModel;
  72130. var padding = normalizeCssArray$1(visualMapModel.get('padding') || 0);
  72131. var rect = group.getBoundingRect();
  72132. group.add(new Rect({
  72133. z2: -1,
  72134. // Lay background rect on the lowest layer.
  72135. silent: true,
  72136. shape: {
  72137. x: rect.x - padding[3],
  72138. y: rect.y - padding[0],
  72139. width: rect.width + padding[3] + padding[1],
  72140. height: rect.height + padding[0] + padding[2]
  72141. },
  72142. style: {
  72143. fill: visualMapModel.get('backgroundColor'),
  72144. stroke: visualMapModel.get('borderColor'),
  72145. lineWidth: visualMapModel.get('borderWidth')
  72146. }
  72147. }));
  72148. },
  72149. /**
  72150. * @protected
  72151. * @param {number} targetValue can be Infinity or -Infinity
  72152. * @param {string=} visualCluster Only can be 'color' 'opacity' 'symbol' 'symbolSize'
  72153. * @param {Object} [opts]
  72154. * @param {string=} [opts.forceState] Specify state, instead of using getValueState method.
  72155. * @param {string=} [opts.convertOpacityToAlpha=false] For color gradient in controller widget.
  72156. * @return {*} Visual value.
  72157. */
  72158. getControllerVisual: function (targetValue, visualCluster, opts) {
  72159. opts = opts || {};
  72160. var forceState = opts.forceState;
  72161. var visualMapModel = this.visualMapModel;
  72162. var visualObj = {}; // Default values.
  72163. if (visualCluster === 'symbol') {
  72164. visualObj.symbol = visualMapModel.get('itemSymbol');
  72165. }
  72166. if (visualCluster === 'color') {
  72167. var defaultColor = visualMapModel.get('contentColor');
  72168. visualObj.color = defaultColor;
  72169. }
  72170. function getter(key) {
  72171. return visualObj[key];
  72172. }
  72173. function setter(key, value) {
  72174. visualObj[key] = value;
  72175. }
  72176. var mappings = visualMapModel.controllerVisuals[forceState || visualMapModel.getValueState(targetValue)];
  72177. var visualTypes = VisualMapping.prepareVisualTypes(mappings);
  72178. each$1(visualTypes, function (type) {
  72179. var visualMapping = mappings[type];
  72180. if (opts.convertOpacityToAlpha && type === 'opacity') {
  72181. type = 'colorAlpha';
  72182. visualMapping = mappings.__alphaForOpacity;
  72183. }
  72184. if (VisualMapping.dependsOn(type, visualCluster)) {
  72185. visualMapping && visualMapping.applyVisual(targetValue, getter, setter);
  72186. }
  72187. });
  72188. return visualObj[visualCluster];
  72189. },
  72190. /**
  72191. * @protected
  72192. */
  72193. positionGroup: function (group) {
  72194. var model = this.visualMapModel;
  72195. var api = this.api;
  72196. positionElement(group, model.getBoxLayoutParams(), {
  72197. width: api.getWidth(),
  72198. height: api.getHeight()
  72199. });
  72200. },
  72201. /**
  72202. * @protected
  72203. * @abstract
  72204. */
  72205. doRender: noop
  72206. });
  72207. /*
  72208. * Licensed to the Apache Software Foundation (ASF) under one
  72209. * or more contributor license agreements. See the NOTICE file
  72210. * distributed with this work for additional information
  72211. * regarding copyright ownership. The ASF licenses this file
  72212. * to you under the Apache License, Version 2.0 (the
  72213. * "License"); you may not use this file except in compliance
  72214. * with the License. You may obtain a copy of the License at
  72215. *
  72216. * http://www.apache.org/licenses/LICENSE-2.0
  72217. *
  72218. * Unless required by applicable law or agreed to in writing,
  72219. * software distributed under the License is distributed on an
  72220. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72221. * KIND, either express or implied. See the License for the
  72222. * specific language governing permissions and limitations
  72223. * under the License.
  72224. */
  72225. /**
  72226. * @param {module:echarts/component/visualMap/VisualMapModel} visualMapModel\
  72227. * @param {module:echarts/ExtensionAPI} api
  72228. * @param {Array.<number>} itemSize always [short, long]
  72229. * @return {string} 'left' or 'right' or 'top' or 'bottom'
  72230. */
  72231. function getItemAlign(visualMapModel, api, itemSize) {
  72232. var modelOption = visualMapModel.option;
  72233. var itemAlign = modelOption.align;
  72234. if (itemAlign != null && itemAlign !== 'auto') {
  72235. return itemAlign;
  72236. } // Auto decision align.
  72237. var ecSize = {
  72238. width: api.getWidth(),
  72239. height: api.getHeight()
  72240. };
  72241. var realIndex = modelOption.orient === 'horizontal' ? 1 : 0;
  72242. var paramsSet = [['left', 'right', 'width'], ['top', 'bottom', 'height']];
  72243. var reals = paramsSet[realIndex];
  72244. var fakeValue = [0, null, 10];
  72245. var layoutInput = {};
  72246. for (var i = 0; i < 3; i++) {
  72247. layoutInput[paramsSet[1 - realIndex][i]] = fakeValue[i];
  72248. layoutInput[reals[i]] = i === 2 ? itemSize[0] : modelOption[reals[i]];
  72249. }
  72250. var rParam = [['x', 'width', 3], ['y', 'height', 0]][realIndex];
  72251. var rect = getLayoutRect(layoutInput, ecSize, modelOption.padding);
  72252. return reals[(rect.margin[rParam[2]] || 0) + rect[rParam[0]] + rect[rParam[1]] * 0.5 < ecSize[rParam[1]] * 0.5 ? 0 : 1];
  72253. }
  72254. /**
  72255. * Prepare dataIndex for outside usage, where dataIndex means rawIndex, and
  72256. * dataIndexInside means filtered index.
  72257. */
  72258. function makeHighDownBatch(batch, visualMapModel) {
  72259. each$1(batch || [], function (batchItem) {
  72260. if (batchItem.dataIndex != null) {
  72261. batchItem.dataIndexInside = batchItem.dataIndex;
  72262. batchItem.dataIndex = null;
  72263. }
  72264. batchItem.highlightKey = 'visualMap' + (visualMapModel ? visualMapModel.componentIndex : '');
  72265. });
  72266. return batch;
  72267. }
  72268. /*
  72269. * Licensed to the Apache Software Foundation (ASF) under one
  72270. * or more contributor license agreements. See the NOTICE file
  72271. * distributed with this work for additional information
  72272. * regarding copyright ownership. The ASF licenses this file
  72273. * to you under the Apache License, Version 2.0 (the
  72274. * "License"); you may not use this file except in compliance
  72275. * with the License. You may obtain a copy of the License at
  72276. *
  72277. * http://www.apache.org/licenses/LICENSE-2.0
  72278. *
  72279. * Unless required by applicable law or agreed to in writing,
  72280. * software distributed under the License is distributed on an
  72281. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72282. * KIND, either express or implied. See the License for the
  72283. * specific language governing permissions and limitations
  72284. * under the License.
  72285. */
  72286. var linearMap$3 = linearMap;
  72287. var each$27 = each$1;
  72288. var mathMin$8 = Math.min;
  72289. var mathMax$8 = Math.max; // Arbitrary value
  72290. var HOVER_LINK_SIZE = 12;
  72291. var HOVER_LINK_OUT = 6; // Notice:
  72292. // Any "interval" should be by the order of [low, high].
  72293. // "handle0" (handleIndex === 0) maps to
  72294. // low data value: this._dataInterval[0] and has low coord.
  72295. // "handle1" (handleIndex === 1) maps to
  72296. // high data value: this._dataInterval[1] and has high coord.
  72297. // The logic of transform is implemented in this._createBarGroup.
  72298. var ContinuousView = VisualMapView.extend({
  72299. type: 'visualMap.continuous',
  72300. /**
  72301. * @override
  72302. */
  72303. init: function () {
  72304. ContinuousView.superApply(this, 'init', arguments);
  72305. /**
  72306. * @private
  72307. */
  72308. this._shapes = {};
  72309. /**
  72310. * @private
  72311. */
  72312. this._dataInterval = [];
  72313. /**
  72314. * @private
  72315. */
  72316. this._handleEnds = [];
  72317. /**
  72318. * @private
  72319. */
  72320. this._orient;
  72321. /**
  72322. * @private
  72323. */
  72324. this._useHandle;
  72325. /**
  72326. * @private
  72327. */
  72328. this._hoverLinkDataIndices = [];
  72329. /**
  72330. * @private
  72331. */
  72332. this._dragging;
  72333. /**
  72334. * @private
  72335. */
  72336. this._hovering;
  72337. },
  72338. /**
  72339. * @protected
  72340. * @override
  72341. */
  72342. doRender: function (visualMapModel, ecModel, api, payload) {
  72343. if (!payload || payload.type !== 'selectDataRange' || payload.from !== this.uid) {
  72344. this._buildView();
  72345. }
  72346. },
  72347. /**
  72348. * @private
  72349. */
  72350. _buildView: function () {
  72351. this.group.removeAll();
  72352. var visualMapModel = this.visualMapModel;
  72353. var thisGroup = this.group;
  72354. this._orient = visualMapModel.get('orient');
  72355. this._useHandle = visualMapModel.get('calculable');
  72356. this._resetInterval();
  72357. this._renderBar(thisGroup);
  72358. var dataRangeText = visualMapModel.get('text');
  72359. this._renderEndsText(thisGroup, dataRangeText, 0);
  72360. this._renderEndsText(thisGroup, dataRangeText, 1); // Do this for background size calculation.
  72361. this._updateView(true); // After updating view, inner shapes is built completely,
  72362. // and then background can be rendered.
  72363. this.renderBackground(thisGroup); // Real update view
  72364. this._updateView();
  72365. this._enableHoverLinkToSeries();
  72366. this._enableHoverLinkFromSeries();
  72367. this.positionGroup(thisGroup);
  72368. },
  72369. /**
  72370. * @private
  72371. */
  72372. _renderEndsText: function (group, dataRangeText, endsIndex) {
  72373. if (!dataRangeText) {
  72374. return;
  72375. } // Compatible with ec2, text[0] map to high value, text[1] map low value.
  72376. var text = dataRangeText[1 - endsIndex];
  72377. text = text != null ? text + '' : '';
  72378. var visualMapModel = this.visualMapModel;
  72379. var textGap = visualMapModel.get('textGap');
  72380. var itemSize = visualMapModel.itemSize;
  72381. var barGroup = this._shapes.barGroup;
  72382. var position = this._applyTransform([itemSize[0] / 2, endsIndex === 0 ? -textGap : itemSize[1] + textGap], barGroup);
  72383. var align = this._applyTransform(endsIndex === 0 ? 'bottom' : 'top', barGroup);
  72384. var orient = this._orient;
  72385. var textStyleModel = this.visualMapModel.textStyleModel;
  72386. this.group.add(new Text({
  72387. style: {
  72388. x: position[0],
  72389. y: position[1],
  72390. textVerticalAlign: orient === 'horizontal' ? 'middle' : align,
  72391. textAlign: orient === 'horizontal' ? align : 'center',
  72392. text: text,
  72393. textFont: textStyleModel.getFont(),
  72394. textFill: textStyleModel.getTextColor()
  72395. }
  72396. }));
  72397. },
  72398. /**
  72399. * @private
  72400. */
  72401. _renderBar: function (targetGroup) {
  72402. var visualMapModel = this.visualMapModel;
  72403. var shapes = this._shapes;
  72404. var itemSize = visualMapModel.itemSize;
  72405. var orient = this._orient;
  72406. var useHandle = this._useHandle;
  72407. var itemAlign = getItemAlign(visualMapModel, this.api, itemSize);
  72408. var barGroup = shapes.barGroup = this._createBarGroup(itemAlign); // Bar
  72409. barGroup.add(shapes.outOfRange = createPolygon());
  72410. barGroup.add(shapes.inRange = createPolygon(null, useHandle ? getCursor$1(this._orient) : null, bind(this._dragHandle, this, 'all', false), bind(this._dragHandle, this, 'all', true)));
  72411. var textRect = visualMapModel.textStyleModel.getTextRect('国');
  72412. var textSize = mathMax$8(textRect.width, textRect.height); // Handle
  72413. if (useHandle) {
  72414. shapes.handleThumbs = [];
  72415. shapes.handleLabels = [];
  72416. shapes.handleLabelPoints = [];
  72417. this._createHandle(barGroup, 0, itemSize, textSize, orient, itemAlign);
  72418. this._createHandle(barGroup, 1, itemSize, textSize, orient, itemAlign);
  72419. }
  72420. this._createIndicator(barGroup, itemSize, textSize, orient);
  72421. targetGroup.add(barGroup);
  72422. },
  72423. /**
  72424. * @private
  72425. */
  72426. _createHandle: function (barGroup, handleIndex, itemSize, textSize, orient) {
  72427. var onDrift = bind(this._dragHandle, this, handleIndex, false);
  72428. var onDragEnd = bind(this._dragHandle, this, handleIndex, true);
  72429. var handleThumb = createPolygon(createHandlePoints(handleIndex, textSize), getCursor$1(this._orient), onDrift, onDragEnd);
  72430. handleThumb.position[0] = itemSize[0];
  72431. barGroup.add(handleThumb); // Text is always horizontal layout but should not be effected by
  72432. // transform (orient/inverse). So label is built separately but not
  72433. // use zrender/graphic/helper/RectText, and is located based on view
  72434. // group (according to handleLabelPoint) but not barGroup.
  72435. var textStyleModel = this.visualMapModel.textStyleModel;
  72436. var handleLabel = new Text({
  72437. draggable: true,
  72438. drift: onDrift,
  72439. onmousemove: function (e) {
  72440. // Fot mobile devicem, prevent screen slider on the button.
  72441. stop(e.event);
  72442. },
  72443. ondragend: onDragEnd,
  72444. style: {
  72445. x: 0,
  72446. y: 0,
  72447. text: '',
  72448. textFont: textStyleModel.getFont(),
  72449. textFill: textStyleModel.getTextColor()
  72450. }
  72451. });
  72452. this.group.add(handleLabel);
  72453. var handleLabelPoint = [orient === 'horizontal' ? textSize / 2 : textSize * 1.5, orient === 'horizontal' ? handleIndex === 0 ? -(textSize * 1.5) : textSize * 1.5 : handleIndex === 0 ? -textSize / 2 : textSize / 2];
  72454. var shapes = this._shapes;
  72455. shapes.handleThumbs[handleIndex] = handleThumb;
  72456. shapes.handleLabelPoints[handleIndex] = handleLabelPoint;
  72457. shapes.handleLabels[handleIndex] = handleLabel;
  72458. },
  72459. /**
  72460. * @private
  72461. */
  72462. _createIndicator: function (barGroup, itemSize, textSize, orient) {
  72463. var indicator = createPolygon([[0, 0]], 'move');
  72464. indicator.position[0] = itemSize[0];
  72465. indicator.attr({
  72466. invisible: true,
  72467. silent: true
  72468. });
  72469. barGroup.add(indicator);
  72470. var textStyleModel = this.visualMapModel.textStyleModel;
  72471. var indicatorLabel = new Text({
  72472. silent: true,
  72473. invisible: true,
  72474. style: {
  72475. x: 0,
  72476. y: 0,
  72477. text: '',
  72478. textFont: textStyleModel.getFont(),
  72479. textFill: textStyleModel.getTextColor()
  72480. }
  72481. });
  72482. this.group.add(indicatorLabel);
  72483. var indicatorLabelPoint = [orient === 'horizontal' ? textSize / 2 : HOVER_LINK_OUT + 3, 0];
  72484. var shapes = this._shapes;
  72485. shapes.indicator = indicator;
  72486. shapes.indicatorLabel = indicatorLabel;
  72487. shapes.indicatorLabelPoint = indicatorLabelPoint;
  72488. },
  72489. /**
  72490. * @private
  72491. */
  72492. _dragHandle: function (handleIndex, isEnd, dx, dy) {
  72493. if (!this._useHandle) {
  72494. return;
  72495. }
  72496. this._dragging = !isEnd;
  72497. if (!isEnd) {
  72498. // Transform dx, dy to bar coordination.
  72499. var vertex = this._applyTransform([dx, dy], this._shapes.barGroup, true);
  72500. this._updateInterval(handleIndex, vertex[1]); // Considering realtime, update view should be executed
  72501. // before dispatch action.
  72502. this._updateView();
  72503. } // dragEnd do not dispatch action when realtime.
  72504. if (isEnd === !this.visualMapModel.get('realtime')) {
  72505. // jshint ignore:line
  72506. this.api.dispatchAction({
  72507. type: 'selectDataRange',
  72508. from: this.uid,
  72509. visualMapId: this.visualMapModel.id,
  72510. selected: this._dataInterval.slice()
  72511. });
  72512. }
  72513. if (isEnd) {
  72514. !this._hovering && this._clearHoverLinkToSeries();
  72515. } else if (useHoverLinkOnHandle(this.visualMapModel)) {
  72516. this._doHoverLinkToSeries(this._handleEnds[handleIndex], false);
  72517. }
  72518. },
  72519. /**
  72520. * @private
  72521. */
  72522. _resetInterval: function () {
  72523. var visualMapModel = this.visualMapModel;
  72524. var dataInterval = this._dataInterval = visualMapModel.getSelected();
  72525. var dataExtent = visualMapModel.getExtent();
  72526. var sizeExtent = [0, visualMapModel.itemSize[1]];
  72527. this._handleEnds = [linearMap$3(dataInterval[0], dataExtent, sizeExtent, true), linearMap$3(dataInterval[1], dataExtent, sizeExtent, true)];
  72528. },
  72529. /**
  72530. * @private
  72531. * @param {(number|string)} handleIndex 0 or 1 or 'all'
  72532. * @param {number} dx
  72533. * @param {number} dy
  72534. */
  72535. _updateInterval: function (handleIndex, delta) {
  72536. delta = delta || 0;
  72537. var visualMapModel = this.visualMapModel;
  72538. var handleEnds = this._handleEnds;
  72539. var sizeExtent = [0, visualMapModel.itemSize[1]];
  72540. sliderMove(delta, handleEnds, sizeExtent, handleIndex, // cross is forbiden
  72541. 0);
  72542. var dataExtent = visualMapModel.getExtent(); // Update data interval.
  72543. this._dataInterval = [linearMap$3(handleEnds[0], sizeExtent, dataExtent, true), linearMap$3(handleEnds[1], sizeExtent, dataExtent, true)];
  72544. },
  72545. /**
  72546. * @private
  72547. */
  72548. _updateView: function (forSketch) {
  72549. var visualMapModel = this.visualMapModel;
  72550. var dataExtent = visualMapModel.getExtent();
  72551. var shapes = this._shapes;
  72552. var outOfRangeHandleEnds = [0, visualMapModel.itemSize[1]];
  72553. var inRangeHandleEnds = forSketch ? outOfRangeHandleEnds : this._handleEnds;
  72554. var visualInRange = this._createBarVisual(this._dataInterval, dataExtent, inRangeHandleEnds, 'inRange');
  72555. var visualOutOfRange = this._createBarVisual(dataExtent, dataExtent, outOfRangeHandleEnds, 'outOfRange');
  72556. shapes.inRange.setStyle({
  72557. fill: visualInRange.barColor,
  72558. opacity: visualInRange.opacity
  72559. }).setShape('points', visualInRange.barPoints);
  72560. shapes.outOfRange.setStyle({
  72561. fill: visualOutOfRange.barColor,
  72562. opacity: visualOutOfRange.opacity
  72563. }).setShape('points', visualOutOfRange.barPoints);
  72564. this._updateHandle(inRangeHandleEnds, visualInRange);
  72565. },
  72566. /**
  72567. * @private
  72568. */
  72569. _createBarVisual: function (dataInterval, dataExtent, handleEnds, forceState) {
  72570. var opts = {
  72571. forceState: forceState,
  72572. convertOpacityToAlpha: true
  72573. };
  72574. var colorStops = this._makeColorGradient(dataInterval, opts);
  72575. var symbolSizes = [this.getControllerVisual(dataInterval[0], 'symbolSize', opts), this.getControllerVisual(dataInterval[1], 'symbolSize', opts)];
  72576. var barPoints = this._createBarPoints(handleEnds, symbolSizes);
  72577. return {
  72578. barColor: new LinearGradient(0, 0, 0, 1, colorStops),
  72579. barPoints: barPoints,
  72580. handlesColor: [colorStops[0].color, colorStops[colorStops.length - 1].color]
  72581. };
  72582. },
  72583. /**
  72584. * @private
  72585. */
  72586. _makeColorGradient: function (dataInterval, opts) {
  72587. // Considering colorHue, which is not linear, so we have to sample
  72588. // to calculate gradient color stops, but not only caculate head
  72589. // and tail.
  72590. var sampleNumber = 100; // Arbitrary value.
  72591. var colorStops = [];
  72592. var step = (dataInterval[1] - dataInterval[0]) / sampleNumber;
  72593. colorStops.push({
  72594. color: this.getControllerVisual(dataInterval[0], 'color', opts),
  72595. offset: 0
  72596. });
  72597. for (var i = 1; i < sampleNumber; i++) {
  72598. var currValue = dataInterval[0] + step * i;
  72599. if (currValue > dataInterval[1]) {
  72600. break;
  72601. }
  72602. colorStops.push({
  72603. color: this.getControllerVisual(currValue, 'color', opts),
  72604. offset: i / sampleNumber
  72605. });
  72606. }
  72607. colorStops.push({
  72608. color: this.getControllerVisual(dataInterval[1], 'color', opts),
  72609. offset: 1
  72610. });
  72611. return colorStops;
  72612. },
  72613. /**
  72614. * @private
  72615. */
  72616. _createBarPoints: function (handleEnds, symbolSizes) {
  72617. var itemSize = this.visualMapModel.itemSize;
  72618. return [[itemSize[0] - symbolSizes[0], handleEnds[0]], [itemSize[0], handleEnds[0]], [itemSize[0], handleEnds[1]], [itemSize[0] - symbolSizes[1], handleEnds[1]]];
  72619. },
  72620. /**
  72621. * @private
  72622. */
  72623. _createBarGroup: function (itemAlign) {
  72624. var orient = this._orient;
  72625. var inverse = this.visualMapModel.get('inverse');
  72626. return new Group(orient === 'horizontal' && !inverse ? {
  72627. scale: itemAlign === 'bottom' ? [1, 1] : [-1, 1],
  72628. rotation: Math.PI / 2
  72629. } : orient === 'horizontal' && inverse ? {
  72630. scale: itemAlign === 'bottom' ? [-1, 1] : [1, 1],
  72631. rotation: -Math.PI / 2
  72632. } : orient === 'vertical' && !inverse ? {
  72633. scale: itemAlign === 'left' ? [1, -1] : [-1, -1]
  72634. } : {
  72635. scale: itemAlign === 'left' ? [1, 1] : [-1, 1]
  72636. });
  72637. },
  72638. /**
  72639. * @private
  72640. */
  72641. _updateHandle: function (handleEnds, visualInRange) {
  72642. if (!this._useHandle) {
  72643. return;
  72644. }
  72645. var shapes = this._shapes;
  72646. var visualMapModel = this.visualMapModel;
  72647. var handleThumbs = shapes.handleThumbs;
  72648. var handleLabels = shapes.handleLabels;
  72649. each$27([0, 1], function (handleIndex) {
  72650. var handleThumb = handleThumbs[handleIndex];
  72651. handleThumb.setStyle('fill', visualInRange.handlesColor[handleIndex]);
  72652. handleThumb.position[1] = handleEnds[handleIndex]; // Update handle label position.
  72653. var textPoint = applyTransform$1(shapes.handleLabelPoints[handleIndex], getTransform(handleThumb, this.group));
  72654. handleLabels[handleIndex].setStyle({
  72655. x: textPoint[0],
  72656. y: textPoint[1],
  72657. text: visualMapModel.formatValueText(this._dataInterval[handleIndex]),
  72658. textVerticalAlign: 'middle',
  72659. textAlign: this._applyTransform(this._orient === 'horizontal' ? handleIndex === 0 ? 'bottom' : 'top' : 'left', shapes.barGroup)
  72660. });
  72661. }, this);
  72662. },
  72663. /**
  72664. * @private
  72665. * @param {number} cursorValue
  72666. * @param {number} textValue
  72667. * @param {string} [rangeSymbol]
  72668. * @param {number} [halfHoverLinkSize]
  72669. */
  72670. _showIndicator: function (cursorValue, textValue, rangeSymbol, halfHoverLinkSize) {
  72671. var visualMapModel = this.visualMapModel;
  72672. var dataExtent = visualMapModel.getExtent();
  72673. var itemSize = visualMapModel.itemSize;
  72674. var sizeExtent = [0, itemSize[1]];
  72675. var pos = linearMap$3(cursorValue, dataExtent, sizeExtent, true);
  72676. var shapes = this._shapes;
  72677. var indicator = shapes.indicator;
  72678. if (!indicator) {
  72679. return;
  72680. }
  72681. indicator.position[1] = pos;
  72682. indicator.attr('invisible', false);
  72683. indicator.setShape('points', createIndicatorPoints(!!rangeSymbol, halfHoverLinkSize, pos, itemSize[1]));
  72684. var opts = {
  72685. convertOpacityToAlpha: true
  72686. };
  72687. var color = this.getControllerVisual(cursorValue, 'color', opts);
  72688. indicator.setStyle('fill', color); // Update handle label position.
  72689. var textPoint = applyTransform$1(shapes.indicatorLabelPoint, getTransform(indicator, this.group));
  72690. var indicatorLabel = shapes.indicatorLabel;
  72691. indicatorLabel.attr('invisible', false);
  72692. var align = this._applyTransform('left', shapes.barGroup);
  72693. var orient = this._orient;
  72694. indicatorLabel.setStyle({
  72695. text: (rangeSymbol ? rangeSymbol : '') + visualMapModel.formatValueText(textValue),
  72696. textVerticalAlign: orient === 'horizontal' ? align : 'middle',
  72697. textAlign: orient === 'horizontal' ? 'center' : align,
  72698. x: textPoint[0],
  72699. y: textPoint[1]
  72700. });
  72701. },
  72702. /**
  72703. * @private
  72704. */
  72705. _enableHoverLinkToSeries: function () {
  72706. var self = this;
  72707. this._shapes.barGroup.on('mousemove', function (e) {
  72708. self._hovering = true;
  72709. if (!self._dragging) {
  72710. var itemSize = self.visualMapModel.itemSize;
  72711. var pos = self._applyTransform([e.offsetX, e.offsetY], self._shapes.barGroup, true, true); // For hover link show when hover handle, which might be
  72712. // below or upper than sizeExtent.
  72713. pos[1] = mathMin$8(mathMax$8(0, pos[1]), itemSize[1]);
  72714. self._doHoverLinkToSeries(pos[1], 0 <= pos[0] && pos[0] <= itemSize[0]);
  72715. }
  72716. }).on('mouseout', function () {
  72717. // When mouse is out of handle, hoverLink still need
  72718. // to be displayed when realtime is set as false.
  72719. self._hovering = false;
  72720. !self._dragging && self._clearHoverLinkToSeries();
  72721. });
  72722. },
  72723. /**
  72724. * @private
  72725. */
  72726. _enableHoverLinkFromSeries: function () {
  72727. var zr = this.api.getZr();
  72728. if (this.visualMapModel.option.hoverLink) {
  72729. zr.on('mouseover', this._hoverLinkFromSeriesMouseOver, this);
  72730. zr.on('mouseout', this._hideIndicator, this);
  72731. } else {
  72732. this._clearHoverLinkFromSeries();
  72733. }
  72734. },
  72735. /**
  72736. * @private
  72737. */
  72738. _doHoverLinkToSeries: function (cursorPos, hoverOnBar) {
  72739. var visualMapModel = this.visualMapModel;
  72740. var itemSize = visualMapModel.itemSize;
  72741. if (!visualMapModel.option.hoverLink) {
  72742. return;
  72743. }
  72744. var sizeExtent = [0, itemSize[1]];
  72745. var dataExtent = visualMapModel.getExtent(); // For hover link show when hover handle, which might be below or upper than sizeExtent.
  72746. cursorPos = mathMin$8(mathMax$8(sizeExtent[0], cursorPos), sizeExtent[1]);
  72747. var halfHoverLinkSize = getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent);
  72748. var hoverRange = [cursorPos - halfHoverLinkSize, cursorPos + halfHoverLinkSize];
  72749. var cursorValue = linearMap$3(cursorPos, sizeExtent, dataExtent, true);
  72750. var valueRange = [linearMap$3(hoverRange[0], sizeExtent, dataExtent, true), linearMap$3(hoverRange[1], sizeExtent, dataExtent, true)]; // Consider data range is out of visualMap range, see test/visualMap-continuous.html,
  72751. // where china and india has very large population.
  72752. hoverRange[0] < sizeExtent[0] && (valueRange[0] = -Infinity);
  72753. hoverRange[1] > sizeExtent[1] && (valueRange[1] = Infinity); // Do not show indicator when mouse is over handle,
  72754. // otherwise labels overlap, especially when dragging.
  72755. if (hoverOnBar) {
  72756. if (valueRange[0] === -Infinity) {
  72757. this._showIndicator(cursorValue, valueRange[1], '< ', halfHoverLinkSize);
  72758. } else if (valueRange[1] === Infinity) {
  72759. this._showIndicator(cursorValue, valueRange[0], '> ', halfHoverLinkSize);
  72760. } else {
  72761. this._showIndicator(cursorValue, cursorValue, '≈ ', halfHoverLinkSize);
  72762. }
  72763. } // When realtime is set as false, handles, which are in barGroup,
  72764. // also trigger hoverLink, which help user to realize where they
  72765. // focus on when dragging. (see test/heatmap-large.html)
  72766. // When realtime is set as true, highlight will not show when hover
  72767. // handle, because the label on handle, which displays a exact value
  72768. // but not range, might mislead users.
  72769. var oldBatch = this._hoverLinkDataIndices;
  72770. var newBatch = [];
  72771. if (hoverOnBar || useHoverLinkOnHandle(visualMapModel)) {
  72772. newBatch = this._hoverLinkDataIndices = visualMapModel.findTargetDataIndices(valueRange);
  72773. }
  72774. var resultBatches = compressBatches(oldBatch, newBatch);
  72775. this._dispatchHighDown('downplay', makeHighDownBatch(resultBatches[0], visualMapModel));
  72776. this._dispatchHighDown('highlight', makeHighDownBatch(resultBatches[1], visualMapModel));
  72777. },
  72778. /**
  72779. * @private
  72780. */
  72781. _hoverLinkFromSeriesMouseOver: function (e) {
  72782. var el = e.target;
  72783. var visualMapModel = this.visualMapModel;
  72784. if (!el || el.dataIndex == null) {
  72785. return;
  72786. }
  72787. var dataModel = this.ecModel.getSeriesByIndex(el.seriesIndex);
  72788. if (!visualMapModel.isTargetSeries(dataModel)) {
  72789. return;
  72790. }
  72791. var data = dataModel.getData(el.dataType);
  72792. var value = data.get(visualMapModel.getDataDimension(data), el.dataIndex, true);
  72793. if (!isNaN(value)) {
  72794. this._showIndicator(value, value);
  72795. }
  72796. },
  72797. /**
  72798. * @private
  72799. */
  72800. _hideIndicator: function () {
  72801. var shapes = this._shapes;
  72802. shapes.indicator && shapes.indicator.attr('invisible', true);
  72803. shapes.indicatorLabel && shapes.indicatorLabel.attr('invisible', true);
  72804. },
  72805. /**
  72806. * @private
  72807. */
  72808. _clearHoverLinkToSeries: function () {
  72809. this._hideIndicator();
  72810. var indices = this._hoverLinkDataIndices;
  72811. this._dispatchHighDown('downplay', makeHighDownBatch(indices, this.visualMapModel));
  72812. indices.length = 0;
  72813. },
  72814. /**
  72815. * @private
  72816. */
  72817. _clearHoverLinkFromSeries: function () {
  72818. this._hideIndicator();
  72819. var zr = this.api.getZr();
  72820. zr.off('mouseover', this._hoverLinkFromSeriesMouseOver);
  72821. zr.off('mouseout', this._hideIndicator);
  72822. },
  72823. /**
  72824. * @private
  72825. */
  72826. _applyTransform: function (vertex, element, inverse, global) {
  72827. var transform = getTransform(element, global ? null : this.group);
  72828. return graphic[isArray(vertex) ? 'applyTransform' : 'transformDirection'](vertex, transform, inverse);
  72829. },
  72830. /**
  72831. * @private
  72832. */
  72833. _dispatchHighDown: function (type, batch) {
  72834. batch && batch.length && this.api.dispatchAction({
  72835. type: type,
  72836. batch: batch
  72837. });
  72838. },
  72839. /**
  72840. * @override
  72841. */
  72842. dispose: function () {
  72843. this._clearHoverLinkFromSeries();
  72844. this._clearHoverLinkToSeries();
  72845. },
  72846. /**
  72847. * @override
  72848. */
  72849. remove: function () {
  72850. this._clearHoverLinkFromSeries();
  72851. this._clearHoverLinkToSeries();
  72852. }
  72853. });
  72854. function createPolygon(points, cursor, onDrift, onDragEnd) {
  72855. return new Polygon({
  72856. shape: {
  72857. points: points
  72858. },
  72859. draggable: !!onDrift,
  72860. cursor: cursor,
  72861. drift: onDrift,
  72862. onmousemove: function (e) {
  72863. // Fot mobile devicem, prevent screen slider on the button.
  72864. stop(e.event);
  72865. },
  72866. ondragend: onDragEnd
  72867. });
  72868. }
  72869. function createHandlePoints(handleIndex, textSize) {
  72870. return handleIndex === 0 ? [[0, 0], [textSize, 0], [textSize, -textSize]] : [[0, 0], [textSize, 0], [textSize, textSize]];
  72871. }
  72872. function createIndicatorPoints(isRange, halfHoverLinkSize, pos, extentMax) {
  72873. return isRange ? [// indicate range
  72874. [0, -mathMin$8(halfHoverLinkSize, mathMax$8(pos, 0))], [HOVER_LINK_OUT, 0], [0, mathMin$8(halfHoverLinkSize, mathMax$8(extentMax - pos, 0))]] : [// indicate single value
  72875. [0, 0], [5, -5], [5, 5]];
  72876. }
  72877. function getHalfHoverLinkSize(visualMapModel, dataExtent, sizeExtent) {
  72878. var halfHoverLinkSize = HOVER_LINK_SIZE / 2;
  72879. var hoverLinkDataSize = visualMapModel.get('hoverLinkDataSize');
  72880. if (hoverLinkDataSize) {
  72881. halfHoverLinkSize = linearMap$3(hoverLinkDataSize, dataExtent, sizeExtent, true) / 2;
  72882. }
  72883. return halfHoverLinkSize;
  72884. }
  72885. function useHoverLinkOnHandle(visualMapModel) {
  72886. var hoverLinkOnHandle = visualMapModel.get('hoverLinkOnHandle');
  72887. return !!(hoverLinkOnHandle == null ? visualMapModel.get('realtime') : hoverLinkOnHandle);
  72888. }
  72889. function getCursor$1(orient) {
  72890. return orient === 'vertical' ? 'ns-resize' : 'ew-resize';
  72891. }
  72892. /*
  72893. * Licensed to the Apache Software Foundation (ASF) under one
  72894. * or more contributor license agreements. See the NOTICE file
  72895. * distributed with this work for additional information
  72896. * regarding copyright ownership. The ASF licenses this file
  72897. * to you under the Apache License, Version 2.0 (the
  72898. * "License"); you may not use this file except in compliance
  72899. * with the License. You may obtain a copy of the License at
  72900. *
  72901. * http://www.apache.org/licenses/LICENSE-2.0
  72902. *
  72903. * Unless required by applicable law or agreed to in writing,
  72904. * software distributed under the License is distributed on an
  72905. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72906. * KIND, either express or implied. See the License for the
  72907. * specific language governing permissions and limitations
  72908. * under the License.
  72909. */
  72910. var actionInfo$2 = {
  72911. type: 'selectDataRange',
  72912. event: 'dataRangeSelected',
  72913. // FIXME use updateView appears wrong
  72914. update: 'update'
  72915. };
  72916. registerAction(actionInfo$2, function (payload, ecModel) {
  72917. ecModel.eachComponent({
  72918. mainType: 'visualMap',
  72919. query: payload
  72920. }, function (model) {
  72921. model.setSelected(payload.selected);
  72922. });
  72923. });
  72924. /*
  72925. * Licensed to the Apache Software Foundation (ASF) under one
  72926. * or more contributor license agreements. See the NOTICE file
  72927. * distributed with this work for additional information
  72928. * regarding copyright ownership. The ASF licenses this file
  72929. * to you under the Apache License, Version 2.0 (the
  72930. * "License"); you may not use this file except in compliance
  72931. * with the License. You may obtain a copy of the License at
  72932. *
  72933. * http://www.apache.org/licenses/LICENSE-2.0
  72934. *
  72935. * Unless required by applicable law or agreed to in writing,
  72936. * software distributed under the License is distributed on an
  72937. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72938. * KIND, either express or implied. See the License for the
  72939. * specific language governing permissions and limitations
  72940. * under the License.
  72941. */
  72942. /**
  72943. * DataZoom component entry
  72944. */
  72945. registerPreprocessor(preprocessor$3);
  72946. /*
  72947. * Licensed to the Apache Software Foundation (ASF) under one
  72948. * or more contributor license agreements. See the NOTICE file
  72949. * distributed with this work for additional information
  72950. * regarding copyright ownership. The ASF licenses this file
  72951. * to you under the Apache License, Version 2.0 (the
  72952. * "License"); you may not use this file except in compliance
  72953. * with the License. You may obtain a copy of the License at
  72954. *
  72955. * http://www.apache.org/licenses/LICENSE-2.0
  72956. *
  72957. * Unless required by applicable law or agreed to in writing,
  72958. * software distributed under the License is distributed on an
  72959. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  72960. * KIND, either express or implied. See the License for the
  72961. * specific language governing permissions and limitations
  72962. * under the License.
  72963. */
  72964. var PiecewiseModel = VisualMapModel.extend({
  72965. type: 'visualMap.piecewise',
  72966. /**
  72967. * Order Rule:
  72968. *
  72969. * option.categories / option.pieces / option.text / option.selected:
  72970. * If !option.inverse,
  72971. * Order when vertical: ['top', ..., 'bottom'].
  72972. * Order when horizontal: ['left', ..., 'right'].
  72973. * If option.inverse, the meaning of
  72974. * the order should be reversed.
  72975. *
  72976. * this._pieceList:
  72977. * The order is always [low, ..., high].
  72978. *
  72979. * Mapping from location to low-high:
  72980. * If !option.inverse
  72981. * When vertical, top is high.
  72982. * When horizontal, right is high.
  72983. * If option.inverse, reverse.
  72984. */
  72985. /**
  72986. * @protected
  72987. */
  72988. defaultOption: {
  72989. selected: null,
  72990. // Object. If not specified, means selected.
  72991. // When pieces and splitNumber: {'0': true, '5': true}
  72992. // When categories: {'cate1': false, 'cate3': true}
  72993. // When selected === false, means all unselected.
  72994. minOpen: false,
  72995. // Whether include values that smaller than `min`.
  72996. maxOpen: false,
  72997. // Whether include values that bigger than `max`.
  72998. align: 'auto',
  72999. // 'auto', 'left', 'right'
  73000. itemWidth: 20,
  73001. // When put the controller vertically, it is the length of
  73002. // horizontal side of each item. Otherwise, vertical side.
  73003. itemHeight: 14,
  73004. // When put the controller vertically, it is the length of
  73005. // vertical side of each item. Otherwise, horizontal side.
  73006. itemSymbol: 'roundRect',
  73007. pieceList: null,
  73008. // Each item is Object, with some of those attrs:
  73009. // {min, max, lt, gt, lte, gte, value,
  73010. // color, colorSaturation, colorAlpha, opacity,
  73011. // symbol, symbolSize}, which customize the range or visual
  73012. // coding of the certain piece. Besides, see "Order Rule".
  73013. categories: null,
  73014. // category names, like: ['some1', 'some2', 'some3'].
  73015. // Attr min/max are ignored when categories set. See "Order Rule"
  73016. splitNumber: 5,
  73017. // If set to 5, auto split five pieces equally.
  73018. // If set to 0 and component type not set, component type will be
  73019. // determined as "continuous". (It is less reasonable but for ec2
  73020. // compatibility, see echarts/component/visualMap/typeDefaulter)
  73021. selectedMode: 'multiple',
  73022. // Can be 'multiple' or 'single'.
  73023. itemGap: 10,
  73024. // The gap between two items, in px.
  73025. hoverLink: true,
  73026. // Enable hover highlight.
  73027. showLabel: null // By default, when text is used, label will hide (the logic
  73028. // is remained for compatibility reason)
  73029. },
  73030. /**
  73031. * @override
  73032. */
  73033. optionUpdated: function (newOption, isInit) {
  73034. PiecewiseModel.superApply(this, 'optionUpdated', arguments);
  73035. /**
  73036. * The order is always [low, ..., high].
  73037. * [{text: string, interval: Array.<number>}, ...]
  73038. * @private
  73039. * @type {Array.<Object>}
  73040. */
  73041. this._pieceList = [];
  73042. this.resetExtent();
  73043. /**
  73044. * 'pieces', 'categories', 'splitNumber'
  73045. * @type {string}
  73046. */
  73047. var mode = this._mode = this._determineMode();
  73048. resetMethods[this._mode].call(this);
  73049. this._resetSelected(newOption, isInit);
  73050. var categories = this.option.categories;
  73051. this.resetVisual(function (mappingOption, state) {
  73052. if (mode === 'categories') {
  73053. mappingOption.mappingMethod = 'category';
  73054. mappingOption.categories = clone(categories);
  73055. } else {
  73056. mappingOption.dataExtent = this.getExtent();
  73057. mappingOption.mappingMethod = 'piecewise';
  73058. mappingOption.pieceList = map(this._pieceList, function (piece) {
  73059. var piece = clone(piece);
  73060. if (state !== 'inRange') {
  73061. // FIXME
  73062. // outOfRange do not support special visual in pieces.
  73063. piece.visual = null;
  73064. }
  73065. return piece;
  73066. });
  73067. }
  73068. });
  73069. },
  73070. /**
  73071. * @protected
  73072. * @override
  73073. */
  73074. completeVisualOption: function () {
  73075. // Consider this case:
  73076. // visualMap: {
  73077. // pieces: [{symbol: 'circle', lt: 0}, {symbol: 'rect', gte: 0}]
  73078. // }
  73079. // where no inRange/outOfRange set but only pieces. So we should make
  73080. // default inRange/outOfRange for this case, otherwise visuals that only
  73081. // appear in `pieces` will not be taken into account in visual encoding.
  73082. var option = this.option;
  73083. var visualTypesInPieces = {};
  73084. var visualTypes = VisualMapping.listVisualTypes();
  73085. var isCategory = this.isCategory();
  73086. each$1(option.pieces, function (piece) {
  73087. each$1(visualTypes, function (visualType) {
  73088. if (piece.hasOwnProperty(visualType)) {
  73089. visualTypesInPieces[visualType] = 1;
  73090. }
  73091. });
  73092. });
  73093. each$1(visualTypesInPieces, function (v, visualType) {
  73094. var exists = 0;
  73095. each$1(this.stateList, function (state) {
  73096. exists |= has(option, state, visualType) || has(option.target, state, visualType);
  73097. }, this);
  73098. !exists && each$1(this.stateList, function (state) {
  73099. (option[state] || (option[state] = {}))[visualType] = visualDefault.get(visualType, state === 'inRange' ? 'active' : 'inactive', isCategory);
  73100. });
  73101. }, this);
  73102. function has(obj, state, visualType) {
  73103. return obj && obj[state] && (isObject$1(obj[state]) ? obj[state].hasOwnProperty(visualType) : obj[state] === visualType // e.g., inRange: 'symbol'
  73104. );
  73105. }
  73106. VisualMapModel.prototype.completeVisualOption.apply(this, arguments);
  73107. },
  73108. _resetSelected: function (newOption, isInit) {
  73109. var thisOption = this.option;
  73110. var pieceList = this._pieceList; // Selected do not merge but all override.
  73111. var selected = (isInit ? thisOption : newOption).selected || {};
  73112. thisOption.selected = selected; // Consider 'not specified' means true.
  73113. each$1(pieceList, function (piece, index) {
  73114. var key = this.getSelectedMapKey(piece);
  73115. if (!selected.hasOwnProperty(key)) {
  73116. selected[key] = true;
  73117. }
  73118. }, this);
  73119. if (thisOption.selectedMode === 'single') {
  73120. // Ensure there is only one selected.
  73121. var hasSel = false;
  73122. each$1(pieceList, function (piece, index) {
  73123. var key = this.getSelectedMapKey(piece);
  73124. if (selected[key]) {
  73125. hasSel ? selected[key] = false : hasSel = true;
  73126. }
  73127. }, this);
  73128. } // thisOption.selectedMode === 'multiple', default: all selected.
  73129. },
  73130. /**
  73131. * @public
  73132. */
  73133. getSelectedMapKey: function (piece) {
  73134. return this._mode === 'categories' ? piece.value + '' : piece.index + '';
  73135. },
  73136. /**
  73137. * @public
  73138. */
  73139. getPieceList: function () {
  73140. return this._pieceList;
  73141. },
  73142. /**
  73143. * @private
  73144. * @return {string}
  73145. */
  73146. _determineMode: function () {
  73147. var option = this.option;
  73148. return option.pieces && option.pieces.length > 0 ? 'pieces' : this.option.categories ? 'categories' : 'splitNumber';
  73149. },
  73150. /**
  73151. * @public
  73152. * @override
  73153. */
  73154. setSelected: function (selected) {
  73155. this.option.selected = clone(selected);
  73156. },
  73157. /**
  73158. * @public
  73159. * @override
  73160. */
  73161. getValueState: function (value) {
  73162. var index = VisualMapping.findPieceIndex(value, this._pieceList);
  73163. return index != null ? this.option.selected[this.getSelectedMapKey(this._pieceList[index])] ? 'inRange' : 'outOfRange' : 'outOfRange';
  73164. },
  73165. /**
  73166. * @public
  73167. * @params {number} pieceIndex piece index in visualMapModel.getPieceList()
  73168. * @return {Array.<Object>} [{seriesId, dataIndex: <Array.<number>>}, ...]
  73169. */
  73170. findTargetDataIndices: function (pieceIndex) {
  73171. var result = [];
  73172. this.eachTargetSeries(function (seriesModel) {
  73173. var dataIndices = [];
  73174. var data = seriesModel.getData();
  73175. data.each(this.getDataDimension(data), function (value, dataIndex) {
  73176. // Should always base on model pieceList, because it is order sensitive.
  73177. var pIdx = VisualMapping.findPieceIndex(value, this._pieceList);
  73178. pIdx === pieceIndex && dataIndices.push(dataIndex);
  73179. }, this);
  73180. result.push({
  73181. seriesId: seriesModel.id,
  73182. dataIndex: dataIndices
  73183. });
  73184. }, this);
  73185. return result;
  73186. },
  73187. /**
  73188. * @private
  73189. * @param {Object} piece piece.value or piece.interval is required.
  73190. * @return {number} Can be Infinity or -Infinity
  73191. */
  73192. getRepresentValue: function (piece) {
  73193. var representValue;
  73194. if (this.isCategory()) {
  73195. representValue = piece.value;
  73196. } else {
  73197. if (piece.value != null) {
  73198. representValue = piece.value;
  73199. } else {
  73200. var pieceInterval = piece.interval || [];
  73201. representValue = pieceInterval[0] === -Infinity && pieceInterval[1] === Infinity ? 0 : (pieceInterval[0] + pieceInterval[1]) / 2;
  73202. }
  73203. }
  73204. return representValue;
  73205. },
  73206. getVisualMeta: function (getColorVisual) {
  73207. // Do not support category. (category axis is ordinal, numerical)
  73208. if (this.isCategory()) {
  73209. return;
  73210. }
  73211. var stops = [];
  73212. var outerColors = [];
  73213. var visualMapModel = this;
  73214. function setStop(interval, valueState) {
  73215. var representValue = visualMapModel.getRepresentValue({
  73216. interval: interval
  73217. });
  73218. if (!valueState) {
  73219. valueState = visualMapModel.getValueState(representValue);
  73220. }
  73221. var color = getColorVisual(representValue, valueState);
  73222. if (interval[0] === -Infinity) {
  73223. outerColors[0] = color;
  73224. } else if (interval[1] === Infinity) {
  73225. outerColors[1] = color;
  73226. } else {
  73227. stops.push({
  73228. value: interval[0],
  73229. color: color
  73230. }, {
  73231. value: interval[1],
  73232. color: color
  73233. });
  73234. }
  73235. } // Suplement
  73236. var pieceList = this._pieceList.slice();
  73237. if (!pieceList.length) {
  73238. pieceList.push({
  73239. interval: [-Infinity, Infinity]
  73240. });
  73241. } else {
  73242. var edge = pieceList[0].interval[0];
  73243. edge !== -Infinity && pieceList.unshift({
  73244. interval: [-Infinity, edge]
  73245. });
  73246. edge = pieceList[pieceList.length - 1].interval[1];
  73247. edge !== Infinity && pieceList.push({
  73248. interval: [edge, Infinity]
  73249. });
  73250. }
  73251. var curr = -Infinity;
  73252. each$1(pieceList, function (piece) {
  73253. var interval = piece.interval;
  73254. if (interval) {
  73255. // Fulfill gap.
  73256. interval[0] > curr && setStop([curr, interval[0]], 'outOfRange');
  73257. setStop(interval.slice());
  73258. curr = interval[1];
  73259. }
  73260. }, this);
  73261. return {
  73262. stops: stops,
  73263. outerColors: outerColors
  73264. };
  73265. }
  73266. });
  73267. /**
  73268. * Key is this._mode
  73269. * @type {Object}
  73270. * @this {module:echarts/component/viusalMap/PiecewiseMode}
  73271. */
  73272. var resetMethods = {
  73273. splitNumber: function () {
  73274. var thisOption = this.option;
  73275. var pieceList = this._pieceList;
  73276. var precision = Math.min(thisOption.precision, 20);
  73277. var dataExtent = this.getExtent();
  73278. var splitNumber = thisOption.splitNumber;
  73279. splitNumber = Math.max(parseInt(splitNumber, 10), 1);
  73280. thisOption.splitNumber = splitNumber;
  73281. var splitStep = (dataExtent[1] - dataExtent[0]) / splitNumber; // Precision auto-adaption
  73282. while (+splitStep.toFixed(precision) !== splitStep && precision < 5) {
  73283. precision++;
  73284. }
  73285. thisOption.precision = precision;
  73286. splitStep = +splitStep.toFixed(precision);
  73287. if (thisOption.minOpen) {
  73288. pieceList.push({
  73289. interval: [-Infinity, dataExtent[0]],
  73290. close: [0, 0]
  73291. });
  73292. }
  73293. for (var index = 0, curr = dataExtent[0]; index < splitNumber; curr += splitStep, index++) {
  73294. var max = index === splitNumber - 1 ? dataExtent[1] : curr + splitStep;
  73295. pieceList.push({
  73296. interval: [curr, max],
  73297. close: [1, 1]
  73298. });
  73299. }
  73300. if (thisOption.maxOpen) {
  73301. pieceList.push({
  73302. interval: [dataExtent[1], Infinity],
  73303. close: [0, 0]
  73304. });
  73305. }
  73306. reformIntervals(pieceList);
  73307. each$1(pieceList, function (piece, index) {
  73308. piece.index = index;
  73309. piece.text = this.formatValueText(piece.interval);
  73310. }, this);
  73311. },
  73312. categories: function () {
  73313. var thisOption = this.option;
  73314. each$1(thisOption.categories, function (cate) {
  73315. // FIXME category模式也使用pieceList,但在visualMapping中不是使用pieceList。
  73316. // 是否改一致。
  73317. this._pieceList.push({
  73318. text: this.formatValueText(cate, true),
  73319. value: cate
  73320. });
  73321. }, this); // See "Order Rule".
  73322. normalizeReverse(thisOption, this._pieceList);
  73323. },
  73324. pieces: function () {
  73325. var thisOption = this.option;
  73326. var pieceList = this._pieceList;
  73327. each$1(thisOption.pieces, function (pieceListItem, index) {
  73328. if (!isObject$1(pieceListItem)) {
  73329. pieceListItem = {
  73330. value: pieceListItem
  73331. };
  73332. }
  73333. var item = {
  73334. text: '',
  73335. index: index
  73336. };
  73337. if (pieceListItem.label != null) {
  73338. item.text = pieceListItem.label;
  73339. }
  73340. if (pieceListItem.hasOwnProperty('value')) {
  73341. var value = item.value = pieceListItem.value;
  73342. item.interval = [value, value];
  73343. item.close = [1, 1];
  73344. } else {
  73345. // `min` `max` is legacy option.
  73346. // `lt` `gt` `lte` `gte` is recommanded.
  73347. var interval = item.interval = [];
  73348. var close = item.close = [0, 0];
  73349. var closeList = [1, 0, 1];
  73350. var infinityList = [-Infinity, Infinity];
  73351. var useMinMax = [];
  73352. for (var lg = 0; lg < 2; lg++) {
  73353. var names = [['gte', 'gt', 'min'], ['lte', 'lt', 'max']][lg];
  73354. for (var i = 0; i < 3 && interval[lg] == null; i++) {
  73355. interval[lg] = pieceListItem[names[i]];
  73356. close[lg] = closeList[i];
  73357. useMinMax[lg] = i === 2;
  73358. }
  73359. interval[lg] == null && (interval[lg] = infinityList[lg]);
  73360. }
  73361. useMinMax[0] && interval[1] === Infinity && (close[0] = 0);
  73362. useMinMax[1] && interval[0] === -Infinity && (close[1] = 0);
  73363. if (interval[0] === interval[1] && close[0] && close[1]) {
  73364. // Consider: [{min: 5, max: 5, visual: {...}}, {min: 0, max: 5}],
  73365. // we use value to lift the priority when min === max
  73366. item.value = interval[0];
  73367. }
  73368. }
  73369. item.visual = VisualMapping.retrieveVisuals(pieceListItem);
  73370. pieceList.push(item);
  73371. }, this); // See "Order Rule".
  73372. normalizeReverse(thisOption, pieceList); // Only pieces
  73373. reformIntervals(pieceList);
  73374. each$1(pieceList, function (piece) {
  73375. var close = piece.close;
  73376. var edgeSymbols = [['<', '≤'][close[1]], ['>', '≥'][close[0]]];
  73377. piece.text = piece.text || this.formatValueText(piece.value != null ? piece.value : piece.interval, false, edgeSymbols);
  73378. }, this);
  73379. }
  73380. };
  73381. function normalizeReverse(thisOption, pieceList) {
  73382. var inverse = thisOption.inverse;
  73383. if (thisOption.orient === 'vertical' ? !inverse : inverse) {
  73384. pieceList.reverse();
  73385. }
  73386. }
  73387. /*
  73388. * Licensed to the Apache Software Foundation (ASF) under one
  73389. * or more contributor license agreements. See the NOTICE file
  73390. * distributed with this work for additional information
  73391. * regarding copyright ownership. The ASF licenses this file
  73392. * to you under the Apache License, Version 2.0 (the
  73393. * "License"); you may not use this file except in compliance
  73394. * with the License. You may obtain a copy of the License at
  73395. *
  73396. * http://www.apache.org/licenses/LICENSE-2.0
  73397. *
  73398. * Unless required by applicable law or agreed to in writing,
  73399. * software distributed under the License is distributed on an
  73400. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73401. * KIND, either express or implied. See the License for the
  73402. * specific language governing permissions and limitations
  73403. * under the License.
  73404. */
  73405. var PiecewiseVisualMapView = VisualMapView.extend({
  73406. type: 'visualMap.piecewise',
  73407. /**
  73408. * @protected
  73409. * @override
  73410. */
  73411. doRender: function () {
  73412. var thisGroup = this.group;
  73413. thisGroup.removeAll();
  73414. var visualMapModel = this.visualMapModel;
  73415. var textGap = visualMapModel.get('textGap');
  73416. var textStyleModel = visualMapModel.textStyleModel;
  73417. var textFont = textStyleModel.getFont();
  73418. var textFill = textStyleModel.getTextColor();
  73419. var itemAlign = this._getItemAlign();
  73420. var itemSize = visualMapModel.itemSize;
  73421. var viewData = this._getViewData();
  73422. var endsText = viewData.endsText;
  73423. var showLabel = retrieve(visualMapModel.get('showLabel', true), !endsText);
  73424. endsText && this._renderEndsText(thisGroup, endsText[0], itemSize, showLabel, itemAlign);
  73425. each$1(viewData.viewPieceList, renderItem, this);
  73426. endsText && this._renderEndsText(thisGroup, endsText[1], itemSize, showLabel, itemAlign);
  73427. box(visualMapModel.get('orient'), thisGroup, visualMapModel.get('itemGap'));
  73428. this.renderBackground(thisGroup);
  73429. this.positionGroup(thisGroup);
  73430. function renderItem(item) {
  73431. var piece = item.piece;
  73432. var itemGroup = new Group();
  73433. itemGroup.onclick = bind(this._onItemClick, this, piece);
  73434. this._enableHoverLink(itemGroup, item.indexInModelPieceList);
  73435. var representValue = visualMapModel.getRepresentValue(piece);
  73436. this._createItemSymbol(itemGroup, representValue, [0, 0, itemSize[0], itemSize[1]]);
  73437. if (showLabel) {
  73438. var visualState = this.visualMapModel.getValueState(representValue);
  73439. itemGroup.add(new Text({
  73440. style: {
  73441. x: itemAlign === 'right' ? -textGap : itemSize[0] + textGap,
  73442. y: itemSize[1] / 2,
  73443. text: piece.text,
  73444. textVerticalAlign: 'middle',
  73445. textAlign: itemAlign,
  73446. textFont: textFont,
  73447. textFill: textFill,
  73448. opacity: visualState === 'outOfRange' ? 0.5 : 1
  73449. }
  73450. }));
  73451. }
  73452. thisGroup.add(itemGroup);
  73453. }
  73454. },
  73455. /**
  73456. * @private
  73457. */
  73458. _enableHoverLink: function (itemGroup, pieceIndex) {
  73459. itemGroup.on('mouseover', bind(onHoverLink, this, 'highlight')).on('mouseout', bind(onHoverLink, this, 'downplay'));
  73460. function onHoverLink(method) {
  73461. var visualMapModel = this.visualMapModel;
  73462. visualMapModel.option.hoverLink && this.api.dispatchAction({
  73463. type: method,
  73464. batch: makeHighDownBatch(visualMapModel.findTargetDataIndices(pieceIndex), visualMapModel)
  73465. });
  73466. }
  73467. },
  73468. /**
  73469. * @private
  73470. */
  73471. _getItemAlign: function () {
  73472. var visualMapModel = this.visualMapModel;
  73473. var modelOption = visualMapModel.option;
  73474. if (modelOption.orient === 'vertical') {
  73475. return getItemAlign(visualMapModel, this.api, visualMapModel.itemSize);
  73476. } else {
  73477. // horizontal, most case left unless specifying right.
  73478. var align = modelOption.align;
  73479. if (!align || align === 'auto') {
  73480. align = 'left';
  73481. }
  73482. return align;
  73483. }
  73484. },
  73485. /**
  73486. * @private
  73487. */
  73488. _renderEndsText: function (group, text, itemSize, showLabel, itemAlign) {
  73489. if (!text) {
  73490. return;
  73491. }
  73492. var itemGroup = new Group();
  73493. var textStyleModel = this.visualMapModel.textStyleModel;
  73494. itemGroup.add(new Text({
  73495. style: {
  73496. x: showLabel ? itemAlign === 'right' ? itemSize[0] : 0 : itemSize[0] / 2,
  73497. y: itemSize[1] / 2,
  73498. textVerticalAlign: 'middle',
  73499. textAlign: showLabel ? itemAlign : 'center',
  73500. text: text,
  73501. textFont: textStyleModel.getFont(),
  73502. textFill: textStyleModel.getTextColor()
  73503. }
  73504. }));
  73505. group.add(itemGroup);
  73506. },
  73507. /**
  73508. * @private
  73509. * @return {Object} {peiceList, endsText} The order is the same as screen pixel order.
  73510. */
  73511. _getViewData: function () {
  73512. var visualMapModel = this.visualMapModel;
  73513. var viewPieceList = map(visualMapModel.getPieceList(), function (piece, index) {
  73514. return {
  73515. piece: piece,
  73516. indexInModelPieceList: index
  73517. };
  73518. });
  73519. var endsText = visualMapModel.get('text'); // Consider orient and inverse.
  73520. var orient = visualMapModel.get('orient');
  73521. var inverse = visualMapModel.get('inverse'); // Order of model pieceList is always [low, ..., high]
  73522. if (orient === 'horizontal' ? inverse : !inverse) {
  73523. viewPieceList.reverse();
  73524. } // Origin order of endsText is [high, low]
  73525. else if (endsText) {
  73526. endsText = endsText.slice().reverse();
  73527. }
  73528. return {
  73529. viewPieceList: viewPieceList,
  73530. endsText: endsText
  73531. };
  73532. },
  73533. /**
  73534. * @private
  73535. */
  73536. _createItemSymbol: function (group, representValue, shapeParam) {
  73537. group.add(createSymbol(this.getControllerVisual(representValue, 'symbol'), shapeParam[0], shapeParam[1], shapeParam[2], shapeParam[3], this.getControllerVisual(representValue, 'color')));
  73538. },
  73539. /**
  73540. * @private
  73541. */
  73542. _onItemClick: function (piece) {
  73543. var visualMapModel = this.visualMapModel;
  73544. var option = visualMapModel.option;
  73545. var selected = clone(option.selected);
  73546. var newKey = visualMapModel.getSelectedMapKey(piece);
  73547. if (option.selectedMode === 'single') {
  73548. selected[newKey] = true;
  73549. each$1(selected, function (o, key) {
  73550. selected[key] = key === newKey;
  73551. });
  73552. } else {
  73553. selected[newKey] = !selected[newKey];
  73554. }
  73555. this.api.dispatchAction({
  73556. type: 'selectDataRange',
  73557. from: this.uid,
  73558. visualMapId: this.visualMapModel.id,
  73559. selected: selected
  73560. });
  73561. }
  73562. });
  73563. /*
  73564. * Licensed to the Apache Software Foundation (ASF) under one
  73565. * or more contributor license agreements. See the NOTICE file
  73566. * distributed with this work for additional information
  73567. * regarding copyright ownership. The ASF licenses this file
  73568. * to you under the Apache License, Version 2.0 (the
  73569. * "License"); you may not use this file except in compliance
  73570. * with the License. You may obtain a copy of the License at
  73571. *
  73572. * http://www.apache.org/licenses/LICENSE-2.0
  73573. *
  73574. * Unless required by applicable law or agreed to in writing,
  73575. * software distributed under the License is distributed on an
  73576. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73577. * KIND, either express or implied. See the License for the
  73578. * specific language governing permissions and limitations
  73579. * under the License.
  73580. */
  73581. /**
  73582. * DataZoom component entry
  73583. */
  73584. registerPreprocessor(preprocessor$3);
  73585. /*
  73586. * Licensed to the Apache Software Foundation (ASF) under one
  73587. * or more contributor license agreements. See the NOTICE file
  73588. * distributed with this work for additional information
  73589. * regarding copyright ownership. The ASF licenses this file
  73590. * to you under the Apache License, Version 2.0 (the
  73591. * "License"); you may not use this file except in compliance
  73592. * with the License. You may obtain a copy of the License at
  73593. *
  73594. * http://www.apache.org/licenses/LICENSE-2.0
  73595. *
  73596. * Unless required by applicable law or agreed to in writing,
  73597. * software distributed under the License is distributed on an
  73598. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73599. * KIND, either express or implied. See the License for the
  73600. * specific language governing permissions and limitations
  73601. * under the License.
  73602. */
  73603. /**
  73604. * visualMap component entry
  73605. */
  73606. /*
  73607. * Licensed to the Apache Software Foundation (ASF) under one
  73608. * or more contributor license agreements. See the NOTICE file
  73609. * distributed with this work for additional information
  73610. * regarding copyright ownership. The ASF licenses this file
  73611. * to you under the Apache License, Version 2.0 (the
  73612. * "License"); you may not use this file except in compliance
  73613. * with the License. You may obtain a copy of the License at
  73614. *
  73615. * http://www.apache.org/licenses/LICENSE-2.0
  73616. *
  73617. * Unless required by applicable law or agreed to in writing,
  73618. * software distributed under the License is distributed on an
  73619. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73620. * KIND, either express or implied. See the License for the
  73621. * specific language governing permissions and limitations
  73622. * under the License.
  73623. */
  73624. var ToolboxModel = extendComponentModel({
  73625. type: 'toolbox',
  73626. layoutMode: {
  73627. type: 'box',
  73628. ignoreSize: true
  73629. },
  73630. optionUpdated: function () {
  73631. ToolboxModel.superApply(this, 'optionUpdated', arguments);
  73632. each$1(this.option.feature, function (featureOpt, featureName) {
  73633. var Feature = get$1(featureName);
  73634. Feature && merge(featureOpt, Feature.defaultOption);
  73635. });
  73636. },
  73637. defaultOption: {
  73638. show: true,
  73639. z: 6,
  73640. zlevel: 0,
  73641. orient: 'horizontal',
  73642. left: 'right',
  73643. top: 'top',
  73644. // right
  73645. // bottom
  73646. backgroundColor: 'transparent',
  73647. borderColor: '#ccc',
  73648. borderRadius: 0,
  73649. borderWidth: 0,
  73650. padding: 5,
  73651. itemSize: 15,
  73652. itemGap: 8,
  73653. showTitle: true,
  73654. iconStyle: {
  73655. borderColor: '#666',
  73656. color: 'none'
  73657. },
  73658. emphasis: {
  73659. iconStyle: {
  73660. borderColor: '#3E98C5'
  73661. }
  73662. },
  73663. // textStyle: {},
  73664. // feature
  73665. tooltip: {
  73666. show: false
  73667. }
  73668. }
  73669. });
  73670. /*
  73671. * Licensed to the Apache Software Foundation (ASF) under one
  73672. * or more contributor license agreements. See the NOTICE file
  73673. * distributed with this work for additional information
  73674. * regarding copyright ownership. The ASF licenses this file
  73675. * to you under the Apache License, Version 2.0 (the
  73676. * "License"); you may not use this file except in compliance
  73677. * with the License. You may obtain a copy of the License at
  73678. *
  73679. * http://www.apache.org/licenses/LICENSE-2.0
  73680. *
  73681. * Unless required by applicable law or agreed to in writing,
  73682. * software distributed under the License is distributed on an
  73683. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73684. * KIND, either express or implied. See the License for the
  73685. * specific language governing permissions and limitations
  73686. * under the License.
  73687. */
  73688. extendComponentView({
  73689. type: 'toolbox',
  73690. render: function (toolboxModel, ecModel, api, payload) {
  73691. var group = this.group;
  73692. group.removeAll();
  73693. if (!toolboxModel.get('show')) {
  73694. return;
  73695. }
  73696. var itemSize = +toolboxModel.get('itemSize');
  73697. var featureOpts = toolboxModel.get('feature') || {};
  73698. var features = this._features || (this._features = {});
  73699. var featureNames = [];
  73700. each$1(featureOpts, function (opt, name) {
  73701. featureNames.push(name);
  73702. });
  73703. new DataDiffer(this._featureNames || [], featureNames).add(processFeature).update(processFeature).remove(curry(processFeature, null)).execute(); // Keep for diff.
  73704. this._featureNames = featureNames;
  73705. function processFeature(newIndex, oldIndex) {
  73706. var featureName = featureNames[newIndex];
  73707. var oldName = featureNames[oldIndex];
  73708. var featureOpt = featureOpts[featureName];
  73709. var featureModel = new Model(featureOpt, toolboxModel, toolboxModel.ecModel);
  73710. var feature; // FIX#11236, merge feature title from MagicType newOption. TODO: consider seriesIndex ?
  73711. if (payload && payload.newTitle != null && payload.featureName === featureName) {
  73712. featureOpt.title = payload.newTitle;
  73713. }
  73714. if (featureName && !oldName) {
  73715. // Create
  73716. if (isUserFeatureName(featureName)) {
  73717. feature = {
  73718. model: featureModel,
  73719. onclick: featureModel.option.onclick,
  73720. featureName: featureName
  73721. };
  73722. } else {
  73723. var Feature = get$1(featureName);
  73724. if (!Feature) {
  73725. return;
  73726. }
  73727. feature = new Feature(featureModel, ecModel, api);
  73728. }
  73729. features[featureName] = feature;
  73730. } else {
  73731. feature = features[oldName]; // If feature does not exsit.
  73732. if (!feature) {
  73733. return;
  73734. }
  73735. feature.model = featureModel;
  73736. feature.ecModel = ecModel;
  73737. feature.api = api;
  73738. }
  73739. if (!featureName && oldName) {
  73740. feature.dispose && feature.dispose(ecModel, api);
  73741. return;
  73742. }
  73743. if (!featureModel.get('show') || feature.unusable) {
  73744. feature.remove && feature.remove(ecModel, api);
  73745. return;
  73746. }
  73747. createIconPaths(featureModel, feature, featureName);
  73748. featureModel.setIconStatus = function (iconName, status) {
  73749. var option = this.option;
  73750. var iconPaths = this.iconPaths;
  73751. option.iconStatus = option.iconStatus || {};
  73752. option.iconStatus[iconName] = status; // FIXME
  73753. iconPaths[iconName] && iconPaths[iconName].trigger(status);
  73754. };
  73755. if (feature.render) {
  73756. feature.render(featureModel, ecModel, api, payload);
  73757. }
  73758. }
  73759. function createIconPaths(featureModel, feature, featureName) {
  73760. var iconStyleModel = featureModel.getModel('iconStyle');
  73761. var iconStyleEmphasisModel = featureModel.getModel('emphasis.iconStyle'); // If one feature has mutiple icon. they are orginaized as
  73762. // {
  73763. // icon: {
  73764. // foo: '',
  73765. // bar: ''
  73766. // },
  73767. // title: {
  73768. // foo: '',
  73769. // bar: ''
  73770. // }
  73771. // }
  73772. var icons = feature.getIcons ? feature.getIcons() : featureModel.get('icon');
  73773. var titles = featureModel.get('title') || {};
  73774. if (typeof icons === 'string') {
  73775. var icon = icons;
  73776. var title = titles;
  73777. icons = {};
  73778. titles = {};
  73779. icons[featureName] = icon;
  73780. titles[featureName] = title;
  73781. }
  73782. var iconPaths = featureModel.iconPaths = {};
  73783. each$1(icons, function (iconStr, iconName) {
  73784. var path = createIcon(iconStr, {}, {
  73785. x: -itemSize / 2,
  73786. y: -itemSize / 2,
  73787. width: itemSize,
  73788. height: itemSize
  73789. });
  73790. path.setStyle(iconStyleModel.getItemStyle());
  73791. path.hoverStyle = iconStyleEmphasisModel.getItemStyle(); // Text position calculation
  73792. path.setStyle({
  73793. text: titles[iconName],
  73794. textAlign: iconStyleEmphasisModel.get('textAlign'),
  73795. textBorderRadius: iconStyleEmphasisModel.get('textBorderRadius'),
  73796. textPadding: iconStyleEmphasisModel.get('textPadding'),
  73797. textFill: null
  73798. });
  73799. var tooltipModel = toolboxModel.getModel('tooltip');
  73800. if (tooltipModel && tooltipModel.get('show')) {
  73801. path.attr('tooltip', extend({
  73802. content: titles[iconName],
  73803. formatter: tooltipModel.get('formatter', true) || function () {
  73804. return titles[iconName];
  73805. },
  73806. formatterParams: {
  73807. componentType: 'toolbox',
  73808. name: iconName,
  73809. title: titles[iconName],
  73810. $vars: ['name', 'title']
  73811. },
  73812. position: tooltipModel.get('position', true) || 'bottom'
  73813. }, tooltipModel.option));
  73814. }
  73815. setHoverStyle(path);
  73816. if (toolboxModel.get('showTitle')) {
  73817. path.__title = titles[iconName];
  73818. path.on('mouseover', function () {
  73819. // Should not reuse above hoverStyle, which might be modified.
  73820. var hoverStyle = iconStyleEmphasisModel.getItemStyle();
  73821. var defaultTextPosition = toolboxModel.get('orient') === 'vertical' ? toolboxModel.get('right') == null ? 'right' : 'left' : toolboxModel.get('bottom') == null ? 'bottom' : 'top';
  73822. path.setStyle({
  73823. textFill: iconStyleEmphasisModel.get('textFill') || hoverStyle.fill || hoverStyle.stroke || '#000',
  73824. textBackgroundColor: iconStyleEmphasisModel.get('textBackgroundColor'),
  73825. textPosition: iconStyleEmphasisModel.get('textPosition') || defaultTextPosition
  73826. });
  73827. }).on('mouseout', function () {
  73828. path.setStyle({
  73829. textFill: null,
  73830. textBackgroundColor: null
  73831. });
  73832. });
  73833. }
  73834. path.trigger(featureModel.get('iconStatus.' + iconName) || 'normal');
  73835. group.add(path);
  73836. path.on('click', bind(feature.onclick, feature, ecModel, api, iconName));
  73837. iconPaths[iconName] = path;
  73838. });
  73839. }
  73840. layout$3(group, toolboxModel, api); // Render background after group is layout
  73841. // FIXME
  73842. group.add(makeBackground(group.getBoundingRect(), toolboxModel)); // Adjust icon title positions to avoid them out of screen
  73843. group.eachChild(function (icon) {
  73844. var titleText = icon.__title;
  73845. var hoverStyle = icon.hoverStyle; // May be background element
  73846. if (hoverStyle && titleText) {
  73847. var rect = getBoundingRect(titleText, makeFont(hoverStyle));
  73848. var offsetX = icon.position[0] + group.position[0];
  73849. var offsetY = icon.position[1] + group.position[1] + itemSize;
  73850. var needPutOnTop = false;
  73851. if (offsetY + rect.height > api.getHeight()) {
  73852. hoverStyle.textPosition = 'top';
  73853. needPutOnTop = true;
  73854. }
  73855. var topOffset = needPutOnTop ? -5 - rect.height : itemSize + 8;
  73856. if (offsetX + rect.width / 2 > api.getWidth()) {
  73857. hoverStyle.textPosition = ['100%', topOffset];
  73858. hoverStyle.textAlign = 'right';
  73859. } else if (offsetX - rect.width / 2 < 0) {
  73860. hoverStyle.textPosition = [0, topOffset];
  73861. hoverStyle.textAlign = 'left';
  73862. }
  73863. }
  73864. });
  73865. },
  73866. updateView: function (toolboxModel, ecModel, api, payload) {
  73867. each$1(this._features, function (feature) {
  73868. feature.updateView && feature.updateView(feature.model, ecModel, api, payload);
  73869. });
  73870. },
  73871. // updateLayout: function (toolboxModel, ecModel, api, payload) {
  73872. // zrUtil.each(this._features, function (feature) {
  73873. // feature.updateLayout && feature.updateLayout(feature.model, ecModel, api, payload);
  73874. // });
  73875. // },
  73876. remove: function (ecModel, api) {
  73877. each$1(this._features, function (feature) {
  73878. feature.remove && feature.remove(ecModel, api);
  73879. });
  73880. this.group.removeAll();
  73881. },
  73882. dispose: function (ecModel, api) {
  73883. each$1(this._features, function (feature) {
  73884. feature.dispose && feature.dispose(ecModel, api);
  73885. });
  73886. }
  73887. });
  73888. function isUserFeatureName(featureName) {
  73889. return featureName.indexOf('my') === 0;
  73890. }
  73891. /*
  73892. * Licensed to the Apache Software Foundation (ASF) under one
  73893. * or more contributor license agreements. See the NOTICE file
  73894. * distributed with this work for additional information
  73895. * regarding copyright ownership. The ASF licenses this file
  73896. * to you under the Apache License, Version 2.0 (the
  73897. * "License"); you may not use this file except in compliance
  73898. * with the License. You may obtain a copy of the License at
  73899. *
  73900. * http://www.apache.org/licenses/LICENSE-2.0
  73901. *
  73902. * Unless required by applicable law or agreed to in writing,
  73903. * software distributed under the License is distributed on an
  73904. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73905. * KIND, either express or implied. See the License for the
  73906. * specific language governing permissions and limitations
  73907. * under the License.
  73908. */
  73909. /* global Uint8Array */
  73910. var saveAsImageLang = lang.toolbox.saveAsImage;
  73911. function SaveAsImage(model) {
  73912. this.model = model;
  73913. }
  73914. SaveAsImage.defaultOption = {
  73915. show: true,
  73916. 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',
  73917. title: saveAsImageLang.title,
  73918. type: 'png',
  73919. // Default use option.backgroundColor
  73920. // backgroundColor: '#fff',
  73921. connectedBackgroundColor: '#fff',
  73922. name: '',
  73923. excludeComponents: ['toolbox'],
  73924. pixelRatio: 1,
  73925. lang: saveAsImageLang.lang.slice()
  73926. };
  73927. SaveAsImage.prototype.unusable = !env$1.canvasSupported;
  73928. var proto$4 = SaveAsImage.prototype;
  73929. proto$4.onclick = function (ecModel, api) {
  73930. var model = this.model;
  73931. var title = model.get('name') || ecModel.get('title.0.text') || 'echarts';
  73932. var isSvg = api.getZr().painter.getType() === 'svg';
  73933. var type = isSvg ? 'svg' : model.get('type', true) || 'png';
  73934. var url = api.getConnectedDataURL({
  73935. type: type,
  73936. backgroundColor: model.get('backgroundColor', true) || ecModel.get('backgroundColor') || '#fff',
  73937. connectedBackgroundColor: model.get('connectedBackgroundColor'),
  73938. excludeComponents: model.get('excludeComponents'),
  73939. pixelRatio: model.get('pixelRatio')
  73940. }); // Chrome and Firefox
  73941. if (typeof MouseEvent === 'function' && !env$1.browser.ie && !env$1.browser.edge) {
  73942. var $a = document.createElement('a');
  73943. $a.download = title + '.' + type;
  73944. $a.target = '_blank';
  73945. $a.href = url;
  73946. var evt = new MouseEvent('click', {
  73947. view: window,
  73948. bubbles: true,
  73949. cancelable: false
  73950. });
  73951. $a.dispatchEvent(evt);
  73952. } // IE
  73953. else {
  73954. if (window.navigator.msSaveOrOpenBlob) {
  73955. var bstr = atob(url.split(',')[1]);
  73956. var n = bstr.length;
  73957. var u8arr = new Uint8Array(n);
  73958. while (n--) {
  73959. u8arr[n] = bstr.charCodeAt(n);
  73960. }
  73961. var blob = new Blob([u8arr]);
  73962. window.navigator.msSaveOrOpenBlob(blob, title + '.' + type);
  73963. } else {
  73964. var lang$$1 = model.get('lang');
  73965. var html = '' + '<body style="margin:0;">' + '<img src="' + url + '" style="max-width:100%;" title="' + (lang$$1 && lang$$1[0] || '') + '" />' + '</body>';
  73966. var tab = window.open();
  73967. tab.document.write(html);
  73968. }
  73969. }
  73970. };
  73971. register$2('saveAsImage', SaveAsImage);
  73972. /*
  73973. * Licensed to the Apache Software Foundation (ASF) under one
  73974. * or more contributor license agreements. See the NOTICE file
  73975. * distributed with this work for additional information
  73976. * regarding copyright ownership. The ASF licenses this file
  73977. * to you under the Apache License, Version 2.0 (the
  73978. * "License"); you may not use this file except in compliance
  73979. * with the License. You may obtain a copy of the License at
  73980. *
  73981. * http://www.apache.org/licenses/LICENSE-2.0
  73982. *
  73983. * Unless required by applicable law or agreed to in writing,
  73984. * software distributed under the License is distributed on an
  73985. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  73986. * KIND, either express or implied. See the License for the
  73987. * specific language governing permissions and limitations
  73988. * under the License.
  73989. */
  73990. var magicTypeLang = lang.toolbox.magicType;
  73991. var INNER_STACK_KEYWORD = '__ec_magicType_stack__';
  73992. function MagicType(model) {
  73993. this.model = model;
  73994. }
  73995. MagicType.defaultOption = {
  73996. show: true,
  73997. type: [],
  73998. // Icon group
  73999. icon: {
  74000. /* eslint-disable */
  74001. line: 'M4.1,28.9h7.1l9.3-22l7.4,38l9.7-19.7l3,12.8h14.9M4.1,58h51.4',
  74002. bar: 'M6.7,22.9h10V48h-10V22.9zM24.9,13h10v35h-10V13zM43.2,2h10v46h-10V2zM3.1,58h53.7',
  74003. 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
  74004. /* eslint-enable */
  74005. },
  74006. // `line`, `bar`, `stack`, `tiled`
  74007. title: clone(magicTypeLang.title),
  74008. option: {},
  74009. seriesIndex: {}
  74010. };
  74011. var proto$5 = MagicType.prototype;
  74012. proto$5.getIcons = function () {
  74013. var model = this.model;
  74014. var availableIcons = model.get('icon');
  74015. var icons = {};
  74016. each$1(model.get('type'), function (type) {
  74017. if (availableIcons[type]) {
  74018. icons[type] = availableIcons[type];
  74019. }
  74020. });
  74021. return icons;
  74022. };
  74023. var seriesOptGenreator = {
  74024. 'line': function (seriesType, seriesId, seriesModel, model) {
  74025. if (seriesType === 'bar') {
  74026. return merge({
  74027. id: seriesId,
  74028. type: 'line',
  74029. // Preserve data related option
  74030. data: seriesModel.get('data'),
  74031. stack: seriesModel.get('stack'),
  74032. markPoint: seriesModel.get('markPoint'),
  74033. markLine: seriesModel.get('markLine')
  74034. }, model.get('option.line') || {}, true);
  74035. }
  74036. },
  74037. 'bar': function (seriesType, seriesId, seriesModel, model) {
  74038. if (seriesType === 'line') {
  74039. return merge({
  74040. id: seriesId,
  74041. type: 'bar',
  74042. // Preserve data related option
  74043. data: seriesModel.get('data'),
  74044. stack: seriesModel.get('stack'),
  74045. markPoint: seriesModel.get('markPoint'),
  74046. markLine: seriesModel.get('markLine')
  74047. }, model.get('option.bar') || {}, true);
  74048. }
  74049. },
  74050. 'stack': function (seriesType, seriesId, seriesModel, model) {
  74051. var isStack = seriesModel.get('stack') === INNER_STACK_KEYWORD;
  74052. if (seriesType === 'line' || seriesType === 'bar') {
  74053. model.setIconStatus('stack', isStack ? 'normal' : 'emphasis');
  74054. return merge({
  74055. id: seriesId,
  74056. stack: isStack ? '' : INNER_STACK_KEYWORD
  74057. }, model.get('option.stack') || {}, true);
  74058. }
  74059. }
  74060. };
  74061. var radioTypes = [['line', 'bar'], ['stack']];
  74062. proto$5.onclick = function (ecModel, api, type) {
  74063. var model = this.model;
  74064. var seriesIndex = model.get('seriesIndex.' + type); // Not supported magicType
  74065. if (!seriesOptGenreator[type]) {
  74066. return;
  74067. }
  74068. var newOption = {
  74069. series: []
  74070. };
  74071. var generateNewSeriesTypes = function (seriesModel) {
  74072. var seriesType = seriesModel.subType;
  74073. var seriesId = seriesModel.id;
  74074. var newSeriesOpt = seriesOptGenreator[type](seriesType, seriesId, seriesModel, model);
  74075. if (newSeriesOpt) {
  74076. // PENDING If merge original option?
  74077. defaults(newSeriesOpt, seriesModel.option);
  74078. newOption.series.push(newSeriesOpt);
  74079. } // Modify boundaryGap
  74080. var coordSys = seriesModel.coordinateSystem;
  74081. if (coordSys && coordSys.type === 'cartesian2d' && (type === 'line' || type === 'bar')) {
  74082. var categoryAxis = coordSys.getAxesByScale('ordinal')[0];
  74083. if (categoryAxis) {
  74084. var axisDim = categoryAxis.dim;
  74085. var axisType = axisDim + 'Axis';
  74086. var axisModel = ecModel.queryComponents({
  74087. mainType: axisType,
  74088. index: seriesModel.get(name + 'Index'),
  74089. id: seriesModel.get(name + 'Id')
  74090. })[0];
  74091. var axisIndex = axisModel.componentIndex;
  74092. newOption[axisType] = newOption[axisType] || [];
  74093. for (var i = 0; i <= axisIndex; i++) {
  74094. newOption[axisType][axisIndex] = newOption[axisType][axisIndex] || {};
  74095. }
  74096. newOption[axisType][axisIndex].boundaryGap = type === 'bar';
  74097. }
  74098. }
  74099. };
  74100. each$1(radioTypes, function (radio) {
  74101. if (indexOf(radio, type) >= 0) {
  74102. each$1(radio, function (item) {
  74103. model.setIconStatus(item, 'normal');
  74104. });
  74105. }
  74106. });
  74107. model.setIconStatus(type, 'emphasis');
  74108. ecModel.eachComponent({
  74109. mainType: 'series',
  74110. query: seriesIndex == null ? null : {
  74111. seriesIndex: seriesIndex
  74112. }
  74113. }, generateNewSeriesTypes);
  74114. var newTitle; // Change title of stack
  74115. if (type === 'stack') {
  74116. var isStack = newOption.series && newOption.series[0] && newOption.series[0].stack === INNER_STACK_KEYWORD;
  74117. newTitle = isStack ? merge({
  74118. stack: magicTypeLang.title.tiled
  74119. }, magicTypeLang.title) : clone(magicTypeLang.title);
  74120. }
  74121. api.dispatchAction({
  74122. type: 'changeMagicType',
  74123. currentType: type,
  74124. newOption: newOption,
  74125. newTitle: newTitle,
  74126. featureName: 'magicType'
  74127. });
  74128. };
  74129. registerAction({
  74130. type: 'changeMagicType',
  74131. event: 'magicTypeChanged',
  74132. update: 'prepareAndUpdate'
  74133. }, function (payload, ecModel) {
  74134. ecModel.mergeOption(payload.newOption);
  74135. });
  74136. register$2('magicType', MagicType);
  74137. /*
  74138. * Licensed to the Apache Software Foundation (ASF) under one
  74139. * or more contributor license agreements. See the NOTICE file
  74140. * distributed with this work for additional information
  74141. * regarding copyright ownership. The ASF licenses this file
  74142. * to you under the Apache License, Version 2.0 (the
  74143. * "License"); you may not use this file except in compliance
  74144. * with the License. You may obtain a copy of the License at
  74145. *
  74146. * http://www.apache.org/licenses/LICENSE-2.0
  74147. *
  74148. * Unless required by applicable law or agreed to in writing,
  74149. * software distributed under the License is distributed on an
  74150. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74151. * KIND, either express or implied. See the License for the
  74152. * specific language governing permissions and limitations
  74153. * under the License.
  74154. */
  74155. var dataViewLang = lang.toolbox.dataView;
  74156. var BLOCK_SPLITER = new Array(60).join('-');
  74157. var ITEM_SPLITER = '\t';
  74158. /**
  74159. * Group series into two types
  74160. * 1. on category axis, like line, bar
  74161. * 2. others, like scatter, pie
  74162. * @param {module:echarts/model/Global} ecModel
  74163. * @return {Object}
  74164. * @inner
  74165. */
  74166. function groupSeries(ecModel) {
  74167. var seriesGroupByCategoryAxis = {};
  74168. var otherSeries = [];
  74169. var meta = [];
  74170. ecModel.eachRawSeries(function (seriesModel) {
  74171. var coordSys = seriesModel.coordinateSystem;
  74172. if (coordSys && (coordSys.type === 'cartesian2d' || coordSys.type === 'polar')) {
  74173. var baseAxis = coordSys.getBaseAxis();
  74174. if (baseAxis.type === 'category') {
  74175. var key = baseAxis.dim + '_' + baseAxis.index;
  74176. if (!seriesGroupByCategoryAxis[key]) {
  74177. seriesGroupByCategoryAxis[key] = {
  74178. categoryAxis: baseAxis,
  74179. valueAxis: coordSys.getOtherAxis(baseAxis),
  74180. series: []
  74181. };
  74182. meta.push({
  74183. axisDim: baseAxis.dim,
  74184. axisIndex: baseAxis.index
  74185. });
  74186. }
  74187. seriesGroupByCategoryAxis[key].series.push(seriesModel);
  74188. } else {
  74189. otherSeries.push(seriesModel);
  74190. }
  74191. } else {
  74192. otherSeries.push(seriesModel);
  74193. }
  74194. });
  74195. return {
  74196. seriesGroupByCategoryAxis: seriesGroupByCategoryAxis,
  74197. other: otherSeries,
  74198. meta: meta
  74199. };
  74200. }
  74201. /**
  74202. * Assemble content of series on cateogory axis
  74203. * @param {Array.<module:echarts/model/Series>} series
  74204. * @return {string}
  74205. * @inner
  74206. */
  74207. function assembleSeriesWithCategoryAxis(series) {
  74208. var tables = [];
  74209. each$1(series, function (group, key) {
  74210. var categoryAxis = group.categoryAxis;
  74211. var valueAxis = group.valueAxis;
  74212. var valueAxisDim = valueAxis.dim;
  74213. var headers = [' '].concat(map(group.series, function (series) {
  74214. return series.name;
  74215. }));
  74216. var columns = [categoryAxis.model.getCategories()];
  74217. each$1(group.series, function (series) {
  74218. columns.push(series.getRawData().mapArray(valueAxisDim, function (val) {
  74219. return val;
  74220. }));
  74221. }); // Assemble table content
  74222. var lines = [headers.join(ITEM_SPLITER)];
  74223. for (var i = 0; i < columns[0].length; i++) {
  74224. var items = [];
  74225. for (var j = 0; j < columns.length; j++) {
  74226. items.push(columns[j][i]);
  74227. }
  74228. lines.push(items.join(ITEM_SPLITER));
  74229. }
  74230. tables.push(lines.join('\n'));
  74231. });
  74232. return tables.join('\n\n' + BLOCK_SPLITER + '\n\n');
  74233. }
  74234. /**
  74235. * Assemble content of other series
  74236. * @param {Array.<module:echarts/model/Series>} series
  74237. * @return {string}
  74238. * @inner
  74239. */
  74240. function assembleOtherSeries(series) {
  74241. return map(series, function (series) {
  74242. var data = series.getRawData();
  74243. var lines = [series.name];
  74244. var vals = [];
  74245. data.each(data.dimensions, function () {
  74246. var argLen = arguments.length;
  74247. var dataIndex = arguments[argLen - 1];
  74248. var name = data.getName(dataIndex);
  74249. for (var i = 0; i < argLen - 1; i++) {
  74250. vals[i] = arguments[i];
  74251. }
  74252. lines.push((name ? name + ITEM_SPLITER : '') + vals.join(ITEM_SPLITER));
  74253. });
  74254. return lines.join('\n');
  74255. }).join('\n\n' + BLOCK_SPLITER + '\n\n');
  74256. }
  74257. /**
  74258. * @param {module:echarts/model/Global}
  74259. * @return {Object}
  74260. * @inner
  74261. */
  74262. function getContentFromModel(ecModel) {
  74263. var result = groupSeries(ecModel);
  74264. return {
  74265. value: filter([assembleSeriesWithCategoryAxis(result.seriesGroupByCategoryAxis), assembleOtherSeries(result.other)], function (str) {
  74266. return str.replace(/[\n\t\s]/g, '');
  74267. }).join('\n\n' + BLOCK_SPLITER + '\n\n'),
  74268. meta: result.meta
  74269. };
  74270. }
  74271. function trim$1(str) {
  74272. return str.replace(/^\s\s*/, '').replace(/\s\s*$/, '');
  74273. }
  74274. /**
  74275. * If a block is tsv format
  74276. */
  74277. function isTSVFormat(block) {
  74278. // Simple method to find out if a block is tsv format
  74279. var firstLine = block.slice(0, block.indexOf('\n'));
  74280. if (firstLine.indexOf(ITEM_SPLITER) >= 0) {
  74281. return true;
  74282. }
  74283. }
  74284. var itemSplitRegex = new RegExp('[' + ITEM_SPLITER + ']+', 'g');
  74285. /**
  74286. * @param {string} tsv
  74287. * @return {Object}
  74288. */
  74289. function parseTSVContents(tsv) {
  74290. var tsvLines = tsv.split(/\n+/g);
  74291. var headers = trim$1(tsvLines.shift()).split(itemSplitRegex);
  74292. var categories = [];
  74293. var series = map(headers, function (header) {
  74294. return {
  74295. name: header,
  74296. data: []
  74297. };
  74298. });
  74299. for (var i = 0; i < tsvLines.length; i++) {
  74300. var items = trim$1(tsvLines[i]).split(itemSplitRegex);
  74301. categories.push(items.shift());
  74302. for (var j = 0; j < items.length; j++) {
  74303. series[j] && (series[j].data[i] = items[j]);
  74304. }
  74305. }
  74306. return {
  74307. series: series,
  74308. categories: categories
  74309. };
  74310. }
  74311. /**
  74312. * @param {string} str
  74313. * @return {Array.<Object>}
  74314. * @inner
  74315. */
  74316. function parseListContents(str) {
  74317. var lines = str.split(/\n+/g);
  74318. var seriesName = trim$1(lines.shift());
  74319. var data = [];
  74320. for (var i = 0; i < lines.length; i++) {
  74321. var items = trim$1(lines[i]).split(itemSplitRegex);
  74322. var name = '';
  74323. var value;
  74324. var hasName = false;
  74325. if (isNaN(items[0])) {
  74326. // First item is name
  74327. hasName = true;
  74328. name = items[0];
  74329. items = items.slice(1);
  74330. data[i] = {
  74331. name: name,
  74332. value: []
  74333. };
  74334. value = data[i].value;
  74335. } else {
  74336. value = data[i] = [];
  74337. }
  74338. for (var j = 0; j < items.length; j++) {
  74339. value.push(+items[j]);
  74340. }
  74341. if (value.length === 1) {
  74342. hasName ? data[i].value = value[0] : data[i] = value[0];
  74343. }
  74344. }
  74345. return {
  74346. name: seriesName,
  74347. data: data
  74348. };
  74349. }
  74350. /**
  74351. * @param {string} str
  74352. * @param {Array.<Object>} blockMetaList
  74353. * @return {Object}
  74354. * @inner
  74355. */
  74356. function parseContents(str, blockMetaList) {
  74357. var blocks = str.split(new RegExp('\n*' + BLOCK_SPLITER + '\n*', 'g'));
  74358. var newOption = {
  74359. series: []
  74360. };
  74361. each$1(blocks, function (block, idx) {
  74362. if (isTSVFormat(block)) {
  74363. var result = parseTSVContents(block);
  74364. var blockMeta = blockMetaList[idx];
  74365. var axisKey = blockMeta.axisDim + 'Axis';
  74366. if (blockMeta) {
  74367. newOption[axisKey] = newOption[axisKey] || [];
  74368. newOption[axisKey][blockMeta.axisIndex] = {
  74369. data: result.categories
  74370. };
  74371. newOption.series = newOption.series.concat(result.series);
  74372. }
  74373. } else {
  74374. var result = parseListContents(block);
  74375. newOption.series.push(result);
  74376. }
  74377. });
  74378. return newOption;
  74379. }
  74380. /**
  74381. * @alias {module:echarts/component/toolbox/feature/DataView}
  74382. * @constructor
  74383. * @param {module:echarts/model/Model} model
  74384. */
  74385. function DataView(model) {
  74386. this._dom = null;
  74387. this.model = model;
  74388. }
  74389. DataView.defaultOption = {
  74390. show: true,
  74391. readOnly: false,
  74392. optionToContent: null,
  74393. contentToOption: null,
  74394. 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',
  74395. title: clone(dataViewLang.title),
  74396. lang: clone(dataViewLang.lang),
  74397. backgroundColor: '#fff',
  74398. textColor: '#000',
  74399. textareaColor: '#fff',
  74400. textareaBorderColor: '#333',
  74401. buttonColor: '#c23531',
  74402. buttonTextColor: '#fff'
  74403. };
  74404. DataView.prototype.onclick = function (ecModel, api) {
  74405. var container = api.getDom();
  74406. var model = this.model;
  74407. if (this._dom) {
  74408. container.removeChild(this._dom);
  74409. }
  74410. var root = document.createElement('div');
  74411. root.style.cssText = 'position:absolute;left:5px;top:5px;bottom:5px;right:5px;';
  74412. root.style.backgroundColor = model.get('backgroundColor') || '#fff'; // Create elements
  74413. var header = document.createElement('h4');
  74414. var lang$$1 = model.get('lang') || [];
  74415. header.innerHTML = lang$$1[0] || model.get('title');
  74416. header.style.cssText = 'margin: 10px 20px;';
  74417. header.style.color = model.get('textColor');
  74418. var viewMain = document.createElement('div');
  74419. var textarea = document.createElement('textarea');
  74420. viewMain.style.cssText = 'display:block;width:100%;overflow:auto;';
  74421. var optionToContent = model.get('optionToContent');
  74422. var contentToOption = model.get('contentToOption');
  74423. var result = getContentFromModel(ecModel);
  74424. if (typeof optionToContent === 'function') {
  74425. var htmlOrDom = optionToContent(api.getOption());
  74426. if (typeof htmlOrDom === 'string') {
  74427. viewMain.innerHTML = htmlOrDom;
  74428. } else if (isDom(htmlOrDom)) {
  74429. viewMain.appendChild(htmlOrDom);
  74430. }
  74431. } else {
  74432. // Use default textarea
  74433. viewMain.appendChild(textarea);
  74434. textarea.readOnly = model.get('readOnly');
  74435. textarea.style.cssText = 'width:100%;height:100%;font-family:monospace;font-size:14px;line-height:1.6rem;';
  74436. textarea.style.color = model.get('textColor');
  74437. textarea.style.borderColor = model.get('textareaBorderColor');
  74438. textarea.style.backgroundColor = model.get('textareaColor');
  74439. textarea.value = result.value;
  74440. }
  74441. var blockMetaList = result.meta;
  74442. var buttonContainer = document.createElement('div');
  74443. buttonContainer.style.cssText = 'position:absolute;bottom:0;left:0;right:0;';
  74444. var buttonStyle = 'float:right;margin-right:20px;border:none;' + 'cursor:pointer;padding:2px 5px;font-size:12px;border-radius:3px';
  74445. var closeButton = document.createElement('div');
  74446. var refreshButton = document.createElement('div');
  74447. buttonStyle += ';background-color:' + model.get('buttonColor');
  74448. buttonStyle += ';color:' + model.get('buttonTextColor');
  74449. var self = this;
  74450. function close() {
  74451. container.removeChild(root);
  74452. self._dom = null;
  74453. }
  74454. addEventListener(closeButton, 'click', close);
  74455. addEventListener(refreshButton, 'click', function () {
  74456. var newOption;
  74457. try {
  74458. if (typeof contentToOption === 'function') {
  74459. newOption = contentToOption(viewMain, api.getOption());
  74460. } else {
  74461. newOption = parseContents(textarea.value, blockMetaList);
  74462. }
  74463. } catch (e) {
  74464. close();
  74465. throw new Error('Data view format error ' + e);
  74466. }
  74467. if (newOption) {
  74468. api.dispatchAction({
  74469. type: 'changeDataView',
  74470. newOption: newOption
  74471. });
  74472. }
  74473. close();
  74474. });
  74475. closeButton.innerHTML = lang$$1[1];
  74476. refreshButton.innerHTML = lang$$1[2];
  74477. refreshButton.style.cssText = buttonStyle;
  74478. closeButton.style.cssText = buttonStyle;
  74479. !model.get('readOnly') && buttonContainer.appendChild(refreshButton);
  74480. buttonContainer.appendChild(closeButton);
  74481. root.appendChild(header);
  74482. root.appendChild(viewMain);
  74483. root.appendChild(buttonContainer);
  74484. viewMain.style.height = container.clientHeight - 80 + 'px';
  74485. container.appendChild(root);
  74486. this._dom = root;
  74487. };
  74488. DataView.prototype.remove = function (ecModel, api) {
  74489. this._dom && api.getDom().removeChild(this._dom);
  74490. };
  74491. DataView.prototype.dispose = function (ecModel, api) {
  74492. this.remove(ecModel, api);
  74493. };
  74494. /**
  74495. * @inner
  74496. */
  74497. function tryMergeDataOption(newData, originalData) {
  74498. return map(newData, function (newVal, idx) {
  74499. var original = originalData && originalData[idx];
  74500. if (isObject$1(original) && !isArray(original)) {
  74501. if (isObject$1(newVal) && !isArray(newVal)) {
  74502. newVal = newVal.value;
  74503. } // Original data has option
  74504. return defaults({
  74505. value: newVal
  74506. }, original);
  74507. } else {
  74508. return newVal;
  74509. }
  74510. });
  74511. }
  74512. register$2('dataView', DataView);
  74513. registerAction({
  74514. type: 'changeDataView',
  74515. event: 'dataViewChanged',
  74516. update: 'prepareAndUpdate'
  74517. }, function (payload, ecModel) {
  74518. var newSeriesOptList = [];
  74519. each$1(payload.newOption.series, function (seriesOpt) {
  74520. var seriesModel = ecModel.getSeriesByName(seriesOpt.name)[0];
  74521. if (!seriesModel) {
  74522. // New created series
  74523. // Geuss the series type
  74524. newSeriesOptList.push(extend({
  74525. // Default is scatter
  74526. type: 'scatter'
  74527. }, seriesOpt));
  74528. } else {
  74529. var originalData = seriesModel.get('data');
  74530. newSeriesOptList.push({
  74531. name: seriesOpt.name,
  74532. data: tryMergeDataOption(seriesOpt.data, originalData)
  74533. });
  74534. }
  74535. });
  74536. ecModel.mergeOption(defaults({
  74537. series: newSeriesOptList
  74538. }, payload.newOption));
  74539. });
  74540. /*
  74541. * Licensed to the Apache Software Foundation (ASF) under one
  74542. * or more contributor license agreements. See the NOTICE file
  74543. * distributed with this work for additional information
  74544. * regarding copyright ownership. The ASF licenses this file
  74545. * to you under the Apache License, Version 2.0 (the
  74546. * "License"); you may not use this file except in compliance
  74547. * with the License. You may obtain a copy of the License at
  74548. *
  74549. * http://www.apache.org/licenses/LICENSE-2.0
  74550. *
  74551. * Unless required by applicable law or agreed to in writing,
  74552. * software distributed under the License is distributed on an
  74553. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74554. * KIND, either express or implied. See the License for the
  74555. * specific language governing permissions and limitations
  74556. * under the License.
  74557. */
  74558. var each$29 = each$1;
  74559. var ATTR$2 = '\0_ec_hist_store';
  74560. /**
  74561. * @param {module:echarts/model/Global} ecModel
  74562. * @param {Object} newSnapshot {dataZoomId, batch: [payloadInfo, ...]}
  74563. */
  74564. function push(ecModel, newSnapshot) {
  74565. var store = giveStore$1(ecModel); // If previous dataZoom can not be found,
  74566. // complete an range with current range.
  74567. each$29(newSnapshot, function (batchItem, dataZoomId) {
  74568. var i = store.length - 1;
  74569. for (; i >= 0; i--) {
  74570. var snapshot = store[i];
  74571. if (snapshot[dataZoomId]) {
  74572. break;
  74573. }
  74574. }
  74575. if (i < 0) {
  74576. // No origin range set, create one by current range.
  74577. var dataZoomModel = ecModel.queryComponents({
  74578. mainType: 'dataZoom',
  74579. subType: 'select',
  74580. id: dataZoomId
  74581. })[0];
  74582. if (dataZoomModel) {
  74583. var percentRange = dataZoomModel.getPercentRange();
  74584. store[0][dataZoomId] = {
  74585. dataZoomId: dataZoomId,
  74586. start: percentRange[0],
  74587. end: percentRange[1]
  74588. };
  74589. }
  74590. }
  74591. });
  74592. store.push(newSnapshot);
  74593. }
  74594. /**
  74595. * @param {module:echarts/model/Global} ecModel
  74596. * @return {Object} snapshot
  74597. */
  74598. function pop(ecModel) {
  74599. var store = giveStore$1(ecModel);
  74600. var head = store[store.length - 1];
  74601. store.length > 1 && store.pop(); // Find top for all dataZoom.
  74602. var snapshot = {};
  74603. each$29(head, function (batchItem, dataZoomId) {
  74604. for (var i = store.length - 1; i >= 0; i--) {
  74605. var batchItem = store[i][dataZoomId];
  74606. if (batchItem) {
  74607. snapshot[dataZoomId] = batchItem;
  74608. break;
  74609. }
  74610. }
  74611. });
  74612. return snapshot;
  74613. }
  74614. /**
  74615. * @param {module:echarts/model/Global} ecModel
  74616. */
  74617. function clear$1(ecModel) {
  74618. ecModel[ATTR$2] = null;
  74619. }
  74620. /**
  74621. * @param {module:echarts/model/Global} ecModel
  74622. * @return {number} records. always >= 1.
  74623. */
  74624. function count(ecModel) {
  74625. return giveStore$1(ecModel).length;
  74626. }
  74627. /**
  74628. * [{key: dataZoomId, value: {dataZoomId, range}}, ...]
  74629. * History length of each dataZoom may be different.
  74630. * this._history[0] is used to store origin range.
  74631. * @type {Array.<Object>}
  74632. */
  74633. function giveStore$1(ecModel) {
  74634. var store = ecModel[ATTR$2];
  74635. if (!store) {
  74636. store = ecModel[ATTR$2] = [{}];
  74637. }
  74638. return store;
  74639. }
  74640. /*
  74641. * Licensed to the Apache Software Foundation (ASF) under one
  74642. * or more contributor license agreements. See the NOTICE file
  74643. * distributed with this work for additional information
  74644. * regarding copyright ownership. The ASF licenses this file
  74645. * to you under the Apache License, Version 2.0 (the
  74646. * "License"); you may not use this file except in compliance
  74647. * with the License. You may obtain a copy of the License at
  74648. *
  74649. * http://www.apache.org/licenses/LICENSE-2.0
  74650. *
  74651. * Unless required by applicable law or agreed to in writing,
  74652. * software distributed under the License is distributed on an
  74653. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74654. * KIND, either express or implied. See the License for the
  74655. * specific language governing permissions and limitations
  74656. * under the License.
  74657. */
  74658. DataZoomModel.extend({
  74659. type: 'dataZoom.select'
  74660. });
  74661. /*
  74662. * Licensed to the Apache Software Foundation (ASF) under one
  74663. * or more contributor license agreements. See the NOTICE file
  74664. * distributed with this work for additional information
  74665. * regarding copyright ownership. The ASF licenses this file
  74666. * to you under the Apache License, Version 2.0 (the
  74667. * "License"); you may not use this file except in compliance
  74668. * with the License. You may obtain a copy of the License at
  74669. *
  74670. * http://www.apache.org/licenses/LICENSE-2.0
  74671. *
  74672. * Unless required by applicable law or agreed to in writing,
  74673. * software distributed under the License is distributed on an
  74674. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74675. * KIND, either express or implied. See the License for the
  74676. * specific language governing permissions and limitations
  74677. * under the License.
  74678. */
  74679. DataZoomView.extend({
  74680. type: 'dataZoom.select'
  74681. });
  74682. /*
  74683. * Licensed to the Apache Software Foundation (ASF) under one
  74684. * or more contributor license agreements. See the NOTICE file
  74685. * distributed with this work for additional information
  74686. * regarding copyright ownership. The ASF licenses this file
  74687. * to you under the Apache License, Version 2.0 (the
  74688. * "License"); you may not use this file except in compliance
  74689. * with the License. You may obtain a copy of the License at
  74690. *
  74691. * http://www.apache.org/licenses/LICENSE-2.0
  74692. *
  74693. * Unless required by applicable law or agreed to in writing,
  74694. * software distributed under the License is distributed on an
  74695. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74696. * KIND, either express or implied. See the License for the
  74697. * specific language governing permissions and limitations
  74698. * under the License.
  74699. */
  74700. /**
  74701. * Only work for toolbox dataZoom. User
  74702. * MUST NOT import this module directly.
  74703. */
  74704. /*
  74705. * Licensed to the Apache Software Foundation (ASF) under one
  74706. * or more contributor license agreements. See the NOTICE file
  74707. * distributed with this work for additional information
  74708. * regarding copyright ownership. The ASF licenses this file
  74709. * to you under the Apache License, Version 2.0 (the
  74710. * "License"); you may not use this file except in compliance
  74711. * with the License. You may obtain a copy of the License at
  74712. *
  74713. * http://www.apache.org/licenses/LICENSE-2.0
  74714. *
  74715. * Unless required by applicable law or agreed to in writing,
  74716. * software distributed under the License is distributed on an
  74717. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74718. * KIND, either express or implied. See the License for the
  74719. * specific language governing permissions and limitations
  74720. * under the License.
  74721. */
  74722. var dataZoomLang = lang.toolbox.dataZoom;
  74723. var each$28 = each$1; // Spectial component id start with \0ec\0, see echarts/model/Global.js~hasInnerId
  74724. var DATA_ZOOM_ID_BASE = '\0_ec_\0toolbox-dataZoom_';
  74725. function DataZoom(model, ecModel, api) {
  74726. /**
  74727. * @private
  74728. * @type {module:echarts/component/helper/BrushController}
  74729. */
  74730. (this._brushController = new BrushController(api.getZr())).on('brush', bind(this._onBrush, this)).mount();
  74731. /**
  74732. * @private
  74733. * @type {boolean}
  74734. */
  74735. this._isZoomActive;
  74736. }
  74737. DataZoom.defaultOption = {
  74738. show: true,
  74739. filterMode: 'filter',
  74740. // Icon group
  74741. icon: {
  74742. zoom: 'M0,13.5h26.9 M13.5,26.9V0 M32.1,13.5H58V58H13.5 V32.1',
  74743. back: 'M22,1.4L9.9,13.5l12.3,12.3 M10.3,13.5H54.9v44.6 H10.3v-26'
  74744. },
  74745. // `zoom`, `back`
  74746. title: clone(dataZoomLang.title)
  74747. };
  74748. var proto$6 = DataZoom.prototype;
  74749. proto$6.render = function (featureModel, ecModel, api, payload) {
  74750. this.model = featureModel;
  74751. this.ecModel = ecModel;
  74752. this.api = api;
  74753. updateZoomBtnStatus(featureModel, ecModel, this, payload, api);
  74754. updateBackBtnStatus(featureModel, ecModel);
  74755. };
  74756. proto$6.onclick = function (ecModel, api, type) {
  74757. handlers$1[type].call(this);
  74758. };
  74759. proto$6.remove = function (ecModel, api) {
  74760. this._brushController.unmount();
  74761. };
  74762. proto$6.dispose = function (ecModel, api) {
  74763. this._brushController.dispose();
  74764. };
  74765. /**
  74766. * @private
  74767. */
  74768. var handlers$1 = {
  74769. zoom: function () {
  74770. var nextActive = !this._isZoomActive;
  74771. this.api.dispatchAction({
  74772. type: 'takeGlobalCursor',
  74773. key: 'dataZoomSelect',
  74774. dataZoomSelectActive: nextActive
  74775. });
  74776. },
  74777. back: function () {
  74778. this._dispatchZoomAction(pop(this.ecModel));
  74779. }
  74780. };
  74781. /**
  74782. * @private
  74783. */
  74784. proto$6._onBrush = function (areas, opt) {
  74785. if (!opt.isEnd || !areas.length) {
  74786. return;
  74787. }
  74788. var snapshot = {};
  74789. var ecModel = this.ecModel;
  74790. this._brushController.updateCovers([]); // remove cover
  74791. var brushTargetManager = new BrushTargetManager(retrieveAxisSetting(this.model.option), ecModel, {
  74792. include: ['grid']
  74793. });
  74794. brushTargetManager.matchOutputRanges(areas, ecModel, function (area, coordRange, coordSys) {
  74795. if (coordSys.type !== 'cartesian2d') {
  74796. return;
  74797. }
  74798. var brushType = area.brushType;
  74799. if (brushType === 'rect') {
  74800. setBatch('x', coordSys, coordRange[0]);
  74801. setBatch('y', coordSys, coordRange[1]);
  74802. } else {
  74803. setBatch({
  74804. lineX: 'x',
  74805. lineY: 'y'
  74806. }[brushType], coordSys, coordRange);
  74807. }
  74808. });
  74809. push(ecModel, snapshot);
  74810. this._dispatchZoomAction(snapshot);
  74811. function setBatch(dimName, coordSys, minMax) {
  74812. var axis = coordSys.getAxis(dimName);
  74813. var axisModel = axis.model;
  74814. var dataZoomModel = findDataZoom(dimName, axisModel, ecModel); // Restrict range.
  74815. var minMaxSpan = dataZoomModel.findRepresentativeAxisProxy(axisModel).getMinMaxSpan();
  74816. if (minMaxSpan.minValueSpan != null || minMaxSpan.maxValueSpan != null) {
  74817. minMax = sliderMove(0, minMax.slice(), axis.scale.getExtent(), 0, minMaxSpan.minValueSpan, minMaxSpan.maxValueSpan);
  74818. }
  74819. dataZoomModel && (snapshot[dataZoomModel.id] = {
  74820. dataZoomId: dataZoomModel.id,
  74821. startValue: minMax[0],
  74822. endValue: minMax[1]
  74823. });
  74824. }
  74825. function findDataZoom(dimName, axisModel, ecModel) {
  74826. var found;
  74827. ecModel.eachComponent({
  74828. mainType: 'dataZoom',
  74829. subType: 'select'
  74830. }, function (dzModel) {
  74831. var has = dzModel.getAxisModel(dimName, axisModel.componentIndex);
  74832. has && (found = dzModel);
  74833. });
  74834. return found;
  74835. }
  74836. };
  74837. /**
  74838. * @private
  74839. */
  74840. proto$6._dispatchZoomAction = function (snapshot) {
  74841. var batch = []; // Convert from hash map to array.
  74842. each$28(snapshot, function (batchItem, dataZoomId) {
  74843. batch.push(clone(batchItem));
  74844. });
  74845. batch.length && this.api.dispatchAction({
  74846. type: 'dataZoom',
  74847. from: this.uid,
  74848. batch: batch
  74849. });
  74850. };
  74851. function retrieveAxisSetting(option) {
  74852. var setting = {}; // Compatible with previous setting: null => all axis, false => no axis.
  74853. each$1(['xAxisIndex', 'yAxisIndex'], function (name) {
  74854. setting[name] = option[name];
  74855. setting[name] == null && (setting[name] = 'all');
  74856. (setting[name] === false || setting[name] === 'none') && (setting[name] = []);
  74857. });
  74858. return setting;
  74859. }
  74860. function updateBackBtnStatus(featureModel, ecModel) {
  74861. featureModel.setIconStatus('back', count(ecModel) > 1 ? 'emphasis' : 'normal');
  74862. }
  74863. function updateZoomBtnStatus(featureModel, ecModel, view, payload, api) {
  74864. var zoomActive = view._isZoomActive;
  74865. if (payload && payload.type === 'takeGlobalCursor') {
  74866. zoomActive = payload.key === 'dataZoomSelect' ? payload.dataZoomSelectActive : false;
  74867. }
  74868. view._isZoomActive = zoomActive;
  74869. featureModel.setIconStatus('zoom', zoomActive ? 'emphasis' : 'normal');
  74870. var brushTargetManager = new BrushTargetManager(retrieveAxisSetting(featureModel.option), ecModel, {
  74871. include: ['grid']
  74872. });
  74873. view._brushController.setPanels(brushTargetManager.makePanelOpts(api, function (targetInfo) {
  74874. return targetInfo.xAxisDeclared && !targetInfo.yAxisDeclared ? 'lineX' : !targetInfo.xAxisDeclared && targetInfo.yAxisDeclared ? 'lineY' : 'rect';
  74875. })).enableBrush(zoomActive ? {
  74876. brushType: 'auto',
  74877. brushStyle: {
  74878. // FIXME user customized?
  74879. lineWidth: 0,
  74880. fill: 'rgba(0,0,0,0.2)'
  74881. }
  74882. } : false);
  74883. }
  74884. register$2('dataZoom', DataZoom); // Create special dataZoom option for select
  74885. // FIXME consider the case of merge option, where axes options are not exists.
  74886. registerPreprocessor(function (option) {
  74887. if (!option) {
  74888. return;
  74889. }
  74890. var dataZoomOpts = option.dataZoom || (option.dataZoom = []);
  74891. if (!isArray(dataZoomOpts)) {
  74892. option.dataZoom = dataZoomOpts = [dataZoomOpts];
  74893. }
  74894. var toolboxOpt = option.toolbox;
  74895. if (toolboxOpt) {
  74896. // Assume there is only one toolbox
  74897. if (isArray(toolboxOpt)) {
  74898. toolboxOpt = toolboxOpt[0];
  74899. }
  74900. if (toolboxOpt && toolboxOpt.feature) {
  74901. var dataZoomOpt = toolboxOpt.feature.dataZoom; // FIXME: If add dataZoom when setOption in merge mode,
  74902. // no axis info to be added. See `test/dataZoom-extreme.html`
  74903. addForAxis('xAxis', dataZoomOpt);
  74904. addForAxis('yAxis', dataZoomOpt);
  74905. }
  74906. }
  74907. function addForAxis(axisName, dataZoomOpt) {
  74908. if (!dataZoomOpt) {
  74909. return;
  74910. } // Try not to modify model, because it is not merged yet.
  74911. var axisIndicesName = axisName + 'Index';
  74912. var givenAxisIndices = dataZoomOpt[axisIndicesName];
  74913. if (givenAxisIndices != null && givenAxisIndices !== 'all' && !isArray(givenAxisIndices)) {
  74914. givenAxisIndices = givenAxisIndices === false || givenAxisIndices === 'none' ? [] : [givenAxisIndices];
  74915. }
  74916. forEachComponent(axisName, function (axisOpt, axisIndex) {
  74917. if (givenAxisIndices != null && givenAxisIndices !== 'all' && indexOf(givenAxisIndices, axisIndex) === -1) {
  74918. return;
  74919. }
  74920. var newOpt = {
  74921. type: 'select',
  74922. $fromToolbox: true,
  74923. // Default to be filter
  74924. filterMode: dataZoomOpt.filterMode || 'filter',
  74925. // Id for merge mapping.
  74926. id: DATA_ZOOM_ID_BASE + axisName + axisIndex
  74927. }; // FIXME
  74928. // Only support one axis now.
  74929. newOpt[axisIndicesName] = axisIndex;
  74930. dataZoomOpts.push(newOpt);
  74931. });
  74932. }
  74933. function forEachComponent(mainType, cb) {
  74934. var opts = option[mainType];
  74935. if (!isArray(opts)) {
  74936. opts = opts ? [opts] : [];
  74937. }
  74938. each$28(opts, cb);
  74939. }
  74940. });
  74941. /*
  74942. * Licensed to the Apache Software Foundation (ASF) under one
  74943. * or more contributor license agreements. See the NOTICE file
  74944. * distributed with this work for additional information
  74945. * regarding copyright ownership. The ASF licenses this file
  74946. * to you under the Apache License, Version 2.0 (the
  74947. * "License"); you may not use this file except in compliance
  74948. * with the License. You may obtain a copy of the License at
  74949. *
  74950. * http://www.apache.org/licenses/LICENSE-2.0
  74951. *
  74952. * Unless required by applicable law or agreed to in writing,
  74953. * software distributed under the License is distributed on an
  74954. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  74955. * KIND, either express or implied. See the License for the
  74956. * specific language governing permissions and limitations
  74957. * under the License.
  74958. */
  74959. var restoreLang = lang.toolbox.restore;
  74960. function Restore(model) {
  74961. this.model = model;
  74962. }
  74963. Restore.defaultOption = {
  74964. show: true,
  74965. /* eslint-disable */
  74966. 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',
  74967. /* eslint-enable */
  74968. title: restoreLang.title
  74969. };
  74970. var proto$7 = Restore.prototype;
  74971. proto$7.onclick = function (ecModel, api, type) {
  74972. clear$1(ecModel);
  74973. api.dispatchAction({
  74974. type: 'restore',
  74975. from: this.uid
  74976. });
  74977. };
  74978. register$2('restore', Restore);
  74979. registerAction({
  74980. type: 'restore',
  74981. event: 'restore',
  74982. update: 'prepareAndUpdate'
  74983. }, function (payload, ecModel) {
  74984. ecModel.resetOption('recreate');
  74985. });
  74986. /*
  74987. * Licensed to the Apache Software Foundation (ASF) under one
  74988. * or more contributor license agreements. See the NOTICE file
  74989. * distributed with this work for additional information
  74990. * regarding copyright ownership. The ASF licenses this file
  74991. * to you under the Apache License, Version 2.0 (the
  74992. * "License"); you may not use this file except in compliance
  74993. * with the License. You may obtain a copy of the License at
  74994. *
  74995. * http://www.apache.org/licenses/LICENSE-2.0
  74996. *
  74997. * Unless required by applicable law or agreed to in writing,
  74998. * software distributed under the License is distributed on an
  74999. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75000. * KIND, either express or implied. See the License for the
  75001. * specific language governing permissions and limitations
  75002. * under the License.
  75003. */
  75004. /*
  75005. * Licensed to the Apache Software Foundation (ASF) under one
  75006. * or more contributor license agreements. See the NOTICE file
  75007. * distributed with this work for additional information
  75008. * regarding copyright ownership. The ASF licenses this file
  75009. * to you under the Apache License, Version 2.0 (the
  75010. * "License"); you may not use this file except in compliance
  75011. * with the License. You may obtain a copy of the License at
  75012. *
  75013. * http://www.apache.org/licenses/LICENSE-2.0
  75014. *
  75015. * Unless required by applicable law or agreed to in writing,
  75016. * software distributed under the License is distributed on an
  75017. * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
  75018. * KIND, either express or implied. See the License for the
  75019. * specific language governing permissions and limitations
  75020. * under the License.
  75021. */
  75022. var _nonShapeGraphicElements = {
  75023. // Reserved but not supported in graphic component.
  75024. path: null,
  75025. compoundPath: null,
  75026. // Supported in graphic component.
  75027. group: Group,
  75028. image: ZImage,
  75029. text: Text
  75030. }; // -------------
  75031. // Preprocessor
  75032. // -------------
  75033. registerPreprocessor(function (option) {
  75034. var graphicOption = option.graphic; // Convert
  75035. // {graphic: [{left: 10, type: 'circle'}, ...]}
  75036. // or
  75037. // {graphic: {left: 10, type: 'circle'}}
  75038. // to
  75039. // {graphic: [{elements: [{left: 10, type: 'circle'}, ...]}]}
  75040. if (isArray(graphicOption)) {
  75041. if (!graphicOption[0] || !graphicOption[0].elements) {
  75042. option.graphic = [{
  75043. elements: graphicOption
  75044. }];
  75045. } else {
  75046. // Only one graphic instance can be instantiated. (We dont
  75047. // want that too many views are created in echarts._viewMap)
  75048. option.graphic = [option.graphic[0]];
  75049. }
  75050. } else if (graphicOption && !graphicOption.elements) {
  75051. option.graphic = [{
  75052. elements: [graphicOption]
  75053. }];
  75054. }
  75055. }); // ------
  75056. // Model
  75057. // ------
  75058. var GraphicModel = extendComponentModel({
  75059. type: 'graphic',
  75060. defaultOption: {
  75061. // Extra properties for each elements:
  75062. //
  75063. // left/right/top/bottom: (like 12, '22%', 'center', default undefined)
  75064. // If left/rigth is set, shape.x/shape.cx/position will not be used.
  75065. // If top/bottom is set, shape.y/shape.cy/position will not be used.
  75066. // This mechanism is useful when you want to position a group/element
  75067. // against the right side or the center of this container.
  75068. //
  75069. // width/height: (can only be pixel value, default 0)
  75070. // Only be used to specify contianer(group) size, if needed. And
  75071. // can not be percentage value (like '33%'). See the reason in the
  75072. // layout algorithm below.
  75073. //
  75074. // bounding: (enum: 'all' (default) | 'raw')
  75075. // Specify how to calculate boundingRect when locating.
  75076. // 'all': Get uioned and transformed boundingRect
  75077. // from both itself and its descendants.
  75078. // This mode simplies confining a group of elements in the bounding
  75079. // of their ancester container (e.g., using 'right: 0').
  75080. // 'raw': Only use the boundingRect of itself and before transformed.
  75081. // This mode is similar to css behavior, which is useful when you
  75082. // want an element to be able to overflow its container. (Consider
  75083. // a rotated circle needs to be located in a corner.)
  75084. // info: custom info. enables user to mount some info on elements and use them
  75085. // in event handlers. Update them only when user specified, otherwise, remain.
  75086. // Note: elements is always behind its ancestors in this elements array.
  75087. elements: [],
  75088. parentId: null
  75089. },
  75090. /**
  75091. * Save el options for the sake of the performance (only update modified graphics).
  75092. * The order is the same as those in option. (ancesters -> descendants)
  75093. *
  75094. * @private
  75095. * @type {Array.<Object>}
  75096. */
  75097. _elOptionsToUpdate: null,
  75098. /**
  75099. * @override
  75100. */
  75101. mergeOption: function (option) {
  75102. // Prevent default merge to elements
  75103. var elements = this.option.elements;
  75104. this.option.elements = null;
  75105. GraphicModel.superApply(this, 'mergeOption', arguments);
  75106. this.option.elements = elements;
  75107. },
  75108. /**
  75109. * @override
  75110. */
  75111. optionUpdated: function (newOption, isInit) {
  75112. var thisOption = this.option;
  75113. var newList = (isInit ? thisOption : newOption).elements;
  75114. var existList = thisOption.elements = isInit ? [] : thisOption.elements;
  75115. var flattenedList = [];
  75116. this._flatten(newList, flattenedList);
  75117. var mappingResult = mappingToExists(existList, flattenedList);
  75118. makeIdAndName(mappingResult); // Clear elOptionsToUpdate
  75119. var elOptionsToUpdate = this._elOptionsToUpdate = [];
  75120. each$1(mappingResult, function (resultItem, index) {
  75121. var newElOption = resultItem.option;
  75122. if (!newElOption) {
  75123. return;
  75124. }
  75125. elOptionsToUpdate.push(newElOption);
  75126. setKeyInfoToNewElOption(resultItem, newElOption);
  75127. mergeNewElOptionToExist(existList, index, newElOption);
  75128. setLayoutInfoToExist(existList[index], newElOption);
  75129. }, this); // Clean
  75130. for (var i = existList.length - 1; i >= 0; i--) {
  75131. if (existList[i] == null) {
  75132. existList.splice(i, 1);
  75133. } else {
  75134. // $action should be volatile, otherwise option gotten from
  75135. // `getOption` will contain unexpected $action.
  75136. delete existList[i].$action;
  75137. }
  75138. }
  75139. },
  75140. /**
  75141. * Convert
  75142. * [{
  75143. * type: 'group',
  75144. * id: 'xx',
  75145. * children: [{type: 'circle'}, {type: 'polygon'}]
  75146. * }]
  75147. * to
  75148. * [
  75149. * {type: 'group', id: 'xx'},
  75150. * {type: 'circle', parentId: 'xx'},
  75151. * {type: 'polygon', parentId: 'xx'}
  75152. * ]
  75153. *
  75154. * @private
  75155. * @param {Array.<Object>} optionList option list
  75156. * @param {Array.<Object>} result result of flatten
  75157. * @param {Object} parentOption parent option
  75158. */
  75159. _flatten: function (optionList, result, parentOption) {
  75160. each$1(optionList, function (option) {
  75161. if (!option) {
  75162. return;
  75163. }
  75164. if (parentOption) {
  75165. option.parentOption = parentOption;
  75166. }
  75167. result.push(option);
  75168. var children = option.children;
  75169. if (option.type === 'group' && children) {
  75170. this._flatten(children, result, option);
  75171. } // Deleting for JSON output, and for not affecting group creation.
  75172. delete option.children;
  75173. }, this);
  75174. },
  75175. // FIXME
  75176. // Pass to view using payload? setOption has a payload?
  75177. useElOptionsToUpdate: function () {
  75178. var els = this._elOptionsToUpdate; // Clear to avoid render duplicately when zooming.
  75179. this._elOptionsToUpdate = null;
  75180. return els;
  75181. }
  75182. }); // -----
  75183. // View
  75184. // -----
  75185. extendComponentView({
  75186. type: 'graphic',
  75187. /**
  75188. * @override
  75189. */
  75190. init: function (ecModel, api) {
  75191. /**
  75192. * @private
  75193. * @type {module:zrender/core/util.HashMap}
  75194. */
  75195. this._elMap = createHashMap();
  75196. /**
  75197. * @private
  75198. * @type {module:echarts/graphic/GraphicModel}
  75199. */
  75200. this._lastGraphicModel;
  75201. },
  75202. /**
  75203. * @override
  75204. */
  75205. render: function (graphicModel, ecModel, api) {
  75206. // Having leveraged between use cases and algorithm complexity, a very
  75207. // simple layout mechanism is used:
  75208. // The size(width/height) can be determined by itself or its parent (not
  75209. // implemented yet), but can not by its children. (Top-down travel)
  75210. // The location(x/y) can be determined by the bounding rect of itself
  75211. // (can including its descendants or not) and the size of its parent.
  75212. // (Bottom-up travel)
  75213. // When `chart.clear()` or `chart.setOption({...}, true)` with the same id,
  75214. // view will be reused.
  75215. if (graphicModel !== this._lastGraphicModel) {
  75216. this._clear();
  75217. }
  75218. this._lastGraphicModel = graphicModel;
  75219. this._updateElements(graphicModel);
  75220. this._relocate(graphicModel, api);
  75221. },
  75222. /**
  75223. * Update graphic elements.
  75224. *
  75225. * @private
  75226. * @param {Object} graphicModel graphic model
  75227. */
  75228. _updateElements: function (graphicModel) {
  75229. var elOptionsToUpdate = graphicModel.useElOptionsToUpdate();
  75230. if (!elOptionsToUpdate) {
  75231. return;
  75232. }
  75233. var elMap = this._elMap;
  75234. var rootGroup = this.group; // Top-down tranverse to assign graphic settings to each elements.
  75235. each$1(elOptionsToUpdate, function (elOption) {
  75236. var $action = elOption.$action;
  75237. var id = elOption.id;
  75238. var existEl = elMap.get(id);
  75239. var parentId = elOption.parentId;
  75240. var targetElParent = parentId != null ? elMap.get(parentId) : rootGroup;
  75241. var elOptionStyle = elOption.style;
  75242. if (elOption.type === 'text' && elOptionStyle) {
  75243. // In top/bottom mode, textVerticalAlign should not be used, which cause
  75244. // inaccurately locating.
  75245. if (elOption.hv && elOption.hv[1]) {
  75246. elOptionStyle.textVerticalAlign = elOptionStyle.textBaseline = null;
  75247. } // Compatible with previous setting: both support fill and textFill,
  75248. // stroke and textStroke.
  75249. !elOptionStyle.hasOwnProperty('textFill') && elOptionStyle.fill && (elOptionStyle.textFill = elOptionStyle.fill);
  75250. !elOptionStyle.hasOwnProperty('textStroke') && elOptionStyle.stroke && (elOptionStyle.textStroke = elOptionStyle.stroke);
  75251. } // Remove unnecessary props to avoid potential problems.
  75252. var elOptionCleaned = getCleanedElOption(elOption); // For simple, do not support parent change, otherwise reorder is needed.
  75253. if (!$action || $action === 'merge') {
  75254. existEl ? existEl.attr(elOptionCleaned) : createEl$1(id, targetElParent, elOptionCleaned, elMap);
  75255. } else if ($action === 'replace') {
  75256. removeEl(existEl, elMap);
  75257. createEl$1(id, targetElParent, elOptionCleaned, elMap);
  75258. } else if ($action === 'remove') {
  75259. removeEl(existEl, elMap);
  75260. }
  75261. var el = elMap.get(id);
  75262. if (el) {
  75263. el.__ecGraphicWidthOption = elOption.width;
  75264. el.__ecGraphicHeightOption = elOption.height;
  75265. setEventData(el, graphicModel, elOption);
  75266. }
  75267. });
  75268. },
  75269. /**
  75270. * Locate graphic elements.
  75271. *
  75272. * @private
  75273. * @param {Object} graphicModel graphic model
  75274. * @param {module:echarts/ExtensionAPI} api extension API
  75275. */
  75276. _relocate: function (graphicModel, api) {
  75277. var elOptions = graphicModel.option.elements;
  75278. var rootGroup = this.group;
  75279. var elMap = this._elMap;
  75280. var apiWidth = api.getWidth();
  75281. var apiHeight = api.getHeight(); // Top-down to calculate percentage width/height of group
  75282. for (var i = 0; i < elOptions.length; i++) {
  75283. var elOption = elOptions[i];
  75284. var el = elMap.get(elOption.id);
  75285. if (!el || !el.isGroup) {
  75286. continue;
  75287. }
  75288. var parentEl = el.parent;
  75289. var isParentRoot = parentEl === rootGroup; // Like 'position:absolut' in css, default 0.
  75290. el.__ecGraphicWidth = parsePercent$1(el.__ecGraphicWidthOption, isParentRoot ? apiWidth : parentEl.__ecGraphicWidth) || 0;
  75291. el.__ecGraphicHeight = parsePercent$1(el.__ecGraphicHeightOption, isParentRoot ? apiHeight : parentEl.__ecGraphicHeight) || 0;
  75292. } // Bottom-up tranvese all elements (consider ec resize) to locate elements.
  75293. for (var i = elOptions.length - 1; i >= 0; i--) {
  75294. var elOption = elOptions[i];
  75295. var el = elMap.get(elOption.id);
  75296. if (!el) {
  75297. continue;
  75298. }
  75299. var parentEl = el.parent;
  75300. var containerInfo = parentEl === rootGroup ? {
  75301. width: apiWidth,
  75302. height: apiHeight
  75303. } : {
  75304. width: parentEl.__ecGraphicWidth,
  75305. height: parentEl.__ecGraphicHeight
  75306. }; // PENDING
  75307. // Currently, when `bounding: 'all'`, the union bounding rect of the group
  75308. // does not include the rect of [0, 0, group.width, group.height], which
  75309. // is probably weird for users. Should we make a break change for it?
  75310. positionElement(el, elOption, containerInfo, null, {
  75311. hv: elOption.hv,
  75312. boundingMode: elOption.bounding
  75313. });
  75314. }
  75315. },
  75316. /**
  75317. * Clear all elements.
  75318. *
  75319. * @private
  75320. */
  75321. _clear: function () {
  75322. var elMap = this._elMap;
  75323. elMap.each(function (el) {
  75324. removeEl(el, elMap);
  75325. });
  75326. this._elMap = createHashMap();
  75327. },
  75328. /**
  75329. * @override
  75330. */
  75331. dispose: function () {
  75332. this._clear();
  75333. }
  75334. });
  75335. function createEl$1(id, targetElParent, elOption, elMap) {
  75336. var graphicType = elOption.type;
  75337. var Clz = _nonShapeGraphicElements.hasOwnProperty(graphicType) // Those graphic elements are not shapes. They should not be
  75338. // overwritten by users, so do them first.
  75339. ? _nonShapeGraphicElements[graphicType] : getShapeClass(graphicType);
  75340. var el = new Clz(elOption);
  75341. targetElParent.add(el);
  75342. elMap.set(id, el);
  75343. el.__ecGraphicId = id;
  75344. }
  75345. function removeEl(existEl, elMap) {
  75346. var existElParent = existEl && existEl.parent;
  75347. if (existElParent) {
  75348. existEl.type === 'group' && existEl.traverse(function (el) {
  75349. removeEl(el, elMap);
  75350. });
  75351. elMap.removeKey(existEl.__ecGraphicId);
  75352. existElParent.remove(existEl);
  75353. }
  75354. } // Remove unnecessary props to avoid potential problems.
  75355. function getCleanedElOption(elOption) {
  75356. elOption = extend({}, elOption);
  75357. each$1(['id', 'parentId', '$action', 'hv', 'bounding'].concat(LOCATION_PARAMS), function (name) {
  75358. delete elOption[name];
  75359. });
  75360. return elOption;
  75361. }
  75362. function isSetLoc(obj, props) {
  75363. var isSet;
  75364. each$1(props, function (prop) {
  75365. obj[prop] != null && obj[prop] !== 'auto' && (isSet = true);
  75366. });
  75367. return isSet;
  75368. }
  75369. function setKeyInfoToNewElOption(resultItem, newElOption) {
  75370. var existElOption = resultItem.exist; // Set id and type after id assigned.
  75371. newElOption.id = resultItem.keyInfo.id;
  75372. !newElOption.type && existElOption && (newElOption.type = existElOption.type); // Set parent id if not specified
  75373. if (newElOption.parentId == null) {
  75374. var newElParentOption = newElOption.parentOption;
  75375. if (newElParentOption) {
  75376. newElOption.parentId = newElParentOption.id;
  75377. } else if (existElOption) {
  75378. newElOption.parentId = existElOption.parentId;
  75379. }
  75380. } // Clear
  75381. newElOption.parentOption = null;
  75382. }
  75383. function mergeNewElOptionToExist(existList, index, newElOption) {
  75384. // Update existing options, for `getOption` feature.
  75385. var newElOptCopy = extend({}, newElOption);
  75386. var existElOption = existList[index];
  75387. var $action = newElOption.$action || 'merge';
  75388. if ($action === 'merge') {
  75389. if (existElOption) {
  75390. // We can ensure that newElOptCopy and existElOption are not
  75391. // the same object, so `merge` will not change newElOptCopy.
  75392. merge(existElOption, newElOptCopy, true); // Rigid body, use ignoreSize.
  75393. mergeLayoutParam(existElOption, newElOptCopy, {
  75394. ignoreSize: true
  75395. }); // Will be used in render.
  75396. copyLayoutParams(newElOption, existElOption);
  75397. } else {
  75398. existList[index] = newElOptCopy;
  75399. }
  75400. } else if ($action === 'replace') {
  75401. existList[index] = newElOptCopy;
  75402. } else if ($action === 'remove') {
  75403. // null will be cleaned later.
  75404. existElOption && (existList[index] = null);
  75405. }
  75406. }
  75407. function setLayoutInfoToExist(existItem, newElOption) {
  75408. if (!existItem) {
  75409. return;
  75410. }
  75411. existItem.hv = newElOption.hv = [// Rigid body, dont care `width`.
  75412. isSetLoc(newElOption, ['left', 'right']), // Rigid body, dont care `height`.
  75413. isSetLoc(newElOption, ['top', 'bottom'])]; // Give default group size. Otherwise layout error may occur.
  75414. if (existItem.type === 'group') {
  75415. existItem.width == null && (existItem.width = newElOption.width = 0);
  75416. existItem.height == null && (existItem.height = newElOption.height = 0);
  75417. }
  75418. }
  75419. function setEventData(el, graphicModel, elOption) {
  75420. var eventData = el.eventData; // Simple optimize for large amount of elements that no need event.
  75421. if (!el.silent && !el.ignore && !eventData) {
  75422. eventData = el.eventData = {
  75423. componentType: 'graphic',
  75424. componentIndex: graphicModel.componentIndex,
  75425. name: el.name
  75426. };
  75427. } // `elOption.info` enables user to mount some info on
  75428. // elements and use them in event handlers.
  75429. if (eventData) {
  75430. eventData.info = el.info;
  75431. }
  75432. }
  75433. exports.version = version;
  75434. exports.dependencies = dependencies;
  75435. exports.PRIORITY = PRIORITY;
  75436. exports.init = init;
  75437. exports.connect = connect;
  75438. exports.disConnect = disConnect;
  75439. exports.disconnect = disconnect;
  75440. exports.dispose = dispose;
  75441. exports.getInstanceByDom = getInstanceByDom;
  75442. exports.getInstanceById = getInstanceById;
  75443. exports.registerTheme = registerTheme;
  75444. exports.registerPreprocessor = registerPreprocessor;
  75445. exports.registerProcessor = registerProcessor;
  75446. exports.registerPostUpdate = registerPostUpdate;
  75447. exports.registerAction = registerAction;
  75448. exports.registerCoordinateSystem = registerCoordinateSystem;
  75449. exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions;
  75450. exports.registerLayout = registerLayout;
  75451. exports.registerVisual = registerVisual;
  75452. exports.registerLoading = registerLoading;
  75453. exports.extendComponentModel = extendComponentModel;
  75454. exports.extendComponentView = extendComponentView;
  75455. exports.extendSeriesModel = extendSeriesModel;
  75456. exports.extendChartView = extendChartView;
  75457. exports.setCanvasCreator = setCanvasCreator;
  75458. exports.registerMap = registerMap;
  75459. exports.getMap = getMap;
  75460. exports.dataTool = dataTool;
  75461. exports.zrender = zrender;
  75462. exports.number = number;
  75463. exports.format = format;
  75464. exports.throttle = throttle;
  75465. exports.helper = helper;
  75466. exports.matrix = matrix;
  75467. exports.vector = vector;
  75468. exports.color = color;
  75469. exports.parseGeoJSON = parseGeoJson$1;
  75470. exports.parseGeoJson = parseGeoJson;
  75471. exports.util = ecUtil;
  75472. exports.graphic = graphic$1;
  75473. exports.List = List;
  75474. exports.Model = Model;
  75475. exports.Axis = Axis;
  75476. exports.env = env$1;
  75477. })));